UNPKG

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