redux-toolkit.legacy-esm.js 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234
  1. // src/index.ts
  2. export * from "redux";
  3. import { produce, current as current2, freeze, original as original2, isDraft as isDraft4 } from "immer";
  4. import { createSelector, createSelectorCreator as createSelectorCreator2, lruMemoize, weakMapMemoize as weakMapMemoize2 } from "reselect";
  5. // src/createDraftSafeSelector.ts
  6. import { current, isDraft } from "immer";
  7. import { createSelectorCreator, weakMapMemoize } from "reselect";
  8. var createDraftSafeSelectorCreator = (...args) => {
  9. const createSelector2 = createSelectorCreator(...args);
  10. return (...args2) => {
  11. const selector = createSelector2(...args2);
  12. const wrappedSelector = (value, ...rest) => selector(isDraft(value) ? current(value) : value, ...rest);
  13. Object.assign(wrappedSelector, selector);
  14. return wrappedSelector;
  15. };
  16. };
  17. var createDraftSafeSelector = createDraftSafeSelectorCreator(weakMapMemoize);
  18. // src/configureStore.ts
  19. import { applyMiddleware, createStore, compose as compose2, combineReducers, isPlainObject as isPlainObject2 } from "redux";
  20. // src/devtoolsExtension.ts
  21. import { compose } from "redux";
  22. var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() {
  23. if (arguments.length === 0)
  24. return void 0;
  25. if (typeof arguments[0] === "object")
  26. return compose;
  27. return compose.apply(null, arguments);
  28. };
  29. var devToolsEnhancer = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function() {
  30. return function(noop3) {
  31. return noop3;
  32. };
  33. };
  34. // src/getDefaultMiddleware.ts
  35. import { thunk as thunkMiddleware, withExtraArgument } from "redux-thunk";
  36. // src/createAction.ts
  37. import { isAction } from "redux";
  38. // src/tsHelpers.ts
  39. var hasMatchFunction = (v) => {
  40. return v && typeof v.match === "function";
  41. };
  42. // src/createAction.ts
  43. function createAction(type, prepareAction) {
  44. function actionCreator(...args) {
  45. if (prepareAction) {
  46. let prepared = prepareAction(...args);
  47. if (!prepared) {
  48. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(0) : "prepareAction did not return an object");
  49. }
  50. return {
  51. type,
  52. payload: prepared.payload,
  53. ..."meta" in prepared && {
  54. meta: prepared.meta
  55. },
  56. ..."error" in prepared && {
  57. error: prepared.error
  58. }
  59. };
  60. }
  61. return {
  62. type,
  63. payload: args[0]
  64. };
  65. }
  66. actionCreator.toString = () => `${type}`;
  67. actionCreator.type = type;
  68. actionCreator.match = (action) => isAction(action) && action.type === type;
  69. return actionCreator;
  70. }
  71. function isActionCreator(action) {
  72. return typeof action === "function" && "type" in action && // hasMatchFunction only wants Matchers but I don't see the point in rewriting it
  73. hasMatchFunction(action);
  74. }
  75. function isFSA(action) {
  76. return isAction(action) && Object.keys(action).every(isValidKey);
  77. }
  78. function isValidKey(key) {
  79. return ["type", "payload", "error", "meta"].indexOf(key) > -1;
  80. }
  81. // src/actionCreatorInvariantMiddleware.ts
  82. function getMessage(type) {
  83. const splitType = type ? `${type}`.split("/") : [];
  84. const actionName = splitType[splitType.length - 1] || "actionCreator";
  85. return `Detected an action creator with type "${type || "unknown"}" being dispatched.
  86. 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.`;
  87. }
  88. function createActionCreatorInvariantMiddleware(options = {}) {
  89. if (process.env.NODE_ENV === "production") {
  90. return () => (next) => (action) => next(action);
  91. }
  92. const {
  93. isActionCreator: isActionCreator2 = isActionCreator
  94. } = options;
  95. return () => (next) => (action) => {
  96. if (isActionCreator2(action)) {
  97. console.warn(getMessage(action.type));
  98. }
  99. return next(action);
  100. };
  101. }
  102. // src/utils.ts
  103. import { produce as createNextState, isDraftable } from "immer";
  104. function getTimeMeasureUtils(maxDelay, fnName) {
  105. let elapsed = 0;
  106. return {
  107. measureTime(fn) {
  108. const started = Date.now();
  109. try {
  110. return fn();
  111. } finally {
  112. const finished = Date.now();
  113. elapsed += finished - started;
  114. }
  115. },
  116. warnIfExceeded() {
  117. if (elapsed > maxDelay) {
  118. console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms.
  119. 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.
  120. It is disabled in production builds, so you don't need to worry about that.`);
  121. }
  122. }
  123. };
  124. }
  125. function find(iterable, comparator) {
  126. for (const entry of iterable) {
  127. if (comparator(entry)) {
  128. return entry;
  129. }
  130. }
  131. return void 0;
  132. }
  133. var Tuple = class _Tuple extends Array {
  134. constructor(...items) {
  135. super(...items);
  136. Object.setPrototypeOf(this, _Tuple.prototype);
  137. }
  138. static get [Symbol.species]() {
  139. return _Tuple;
  140. }
  141. concat(...arr) {
  142. return super.concat.apply(this, arr);
  143. }
  144. prepend(...arr) {
  145. if (arr.length === 1 && Array.isArray(arr[0])) {
  146. return new _Tuple(...arr[0].concat(this));
  147. }
  148. return new _Tuple(...arr.concat(this));
  149. }
  150. };
  151. function freezeDraftable(val) {
  152. return isDraftable(val) ? createNextState(val, () => {
  153. }) : val;
  154. }
  155. function emplace(map, key, handler) {
  156. if (map.has(key)) {
  157. let value = map.get(key);
  158. if (handler.update) {
  159. value = handler.update(value, key, map);
  160. map.set(key, value);
  161. }
  162. return value;
  163. }
  164. if (!handler.insert)
  165. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(10) : "No insert provided for key not already in map");
  166. const inserted = handler.insert(key, map);
  167. map.set(key, inserted);
  168. return inserted;
  169. }
  170. // src/immutableStateInvariantMiddleware.ts
  171. function isImmutableDefault(value) {
  172. return typeof value !== "object" || value == null || Object.isFrozen(value);
  173. }
  174. function trackForMutations(isImmutable, ignorePaths, obj) {
  175. const trackedProperties = trackProperties(isImmutable, ignorePaths, obj);
  176. return {
  177. detectMutations() {
  178. return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);
  179. }
  180. };
  181. }
  182. function trackProperties(isImmutable, ignorePaths = [], obj, path = "", checkedObjects = /* @__PURE__ */ new Set()) {
  183. const tracked = {
  184. value: obj
  185. };
  186. if (!isImmutable(obj) && !checkedObjects.has(obj)) {
  187. checkedObjects.add(obj);
  188. tracked.children = {};
  189. for (const key in obj) {
  190. const childPath = path ? path + "." + key : key;
  191. if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {
  192. continue;
  193. }
  194. tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);
  195. }
  196. }
  197. return tracked;
  198. }
  199. function detectMutations(isImmutable, ignoredPaths = [], trackedProperty, obj, sameParentRef = false, path = "") {
  200. const prevObj = trackedProperty ? trackedProperty.value : void 0;
  201. const sameRef = prevObj === obj;
  202. if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
  203. return {
  204. wasMutated: true,
  205. path
  206. };
  207. }
  208. if (isImmutable(prevObj) || isImmutable(obj)) {
  209. return {
  210. wasMutated: false
  211. };
  212. }
  213. const keysToDetect = {};
  214. for (let key in trackedProperty.children) {
  215. keysToDetect[key] = true;
  216. }
  217. for (let key in obj) {
  218. keysToDetect[key] = true;
  219. }
  220. const hasIgnoredPaths = ignoredPaths.length > 0;
  221. for (let key in keysToDetect) {
  222. const nestedPath = path ? path + "." + key : key;
  223. if (hasIgnoredPaths) {
  224. const hasMatches = ignoredPaths.some((ignored) => {
  225. if (ignored instanceof RegExp) {
  226. return ignored.test(nestedPath);
  227. }
  228. return nestedPath === ignored;
  229. });
  230. if (hasMatches) {
  231. continue;
  232. }
  233. }
  234. const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);
  235. if (result.wasMutated) {
  236. return result;
  237. }
  238. }
  239. return {
  240. wasMutated: false
  241. };
  242. }
  243. function createImmutableStateInvariantMiddleware(options = {}) {
  244. if (process.env.NODE_ENV === "production") {
  245. return () => (next) => (action) => next(action);
  246. } else {
  247. let stringify2 = function(obj, serializer, indent, decycler) {
  248. return JSON.stringify(obj, getSerialize2(serializer, decycler), indent);
  249. }, getSerialize2 = function(serializer, decycler) {
  250. let stack = [], keys = [];
  251. if (!decycler)
  252. decycler = function(_, value) {
  253. if (stack[0] === value)
  254. return "[Circular ~]";
  255. return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
  256. };
  257. return function(key, value) {
  258. if (stack.length > 0) {
  259. var thisPos = stack.indexOf(this);
  260. ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
  261. ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
  262. if (~stack.indexOf(value))
  263. value = decycler.call(this, key, value);
  264. } else
  265. stack.push(value);
  266. return serializer == null ? value : serializer.call(this, key, value);
  267. };
  268. };
  269. var stringify = stringify2, getSerialize = getSerialize2;
  270. let {
  271. isImmutable = isImmutableDefault,
  272. ignoredPaths,
  273. warnAfter = 32
  274. } = options;
  275. const track = trackForMutations.bind(null, isImmutable, ignoredPaths);
  276. return ({
  277. getState
  278. }) => {
  279. let state = getState();
  280. let tracker = track(state);
  281. let result;
  282. return (next) => (action) => {
  283. const measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
  284. measureUtils.measureTime(() => {
  285. state = getState();
  286. result = tracker.detectMutations();
  287. tracker = track(state);
  288. if (result.wasMutated) {
  289. 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)`);
  290. }
  291. });
  292. const dispatchedAction = next(action);
  293. measureUtils.measureTime(() => {
  294. state = getState();
  295. result = tracker.detectMutations();
  296. tracker = track(state);
  297. if (result.wasMutated) {
  298. 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)`);
  299. }
  300. });
  301. measureUtils.warnIfExceeded();
  302. return dispatchedAction;
  303. };
  304. };
  305. }
  306. }
  307. // src/serializableStateInvariantMiddleware.ts
  308. import { isAction as isAction2, isPlainObject } from "redux";
  309. function isPlain(val) {
  310. const type = typeof val;
  311. return val == null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || isPlainObject(val);
  312. }
  313. function findNonSerializableValue(value, path = "", isSerializable = isPlain, getEntries, ignoredPaths = [], cache) {
  314. let foundNestedSerializable;
  315. if (!isSerializable(value)) {
  316. return {
  317. keyPath: path || "<root>",
  318. value
  319. };
  320. }
  321. if (typeof value !== "object" || value === null) {
  322. return false;
  323. }
  324. if (cache?.has(value))
  325. return false;
  326. const entries = getEntries != null ? getEntries(value) : Object.entries(value);
  327. const hasIgnoredPaths = ignoredPaths.length > 0;
  328. for (const [key, nestedValue] of entries) {
  329. const nestedPath = path ? path + "." + key : key;
  330. if (hasIgnoredPaths) {
  331. const hasMatches = ignoredPaths.some((ignored) => {
  332. if (ignored instanceof RegExp) {
  333. return ignored.test(nestedPath);
  334. }
  335. return nestedPath === ignored;
  336. });
  337. if (hasMatches) {
  338. continue;
  339. }
  340. }
  341. if (!isSerializable(nestedValue)) {
  342. return {
  343. keyPath: nestedPath,
  344. value: nestedValue
  345. };
  346. }
  347. if (typeof nestedValue === "object") {
  348. foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);
  349. if (foundNestedSerializable) {
  350. return foundNestedSerializable;
  351. }
  352. }
  353. }
  354. if (cache && isNestedFrozen(value))
  355. cache.add(value);
  356. return false;
  357. }
  358. function isNestedFrozen(value) {
  359. if (!Object.isFrozen(value))
  360. return false;
  361. for (const nestedValue of Object.values(value)) {
  362. if (typeof nestedValue !== "object" || nestedValue === null)
  363. continue;
  364. if (!isNestedFrozen(nestedValue))
  365. return false;
  366. }
  367. return true;
  368. }
  369. function createSerializableStateInvariantMiddleware(options = {}) {
  370. if (process.env.NODE_ENV === "production") {
  371. return () => (next) => (action) => next(action);
  372. } else {
  373. const {
  374. isSerializable = isPlain,
  375. getEntries,
  376. ignoredActions = [],
  377. ignoredActionPaths = ["meta.arg", "meta.baseQueryMeta"],
  378. ignoredPaths = [],
  379. warnAfter = 32,
  380. ignoreState = false,
  381. ignoreActions = false,
  382. disableCache = false
  383. } = options;
  384. const cache = !disableCache && WeakSet ? /* @__PURE__ */ new WeakSet() : void 0;
  385. return (storeAPI) => (next) => (action) => {
  386. if (!isAction2(action)) {
  387. return next(action);
  388. }
  389. const result = next(action);
  390. const measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
  391. if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {
  392. measureUtils.measureTime(() => {
  393. const foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths, cache);
  394. if (foundActionNonSerializableValue) {
  395. const {
  396. keyPath,
  397. value
  398. } = foundActionNonSerializableValue;
  399. 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)");
  400. }
  401. });
  402. }
  403. if (!ignoreState) {
  404. measureUtils.measureTime(() => {
  405. const state = storeAPI.getState();
  406. const foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths, cache);
  407. if (foundStateNonSerializableValue) {
  408. const {
  409. keyPath,
  410. value
  411. } = foundStateNonSerializableValue;
  412. console.error(`A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`, value, `
  413. Take a look at the reducer(s) handling this action type: ${action.type}.
  414. (See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);
  415. }
  416. });
  417. measureUtils.warnIfExceeded();
  418. }
  419. return result;
  420. };
  421. }
  422. }
  423. // src/getDefaultMiddleware.ts
  424. function isBoolean(x) {
  425. return typeof x === "boolean";
  426. }
  427. var buildGetDefaultMiddleware = () => function getDefaultMiddleware(options) {
  428. const {
  429. thunk = true,
  430. immutableCheck = true,
  431. serializableCheck = true,
  432. actionCreatorCheck = true
  433. } = options ?? {};
  434. let middlewareArray = new Tuple();
  435. if (thunk) {
  436. if (isBoolean(thunk)) {
  437. middlewareArray.push(thunkMiddleware);
  438. } else {
  439. middlewareArray.push(withExtraArgument(thunk.extraArgument));
  440. }
  441. }
  442. if (process.env.NODE_ENV !== "production") {
  443. if (immutableCheck) {
  444. let immutableOptions = {};
  445. if (!isBoolean(immutableCheck)) {
  446. immutableOptions = immutableCheck;
  447. }
  448. middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
  449. }
  450. if (serializableCheck) {
  451. let serializableOptions = {};
  452. if (!isBoolean(serializableCheck)) {
  453. serializableOptions = serializableCheck;
  454. }
  455. middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
  456. }
  457. if (actionCreatorCheck) {
  458. let actionCreatorOptions = {};
  459. if (!isBoolean(actionCreatorCheck)) {
  460. actionCreatorOptions = actionCreatorCheck;
  461. }
  462. middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));
  463. }
  464. }
  465. return middlewareArray;
  466. };
  467. // src/autoBatchEnhancer.ts
  468. var SHOULD_AUTOBATCH = "RTK_autoBatch";
  469. var prepareAutoBatched = () => (payload) => ({
  470. payload,
  471. meta: {
  472. [SHOULD_AUTOBATCH]: true
  473. }
  474. });
  475. var createQueueWithTimer = (timeout) => {
  476. return (notify) => {
  477. setTimeout(notify, timeout);
  478. };
  479. };
  480. var rAF = typeof window !== "undefined" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10);
  481. var autoBatchEnhancer = (options = {
  482. type: "raf"
  483. }) => (next) => (...args) => {
  484. const store = next(...args);
  485. let notifying = true;
  486. let shouldNotifyAtEndOfTick = false;
  487. let notificationQueued = false;
  488. const listeners = /* @__PURE__ */ new Set();
  489. const queueCallback = options.type === "tick" ? queueMicrotask : options.type === "raf" ? rAF : options.type === "callback" ? options.queueNotification : createQueueWithTimer(options.timeout);
  490. const notifyListeners = () => {
  491. notificationQueued = false;
  492. if (shouldNotifyAtEndOfTick) {
  493. shouldNotifyAtEndOfTick = false;
  494. listeners.forEach((l) => l());
  495. }
  496. };
  497. return Object.assign({}, store, {
  498. // Override the base `store.subscribe` method to keep original listeners
  499. // from running if we're delaying notifications
  500. subscribe(listener2) {
  501. const wrappedListener = () => notifying && listener2();
  502. const unsubscribe = store.subscribe(wrappedListener);
  503. listeners.add(listener2);
  504. return () => {
  505. unsubscribe();
  506. listeners.delete(listener2);
  507. };
  508. },
  509. // Override the base `store.dispatch` method so that we can check actions
  510. // for the `shouldAutoBatch` flag and determine if batching is active
  511. dispatch(action) {
  512. try {
  513. notifying = !action?.meta?.[SHOULD_AUTOBATCH];
  514. shouldNotifyAtEndOfTick = !notifying;
  515. if (shouldNotifyAtEndOfTick) {
  516. if (!notificationQueued) {
  517. notificationQueued = true;
  518. queueCallback(notifyListeners);
  519. }
  520. }
  521. return store.dispatch(action);
  522. } finally {
  523. notifying = true;
  524. }
  525. }
  526. });
  527. };
  528. // src/getDefaultEnhancers.ts
  529. var buildGetDefaultEnhancers = (middlewareEnhancer) => function getDefaultEnhancers(options) {
  530. const {
  531. autoBatch = true
  532. } = options ?? {};
  533. let enhancerArray = new Tuple(middlewareEnhancer);
  534. if (autoBatch) {
  535. enhancerArray.push(autoBatchEnhancer(typeof autoBatch === "object" ? autoBatch : void 0));
  536. }
  537. return enhancerArray;
  538. };
  539. // src/configureStore.ts
  540. var IS_PRODUCTION = process.env.NODE_ENV === "production";
  541. function configureStore(options) {
  542. const getDefaultMiddleware = buildGetDefaultMiddleware();
  543. const {
  544. reducer = void 0,
  545. middleware,
  546. devTools = true,
  547. preloadedState = void 0,
  548. enhancers = void 0
  549. } = options || {};
  550. let rootReducer;
  551. if (typeof reducer === "function") {
  552. rootReducer = reducer;
  553. } else if (isPlainObject2(reducer)) {
  554. rootReducer = combineReducers(reducer);
  555. } else {
  556. 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");
  557. }
  558. if (!IS_PRODUCTION && middleware && typeof middleware !== "function") {
  559. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(2) : "`middleware` field must be a callback");
  560. }
  561. let finalMiddleware;
  562. if (typeof middleware === "function") {
  563. finalMiddleware = middleware(getDefaultMiddleware);
  564. if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {
  565. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(3) : "when using a middleware builder function, an array of middleware must be returned");
  566. }
  567. } else {
  568. finalMiddleware = getDefaultMiddleware();
  569. }
  570. if (!IS_PRODUCTION && finalMiddleware.some((item) => typeof item !== "function")) {
  571. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(4) : "each middleware provided to configureStore must be a function");
  572. }
  573. let finalCompose = compose2;
  574. if (devTools) {
  575. finalCompose = composeWithDevTools({
  576. // Enable capture of stack traces for dispatched Redux actions
  577. trace: !IS_PRODUCTION,
  578. ...typeof devTools === "object" && devTools
  579. });
  580. }
  581. const middlewareEnhancer = applyMiddleware(...finalMiddleware);
  582. const getDefaultEnhancers = buildGetDefaultEnhancers(middlewareEnhancer);
  583. if (!IS_PRODUCTION && enhancers && typeof enhancers !== "function") {
  584. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(5) : "`enhancers` field must be a callback");
  585. }
  586. let storeEnhancers = typeof enhancers === "function" ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();
  587. if (!IS_PRODUCTION && !Array.isArray(storeEnhancers)) {
  588. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(6) : "`enhancers` callback must return an array");
  589. }
  590. if (!IS_PRODUCTION && storeEnhancers.some((item) => typeof item !== "function")) {
  591. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(7) : "each enhancer provided to configureStore must be a function");
  592. }
  593. if (!IS_PRODUCTION && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {
  594. console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");
  595. }
  596. const composedEnhancer = finalCompose(...storeEnhancers);
  597. return createStore(rootReducer, preloadedState, composedEnhancer);
  598. }
  599. // src/createReducer.ts
  600. import { produce as createNextState2, isDraft as isDraft2, isDraftable as isDraftable2 } from "immer";
  601. // src/mapBuilders.ts
  602. function executeReducerBuilderCallback(builderCallback) {
  603. const actionsMap = {};
  604. const actionMatchers = [];
  605. let defaultCaseReducer;
  606. const builder = {
  607. addCase(typeOrActionCreator, reducer) {
  608. if (process.env.NODE_ENV !== "production") {
  609. if (actionMatchers.length > 0) {
  610. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(26) : "`builder.addCase` should only be called before calling `builder.addMatcher`");
  611. }
  612. if (defaultCaseReducer) {
  613. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(27) : "`builder.addCase` should only be called before calling `builder.addDefaultCase`");
  614. }
  615. }
  616. const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
  617. if (!type) {
  618. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(28) : "`builder.addCase` cannot be called with an empty action type");
  619. }
  620. if (type in actionsMap) {
  621. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(29) : `\`builder.addCase\` cannot be called with two reducers for the same action type '${type}'`);
  622. }
  623. actionsMap[type] = reducer;
  624. return builder;
  625. },
  626. addMatcher(matcher, reducer) {
  627. if (process.env.NODE_ENV !== "production") {
  628. if (defaultCaseReducer) {
  629. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(30) : "`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
  630. }
  631. }
  632. actionMatchers.push({
  633. matcher,
  634. reducer
  635. });
  636. return builder;
  637. },
  638. addDefaultCase(reducer) {
  639. if (process.env.NODE_ENV !== "production") {
  640. if (defaultCaseReducer) {
  641. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(31) : "`builder.addDefaultCase` can only be called once");
  642. }
  643. }
  644. defaultCaseReducer = reducer;
  645. return builder;
  646. }
  647. };
  648. builderCallback(builder);
  649. return [actionsMap, actionMatchers, defaultCaseReducer];
  650. }
  651. // src/createReducer.ts
  652. function isStateFunction(x) {
  653. return typeof x === "function";
  654. }
  655. function createReducer(initialState, mapOrBuilderCallback) {
  656. if (process.env.NODE_ENV !== "production") {
  657. if (typeof mapOrBuilderCallback === "object") {
  658. 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");
  659. }
  660. }
  661. let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);
  662. let getInitialState;
  663. if (isStateFunction(initialState)) {
  664. getInitialState = () => freezeDraftable(initialState());
  665. } else {
  666. const frozenInitialState = freezeDraftable(initialState);
  667. getInitialState = () => frozenInitialState;
  668. }
  669. function reducer(state = getInitialState(), action) {
  670. let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({
  671. matcher
  672. }) => matcher(action)).map(({
  673. reducer: reducer2
  674. }) => reducer2)];
  675. if (caseReducers.filter((cr) => !!cr).length === 0) {
  676. caseReducers = [finalDefaultCaseReducer];
  677. }
  678. return caseReducers.reduce((previousState, caseReducer) => {
  679. if (caseReducer) {
  680. if (isDraft2(previousState)) {
  681. const draft = previousState;
  682. const result = caseReducer(draft, action);
  683. if (result === void 0) {
  684. return previousState;
  685. }
  686. return result;
  687. } else if (!isDraftable2(previousState)) {
  688. const result = caseReducer(previousState, action);
  689. if (result === void 0) {
  690. if (previousState === null) {
  691. return previousState;
  692. }
  693. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(9) : "A case reducer on a non-draftable value must not return undefined");
  694. }
  695. return result;
  696. } else {
  697. return createNextState2(previousState, (draft) => {
  698. return caseReducer(draft, action);
  699. });
  700. }
  701. }
  702. return previousState;
  703. }, state);
  704. }
  705. reducer.getInitialState = getInitialState;
  706. return reducer;
  707. }
  708. // src/nanoid.ts
  709. var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
  710. var nanoid = (size = 21) => {
  711. let id = "";
  712. let i = size;
  713. while (i--) {
  714. id += urlAlphabet[Math.random() * 64 | 0];
  715. }
  716. return id;
  717. };
  718. // src/matchers.ts
  719. var matches = (matcher, action) => {
  720. if (hasMatchFunction(matcher)) {
  721. return matcher.match(action);
  722. } else {
  723. return matcher(action);
  724. }
  725. };
  726. function isAnyOf(...matchers) {
  727. return (action) => {
  728. return matchers.some((matcher) => matches(matcher, action));
  729. };
  730. }
  731. function isAllOf(...matchers) {
  732. return (action) => {
  733. return matchers.every((matcher) => matches(matcher, action));
  734. };
  735. }
  736. function hasExpectedRequestMetadata(action, validStatus) {
  737. if (!action || !action.meta)
  738. return false;
  739. const hasValidRequestId = typeof action.meta.requestId === "string";
  740. const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
  741. return hasValidRequestId && hasValidRequestStatus;
  742. }
  743. function isAsyncThunkArray(a) {
  744. return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
  745. }
  746. function isPending(...asyncThunks) {
  747. if (asyncThunks.length === 0) {
  748. return (action) => hasExpectedRequestMetadata(action, ["pending"]);
  749. }
  750. if (!isAsyncThunkArray(asyncThunks)) {
  751. return isPending()(asyncThunks[0]);
  752. }
  753. return (action) => {
  754. const matchers = asyncThunks.map((asyncThunk) => asyncThunk.pending);
  755. const combinedMatcher = isAnyOf(...matchers);
  756. return combinedMatcher(action);
  757. };
  758. }
  759. function isRejected(...asyncThunks) {
  760. if (asyncThunks.length === 0) {
  761. return (action) => hasExpectedRequestMetadata(action, ["rejected"]);
  762. }
  763. if (!isAsyncThunkArray(asyncThunks)) {
  764. return isRejected()(asyncThunks[0]);
  765. }
  766. return (action) => {
  767. const matchers = asyncThunks.map((asyncThunk) => asyncThunk.rejected);
  768. const combinedMatcher = isAnyOf(...matchers);
  769. return combinedMatcher(action);
  770. };
  771. }
  772. function isRejectedWithValue(...asyncThunks) {
  773. const hasFlag = (action) => {
  774. return action && action.meta && action.meta.rejectedWithValue;
  775. };
  776. if (asyncThunks.length === 0) {
  777. return (action) => {
  778. const combinedMatcher = isAllOf(isRejected(...asyncThunks), hasFlag);
  779. return combinedMatcher(action);
  780. };
  781. }
  782. if (!isAsyncThunkArray(asyncThunks)) {
  783. return isRejectedWithValue()(asyncThunks[0]);
  784. }
  785. return (action) => {
  786. const combinedMatcher = isAllOf(isRejected(...asyncThunks), hasFlag);
  787. return combinedMatcher(action);
  788. };
  789. }
  790. function isFulfilled(...asyncThunks) {
  791. if (asyncThunks.length === 0) {
  792. return (action) => hasExpectedRequestMetadata(action, ["fulfilled"]);
  793. }
  794. if (!isAsyncThunkArray(asyncThunks)) {
  795. return isFulfilled()(asyncThunks[0]);
  796. }
  797. return (action) => {
  798. const matchers = asyncThunks.map((asyncThunk) => asyncThunk.fulfilled);
  799. const combinedMatcher = isAnyOf(...matchers);
  800. return combinedMatcher(action);
  801. };
  802. }
  803. function isAsyncThunkAction(...asyncThunks) {
  804. if (asyncThunks.length === 0) {
  805. return (action) => hasExpectedRequestMetadata(action, ["pending", "fulfilled", "rejected"]);
  806. }
  807. if (!isAsyncThunkArray(asyncThunks)) {
  808. return isAsyncThunkAction()(asyncThunks[0]);
  809. }
  810. return (action) => {
  811. const matchers = [];
  812. for (const asyncThunk of asyncThunks) {
  813. matchers.push(asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled);
  814. }
  815. const combinedMatcher = isAnyOf(...matchers);
  816. return combinedMatcher(action);
  817. };
  818. }
  819. // src/createAsyncThunk.ts
  820. var commonProperties = ["name", "message", "stack", "code"];
  821. var RejectWithValue = class {
  822. constructor(payload, meta) {
  823. this.payload = payload;
  824. this.meta = meta;
  825. }
  826. /*
  827. type-only property to distinguish between RejectWithValue and FulfillWithMeta
  828. does not exist at runtime
  829. */
  830. _type;
  831. };
  832. var FulfillWithMeta = class {
  833. constructor(payload, meta) {
  834. this.payload = payload;
  835. this.meta = meta;
  836. }
  837. /*
  838. type-only property to distinguish between RejectWithValue and FulfillWithMeta
  839. does not exist at runtime
  840. */
  841. _type;
  842. };
  843. var miniSerializeError = (value) => {
  844. if (typeof value === "object" && value !== null) {
  845. const simpleError = {};
  846. for (const property of commonProperties) {
  847. if (typeof value[property] === "string") {
  848. simpleError[property] = value[property];
  849. }
  850. }
  851. return simpleError;
  852. }
  853. return {
  854. message: String(value)
  855. };
  856. };
  857. var createAsyncThunk = /* @__PURE__ */ (() => {
  858. function createAsyncThunk2(typePrefix, payloadCreator, options) {
  859. const fulfilled = createAction(typePrefix + "/fulfilled", (payload, requestId, arg, meta) => ({
  860. payload,
  861. meta: {
  862. ...meta || {},
  863. arg,
  864. requestId,
  865. requestStatus: "fulfilled"
  866. }
  867. }));
  868. const pending = createAction(typePrefix + "/pending", (requestId, arg, meta) => ({
  869. payload: void 0,
  870. meta: {
  871. ...meta || {},
  872. arg,
  873. requestId,
  874. requestStatus: "pending"
  875. }
  876. }));
  877. const rejected = createAction(typePrefix + "/rejected", (error, requestId, arg, payload, meta) => ({
  878. payload,
  879. error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
  880. meta: {
  881. ...meta || {},
  882. arg,
  883. requestId,
  884. rejectedWithValue: !!payload,
  885. requestStatus: "rejected",
  886. aborted: error?.name === "AbortError",
  887. condition: error?.name === "ConditionError"
  888. }
  889. }));
  890. function actionCreator(arg) {
  891. return (dispatch, getState, extra) => {
  892. const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();
  893. const abortController = new AbortController();
  894. let abortReason;
  895. function abort(reason) {
  896. abortReason = reason;
  897. abortController.abort();
  898. }
  899. const promise = async function() {
  900. let finalAction;
  901. try {
  902. let conditionResult = options?.condition?.(arg, {
  903. getState,
  904. extra
  905. });
  906. if (isThenable(conditionResult)) {
  907. conditionResult = await conditionResult;
  908. }
  909. if (conditionResult === false || abortController.signal.aborted) {
  910. throw {
  911. name: "ConditionError",
  912. message: "Aborted due to condition callback returning false."
  913. };
  914. }
  915. const abortedPromise = new Promise((_, reject) => abortController.signal.addEventListener("abort", () => reject({
  916. name: "AbortError",
  917. message: abortReason || "Aborted"
  918. })));
  919. dispatch(pending(requestId, arg, options?.getPendingMeta?.({
  920. requestId,
  921. arg
  922. }, {
  923. getState,
  924. extra
  925. })));
  926. finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {
  927. dispatch,
  928. getState,
  929. extra,
  930. requestId,
  931. signal: abortController.signal,
  932. abort,
  933. rejectWithValue: (value, meta) => {
  934. return new RejectWithValue(value, meta);
  935. },
  936. fulfillWithValue: (value, meta) => {
  937. return new FulfillWithMeta(value, meta);
  938. }
  939. })).then((result) => {
  940. if (result instanceof RejectWithValue) {
  941. throw result;
  942. }
  943. if (result instanceof FulfillWithMeta) {
  944. return fulfilled(result.payload, requestId, arg, result.meta);
  945. }
  946. return fulfilled(result, requestId, arg);
  947. })]);
  948. } catch (err) {
  949. finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);
  950. }
  951. const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;
  952. if (!skipDispatch) {
  953. dispatch(finalAction);
  954. }
  955. return finalAction;
  956. }();
  957. return Object.assign(promise, {
  958. abort,
  959. requestId,
  960. arg,
  961. unwrap() {
  962. return promise.then(unwrapResult);
  963. }
  964. });
  965. };
  966. }
  967. return Object.assign(actionCreator, {
  968. pending,
  969. rejected,
  970. fulfilled,
  971. settled: isAnyOf(rejected, fulfilled),
  972. typePrefix
  973. });
  974. }
  975. createAsyncThunk2.withTypes = () => createAsyncThunk2;
  976. return createAsyncThunk2;
  977. })();
  978. function unwrapResult(action) {
  979. if (action.meta && action.meta.rejectedWithValue) {
  980. throw action.payload;
  981. }
  982. if (action.error) {
  983. throw action.error;
  984. }
  985. return action.payload;
  986. }
  987. function isThenable(value) {
  988. return value !== null && typeof value === "object" && typeof value.then === "function";
  989. }
  990. // src/createSlice.ts
  991. var asyncThunkSymbol = Symbol.for("rtk-slice-createasyncthunk");
  992. var asyncThunkCreator = {
  993. [asyncThunkSymbol]: createAsyncThunk
  994. };
  995. var ReducerType = /* @__PURE__ */ ((ReducerType2) => {
  996. ReducerType2["reducer"] = "reducer";
  997. ReducerType2["reducerWithPrepare"] = "reducerWithPrepare";
  998. ReducerType2["asyncThunk"] = "asyncThunk";
  999. return ReducerType2;
  1000. })(ReducerType || {});
  1001. function getType(slice, actionKey) {
  1002. return `${slice}/${actionKey}`;
  1003. }
  1004. function buildCreateSlice({
  1005. creators
  1006. } = {}) {
  1007. const cAT = creators?.asyncThunk?.[asyncThunkSymbol];
  1008. return function createSlice2(options) {
  1009. const {
  1010. name,
  1011. reducerPath = name
  1012. } = options;
  1013. if (!name) {
  1014. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(11) : "`name` is a required option for createSlice");
  1015. }
  1016. if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
  1017. if (options.initialState === void 0) {
  1018. console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");
  1019. }
  1020. }
  1021. const reducers = (typeof options.reducers === "function" ? options.reducers(buildReducerCreators()) : options.reducers) || {};
  1022. const reducerNames = Object.keys(reducers);
  1023. const context = {
  1024. sliceCaseReducersByName: {},
  1025. sliceCaseReducersByType: {},
  1026. actionCreators: {},
  1027. sliceMatchers: []
  1028. };
  1029. const contextMethods = {
  1030. addCase(typeOrActionCreator, reducer) {
  1031. const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
  1032. if (!type) {
  1033. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(12) : "`context.addCase` cannot be called with an empty action type");
  1034. }
  1035. if (type in context.sliceCaseReducersByType) {
  1036. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(13) : "`context.addCase` cannot be called with two reducers for the same action type: " + type);
  1037. }
  1038. context.sliceCaseReducersByType[type] = reducer;
  1039. return contextMethods;
  1040. },
  1041. addMatcher(matcher, reducer) {
  1042. context.sliceMatchers.push({
  1043. matcher,
  1044. reducer
  1045. });
  1046. return contextMethods;
  1047. },
  1048. exposeAction(name2, actionCreator) {
  1049. context.actionCreators[name2] = actionCreator;
  1050. return contextMethods;
  1051. },
  1052. exposeCaseReducer(name2, reducer) {
  1053. context.sliceCaseReducersByName[name2] = reducer;
  1054. return contextMethods;
  1055. }
  1056. };
  1057. reducerNames.forEach((reducerName) => {
  1058. const reducerDefinition = reducers[reducerName];
  1059. const reducerDetails = {
  1060. reducerName,
  1061. type: getType(name, reducerName),
  1062. createNotation: typeof options.reducers === "function"
  1063. };
  1064. if (isAsyncThunkSliceReducerDefinition(reducerDefinition)) {
  1065. handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);
  1066. } else {
  1067. handleNormalReducerDefinition(reducerDetails, reducerDefinition, contextMethods);
  1068. }
  1069. });
  1070. function buildReducer() {
  1071. if (process.env.NODE_ENV !== "production") {
  1072. if (typeof options.extraReducers === "object") {
  1073. 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");
  1074. }
  1075. }
  1076. const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];
  1077. const finalCaseReducers = {
  1078. ...extraReducers,
  1079. ...context.sliceCaseReducersByType
  1080. };
  1081. return createReducer(options.initialState, (builder) => {
  1082. for (let key in finalCaseReducers) {
  1083. builder.addCase(key, finalCaseReducers[key]);
  1084. }
  1085. for (let sM of context.sliceMatchers) {
  1086. builder.addMatcher(sM.matcher, sM.reducer);
  1087. }
  1088. for (let m of actionMatchers) {
  1089. builder.addMatcher(m.matcher, m.reducer);
  1090. }
  1091. if (defaultCaseReducer) {
  1092. builder.addDefaultCase(defaultCaseReducer);
  1093. }
  1094. });
  1095. }
  1096. const selectSelf = (state) => state;
  1097. const injectedSelectorCache = /* @__PURE__ */ new WeakMap();
  1098. let _reducer;
  1099. const slice = {
  1100. name,
  1101. reducerPath,
  1102. reducer(state, action) {
  1103. if (!_reducer)
  1104. _reducer = buildReducer();
  1105. return _reducer(state, action);
  1106. },
  1107. actions: context.actionCreators,
  1108. caseReducers: context.sliceCaseReducersByName,
  1109. getInitialState() {
  1110. if (!_reducer)
  1111. _reducer = buildReducer();
  1112. return _reducer.getInitialState();
  1113. },
  1114. getSelectors(selectState = selectSelf) {
  1115. const selectorCache = emplace(injectedSelectorCache, this, {
  1116. insert: () => /* @__PURE__ */ new WeakMap()
  1117. });
  1118. return emplace(selectorCache, selectState, {
  1119. insert: () => {
  1120. const map = {};
  1121. for (const [name2, selector] of Object.entries(options.selectors ?? {})) {
  1122. map[name2] = wrapSelector(this, selector, selectState, this !== slice);
  1123. }
  1124. return map;
  1125. }
  1126. });
  1127. },
  1128. selectSlice(state) {
  1129. let sliceState = state[this.reducerPath];
  1130. if (typeof sliceState === "undefined") {
  1131. if (this !== slice) {
  1132. sliceState = this.getInitialState();
  1133. } else if (process.env.NODE_ENV !== "production") {
  1134. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(15) : "selectSlice returned undefined for an uninjected slice reducer");
  1135. }
  1136. }
  1137. return sliceState;
  1138. },
  1139. get selectors() {
  1140. return this.getSelectors(this.selectSlice);
  1141. },
  1142. injectInto(injectable, {
  1143. reducerPath: pathOpt,
  1144. ...config
  1145. } = {}) {
  1146. const reducerPath2 = pathOpt ?? this.reducerPath;
  1147. injectable.inject({
  1148. reducerPath: reducerPath2,
  1149. reducer: this.reducer
  1150. }, config);
  1151. return {
  1152. ...this,
  1153. reducerPath: reducerPath2
  1154. };
  1155. }
  1156. };
  1157. return slice;
  1158. };
  1159. }
  1160. function wrapSelector(slice, selector, selectState, injected) {
  1161. function wrapper(rootState, ...args) {
  1162. let sliceState = selectState.call(slice, rootState);
  1163. if (typeof sliceState === "undefined") {
  1164. if (injected) {
  1165. sliceState = slice.getInitialState();
  1166. } else if (process.env.NODE_ENV !== "production") {
  1167. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(16) : "selectState returned undefined for an uninjected slice reducer");
  1168. }
  1169. }
  1170. return selector(sliceState, ...args);
  1171. }
  1172. wrapper.unwrapped = selector;
  1173. return wrapper;
  1174. }
  1175. var createSlice = buildCreateSlice();
  1176. function buildReducerCreators() {
  1177. function asyncThunk(payloadCreator, config) {
  1178. return {
  1179. _reducerDefinitionType: "asyncThunk" /* asyncThunk */,
  1180. payloadCreator,
  1181. ...config
  1182. };
  1183. }
  1184. asyncThunk.withTypes = () => asyncThunk;
  1185. return {
  1186. reducer(caseReducer) {
  1187. return Object.assign({
  1188. // hack so the wrapping function has the same name as the original
  1189. // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original
  1190. [caseReducer.name](...args) {
  1191. return caseReducer(...args);
  1192. }
  1193. }[caseReducer.name], {
  1194. _reducerDefinitionType: "reducer" /* reducer */
  1195. });
  1196. },
  1197. preparedReducer(prepare, reducer) {
  1198. return {
  1199. _reducerDefinitionType: "reducerWithPrepare" /* reducerWithPrepare */,
  1200. prepare,
  1201. reducer
  1202. };
  1203. },
  1204. asyncThunk
  1205. };
  1206. }
  1207. function handleNormalReducerDefinition({
  1208. type,
  1209. reducerName,
  1210. createNotation
  1211. }, maybeReducerWithPrepare, context) {
  1212. let caseReducer;
  1213. let prepareCallback;
  1214. if ("reducer" in maybeReducerWithPrepare) {
  1215. if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {
  1216. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(17) : "Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");
  1217. }
  1218. caseReducer = maybeReducerWithPrepare.reducer;
  1219. prepareCallback = maybeReducerWithPrepare.prepare;
  1220. } else {
  1221. caseReducer = maybeReducerWithPrepare;
  1222. }
  1223. context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));
  1224. }
  1225. function isAsyncThunkSliceReducerDefinition(reducerDefinition) {
  1226. return reducerDefinition._reducerDefinitionType === "asyncThunk" /* asyncThunk */;
  1227. }
  1228. function isCaseReducerWithPrepareDefinition(reducerDefinition) {
  1229. return reducerDefinition._reducerDefinitionType === "reducerWithPrepare" /* reducerWithPrepare */;
  1230. }
  1231. function handleThunkCaseReducerDefinition({
  1232. type,
  1233. reducerName
  1234. }, reducerDefinition, context, cAT) {
  1235. if (!cAT) {
  1236. 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`.");
  1237. }
  1238. const {
  1239. payloadCreator,
  1240. fulfilled,
  1241. pending,
  1242. rejected,
  1243. settled,
  1244. options
  1245. } = reducerDefinition;
  1246. const thunk = cAT(type, payloadCreator, options);
  1247. context.exposeAction(reducerName, thunk);
  1248. if (fulfilled) {
  1249. context.addCase(thunk.fulfilled, fulfilled);
  1250. }
  1251. if (pending) {
  1252. context.addCase(thunk.pending, pending);
  1253. }
  1254. if (rejected) {
  1255. context.addCase(thunk.rejected, rejected);
  1256. }
  1257. if (settled) {
  1258. context.addMatcher(thunk.settled, settled);
  1259. }
  1260. context.exposeCaseReducer(reducerName, {
  1261. fulfilled: fulfilled || noop,
  1262. pending: pending || noop,
  1263. rejected: rejected || noop,
  1264. settled: settled || noop
  1265. });
  1266. }
  1267. function noop() {
  1268. }
  1269. // src/entities/entity_state.ts
  1270. function getInitialEntityState() {
  1271. return {
  1272. ids: [],
  1273. entities: {}
  1274. };
  1275. }
  1276. function createInitialStateFactory() {
  1277. function getInitialState(additionalState = {}) {
  1278. return Object.assign(getInitialEntityState(), additionalState);
  1279. }
  1280. return {
  1281. getInitialState
  1282. };
  1283. }
  1284. // src/entities/state_selectors.ts
  1285. function createSelectorsFactory() {
  1286. function getSelectors(selectState, options = {}) {
  1287. const {
  1288. createSelector: createSelector2 = createDraftSafeSelector
  1289. } = options;
  1290. const selectIds = (state) => state.ids;
  1291. const selectEntities = (state) => state.entities;
  1292. const selectAll = createSelector2(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));
  1293. const selectId = (_, id) => id;
  1294. const selectById = (entities, id) => entities[id];
  1295. const selectTotal = createSelector2(selectIds, (ids) => ids.length);
  1296. if (!selectState) {
  1297. return {
  1298. selectIds,
  1299. selectEntities,
  1300. selectAll,
  1301. selectTotal,
  1302. selectById: createSelector2(selectEntities, selectId, selectById)
  1303. };
  1304. }
  1305. const selectGlobalizedEntities = createSelector2(selectState, selectEntities);
  1306. return {
  1307. selectIds: createSelector2(selectState, selectIds),
  1308. selectEntities: selectGlobalizedEntities,
  1309. selectAll: createSelector2(selectState, selectAll),
  1310. selectTotal: createSelector2(selectState, selectTotal),
  1311. selectById: createSelector2(selectGlobalizedEntities, selectId, selectById)
  1312. };
  1313. }
  1314. return {
  1315. getSelectors
  1316. };
  1317. }
  1318. // src/entities/state_adapter.ts
  1319. import { produce as createNextState3, isDraft as isDraft3 } from "immer";
  1320. var isDraftTyped = isDraft3;
  1321. function createSingleArgumentStateOperator(mutator) {
  1322. const operator = createStateOperator((_, state) => mutator(state));
  1323. return function operation(state) {
  1324. return operator(state, void 0);
  1325. };
  1326. }
  1327. function createStateOperator(mutator) {
  1328. return function operation(state, arg) {
  1329. function isPayloadActionArgument(arg2) {
  1330. return isFSA(arg2);
  1331. }
  1332. const runMutator = (draft) => {
  1333. if (isPayloadActionArgument(arg)) {
  1334. mutator(arg.payload, draft);
  1335. } else {
  1336. mutator(arg, draft);
  1337. }
  1338. };
  1339. if (isDraftTyped(state)) {
  1340. runMutator(state);
  1341. return state;
  1342. }
  1343. return createNextState3(state, runMutator);
  1344. };
  1345. }
  1346. // src/entities/utils.ts
  1347. function selectIdValue(entity, selectId) {
  1348. const key = selectId(entity);
  1349. if (process.env.NODE_ENV !== "production" && key === void 0) {
  1350. 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());
  1351. }
  1352. return key;
  1353. }
  1354. function ensureEntitiesArray(entities) {
  1355. if (!Array.isArray(entities)) {
  1356. entities = Object.values(entities);
  1357. }
  1358. return entities;
  1359. }
  1360. function splitAddedUpdatedEntities(newEntities, selectId, state) {
  1361. newEntities = ensureEntitiesArray(newEntities);
  1362. const added = [];
  1363. const updated = [];
  1364. for (const entity of newEntities) {
  1365. const id = selectIdValue(entity, selectId);
  1366. if (id in state.entities) {
  1367. updated.push({
  1368. id,
  1369. changes: entity
  1370. });
  1371. } else {
  1372. added.push(entity);
  1373. }
  1374. }
  1375. return [added, updated];
  1376. }
  1377. // src/entities/unsorted_state_adapter.ts
  1378. function createUnsortedStateAdapter(selectId) {
  1379. function addOneMutably(entity, state) {
  1380. const key = selectIdValue(entity, selectId);
  1381. if (key in state.entities) {
  1382. return;
  1383. }
  1384. state.ids.push(key);
  1385. state.entities[key] = entity;
  1386. }
  1387. function addManyMutably(newEntities, state) {
  1388. newEntities = ensureEntitiesArray(newEntities);
  1389. for (const entity of newEntities) {
  1390. addOneMutably(entity, state);
  1391. }
  1392. }
  1393. function setOneMutably(entity, state) {
  1394. const key = selectIdValue(entity, selectId);
  1395. if (!(key in state.entities)) {
  1396. state.ids.push(key);
  1397. }
  1398. state.entities[key] = entity;
  1399. }
  1400. function setManyMutably(newEntities, state) {
  1401. newEntities = ensureEntitiesArray(newEntities);
  1402. for (const entity of newEntities) {
  1403. setOneMutably(entity, state);
  1404. }
  1405. }
  1406. function setAllMutably(newEntities, state) {
  1407. newEntities = ensureEntitiesArray(newEntities);
  1408. state.ids = [];
  1409. state.entities = {};
  1410. addManyMutably(newEntities, state);
  1411. }
  1412. function removeOneMutably(key, state) {
  1413. return removeManyMutably([key], state);
  1414. }
  1415. function removeManyMutably(keys, state) {
  1416. let didMutate = false;
  1417. keys.forEach((key) => {
  1418. if (key in state.entities) {
  1419. delete state.entities[key];
  1420. didMutate = true;
  1421. }
  1422. });
  1423. if (didMutate) {
  1424. state.ids = state.ids.filter((id) => id in state.entities);
  1425. }
  1426. }
  1427. function removeAllMutably(state) {
  1428. Object.assign(state, {
  1429. ids: [],
  1430. entities: {}
  1431. });
  1432. }
  1433. function takeNewKey(keys, update, state) {
  1434. const original3 = state.entities[update.id];
  1435. if (original3 === void 0) {
  1436. return false;
  1437. }
  1438. const updated = Object.assign({}, original3, update.changes);
  1439. const newKey = selectIdValue(updated, selectId);
  1440. const hasNewKey = newKey !== update.id;
  1441. if (hasNewKey) {
  1442. keys[update.id] = newKey;
  1443. delete state.entities[update.id];
  1444. }
  1445. state.entities[newKey] = updated;
  1446. return hasNewKey;
  1447. }
  1448. function updateOneMutably(update, state) {
  1449. return updateManyMutably([update], state);
  1450. }
  1451. function updateManyMutably(updates, state) {
  1452. const newKeys = {};
  1453. const updatesPerEntity = {};
  1454. updates.forEach((update) => {
  1455. if (update.id in state.entities) {
  1456. updatesPerEntity[update.id] = {
  1457. id: update.id,
  1458. // Spreads ignore falsy values, so this works even if there isn't
  1459. // an existing update already at this key
  1460. changes: {
  1461. ...updatesPerEntity[update.id] ? updatesPerEntity[update.id].changes : null,
  1462. ...update.changes
  1463. }
  1464. };
  1465. }
  1466. });
  1467. updates = Object.values(updatesPerEntity);
  1468. const didMutateEntities = updates.length > 0;
  1469. if (didMutateEntities) {
  1470. const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0;
  1471. if (didMutateIds) {
  1472. state.ids = Object.values(state.entities).map((e) => selectIdValue(e, selectId));
  1473. }
  1474. }
  1475. }
  1476. function upsertOneMutably(entity, state) {
  1477. return upsertManyMutably([entity], state);
  1478. }
  1479. function upsertManyMutably(newEntities, state) {
  1480. const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
  1481. updateManyMutably(updated, state);
  1482. addManyMutably(added, state);
  1483. }
  1484. return {
  1485. removeAll: createSingleArgumentStateOperator(removeAllMutably),
  1486. addOne: createStateOperator(addOneMutably),
  1487. addMany: createStateOperator(addManyMutably),
  1488. setOne: createStateOperator(setOneMutably),
  1489. setMany: createStateOperator(setManyMutably),
  1490. setAll: createStateOperator(setAllMutably),
  1491. updateOne: createStateOperator(updateOneMutably),
  1492. updateMany: createStateOperator(updateManyMutably),
  1493. upsertOne: createStateOperator(upsertOneMutably),
  1494. upsertMany: createStateOperator(upsertManyMutably),
  1495. removeOne: createStateOperator(removeOneMutably),
  1496. removeMany: createStateOperator(removeManyMutably)
  1497. };
  1498. }
  1499. // src/entities/sorted_state_adapter.ts
  1500. function createSortedStateAdapter(selectId, sort) {
  1501. const {
  1502. removeOne,
  1503. removeMany,
  1504. removeAll
  1505. } = createUnsortedStateAdapter(selectId);
  1506. function addOneMutably(entity, state) {
  1507. return addManyMutably([entity], state);
  1508. }
  1509. function addManyMutably(newEntities, state) {
  1510. newEntities = ensureEntitiesArray(newEntities);
  1511. const models = newEntities.filter((model) => !(selectIdValue(model, selectId) in state.entities));
  1512. if (models.length !== 0) {
  1513. merge(models, state);
  1514. }
  1515. }
  1516. function setOneMutably(entity, state) {
  1517. return setManyMutably([entity], state);
  1518. }
  1519. function setManyMutably(newEntities, state) {
  1520. newEntities = ensureEntitiesArray(newEntities);
  1521. if (newEntities.length !== 0) {
  1522. merge(newEntities, state);
  1523. }
  1524. }
  1525. function setAllMutably(newEntities, state) {
  1526. newEntities = ensureEntitiesArray(newEntities);
  1527. state.entities = {};
  1528. state.ids = [];
  1529. addManyMutably(newEntities, state);
  1530. }
  1531. function updateOneMutably(update, state) {
  1532. return updateManyMutably([update], state);
  1533. }
  1534. function updateManyMutably(updates, state) {
  1535. let appliedUpdates = false;
  1536. for (let update of updates) {
  1537. const entity = state.entities[update.id];
  1538. if (!entity) {
  1539. continue;
  1540. }
  1541. appliedUpdates = true;
  1542. Object.assign(entity, update.changes);
  1543. const newId = selectId(entity);
  1544. if (update.id !== newId) {
  1545. delete state.entities[update.id];
  1546. state.entities[newId] = entity;
  1547. }
  1548. }
  1549. if (appliedUpdates) {
  1550. resortEntities(state);
  1551. }
  1552. }
  1553. function upsertOneMutably(entity, state) {
  1554. return upsertManyMutably([entity], state);
  1555. }
  1556. function upsertManyMutably(newEntities, state) {
  1557. const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
  1558. updateManyMutably(updated, state);
  1559. addManyMutably(added, state);
  1560. }
  1561. function areArraysEqual(a, b) {
  1562. if (a.length !== b.length) {
  1563. return false;
  1564. }
  1565. for (let i = 0; i < a.length && i < b.length; i++) {
  1566. if (a[i] === b[i]) {
  1567. continue;
  1568. }
  1569. return false;
  1570. }
  1571. return true;
  1572. }
  1573. function merge(models, state) {
  1574. models.forEach((model) => {
  1575. state.entities[selectId(model)] = model;
  1576. });
  1577. resortEntities(state);
  1578. }
  1579. function resortEntities(state) {
  1580. const allEntities = Object.values(state.entities);
  1581. allEntities.sort(sort);
  1582. const newSortedIds = allEntities.map(selectId);
  1583. const {
  1584. ids
  1585. } = state;
  1586. if (!areArraysEqual(ids, newSortedIds)) {
  1587. state.ids = newSortedIds;
  1588. }
  1589. }
  1590. return {
  1591. removeOne,
  1592. removeMany,
  1593. removeAll,
  1594. addOne: createStateOperator(addOneMutably),
  1595. updateOne: createStateOperator(updateOneMutably),
  1596. upsertOne: createStateOperator(upsertOneMutably),
  1597. setOne: createStateOperator(setOneMutably),
  1598. setMany: createStateOperator(setManyMutably),
  1599. setAll: createStateOperator(setAllMutably),
  1600. addMany: createStateOperator(addManyMutably),
  1601. updateMany: createStateOperator(updateManyMutably),
  1602. upsertMany: createStateOperator(upsertManyMutably)
  1603. };
  1604. }
  1605. // src/entities/create_adapter.ts
  1606. function createEntityAdapter(options = {}) {
  1607. const {
  1608. selectId,
  1609. sortComparer
  1610. } = {
  1611. sortComparer: false,
  1612. selectId: (instance) => instance.id,
  1613. ...options
  1614. };
  1615. const stateFactory = createInitialStateFactory();
  1616. const selectorsFactory = createSelectorsFactory();
  1617. const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
  1618. return {
  1619. selectId,
  1620. sortComparer,
  1621. ...stateFactory,
  1622. ...selectorsFactory,
  1623. ...stateAdapter
  1624. };
  1625. }
  1626. // src/listenerMiddleware/index.ts
  1627. import { isAction as isAction3 } from "redux";
  1628. // src/listenerMiddleware/utils.ts
  1629. var assertFunction = (func, expected) => {
  1630. if (typeof func !== "function") {
  1631. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(32) : `${expected} is not a function`);
  1632. }
  1633. };
  1634. var noop2 = () => {
  1635. };
  1636. var catchRejection = (promise, onError = noop2) => {
  1637. promise.catch(onError);
  1638. return promise;
  1639. };
  1640. var addAbortSignalListener = (abortSignal, callback) => {
  1641. abortSignal.addEventListener("abort", callback, {
  1642. once: true
  1643. });
  1644. return () => abortSignal.removeEventListener("abort", callback);
  1645. };
  1646. var abortControllerWithReason = (abortController, reason) => {
  1647. const signal = abortController.signal;
  1648. if (signal.aborted) {
  1649. return;
  1650. }
  1651. if (!("reason" in signal)) {
  1652. Object.defineProperty(signal, "reason", {
  1653. enumerable: true,
  1654. value: reason,
  1655. configurable: true,
  1656. writable: true
  1657. });
  1658. }
  1659. ;
  1660. abortController.abort(reason);
  1661. };
  1662. // src/listenerMiddleware/exceptions.ts
  1663. var task = "task";
  1664. var listener = "listener";
  1665. var completed = "completed";
  1666. var cancelled = "cancelled";
  1667. var taskCancelled = `task-${cancelled}`;
  1668. var taskCompleted = `task-${completed}`;
  1669. var listenerCancelled = `${listener}-${cancelled}`;
  1670. var listenerCompleted = `${listener}-${completed}`;
  1671. var TaskAbortError = class {
  1672. constructor(code) {
  1673. this.code = code;
  1674. this.message = `${task} ${cancelled} (reason: ${code})`;
  1675. }
  1676. name = "TaskAbortError";
  1677. message;
  1678. };
  1679. // src/listenerMiddleware/task.ts
  1680. var validateActive = (signal) => {
  1681. if (signal.aborted) {
  1682. const {
  1683. reason
  1684. } = signal;
  1685. throw new TaskAbortError(reason);
  1686. }
  1687. };
  1688. function raceWithSignal(signal, promise) {
  1689. let cleanup = noop2;
  1690. return new Promise((resolve, reject) => {
  1691. const notifyRejection = () => reject(new TaskAbortError(signal.reason));
  1692. if (signal.aborted) {
  1693. notifyRejection();
  1694. return;
  1695. }
  1696. cleanup = addAbortSignalListener(signal, notifyRejection);
  1697. promise.finally(() => cleanup()).then(resolve, reject);
  1698. }).finally(() => {
  1699. cleanup = noop2;
  1700. });
  1701. }
  1702. var runTask = async (task2, cleanUp) => {
  1703. try {
  1704. await Promise.resolve();
  1705. const value = await task2();
  1706. return {
  1707. status: "ok",
  1708. value
  1709. };
  1710. } catch (error) {
  1711. return {
  1712. status: error instanceof TaskAbortError ? "cancelled" : "rejected",
  1713. error
  1714. };
  1715. } finally {
  1716. cleanUp?.();
  1717. }
  1718. };
  1719. var createPause = (signal) => {
  1720. return (promise) => {
  1721. return catchRejection(raceWithSignal(signal, promise).then((output) => {
  1722. validateActive(signal);
  1723. return output;
  1724. }));
  1725. };
  1726. };
  1727. var createDelay = (signal) => {
  1728. const pause = createPause(signal);
  1729. return (timeoutMs) => {
  1730. return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)));
  1731. };
  1732. };
  1733. // src/listenerMiddleware/index.ts
  1734. var {
  1735. assign
  1736. } = Object;
  1737. var INTERNAL_NIL_TOKEN = {};
  1738. var alm = "listenerMiddleware";
  1739. var createFork = (parentAbortSignal, parentBlockingPromises) => {
  1740. const linkControllers = (controller) => addAbortSignalListener(parentAbortSignal, () => abortControllerWithReason(controller, parentAbortSignal.reason));
  1741. return (taskExecutor, opts) => {
  1742. assertFunction(taskExecutor, "taskExecutor");
  1743. const childAbortController = new AbortController();
  1744. linkControllers(childAbortController);
  1745. const result = runTask(async () => {
  1746. validateActive(parentAbortSignal);
  1747. validateActive(childAbortController.signal);
  1748. const result2 = await taskExecutor({
  1749. pause: createPause(childAbortController.signal),
  1750. delay: createDelay(childAbortController.signal),
  1751. signal: childAbortController.signal
  1752. });
  1753. validateActive(childAbortController.signal);
  1754. return result2;
  1755. }, () => abortControllerWithReason(childAbortController, taskCompleted));
  1756. if (opts?.autoJoin) {
  1757. parentBlockingPromises.push(result);
  1758. }
  1759. return {
  1760. result: createPause(parentAbortSignal)(result),
  1761. cancel() {
  1762. abortControllerWithReason(childAbortController, taskCancelled);
  1763. }
  1764. };
  1765. };
  1766. };
  1767. var createTakePattern = (startListening, signal) => {
  1768. const take = async (predicate, timeout) => {
  1769. validateActive(signal);
  1770. let unsubscribe = () => {
  1771. };
  1772. const tuplePromise = new Promise((resolve, reject) => {
  1773. let stopListening = startListening({
  1774. predicate,
  1775. effect: (action, listenerApi) => {
  1776. listenerApi.unsubscribe();
  1777. resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);
  1778. }
  1779. });
  1780. unsubscribe = () => {
  1781. stopListening();
  1782. reject();
  1783. };
  1784. });
  1785. const promises = [tuplePromise];
  1786. if (timeout != null) {
  1787. promises.push(new Promise((resolve) => setTimeout(resolve, timeout, null)));
  1788. }
  1789. try {
  1790. const output = await raceWithSignal(signal, Promise.race(promises));
  1791. validateActive(signal);
  1792. return output;
  1793. } finally {
  1794. unsubscribe();
  1795. }
  1796. };
  1797. return (predicate, timeout) => catchRejection(take(predicate, timeout));
  1798. };
  1799. var getListenerEntryPropsFrom = (options) => {
  1800. let {
  1801. type,
  1802. actionCreator,
  1803. matcher,
  1804. predicate,
  1805. effect
  1806. } = options;
  1807. if (type) {
  1808. predicate = createAction(type).match;
  1809. } else if (actionCreator) {
  1810. type = actionCreator.type;
  1811. predicate = actionCreator.match;
  1812. } else if (matcher) {
  1813. predicate = matcher;
  1814. } else if (predicate) {
  1815. } else {
  1816. 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");
  1817. }
  1818. assertFunction(effect, "options.listener");
  1819. return {
  1820. predicate,
  1821. type,
  1822. effect
  1823. };
  1824. };
  1825. var createListenerEntry = (options) => {
  1826. const {
  1827. type,
  1828. predicate,
  1829. effect
  1830. } = getListenerEntryPropsFrom(options);
  1831. const id = nanoid();
  1832. const entry = {
  1833. id,
  1834. effect,
  1835. type,
  1836. predicate,
  1837. pending: /* @__PURE__ */ new Set(),
  1838. unsubscribe: () => {
  1839. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(22) : "Unsubscribe not initialized");
  1840. }
  1841. };
  1842. return entry;
  1843. };
  1844. var cancelActiveListeners = (entry) => {
  1845. entry.pending.forEach((controller) => {
  1846. abortControllerWithReason(controller, listenerCancelled);
  1847. });
  1848. };
  1849. var createClearListenerMiddleware = (listenerMap) => {
  1850. return () => {
  1851. listenerMap.forEach(cancelActiveListeners);
  1852. listenerMap.clear();
  1853. };
  1854. };
  1855. var safelyNotifyError = (errorHandler, errorToNotify, errorInfo) => {
  1856. try {
  1857. errorHandler(errorToNotify, errorInfo);
  1858. } catch (errorHandlerError) {
  1859. setTimeout(() => {
  1860. throw errorHandlerError;
  1861. }, 0);
  1862. }
  1863. };
  1864. var addListener = createAction(`${alm}/add`);
  1865. var clearAllListeners = createAction(`${alm}/removeAll`);
  1866. var removeListener = createAction(`${alm}/remove`);
  1867. var defaultErrorHandler = (...args) => {
  1868. console.error(`${alm}/error`, ...args);
  1869. };
  1870. function createListenerMiddleware(middlewareOptions = {}) {
  1871. const listenerMap = /* @__PURE__ */ new Map();
  1872. const {
  1873. extra,
  1874. onError = defaultErrorHandler
  1875. } = middlewareOptions;
  1876. assertFunction(onError, "onError");
  1877. const insertEntry = (entry) => {
  1878. entry.unsubscribe = () => listenerMap.delete(entry.id);
  1879. listenerMap.set(entry.id, entry);
  1880. return (cancelOptions) => {
  1881. entry.unsubscribe();
  1882. if (cancelOptions?.cancelActive) {
  1883. cancelActiveListeners(entry);
  1884. }
  1885. };
  1886. };
  1887. const startListening = (options) => {
  1888. let entry = find(Array.from(listenerMap.values()), (existingEntry) => existingEntry.effect === options.effect);
  1889. if (!entry) {
  1890. entry = createListenerEntry(options);
  1891. }
  1892. return insertEntry(entry);
  1893. };
  1894. const stopListening = (options) => {
  1895. const {
  1896. type,
  1897. effect,
  1898. predicate
  1899. } = getListenerEntryPropsFrom(options);
  1900. const entry = find(Array.from(listenerMap.values()), (entry2) => {
  1901. const matchPredicateOrType = typeof type === "string" ? entry2.type === type : entry2.predicate === predicate;
  1902. return matchPredicateOrType && entry2.effect === effect;
  1903. });
  1904. if (entry) {
  1905. entry.unsubscribe();
  1906. if (options.cancelActive) {
  1907. cancelActiveListeners(entry);
  1908. }
  1909. }
  1910. return !!entry;
  1911. };
  1912. const notifyListener = async (entry, action, api, getOriginalState) => {
  1913. const internalTaskController = new AbortController();
  1914. const take = createTakePattern(startListening, internalTaskController.signal);
  1915. const autoJoinPromises = [];
  1916. try {
  1917. entry.pending.add(internalTaskController);
  1918. await Promise.resolve(entry.effect(
  1919. action,
  1920. // Use assign() rather than ... to avoid extra helper functions added to bundle
  1921. assign({}, api, {
  1922. getOriginalState,
  1923. condition: (predicate, timeout) => take(predicate, timeout).then(Boolean),
  1924. take,
  1925. delay: createDelay(internalTaskController.signal),
  1926. pause: createPause(internalTaskController.signal),
  1927. extra,
  1928. signal: internalTaskController.signal,
  1929. fork: createFork(internalTaskController.signal, autoJoinPromises),
  1930. unsubscribe: entry.unsubscribe,
  1931. subscribe: () => {
  1932. listenerMap.set(entry.id, entry);
  1933. },
  1934. cancelActiveListeners: () => {
  1935. entry.pending.forEach((controller, _, set) => {
  1936. if (controller !== internalTaskController) {
  1937. abortControllerWithReason(controller, listenerCancelled);
  1938. set.delete(controller);
  1939. }
  1940. });
  1941. },
  1942. cancel: () => {
  1943. abortControllerWithReason(internalTaskController, listenerCancelled);
  1944. entry.pending.delete(internalTaskController);
  1945. },
  1946. throwIfCancelled: () => {
  1947. validateActive(internalTaskController.signal);
  1948. }
  1949. })
  1950. ));
  1951. } catch (listenerError) {
  1952. if (!(listenerError instanceof TaskAbortError)) {
  1953. safelyNotifyError(onError, listenerError, {
  1954. raisedBy: "effect"
  1955. });
  1956. }
  1957. } finally {
  1958. await Promise.allSettled(autoJoinPromises);
  1959. abortControllerWithReason(internalTaskController, listenerCompleted);
  1960. entry.pending.delete(internalTaskController);
  1961. }
  1962. };
  1963. const clearListenerMiddleware = createClearListenerMiddleware(listenerMap);
  1964. const middleware = (api) => (next) => (action) => {
  1965. if (!isAction3(action)) {
  1966. return next(action);
  1967. }
  1968. if (addListener.match(action)) {
  1969. return startListening(action.payload);
  1970. }
  1971. if (clearAllListeners.match(action)) {
  1972. clearListenerMiddleware();
  1973. return;
  1974. }
  1975. if (removeListener.match(action)) {
  1976. return stopListening(action.payload);
  1977. }
  1978. let originalState = api.getState();
  1979. const getOriginalState = () => {
  1980. if (originalState === INTERNAL_NIL_TOKEN) {
  1981. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(23) : `${alm}: getOriginalState can only be called synchronously`);
  1982. }
  1983. return originalState;
  1984. };
  1985. let result;
  1986. try {
  1987. result = next(action);
  1988. if (listenerMap.size > 0) {
  1989. let currentState = api.getState();
  1990. const listenerEntries = Array.from(listenerMap.values());
  1991. for (let entry of listenerEntries) {
  1992. let runListener = false;
  1993. try {
  1994. runListener = entry.predicate(action, currentState, originalState);
  1995. } catch (predicateError) {
  1996. runListener = false;
  1997. safelyNotifyError(onError, predicateError, {
  1998. raisedBy: "predicate"
  1999. });
  2000. }
  2001. if (!runListener) {
  2002. continue;
  2003. }
  2004. notifyListener(entry, action, api, getOriginalState);
  2005. }
  2006. }
  2007. } finally {
  2008. originalState = INTERNAL_NIL_TOKEN;
  2009. }
  2010. return result;
  2011. };
  2012. return {
  2013. middleware,
  2014. startListening,
  2015. stopListening,
  2016. clearListeners: clearListenerMiddleware
  2017. };
  2018. }
  2019. // src/dynamicMiddleware/index.ts
  2020. import { compose as compose3 } from "redux";
  2021. var createMiddlewareEntry = (middleware) => ({
  2022. id: nanoid(),
  2023. middleware,
  2024. applied: /* @__PURE__ */ new Map()
  2025. });
  2026. var matchInstance = (instanceId) => (action) => action?.meta?.instanceId === instanceId;
  2027. var createDynamicMiddleware = () => {
  2028. const instanceId = nanoid();
  2029. const middlewareMap = /* @__PURE__ */ new Map();
  2030. const withMiddleware = Object.assign(createAction("dynamicMiddleware/add", (...middlewares) => ({
  2031. payload: middlewares,
  2032. meta: {
  2033. instanceId
  2034. }
  2035. })), {
  2036. withTypes: () => withMiddleware
  2037. });
  2038. const addMiddleware = Object.assign(function addMiddleware2(...middlewares) {
  2039. middlewares.forEach((middleware2) => {
  2040. let entry = find(Array.from(middlewareMap.values()), (entry2) => entry2.middleware === middleware2);
  2041. if (!entry) {
  2042. entry = createMiddlewareEntry(middleware2);
  2043. }
  2044. middlewareMap.set(entry.id, entry);
  2045. });
  2046. }, {
  2047. withTypes: () => addMiddleware
  2048. });
  2049. const getFinalMiddleware = (api) => {
  2050. const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) => emplace(entry.applied, api, {
  2051. insert: () => entry.middleware(api)
  2052. }));
  2053. return compose3(...appliedMiddleware);
  2054. };
  2055. const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));
  2056. const middleware = (api) => (next) => (action) => {
  2057. if (isWithMiddleware(action)) {
  2058. addMiddleware(...action.payload);
  2059. return api.dispatch;
  2060. }
  2061. return getFinalMiddleware(api)(next)(action);
  2062. };
  2063. return {
  2064. middleware,
  2065. addMiddleware,
  2066. withMiddleware,
  2067. instanceId
  2068. };
  2069. };
  2070. // src/combineSlices.ts
  2071. import { combineReducers as combineReducers2 } from "redux";
  2072. var isSliceLike = (maybeSliceLike) => "reducerPath" in maybeSliceLike && typeof maybeSliceLike.reducerPath === "string";
  2073. var getReducers = (slices) => slices.flatMap((sliceOrMap) => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));
  2074. var ORIGINAL_STATE = Symbol.for("rtk-state-proxy-original");
  2075. var isStateProxy = (value) => !!value && !!value[ORIGINAL_STATE];
  2076. var stateProxyMap = /* @__PURE__ */ new WeakMap();
  2077. var createStateProxy = (state, reducerMap) => emplace(stateProxyMap, state, {
  2078. insert: () => new Proxy(state, {
  2079. get: (target, prop, receiver) => {
  2080. if (prop === ORIGINAL_STATE)
  2081. return target;
  2082. const result = Reflect.get(target, prop, receiver);
  2083. if (typeof result === "undefined") {
  2084. const reducer = reducerMap[prop.toString()];
  2085. if (reducer) {
  2086. const reducerResult = reducer(void 0, {
  2087. type: nanoid()
  2088. });
  2089. if (typeof reducerResult === "undefined") {
  2090. 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.`);
  2091. }
  2092. return reducerResult;
  2093. }
  2094. }
  2095. return result;
  2096. }
  2097. })
  2098. });
  2099. var original = (state) => {
  2100. if (!isStateProxy(state)) {
  2101. throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(25) : "original must be used on state Proxy");
  2102. }
  2103. return state[ORIGINAL_STATE];
  2104. };
  2105. function combineSlices(...slices) {
  2106. const reducerMap = Object.fromEntries(getReducers(slices));
  2107. const getReducer = () => combineReducers2(reducerMap);
  2108. let reducer = getReducer();
  2109. function combinedReducer(state, action) {
  2110. return reducer(state, action);
  2111. }
  2112. combinedReducer.withLazyLoadedSlices = () => combinedReducer;
  2113. const inject = (slice, config = {}) => {
  2114. const {
  2115. reducerPath,
  2116. reducer: reducerToInject
  2117. } = slice;
  2118. const currentReducer = reducerMap[reducerPath];
  2119. if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {
  2120. if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
  2121. console.error(`called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``);
  2122. }
  2123. return combinedReducer;
  2124. }
  2125. reducerMap[reducerPath] = reducerToInject;
  2126. reducer = getReducer();
  2127. return combinedReducer;
  2128. };
  2129. const selector = Object.assign(function makeSelector(selectorFn, selectState) {
  2130. return function selector2(state, ...args) {
  2131. return selectorFn(createStateProxy(selectState ? selectState(state, ...args) : state, reducerMap), ...args);
  2132. };
  2133. }, {
  2134. original
  2135. });
  2136. return Object.assign(combinedReducer, {
  2137. inject,
  2138. selector
  2139. });
  2140. }
  2141. // src/formatProdErrorMessage.ts
  2142. function formatProdErrorMessage(code) {
  2143. 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. `;
  2144. }
  2145. export {
  2146. ReducerType,
  2147. SHOULD_AUTOBATCH,
  2148. TaskAbortError,
  2149. Tuple,
  2150. addListener,
  2151. asyncThunkCreator,
  2152. autoBatchEnhancer,
  2153. buildCreateSlice,
  2154. clearAllListeners,
  2155. combineSlices,
  2156. configureStore,
  2157. createAction,
  2158. createActionCreatorInvariantMiddleware,
  2159. createAsyncThunk,
  2160. createDraftSafeSelector,
  2161. createDraftSafeSelectorCreator,
  2162. createDynamicMiddleware,
  2163. createEntityAdapter,
  2164. createImmutableStateInvariantMiddleware,
  2165. createListenerMiddleware,
  2166. produce as createNextState,
  2167. createReducer,
  2168. createSelector,
  2169. createSelectorCreator2 as createSelectorCreator,
  2170. createSerializableStateInvariantMiddleware,
  2171. createSlice,
  2172. current2 as current,
  2173. findNonSerializableValue,
  2174. formatProdErrorMessage,
  2175. freeze,
  2176. isActionCreator,
  2177. isAllOf,
  2178. isAnyOf,
  2179. isAsyncThunkAction,
  2180. isDraft4 as isDraft,
  2181. isFSA as isFluxStandardAction,
  2182. isFulfilled,
  2183. isImmutableDefault,
  2184. isPending,
  2185. isPlain,
  2186. isRejected,
  2187. isRejectedWithValue,
  2188. lruMemoize,
  2189. miniSerializeError,
  2190. nanoid,
  2191. original2 as original,
  2192. prepareAutoBatched,
  2193. removeListener,
  2194. unwrapResult,
  2195. weakMapMemoize2 as weakMapMemoize
  2196. };
  2197. //# sourceMappingURL=redux-toolkit.legacy-esm.js.map