Debian Codegraph @

install/freeipa-webui/node_modules/@reduxjs/toolkit/dist/cjs/redux-toolkit.development.cjs

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