Debian Codegraph @

install/freeipa-webui/node_modules/@reduxjs/toolkit/dist/redux-toolkit.legacy-esm.js

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