@me1a/ui 1.2.9 → 1.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,3719 @@
1
+ // src/utils/formatProdErrorMessage.ts
2
+ function formatProdErrorMessage$1(code) {
3
+ return `Minified Redux error #${code}; visit https://redux.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
4
+ }
1
5
 
6
+ // src/utils/symbol-observable.ts
7
+ var $$observable = /* @__PURE__ */ (() => typeof Symbol === "function" && Symbol.observable || "@@observable")();
8
+ var symbol_observable_default = $$observable;
9
+
10
+ // src/utils/actionTypes.ts
11
+ var randomString = () => Math.random().toString(36).substring(7).split("").join(".");
12
+ var ActionTypes = {
13
+ INIT: `@@redux/INIT${/* @__PURE__ */ randomString()}`,
14
+ REPLACE: `@@redux/REPLACE${/* @__PURE__ */ randomString()}`,
15
+ PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`
16
+ };
17
+ var actionTypes_default = ActionTypes;
18
+
19
+ // src/utils/isPlainObject.ts
20
+ function isPlainObject$1(obj) {
21
+ if (typeof obj !== "object" || obj === null)
22
+ return false;
23
+ let proto = obj;
24
+ while (Object.getPrototypeOf(proto) !== null) {
25
+ proto = Object.getPrototypeOf(proto);
26
+ }
27
+ return Object.getPrototypeOf(obj) === proto || Object.getPrototypeOf(obj) === null;
28
+ }
29
+
30
+ // src/utils/kindOf.ts
31
+ function miniKindOf(val) {
32
+ if (val === void 0)
33
+ return "undefined";
34
+ if (val === null)
35
+ return "null";
36
+ const type = typeof val;
37
+ switch (type) {
38
+ case "boolean":
39
+ case "string":
40
+ case "number":
41
+ case "symbol":
42
+ case "function": {
43
+ return type;
44
+ }
45
+ }
46
+ if (Array.isArray(val))
47
+ return "array";
48
+ if (isDate(val))
49
+ return "date";
50
+ if (isError(val))
51
+ return "error";
52
+ const constructorName = ctorName(val);
53
+ switch (constructorName) {
54
+ case "Symbol":
55
+ case "Promise":
56
+ case "WeakMap":
57
+ case "WeakSet":
58
+ case "Map":
59
+ case "Set":
60
+ return constructorName;
61
+ }
62
+ return Object.prototype.toString.call(val).slice(8, -1).toLowerCase().replace(/\s/g, "");
63
+ }
64
+ function ctorName(val) {
65
+ return typeof val.constructor === "function" ? val.constructor.name : null;
66
+ }
67
+ function isError(val) {
68
+ return val instanceof Error || typeof val.message === "string" && val.constructor && typeof val.constructor.stackTraceLimit === "number";
69
+ }
70
+ function isDate(val) {
71
+ if (val instanceof Date)
72
+ return true;
73
+ return typeof val.toDateString === "function" && typeof val.getDate === "function" && typeof val.setDate === "function";
74
+ }
75
+ function kindOf(val) {
76
+ let typeOfVal = typeof val;
77
+ if (process.env.NODE_ENV !== "production") {
78
+ typeOfVal = miniKindOf(val);
79
+ }
80
+ return typeOfVal;
81
+ }
82
+
83
+ // src/createStore.ts
84
+ function createStore(reducer, preloadedState, enhancer) {
85
+ if (typeof reducer !== "function") {
86
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(2) : `Expected the root reducer to be a function. Instead, received: '${kindOf(reducer)}'`);
87
+ }
88
+ if (typeof preloadedState === "function" && typeof enhancer === "function" || typeof enhancer === "function" && typeof arguments[3] === "function") {
89
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(0) : "It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.");
90
+ }
91
+ if (typeof preloadedState === "function" && typeof enhancer === "undefined") {
92
+ enhancer = preloadedState;
93
+ preloadedState = void 0;
94
+ }
95
+ if (typeof enhancer !== "undefined") {
96
+ if (typeof enhancer !== "function") {
97
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(1) : `Expected the enhancer to be a function. Instead, received: '${kindOf(enhancer)}'`);
98
+ }
99
+ return enhancer(createStore)(reducer, preloadedState);
100
+ }
101
+ let currentReducer = reducer;
102
+ let currentState = preloadedState;
103
+ let currentListeners = /* @__PURE__ */ new Map();
104
+ let nextListeners = currentListeners;
105
+ let listenerIdCounter = 0;
106
+ let isDispatching = false;
107
+ function ensureCanMutateNextListeners() {
108
+ if (nextListeners === currentListeners) {
109
+ nextListeners = /* @__PURE__ */ new Map();
110
+ currentListeners.forEach((listener, key) => {
111
+ nextListeners.set(key, listener);
112
+ });
113
+ }
114
+ }
115
+ function getState() {
116
+ if (isDispatching) {
117
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(3) : "You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");
118
+ }
119
+ return currentState;
120
+ }
121
+ function subscribe(listener) {
122
+ if (typeof listener !== "function") {
123
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(4) : `Expected the listener to be a function. Instead, received: '${kindOf(listener)}'`);
124
+ }
125
+ if (isDispatching) {
126
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(5) : "You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.");
127
+ }
128
+ let isSubscribed = true;
129
+ ensureCanMutateNextListeners();
130
+ const listenerId = listenerIdCounter++;
131
+ nextListeners.set(listenerId, listener);
132
+ return function unsubscribe() {
133
+ if (!isSubscribed) {
134
+ return;
135
+ }
136
+ if (isDispatching) {
137
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(6) : "You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.");
138
+ }
139
+ isSubscribed = false;
140
+ ensureCanMutateNextListeners();
141
+ nextListeners.delete(listenerId);
142
+ currentListeners = null;
143
+ };
144
+ }
145
+ function dispatch(action) {
146
+ if (!isPlainObject$1(action)) {
147
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(7) : `Actions must be plain objects. Instead, the actual type was: '${kindOf(action)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`);
148
+ }
149
+ if (typeof action.type === "undefined") {
150
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(8) : 'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');
151
+ }
152
+ if (typeof action.type !== "string") {
153
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(17) : `Action "type" property must be a string. Instead, the actual type was: '${kindOf(action.type)}'. Value was: '${action.type}' (stringified)`);
154
+ }
155
+ if (isDispatching) {
156
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(9) : "Reducers may not dispatch actions.");
157
+ }
158
+ try {
159
+ isDispatching = true;
160
+ currentState = currentReducer(currentState, action);
161
+ } finally {
162
+ isDispatching = false;
163
+ }
164
+ const listeners = currentListeners = nextListeners;
165
+ listeners.forEach((listener) => {
166
+ listener();
167
+ });
168
+ return action;
169
+ }
170
+ function replaceReducer(nextReducer) {
171
+ if (typeof nextReducer !== "function") {
172
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(10) : `Expected the nextReducer to be a function. Instead, received: '${kindOf(nextReducer)}`);
173
+ }
174
+ currentReducer = nextReducer;
175
+ dispatch({
176
+ type: actionTypes_default.REPLACE
177
+ });
178
+ }
179
+ function observable() {
180
+ const outerSubscribe = subscribe;
181
+ return {
182
+ /**
183
+ * The minimal observable subscription method.
184
+ * @param observer Any object that can be used as an observer.
185
+ * The observer object should have a `next` method.
186
+ * @returns An object with an `unsubscribe` method that can
187
+ * be used to unsubscribe the observable from the store, and prevent further
188
+ * emission of values from the observable.
189
+ */
190
+ subscribe(observer) {
191
+ if (typeof observer !== "object" || observer === null) {
192
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(11) : `Expected the observer to be an object. Instead, received: '${kindOf(observer)}'`);
193
+ }
194
+ function observeState() {
195
+ const observerAsObserver = observer;
196
+ if (observerAsObserver.next) {
197
+ observerAsObserver.next(getState());
198
+ }
199
+ }
200
+ observeState();
201
+ const unsubscribe = outerSubscribe(observeState);
202
+ return {
203
+ unsubscribe
204
+ };
205
+ },
206
+ [symbol_observable_default]() {
207
+ return this;
208
+ }
209
+ };
210
+ }
211
+ dispatch({
212
+ type: actionTypes_default.INIT
213
+ });
214
+ const store = {
215
+ dispatch,
216
+ subscribe,
217
+ getState,
218
+ replaceReducer,
219
+ [symbol_observable_default]: observable
220
+ };
221
+ return store;
222
+ }
223
+ function legacy_createStore(reducer, preloadedState, enhancer) {
224
+ return createStore(reducer, preloadedState, enhancer);
225
+ }
226
+
227
+ // src/utils/warning.ts
228
+ function warning(message) {
229
+ if (typeof console !== "undefined" && typeof console.error === "function") {
230
+ console.error(message);
231
+ }
232
+ try {
233
+ throw new Error(message);
234
+ } catch (e) {
235
+ }
236
+ }
237
+
238
+ // src/combineReducers.ts
239
+ function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
240
+ const reducerKeys = Object.keys(reducers);
241
+ const argumentName = action && action.type === actionTypes_default.INIT ? "preloadedState argument passed to createStore" : "previous state received by the reducer";
242
+ if (reducerKeys.length === 0) {
243
+ return "Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";
244
+ }
245
+ if (!isPlainObject$1(inputState)) {
246
+ return `The ${argumentName} has unexpected type of "${kindOf(inputState)}". Expected argument to be an object with the following keys: "${reducerKeys.join('", "')}"`;
247
+ }
248
+ const unexpectedKeys = Object.keys(inputState).filter((key) => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]);
249
+ unexpectedKeys.forEach((key) => {
250
+ unexpectedKeyCache[key] = true;
251
+ });
252
+ if (action && action.type === actionTypes_default.REPLACE)
253
+ return;
254
+ if (unexpectedKeys.length > 0) {
255
+ return `Unexpected ${unexpectedKeys.length > 1 ? "keys" : "key"} "${unexpectedKeys.join('", "')}" found in ${argumentName}. Expected to find one of the known reducer keys instead: "${reducerKeys.join('", "')}". Unexpected keys will be ignored.`;
256
+ }
257
+ }
258
+ function assertReducerShape(reducers) {
259
+ Object.keys(reducers).forEach((key) => {
260
+ const reducer = reducers[key];
261
+ const initialState = reducer(void 0, {
262
+ type: actionTypes_default.INIT
263
+ });
264
+ if (typeof initialState === "undefined") {
265
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(12) : `The slice reducer for key "${key}" returned undefined during initialization. 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.`);
266
+ }
267
+ if (typeof reducer(void 0, {
268
+ type: actionTypes_default.PROBE_UNKNOWN_ACTION()
269
+ }) === "undefined") {
270
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(13) : `The slice reducer for key "${key}" returned undefined when probed with a random type. Don't try to handle '${actionTypes_default.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`);
271
+ }
272
+ });
273
+ }
274
+ function combineReducers(reducers) {
275
+ const reducerKeys = Object.keys(reducers);
276
+ const finalReducers = {};
277
+ for (let i = 0; i < reducerKeys.length; i++) {
278
+ const key = reducerKeys[i];
279
+ if (process.env.NODE_ENV !== "production") {
280
+ if (typeof reducers[key] === "undefined") {
281
+ warning(`No reducer provided for key "${key}"`);
282
+ }
283
+ }
284
+ if (typeof reducers[key] === "function") {
285
+ finalReducers[key] = reducers[key];
286
+ }
287
+ }
288
+ const finalReducerKeys = Object.keys(finalReducers);
289
+ let unexpectedKeyCache;
290
+ if (process.env.NODE_ENV !== "production") {
291
+ unexpectedKeyCache = {};
292
+ }
293
+ let shapeAssertionError;
294
+ try {
295
+ assertReducerShape(finalReducers);
296
+ } catch (e) {
297
+ shapeAssertionError = e;
298
+ }
299
+ return function combination(state = {}, action) {
300
+ if (shapeAssertionError) {
301
+ throw shapeAssertionError;
302
+ }
303
+ if (process.env.NODE_ENV !== "production") {
304
+ const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
305
+ if (warningMessage) {
306
+ warning(warningMessage);
307
+ }
308
+ }
309
+ let hasChanged = false;
310
+ const nextState = {};
311
+ for (let i = 0; i < finalReducerKeys.length; i++) {
312
+ const key = finalReducerKeys[i];
313
+ const reducer = finalReducers[key];
314
+ const previousStateForKey = state[key];
315
+ const nextStateForKey = reducer(previousStateForKey, action);
316
+ if (typeof nextStateForKey === "undefined") {
317
+ const actionType = action && action.type;
318
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(14) : `When called with an action of type ${actionType ? `"${String(actionType)}"` : "(unknown type)"}, the slice reducer for key "${key}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`);
319
+ }
320
+ nextState[key] = nextStateForKey;
321
+ hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
322
+ }
323
+ hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
324
+ return hasChanged ? nextState : state;
325
+ };
326
+ }
327
+
328
+ // src/bindActionCreators.ts
329
+ function bindActionCreator(actionCreator, dispatch) {
330
+ return function(...args) {
331
+ return dispatch(actionCreator.apply(this, args));
332
+ };
333
+ }
334
+ function bindActionCreators(actionCreators, dispatch) {
335
+ if (typeof actionCreators === "function") {
336
+ return bindActionCreator(actionCreators, dispatch);
337
+ }
338
+ if (typeof actionCreators !== "object" || actionCreators === null) {
339
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(16) : `bindActionCreators expected an object or a function, but instead received: '${kindOf(actionCreators)}'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`);
340
+ }
341
+ const boundActionCreators = {};
342
+ for (const key in actionCreators) {
343
+ const actionCreator = actionCreators[key];
344
+ if (typeof actionCreator === "function") {
345
+ boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
346
+ }
347
+ }
348
+ return boundActionCreators;
349
+ }
350
+
351
+ // src/compose.ts
352
+ function compose(...funcs) {
353
+ if (funcs.length === 0) {
354
+ return (arg) => arg;
355
+ }
356
+ if (funcs.length === 1) {
357
+ return funcs[0];
358
+ }
359
+ return funcs.reduce((a, b) => (...args) => a(b(...args)));
360
+ }
361
+
362
+ // src/applyMiddleware.ts
363
+ function applyMiddleware(...middlewares) {
364
+ return (createStore2) => (reducer, preloadedState) => {
365
+ const store = createStore2(reducer, preloadedState);
366
+ let dispatch = () => {
367
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage$1(15) : "Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.");
368
+ };
369
+ const middlewareAPI = {
370
+ getState: store.getState,
371
+ dispatch: (action, ...args) => dispatch(action, ...args)
372
+ };
373
+ const chain = middlewares.map((middleware) => middleware(middlewareAPI));
374
+ dispatch = compose(...chain)(store.dispatch);
375
+ return {
376
+ ...store,
377
+ dispatch
378
+ };
379
+ };
380
+ }
381
+
382
+ // src/utils/isAction.ts
383
+ function isAction(action) {
384
+ return isPlainObject$1(action) && "type" in action && typeof action.type === "string";
385
+ }
386
+
387
+ // src/utils/env.ts
388
+ var NOTHING = Symbol.for("immer-nothing");
389
+ var DRAFTABLE = Symbol.for("immer-draftable");
390
+ var DRAFT_STATE = Symbol.for("immer-state");
391
+
392
+ // src/utils/errors.ts
393
+ var errors = process.env.NODE_ENV !== "production" ? [
394
+ // All error codes, starting by 0:
395
+ function(plugin) {
396
+ return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`;
397
+ },
398
+ function(thing) {
399
+ return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;
400
+ },
401
+ "This object has been frozen and should not be mutated",
402
+ function(data) {
403
+ return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data;
404
+ },
405
+ "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
406
+ "Immer forbids circular references",
407
+ "The first or second argument to `produce` must be a function",
408
+ "The third argument to `produce` must be a function or undefined",
409
+ "First argument to `createDraft` must be a plain object, an array, or an immerable object",
410
+ "First argument to `finishDraft` must be a draft returned by `createDraft`",
411
+ function(thing) {
412
+ return `'current' expects a draft, got: ${thing}`;
413
+ },
414
+ "Object.defineProperty() cannot be used on an Immer draft",
415
+ "Object.setPrototypeOf() cannot be used on an Immer draft",
416
+ "Immer only supports deleting array indices",
417
+ "Immer only supports setting array indices and the 'length' property",
418
+ function(thing) {
419
+ return `'original' expects a draft, got: ${thing}`;
420
+ }
421
+ // Note: if more errors are added, the errorOffset in Patches.ts should be increased
422
+ // See Patches.ts for additional errors
423
+ ] : [];
424
+ function die(error, ...args) {
425
+ if (process.env.NODE_ENV !== "production") {
426
+ const e = errors[error];
427
+ const msg = typeof e === "function" ? e.apply(null, args) : e;
428
+ throw new Error(`[Immer] ${msg}`);
429
+ }
430
+ throw new Error(
431
+ `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`
432
+ );
433
+ }
434
+
435
+ // src/utils/common.ts
436
+ var getPrototypeOf = Object.getPrototypeOf;
437
+ function isDraft(value) {
438
+ return !!value && !!value[DRAFT_STATE];
439
+ }
440
+ function isDraftable(value) {
441
+ if (!value)
442
+ return false;
443
+ return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap(value) || isSet(value);
444
+ }
445
+ var objectCtorString = Object.prototype.constructor.toString();
446
+ function isPlainObject(value) {
447
+ if (!value || typeof value !== "object")
448
+ return false;
449
+ const proto = getPrototypeOf(value);
450
+ if (proto === null) {
451
+ return true;
452
+ }
453
+ const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
454
+ if (Ctor === Object)
455
+ return true;
456
+ return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString;
457
+ }
458
+ function original$1(value) {
459
+ if (!isDraft(value))
460
+ die(15, value);
461
+ return value[DRAFT_STATE].base_;
462
+ }
463
+ function each(obj, iter) {
464
+ if (getArchtype(obj) === 0 /* Object */) {
465
+ Reflect.ownKeys(obj).forEach((key) => {
466
+ iter(key, obj[key], obj);
467
+ });
468
+ } else {
469
+ obj.forEach((entry, index) => iter(index, entry, obj));
470
+ }
471
+ }
472
+ function getArchtype(thing) {
473
+ const state = thing[DRAFT_STATE];
474
+ return state ? state.type_ : Array.isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;
475
+ }
476
+ function has(thing, prop) {
477
+ return getArchtype(thing) === 2 /* Map */ ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
478
+ }
479
+ function set(thing, propOrOldValue, value) {
480
+ const t = getArchtype(thing);
481
+ if (t === 2 /* Map */)
482
+ thing.set(propOrOldValue, value);
483
+ else if (t === 3 /* Set */) {
484
+ thing.add(value);
485
+ } else
486
+ thing[propOrOldValue] = value;
487
+ }
488
+ function is(x, y) {
489
+ if (x === y) {
490
+ return x !== 0 || 1 / x === 1 / y;
491
+ } else {
492
+ return x !== x && y !== y;
493
+ }
494
+ }
495
+ function isMap(target) {
496
+ return target instanceof Map;
497
+ }
498
+ function isSet(target) {
499
+ return target instanceof Set;
500
+ }
501
+ function latest(state) {
502
+ return state.copy_ || state.base_;
503
+ }
504
+ function shallowCopy(base, strict) {
505
+ if (isMap(base)) {
506
+ return new Map(base);
507
+ }
508
+ if (isSet(base)) {
509
+ return new Set(base);
510
+ }
511
+ if (Array.isArray(base))
512
+ return Array.prototype.slice.call(base);
513
+ const isPlain = isPlainObject(base);
514
+ if (strict === true || strict === "class_only" && !isPlain) {
515
+ const descriptors = Object.getOwnPropertyDescriptors(base);
516
+ delete descriptors[DRAFT_STATE];
517
+ let keys = Reflect.ownKeys(descriptors);
518
+ for (let i = 0; i < keys.length; i++) {
519
+ const key = keys[i];
520
+ const desc = descriptors[key];
521
+ if (desc.writable === false) {
522
+ desc.writable = true;
523
+ desc.configurable = true;
524
+ }
525
+ if (desc.get || desc.set)
526
+ descriptors[key] = {
527
+ configurable: true,
528
+ writable: true,
529
+ // could live with !!desc.set as well here...
530
+ enumerable: desc.enumerable,
531
+ value: base[key]
532
+ };
533
+ }
534
+ return Object.create(getPrototypeOf(base), descriptors);
535
+ } else {
536
+ const proto = getPrototypeOf(base);
537
+ if (proto !== null && isPlain) {
538
+ return { ...base };
539
+ }
540
+ const obj = Object.create(proto);
541
+ return Object.assign(obj, base);
542
+ }
543
+ }
544
+ function freeze(obj, deep = false) {
545
+ if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
546
+ return obj;
547
+ if (getArchtype(obj) > 1) {
548
+ obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;
549
+ }
550
+ Object.freeze(obj);
551
+ if (deep)
552
+ Object.entries(obj).forEach(([key, value]) => freeze(value, true));
553
+ return obj;
554
+ }
555
+ function dontMutateFrozenCollections() {
556
+ die(2);
557
+ }
558
+ function isFrozen(obj) {
559
+ return Object.isFrozen(obj);
560
+ }
561
+
562
+ // src/utils/plugins.ts
563
+ var plugins = {};
564
+ function getPlugin(pluginKey) {
565
+ const plugin = plugins[pluginKey];
566
+ if (!plugin) {
567
+ die(0, pluginKey);
568
+ }
569
+ return plugin;
570
+ }
571
+
572
+ // src/core/scope.ts
573
+ var currentScope;
574
+ function getCurrentScope() {
575
+ return currentScope;
576
+ }
577
+ function createScope(parent_, immer_) {
578
+ return {
579
+ drafts_: [],
580
+ parent_,
581
+ immer_,
582
+ // Whenever the modified draft contains a draft from another scope, we
583
+ // need to prevent auto-freezing so the unowned draft can be finalized.
584
+ canAutoFreeze_: true,
585
+ unfinalizedDrafts_: 0
586
+ };
587
+ }
588
+ function usePatchesInScope(scope, patchListener) {
589
+ if (patchListener) {
590
+ getPlugin("Patches");
591
+ scope.patches_ = [];
592
+ scope.inversePatches_ = [];
593
+ scope.patchListener_ = patchListener;
594
+ }
595
+ }
596
+ function revokeScope(scope) {
597
+ leaveScope(scope);
598
+ scope.drafts_.forEach(revokeDraft);
599
+ scope.drafts_ = null;
600
+ }
601
+ function leaveScope(scope) {
602
+ if (scope === currentScope) {
603
+ currentScope = scope.parent_;
604
+ }
605
+ }
606
+ function enterScope(immer2) {
607
+ return currentScope = createScope(currentScope, immer2);
608
+ }
609
+ function revokeDraft(draft) {
610
+ const state = draft[DRAFT_STATE];
611
+ if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)
612
+ state.revoke_();
613
+ else
614
+ state.revoked_ = true;
615
+ }
616
+
617
+ // src/core/finalize.ts
618
+ function processResult(result, scope) {
619
+ scope.unfinalizedDrafts_ = scope.drafts_.length;
620
+ const baseDraft = scope.drafts_[0];
621
+ const isReplaced = result !== void 0 && result !== baseDraft;
622
+ if (isReplaced) {
623
+ if (baseDraft[DRAFT_STATE].modified_) {
624
+ revokeScope(scope);
625
+ die(4);
626
+ }
627
+ if (isDraftable(result)) {
628
+ result = finalize(scope, result);
629
+ if (!scope.parent_)
630
+ maybeFreeze(scope, result);
631
+ }
632
+ if (scope.patches_) {
633
+ getPlugin("Patches").generateReplacementPatches_(
634
+ baseDraft[DRAFT_STATE].base_,
635
+ result,
636
+ scope.patches_,
637
+ scope.inversePatches_
638
+ );
639
+ }
640
+ } else {
641
+ result = finalize(scope, baseDraft, []);
642
+ }
643
+ revokeScope(scope);
644
+ if (scope.patches_) {
645
+ scope.patchListener_(scope.patches_, scope.inversePatches_);
646
+ }
647
+ return result !== NOTHING ? result : void 0;
648
+ }
649
+ function finalize(rootScope, value, path) {
650
+ if (isFrozen(value))
651
+ return value;
652
+ const state = value[DRAFT_STATE];
653
+ if (!state) {
654
+ each(
655
+ value,
656
+ (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path)
657
+ );
658
+ return value;
659
+ }
660
+ if (state.scope_ !== rootScope)
661
+ return value;
662
+ if (!state.modified_) {
663
+ maybeFreeze(rootScope, state.base_, true);
664
+ return state.base_;
665
+ }
666
+ if (!state.finalized_) {
667
+ state.finalized_ = true;
668
+ state.scope_.unfinalizedDrafts_--;
669
+ const result = state.copy_;
670
+ let resultEach = result;
671
+ let isSet2 = false;
672
+ if (state.type_ === 3 /* Set */) {
673
+ resultEach = new Set(result);
674
+ result.clear();
675
+ isSet2 = true;
676
+ }
677
+ each(
678
+ resultEach,
679
+ (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path, isSet2)
680
+ );
681
+ maybeFreeze(rootScope, result, false);
682
+ if (path && rootScope.patches_) {
683
+ getPlugin("Patches").generatePatches_(
684
+ state,
685
+ path,
686
+ rootScope.patches_,
687
+ rootScope.inversePatches_
688
+ );
689
+ }
690
+ }
691
+ return state.copy_;
692
+ }
693
+ function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {
694
+ if (process.env.NODE_ENV !== "production" && childValue === targetObject)
695
+ die(5);
696
+ if (isDraft(childValue)) {
697
+ const path = rootPath && parentState && parentState.type_ !== 3 /* Set */ && // Set objects are atomic since they have no keys.
698
+ !has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0;
699
+ const res = finalize(rootScope, childValue, path);
700
+ set(targetObject, prop, res);
701
+ if (isDraft(res)) {
702
+ rootScope.canAutoFreeze_ = false;
703
+ } else
704
+ return;
705
+ } else if (targetIsSet) {
706
+ targetObject.add(childValue);
707
+ }
708
+ if (isDraftable(childValue) && !isFrozen(childValue)) {
709
+ if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
710
+ return;
711
+ }
712
+ finalize(rootScope, childValue);
713
+ if ((!parentState || !parentState.scope_.parent_) && typeof prop !== "symbol" && Object.prototype.propertyIsEnumerable.call(targetObject, prop))
714
+ maybeFreeze(rootScope, childValue);
715
+ }
716
+ }
717
+ function maybeFreeze(scope, value, deep = false) {
718
+ if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
719
+ freeze(value, deep);
720
+ }
721
+ }
722
+
723
+ // src/core/proxy.ts
724
+ function createProxyProxy(base, parent) {
725
+ const isArray = Array.isArray(base);
726
+ const state = {
727
+ type_: isArray ? 1 /* Array */ : 0 /* Object */,
728
+ // Track which produce call this is associated with.
729
+ scope_: parent ? parent.scope_ : getCurrentScope(),
730
+ // True for both shallow and deep changes.
731
+ modified_: false,
732
+ // Used during finalization.
733
+ finalized_: false,
734
+ // Track which properties have been assigned (true) or deleted (false).
735
+ assigned_: {},
736
+ // The parent draft state.
737
+ parent_: parent,
738
+ // The base state.
739
+ base_: base,
740
+ // The base proxy.
741
+ draft_: null,
742
+ // set below
743
+ // The base copy with any updated values.
744
+ copy_: null,
745
+ // Called by the `produce` function.
746
+ revoke_: null,
747
+ isManual_: false
748
+ };
749
+ let target = state;
750
+ let traps = objectTraps;
751
+ if (isArray) {
752
+ target = [state];
753
+ traps = arrayTraps;
754
+ }
755
+ const { revoke, proxy } = Proxy.revocable(target, traps);
756
+ state.draft_ = proxy;
757
+ state.revoke_ = revoke;
758
+ return proxy;
759
+ }
760
+ var objectTraps = {
761
+ get(state, prop) {
762
+ if (prop === DRAFT_STATE)
763
+ return state;
764
+ const source = latest(state);
765
+ if (!has(source, prop)) {
766
+ return readPropFromProto(state, source, prop);
767
+ }
768
+ const value = source[prop];
769
+ if (state.finalized_ || !isDraftable(value)) {
770
+ return value;
771
+ }
772
+ if (value === peek(state.base_, prop)) {
773
+ prepareCopy(state);
774
+ return state.copy_[prop] = createProxy(value, state);
775
+ }
776
+ return value;
777
+ },
778
+ has(state, prop) {
779
+ return prop in latest(state);
780
+ },
781
+ ownKeys(state) {
782
+ return Reflect.ownKeys(latest(state));
783
+ },
784
+ set(state, prop, value) {
785
+ const desc = getDescriptorFromProto(latest(state), prop);
786
+ if (desc?.set) {
787
+ desc.set.call(state.draft_, value);
788
+ return true;
789
+ }
790
+ if (!state.modified_) {
791
+ const current2 = peek(latest(state), prop);
792
+ const currentState = current2?.[DRAFT_STATE];
793
+ if (currentState && currentState.base_ === value) {
794
+ state.copy_[prop] = value;
795
+ state.assigned_[prop] = false;
796
+ return true;
797
+ }
798
+ if (is(value, current2) && (value !== void 0 || has(state.base_, prop)))
799
+ return true;
800
+ prepareCopy(state);
801
+ markChanged(state);
802
+ }
803
+ if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'
804
+ (value !== void 0 || prop in state.copy_) || // special case: NaN
805
+ Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
806
+ return true;
807
+ state.copy_[prop] = value;
808
+ state.assigned_[prop] = true;
809
+ return true;
810
+ },
811
+ deleteProperty(state, prop) {
812
+ if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
813
+ state.assigned_[prop] = false;
814
+ prepareCopy(state);
815
+ markChanged(state);
816
+ } else {
817
+ delete state.assigned_[prop];
818
+ }
819
+ if (state.copy_) {
820
+ delete state.copy_[prop];
821
+ }
822
+ return true;
823
+ },
824
+ // Note: We never coerce `desc.value` into an Immer draft, because we can't make
825
+ // the same guarantee in ES5 mode.
826
+ getOwnPropertyDescriptor(state, prop) {
827
+ const owner = latest(state);
828
+ const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
829
+ if (!desc)
830
+ return desc;
831
+ return {
832
+ writable: true,
833
+ configurable: state.type_ !== 1 /* Array */ || prop !== "length",
834
+ enumerable: desc.enumerable,
835
+ value: owner[prop]
836
+ };
837
+ },
838
+ defineProperty() {
839
+ die(11);
840
+ },
841
+ getPrototypeOf(state) {
842
+ return getPrototypeOf(state.base_);
843
+ },
844
+ setPrototypeOf() {
845
+ die(12);
846
+ }
847
+ };
848
+ var arrayTraps = {};
849
+ each(objectTraps, (key, fn) => {
850
+ arrayTraps[key] = function() {
851
+ arguments[0] = arguments[0][0];
852
+ return fn.apply(this, arguments);
853
+ };
854
+ });
855
+ arrayTraps.deleteProperty = function(state, prop) {
856
+ if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop)))
857
+ die(13);
858
+ return arrayTraps.set.call(this, state, prop, void 0);
859
+ };
860
+ arrayTraps.set = function(state, prop, value) {
861
+ if (process.env.NODE_ENV !== "production" && prop !== "length" && isNaN(parseInt(prop)))
862
+ die(14);
863
+ return objectTraps.set.call(this, state[0], prop, value, state[0]);
864
+ };
865
+ function peek(draft, prop) {
866
+ const state = draft[DRAFT_STATE];
867
+ const source = state ? latest(state) : draft;
868
+ return source[prop];
869
+ }
870
+ function readPropFromProto(state, source, prop) {
871
+ const desc = getDescriptorFromProto(source, prop);
872
+ return desc ? `value` in desc ? desc.value : (
873
+ // This is a very special case, if the prop is a getter defined by the
874
+ // prototype, we should invoke it with the draft as context!
875
+ desc.get?.call(state.draft_)
876
+ ) : void 0;
877
+ }
878
+ function getDescriptorFromProto(source, prop) {
879
+ if (!(prop in source))
880
+ return void 0;
881
+ let proto = getPrototypeOf(source);
882
+ while (proto) {
883
+ const desc = Object.getOwnPropertyDescriptor(proto, prop);
884
+ if (desc)
885
+ return desc;
886
+ proto = getPrototypeOf(proto);
887
+ }
888
+ return void 0;
889
+ }
890
+ function markChanged(state) {
891
+ if (!state.modified_) {
892
+ state.modified_ = true;
893
+ if (state.parent_) {
894
+ markChanged(state.parent_);
895
+ }
896
+ }
897
+ }
898
+ function prepareCopy(state) {
899
+ if (!state.copy_) {
900
+ state.copy_ = shallowCopy(
901
+ state.base_,
902
+ state.scope_.immer_.useStrictShallowCopy_
903
+ );
904
+ }
905
+ }
906
+
907
+ // src/core/immerClass.ts
908
+ var Immer2 = class {
909
+ constructor(config) {
910
+ this.autoFreeze_ = true;
911
+ this.useStrictShallowCopy_ = false;
912
+ /**
913
+ * The `produce` function takes a value and a "recipe function" (whose
914
+ * return value often depends on the base state). The recipe function is
915
+ * free to mutate its first argument however it wants. All mutations are
916
+ * only ever applied to a __copy__ of the base state.
917
+ *
918
+ * Pass only a function to create a "curried producer" which relieves you
919
+ * from passing the recipe function every time.
920
+ *
921
+ * Only plain objects and arrays are made mutable. All other objects are
922
+ * considered uncopyable.
923
+ *
924
+ * Note: This function is __bound__ to its `Immer` instance.
925
+ *
926
+ * @param {any} base - the initial state
927
+ * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified
928
+ * @param {Function} patchListener - optional function that will be called with all the patches produced here
929
+ * @returns {any} a new state, or the initial state if nothing was modified
930
+ */
931
+ this.produce = (base, recipe, patchListener) => {
932
+ if (typeof base === "function" && typeof recipe !== "function") {
933
+ const defaultBase = recipe;
934
+ recipe = base;
935
+ const self = this;
936
+ return function curriedProduce(base2 = defaultBase, ...args) {
937
+ return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
938
+ };
939
+ }
940
+ if (typeof recipe !== "function")
941
+ die(6);
942
+ if (patchListener !== void 0 && typeof patchListener !== "function")
943
+ die(7);
944
+ let result;
945
+ if (isDraftable(base)) {
946
+ const scope = enterScope(this);
947
+ const proxy = createProxy(base, void 0);
948
+ let hasError = true;
949
+ try {
950
+ result = recipe(proxy);
951
+ hasError = false;
952
+ } finally {
953
+ if (hasError)
954
+ revokeScope(scope);
955
+ else
956
+ leaveScope(scope);
957
+ }
958
+ usePatchesInScope(scope, patchListener);
959
+ return processResult(result, scope);
960
+ } else if (!base || typeof base !== "object") {
961
+ result = recipe(base);
962
+ if (result === void 0)
963
+ result = base;
964
+ if (result === NOTHING)
965
+ result = void 0;
966
+ if (this.autoFreeze_)
967
+ freeze(result, true);
968
+ if (patchListener) {
969
+ const p = [];
970
+ const ip = [];
971
+ getPlugin("Patches").generateReplacementPatches_(base, result, p, ip);
972
+ patchListener(p, ip);
973
+ }
974
+ return result;
975
+ } else
976
+ die(1, base);
977
+ };
978
+ this.produceWithPatches = (base, recipe) => {
979
+ if (typeof base === "function") {
980
+ return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
981
+ }
982
+ let patches, inversePatches;
983
+ const result = this.produce(base, recipe, (p, ip) => {
984
+ patches = p;
985
+ inversePatches = ip;
986
+ });
987
+ return [result, patches, inversePatches];
988
+ };
989
+ if (typeof config?.autoFreeze === "boolean")
990
+ this.setAutoFreeze(config.autoFreeze);
991
+ if (typeof config?.useStrictShallowCopy === "boolean")
992
+ this.setUseStrictShallowCopy(config.useStrictShallowCopy);
993
+ }
994
+ createDraft(base) {
995
+ if (!isDraftable(base))
996
+ die(8);
997
+ if (isDraft(base))
998
+ base = current(base);
999
+ const scope = enterScope(this);
1000
+ const proxy = createProxy(base, void 0);
1001
+ proxy[DRAFT_STATE].isManual_ = true;
1002
+ leaveScope(scope);
1003
+ return proxy;
1004
+ }
1005
+ finishDraft(draft, patchListener) {
1006
+ const state = draft && draft[DRAFT_STATE];
1007
+ if (!state || !state.isManual_)
1008
+ die(9);
1009
+ const { scope_: scope } = state;
1010
+ usePatchesInScope(scope, patchListener);
1011
+ return processResult(void 0, scope);
1012
+ }
1013
+ /**
1014
+ * Pass true to automatically freeze all copies created by Immer.
1015
+ *
1016
+ * By default, auto-freezing is enabled.
1017
+ */
1018
+ setAutoFreeze(value) {
1019
+ this.autoFreeze_ = value;
1020
+ }
1021
+ /**
1022
+ * Pass true to enable strict shallow copy.
1023
+ *
1024
+ * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
1025
+ */
1026
+ setUseStrictShallowCopy(value) {
1027
+ this.useStrictShallowCopy_ = value;
1028
+ }
1029
+ applyPatches(base, patches) {
1030
+ let i;
1031
+ for (i = patches.length - 1; i >= 0; i--) {
1032
+ const patch = patches[i];
1033
+ if (patch.path.length === 0 && patch.op === "replace") {
1034
+ base = patch.value;
1035
+ break;
1036
+ }
1037
+ }
1038
+ if (i > -1) {
1039
+ patches = patches.slice(i + 1);
1040
+ }
1041
+ const applyPatchesImpl = getPlugin("Patches").applyPatches_;
1042
+ if (isDraft(base)) {
1043
+ return applyPatchesImpl(base, patches);
1044
+ }
1045
+ return this.produce(
1046
+ base,
1047
+ (draft) => applyPatchesImpl(draft, patches)
1048
+ );
1049
+ }
1050
+ };
1051
+ function createProxy(value, parent) {
1052
+ const draft = isMap(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet(value) ? getPlugin("MapSet").proxySet_(value, parent) : createProxyProxy(value, parent);
1053
+ const scope = parent ? parent.scope_ : getCurrentScope();
1054
+ scope.drafts_.push(draft);
1055
+ return draft;
1056
+ }
1057
+
1058
+ // src/core/current.ts
1059
+ function current(value) {
1060
+ if (!isDraft(value))
1061
+ die(10, value);
1062
+ return currentImpl(value);
1063
+ }
1064
+ function currentImpl(value) {
1065
+ if (!isDraftable(value) || isFrozen(value))
1066
+ return value;
1067
+ const state = value[DRAFT_STATE];
1068
+ let copy;
1069
+ if (state) {
1070
+ if (!state.modified_)
1071
+ return state.base_;
1072
+ state.finalized_ = true;
1073
+ copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
1074
+ } else {
1075
+ copy = shallowCopy(value, true);
1076
+ }
1077
+ each(copy, (key, childValue) => {
1078
+ set(copy, key, currentImpl(childValue));
1079
+ });
1080
+ if (state) {
1081
+ state.finalized_ = false;
1082
+ }
1083
+ return copy;
1084
+ }
1085
+
1086
+ // src/immer.ts
1087
+ var immer = new Immer2();
1088
+ var produce = immer.produce;
1089
+ immer.produceWithPatches.bind(
1090
+ immer
1091
+ );
1092
+ immer.setAutoFreeze.bind(immer);
1093
+ immer.setUseStrictShallowCopy.bind(immer);
1094
+ immer.applyPatches.bind(immer);
1095
+ immer.createDraft.bind(immer);
1096
+ immer.finishDraft.bind(immer);
1097
+
1098
+ // src/devModeChecks/identityFunctionCheck.ts
1099
+ var runIdentityFunctionCheck = (resultFunc, inputSelectorsResults, outputSelectorResult) => {
1100
+ if (inputSelectorsResults.length === 1 && inputSelectorsResults[0] === outputSelectorResult) {
1101
+ let isInputSameAsOutput = false;
1102
+ try {
1103
+ const emptyObject = {};
1104
+ if (resultFunc(emptyObject) === emptyObject)
1105
+ isInputSameAsOutput = true;
1106
+ } catch {
1107
+ }
1108
+ if (isInputSameAsOutput) {
1109
+ let stack = void 0;
1110
+ try {
1111
+ throw new Error();
1112
+ } catch (e) {
1113
+ ({ stack } = e);
1114
+ }
1115
+ console.warn(
1116
+ "The result function returned its own inputs without modification. e.g\n`createSelector([state => state.todos], todos => todos)`\nThis could lead to inefficient memoization and unnecessary re-renders.\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.",
1117
+ { stack }
1118
+ );
1119
+ }
1120
+ }
1121
+ };
1122
+
1123
+ // src/devModeChecks/inputStabilityCheck.ts
1124
+ var runInputStabilityCheck = (inputSelectorResultsObject, options, inputSelectorArgs) => {
1125
+ const { memoize, memoizeOptions } = options;
1126
+ const { inputSelectorResults, inputSelectorResultsCopy } = inputSelectorResultsObject;
1127
+ const createAnEmptyObject = memoize(() => ({}), ...memoizeOptions);
1128
+ const areInputSelectorResultsEqual = createAnEmptyObject.apply(null, inputSelectorResults) === createAnEmptyObject.apply(null, inputSelectorResultsCopy);
1129
+ if (!areInputSelectorResultsEqual) {
1130
+ let stack = void 0;
1131
+ try {
1132
+ throw new Error();
1133
+ } catch (e) {
1134
+ ({ stack } = e);
1135
+ }
1136
+ console.warn(
1137
+ "An input selector returned a different result when passed same arguments.\nThis means your output selector will likely run more frequently than intended.\nAvoid returning a new reference inside your input selector, e.g.\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`",
1138
+ {
1139
+ arguments: inputSelectorArgs,
1140
+ firstInputs: inputSelectorResults,
1141
+ secondInputs: inputSelectorResultsCopy,
1142
+ stack
1143
+ }
1144
+ );
1145
+ }
1146
+ };
1147
+
1148
+ // src/devModeChecks/setGlobalDevModeChecks.ts
1149
+ var globalDevModeChecks = {
1150
+ inputStabilityCheck: "once",
1151
+ identityFunctionCheck: "once"
1152
+ };
1153
+
1154
+ // src/utils.ts
1155
+ var NOT_FOUND = /* @__PURE__ */ Symbol("NOT_FOUND");
1156
+ function assertIsFunction(func, errorMessage = `expected a function, instead received ${typeof func}`) {
1157
+ if (typeof func !== "function") {
1158
+ throw new TypeError(errorMessage);
1159
+ }
1160
+ }
1161
+ function assertIsObject(object, errorMessage = `expected an object, instead received ${typeof object}`) {
1162
+ if (typeof object !== "object") {
1163
+ throw new TypeError(errorMessage);
1164
+ }
1165
+ }
1166
+ function assertIsArrayOfFunctions(array, errorMessage = `expected all items to be functions, instead received the following types: `) {
1167
+ if (!array.every((item) => typeof item === "function")) {
1168
+ const itemTypes = array.map(
1169
+ (item) => typeof item === "function" ? `function ${item.name || "unnamed"}()` : typeof item
1170
+ ).join(", ");
1171
+ throw new TypeError(`${errorMessage}[${itemTypes}]`);
1172
+ }
1173
+ }
1174
+ var ensureIsArray = (item) => {
1175
+ return Array.isArray(item) ? item : [item];
1176
+ };
1177
+ function getDependencies(createSelectorArgs) {
1178
+ const dependencies = Array.isArray(createSelectorArgs[0]) ? createSelectorArgs[0] : createSelectorArgs;
1179
+ assertIsArrayOfFunctions(
1180
+ dependencies,
1181
+ `createSelector expects all input-selectors to be functions, but received the following types: `
1182
+ );
1183
+ return dependencies;
1184
+ }
1185
+ function collectInputSelectorResults(dependencies, inputSelectorArgs) {
1186
+ const inputSelectorResults = [];
1187
+ const { length } = dependencies;
1188
+ for (let i = 0; i < length; i++) {
1189
+ inputSelectorResults.push(dependencies[i].apply(null, inputSelectorArgs));
1190
+ }
1191
+ return inputSelectorResults;
1192
+ }
1193
+ var getDevModeChecksExecutionInfo = (firstRun, devModeChecks) => {
1194
+ const { identityFunctionCheck, inputStabilityCheck } = {
1195
+ ...globalDevModeChecks,
1196
+ ...devModeChecks
1197
+ };
1198
+ return {
1199
+ identityFunctionCheck: {
1200
+ shouldRun: identityFunctionCheck === "always" || identityFunctionCheck === "once" && firstRun,
1201
+ run: runIdentityFunctionCheck
1202
+ },
1203
+ inputStabilityCheck: {
1204
+ shouldRun: inputStabilityCheck === "always" || inputStabilityCheck === "once" && firstRun,
1205
+ run: runInputStabilityCheck
1206
+ }
1207
+ };
1208
+ };
1209
+
1210
+ // src/lruMemoize.ts
1211
+ function createSingletonCache(equals) {
1212
+ let entry;
1213
+ return {
1214
+ get(key) {
1215
+ if (entry && equals(entry.key, key)) {
1216
+ return entry.value;
1217
+ }
1218
+ return NOT_FOUND;
1219
+ },
1220
+ put(key, value) {
1221
+ entry = { key, value };
1222
+ },
1223
+ getEntries() {
1224
+ return entry ? [entry] : [];
1225
+ },
1226
+ clear() {
1227
+ entry = void 0;
1228
+ }
1229
+ };
1230
+ }
1231
+ function createLruCache(maxSize, equals) {
1232
+ let entries = [];
1233
+ function get(key) {
1234
+ const cacheIndex = entries.findIndex((entry) => equals(key, entry.key));
1235
+ if (cacheIndex > -1) {
1236
+ const entry = entries[cacheIndex];
1237
+ if (cacheIndex > 0) {
1238
+ entries.splice(cacheIndex, 1);
1239
+ entries.unshift(entry);
1240
+ }
1241
+ return entry.value;
1242
+ }
1243
+ return NOT_FOUND;
1244
+ }
1245
+ function put(key, value) {
1246
+ if (get(key) === NOT_FOUND) {
1247
+ entries.unshift({ key, value });
1248
+ if (entries.length > maxSize) {
1249
+ entries.pop();
1250
+ }
1251
+ }
1252
+ }
1253
+ function getEntries() {
1254
+ return entries;
1255
+ }
1256
+ function clear() {
1257
+ entries = [];
1258
+ }
1259
+ return { get, put, getEntries, clear };
1260
+ }
1261
+ var referenceEqualityCheck = (a, b) => a === b;
1262
+ function createCacheKeyComparator(equalityCheck) {
1263
+ return function areArgumentsShallowlyEqual(prev, next) {
1264
+ if (prev === null || next === null || prev.length !== next.length) {
1265
+ return false;
1266
+ }
1267
+ const { length } = prev;
1268
+ for (let i = 0; i < length; i++) {
1269
+ if (!equalityCheck(prev[i], next[i])) {
1270
+ return false;
1271
+ }
1272
+ }
1273
+ return true;
1274
+ };
1275
+ }
1276
+ function lruMemoize(func, equalityCheckOrOptions) {
1277
+ const providedOptions = typeof equalityCheckOrOptions === "object" ? equalityCheckOrOptions : { equalityCheck: equalityCheckOrOptions };
1278
+ const {
1279
+ equalityCheck = referenceEqualityCheck,
1280
+ maxSize = 1,
1281
+ resultEqualityCheck
1282
+ } = providedOptions;
1283
+ const comparator = createCacheKeyComparator(equalityCheck);
1284
+ let resultsCount = 0;
1285
+ const cache = maxSize <= 1 ? createSingletonCache(comparator) : createLruCache(maxSize, comparator);
1286
+ function memoized() {
1287
+ let value = cache.get(arguments);
1288
+ if (value === NOT_FOUND) {
1289
+ value = func.apply(null, arguments);
1290
+ resultsCount++;
1291
+ if (resultEqualityCheck) {
1292
+ const entries = cache.getEntries();
1293
+ const matchingEntry = entries.find(
1294
+ (entry) => resultEqualityCheck(entry.value, value)
1295
+ );
1296
+ if (matchingEntry) {
1297
+ value = matchingEntry.value;
1298
+ resultsCount !== 0 && resultsCount--;
1299
+ }
1300
+ }
1301
+ cache.put(arguments, value);
1302
+ }
1303
+ return value;
1304
+ }
1305
+ memoized.clearCache = () => {
1306
+ cache.clear();
1307
+ memoized.resetResultsCount();
1308
+ };
1309
+ memoized.resultsCount = () => resultsCount;
1310
+ memoized.resetResultsCount = () => {
1311
+ resultsCount = 0;
1312
+ };
1313
+ return memoized;
1314
+ }
1315
+
1316
+ // src/weakMapMemoize.ts
1317
+ var StrongRef = class {
1318
+ constructor(value) {
1319
+ this.value = value;
1320
+ }
1321
+ deref() {
1322
+ return this.value;
1323
+ }
1324
+ };
1325
+ var Ref = typeof WeakRef !== "undefined" ? WeakRef : StrongRef;
1326
+ var UNTERMINATED = 0;
1327
+ var TERMINATED = 1;
1328
+ function createCacheNode() {
1329
+ return {
1330
+ s: UNTERMINATED,
1331
+ v: void 0,
1332
+ o: null,
1333
+ p: null
1334
+ };
1335
+ }
1336
+ function weakMapMemoize(func, options = {}) {
1337
+ let fnNode = createCacheNode();
1338
+ const { resultEqualityCheck } = options;
1339
+ let lastResult;
1340
+ let resultsCount = 0;
1341
+ function memoized() {
1342
+ let cacheNode = fnNode;
1343
+ const { length } = arguments;
1344
+ for (let i = 0, l = length; i < l; i++) {
1345
+ const arg = arguments[i];
1346
+ if (typeof arg === "function" || typeof arg === "object" && arg !== null) {
1347
+ let objectCache = cacheNode.o;
1348
+ if (objectCache === null) {
1349
+ cacheNode.o = objectCache = /* @__PURE__ */ new WeakMap();
1350
+ }
1351
+ const objectNode = objectCache.get(arg);
1352
+ if (objectNode === void 0) {
1353
+ cacheNode = createCacheNode();
1354
+ objectCache.set(arg, cacheNode);
1355
+ } else {
1356
+ cacheNode = objectNode;
1357
+ }
1358
+ } else {
1359
+ let primitiveCache = cacheNode.p;
1360
+ if (primitiveCache === null) {
1361
+ cacheNode.p = primitiveCache = /* @__PURE__ */ new Map();
1362
+ }
1363
+ const primitiveNode = primitiveCache.get(arg);
1364
+ if (primitiveNode === void 0) {
1365
+ cacheNode = createCacheNode();
1366
+ primitiveCache.set(arg, cacheNode);
1367
+ } else {
1368
+ cacheNode = primitiveNode;
1369
+ }
1370
+ }
1371
+ }
1372
+ const terminatedNode = cacheNode;
1373
+ let result;
1374
+ if (cacheNode.s === TERMINATED) {
1375
+ result = cacheNode.v;
1376
+ } else {
1377
+ result = func.apply(null, arguments);
1378
+ resultsCount++;
1379
+ if (resultEqualityCheck) {
1380
+ const lastResultValue = lastResult?.deref?.() ?? lastResult;
1381
+ if (lastResultValue != null && resultEqualityCheck(lastResultValue, result)) {
1382
+ result = lastResultValue;
1383
+ resultsCount !== 0 && resultsCount--;
1384
+ }
1385
+ const needsWeakRef = typeof result === "object" && result !== null || typeof result === "function";
1386
+ lastResult = needsWeakRef ? new Ref(result) : result;
1387
+ }
1388
+ }
1389
+ terminatedNode.s = TERMINATED;
1390
+ terminatedNode.v = result;
1391
+ return result;
1392
+ }
1393
+ memoized.clearCache = () => {
1394
+ fnNode = createCacheNode();
1395
+ memoized.resetResultsCount();
1396
+ };
1397
+ memoized.resultsCount = () => resultsCount;
1398
+ memoized.resetResultsCount = () => {
1399
+ resultsCount = 0;
1400
+ };
1401
+ return memoized;
1402
+ }
1403
+
1404
+ // src/createSelectorCreator.ts
1405
+ function createSelectorCreator(memoizeOrOptions, ...memoizeOptionsFromArgs) {
1406
+ const createSelectorCreatorOptions = typeof memoizeOrOptions === "function" ? {
1407
+ memoize: memoizeOrOptions,
1408
+ memoizeOptions: memoizeOptionsFromArgs
1409
+ } : memoizeOrOptions;
1410
+ const createSelector2 = (...createSelectorArgs) => {
1411
+ let recomputations = 0;
1412
+ let dependencyRecomputations = 0;
1413
+ let lastResult;
1414
+ let directlyPassedOptions = {};
1415
+ let resultFunc = createSelectorArgs.pop();
1416
+ if (typeof resultFunc === "object") {
1417
+ directlyPassedOptions = resultFunc;
1418
+ resultFunc = createSelectorArgs.pop();
1419
+ }
1420
+ assertIsFunction(
1421
+ resultFunc,
1422
+ `createSelector expects an output function after the inputs, but received: [${typeof resultFunc}]`
1423
+ );
1424
+ const combinedOptions = {
1425
+ ...createSelectorCreatorOptions,
1426
+ ...directlyPassedOptions
1427
+ };
1428
+ const {
1429
+ memoize,
1430
+ memoizeOptions = [],
1431
+ argsMemoize = weakMapMemoize,
1432
+ argsMemoizeOptions = [],
1433
+ devModeChecks = {}
1434
+ } = combinedOptions;
1435
+ const finalMemoizeOptions = ensureIsArray(memoizeOptions);
1436
+ const finalArgsMemoizeOptions = ensureIsArray(argsMemoizeOptions);
1437
+ const dependencies = getDependencies(createSelectorArgs);
1438
+ const memoizedResultFunc = memoize(function recomputationWrapper() {
1439
+ recomputations++;
1440
+ return resultFunc.apply(
1441
+ null,
1442
+ arguments
1443
+ );
1444
+ }, ...finalMemoizeOptions);
1445
+ let firstRun = true;
1446
+ const selector = argsMemoize(function dependenciesChecker() {
1447
+ dependencyRecomputations++;
1448
+ const inputSelectorResults = collectInputSelectorResults(
1449
+ dependencies,
1450
+ arguments
1451
+ );
1452
+ lastResult = memoizedResultFunc.apply(null, inputSelectorResults);
1453
+ if (process.env.NODE_ENV !== "production") {
1454
+ const { identityFunctionCheck, inputStabilityCheck } = getDevModeChecksExecutionInfo(firstRun, devModeChecks);
1455
+ if (identityFunctionCheck.shouldRun) {
1456
+ identityFunctionCheck.run(
1457
+ resultFunc,
1458
+ inputSelectorResults,
1459
+ lastResult
1460
+ );
1461
+ }
1462
+ if (inputStabilityCheck.shouldRun) {
1463
+ const inputSelectorResultsCopy = collectInputSelectorResults(
1464
+ dependencies,
1465
+ arguments
1466
+ );
1467
+ inputStabilityCheck.run(
1468
+ { inputSelectorResults, inputSelectorResultsCopy },
1469
+ { memoize, memoizeOptions: finalMemoizeOptions },
1470
+ arguments
1471
+ );
1472
+ }
1473
+ if (firstRun)
1474
+ firstRun = false;
1475
+ }
1476
+ return lastResult;
1477
+ }, ...finalArgsMemoizeOptions);
1478
+ return Object.assign(selector, {
1479
+ resultFunc,
1480
+ memoizedResultFunc,
1481
+ dependencies,
1482
+ dependencyRecomputations: () => dependencyRecomputations,
1483
+ resetDependencyRecomputations: () => {
1484
+ dependencyRecomputations = 0;
1485
+ },
1486
+ lastResult: () => lastResult,
1487
+ recomputations: () => recomputations,
1488
+ resetRecomputations: () => {
1489
+ recomputations = 0;
1490
+ },
1491
+ memoize,
1492
+ argsMemoize
1493
+ });
1494
+ };
1495
+ Object.assign(createSelector2, {
1496
+ withTypes: () => createSelector2
1497
+ });
1498
+ return createSelector2;
1499
+ }
1500
+ var createSelector = /* @__PURE__ */ createSelectorCreator(weakMapMemoize);
1501
+
1502
+ // src/createStructuredSelector.ts
1503
+ var createStructuredSelector = Object.assign(
1504
+ (inputSelectorsObject, selectorCreator = createSelector) => {
1505
+ assertIsObject(
1506
+ inputSelectorsObject,
1507
+ `createStructuredSelector expects first argument to be an object where each property is a selector, instead received a ${typeof inputSelectorsObject}`
1508
+ );
1509
+ const inputSelectorKeys = Object.keys(inputSelectorsObject);
1510
+ const dependencies = inputSelectorKeys.map(
1511
+ (key) => inputSelectorsObject[key]
1512
+ );
1513
+ const structuredSelector = selectorCreator(
1514
+ dependencies,
1515
+ (...inputSelectorResults) => {
1516
+ return inputSelectorResults.reduce((composition, value, index) => {
1517
+ composition[inputSelectorKeys[index]] = value;
1518
+ return composition;
1519
+ }, {});
1520
+ }
1521
+ );
1522
+ return structuredSelector;
1523
+ },
1524
+ { withTypes: () => createStructuredSelector }
1525
+ );
1526
+
1527
+ // src/index.ts
1528
+ function createThunkMiddleware(extraArgument) {
1529
+ const middleware = ({ dispatch, getState }) => (next) => (action) => {
1530
+ if (typeof action === "function") {
1531
+ return action(dispatch, getState, extraArgument);
1532
+ }
1533
+ return next(action);
1534
+ };
1535
+ return middleware;
1536
+ }
1537
+ var thunk = createThunkMiddleware();
1538
+ var withExtraArgument = createThunkMiddleware;
1539
+
1540
+ // src/index.ts
1541
+ var createDraftSafeSelectorCreator = (...args) => {
1542
+ const createSelector2 = createSelectorCreator(...args);
1543
+ const createDraftSafeSelector2 = Object.assign((...args2) => {
1544
+ const selector = createSelector2(...args2);
1545
+ const wrappedSelector = (value, ...rest) => selector(isDraft(value) ? current(value) : value, ...rest);
1546
+ Object.assign(wrappedSelector, selector);
1547
+ return wrappedSelector;
1548
+ }, {
1549
+ withTypes: () => createDraftSafeSelector2
1550
+ });
1551
+ return createDraftSafeSelector2;
1552
+ };
1553
+ var createDraftSafeSelector = /* @__PURE__ */ createDraftSafeSelectorCreator(weakMapMemoize);
1554
+ var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() {
1555
+ if (arguments.length === 0) return void 0;
1556
+ if (typeof arguments[0] === "object") return compose;
1557
+ return compose.apply(null, arguments);
1558
+ };
1559
+
1560
+ // src/tsHelpers.ts
1561
+ var hasMatchFunction = (v) => {
1562
+ return v && typeof v.match === "function";
1563
+ };
1564
+
1565
+ // src/createAction.ts
1566
+ function createAction(type, prepareAction) {
1567
+ function actionCreator(...args) {
1568
+ if (prepareAction) {
1569
+ let prepared = prepareAction(...args);
1570
+ if (!prepared) {
1571
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(0) : "prepareAction did not return an object");
1572
+ }
1573
+ return {
1574
+ type,
1575
+ payload: prepared.payload,
1576
+ ..."meta" in prepared && {
1577
+ meta: prepared.meta
1578
+ },
1579
+ ..."error" in prepared && {
1580
+ error: prepared.error
1581
+ }
1582
+ };
1583
+ }
1584
+ return {
1585
+ type,
1586
+ payload: args[0]
1587
+ };
1588
+ }
1589
+ actionCreator.toString = () => `${type}`;
1590
+ actionCreator.type = type;
1591
+ actionCreator.match = (action) => isAction(action) && action.type === type;
1592
+ return actionCreator;
1593
+ }
1594
+ function isActionCreator(action) {
1595
+ return typeof action === "function" && "type" in action && // hasMatchFunction only wants Matchers but I don't see the point in rewriting it
1596
+ hasMatchFunction(action);
1597
+ }
1598
+ function isFSA(action) {
1599
+ return isAction(action) && Object.keys(action).every(isValidKey);
1600
+ }
1601
+ function isValidKey(key) {
1602
+ return ["type", "payload", "error", "meta"].indexOf(key) > -1;
1603
+ }
1604
+
1605
+ // src/actionCreatorInvariantMiddleware.ts
1606
+ function getMessage(type) {
1607
+ const splitType = type ? `${type}`.split("/") : [];
1608
+ const actionName = splitType[splitType.length - 1] || "actionCreator";
1609
+ return `Detected an action creator with type "${type || "unknown"}" being dispatched.
1610
+ 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.`;
1611
+ }
1612
+ function createActionCreatorInvariantMiddleware(options = {}) {
1613
+ if (process.env.NODE_ENV === "production") {
1614
+ return () => (next) => (action) => next(action);
1615
+ }
1616
+ const {
1617
+ isActionCreator: isActionCreator2 = isActionCreator
1618
+ } = options;
1619
+ return () => (next) => (action) => {
1620
+ if (isActionCreator2(action)) {
1621
+ console.warn(getMessage(action.type));
1622
+ }
1623
+ return next(action);
1624
+ };
1625
+ }
1626
+ function getTimeMeasureUtils(maxDelay, fnName) {
1627
+ let elapsed = 0;
1628
+ return {
1629
+ measureTime(fn) {
1630
+ const started = Date.now();
1631
+ try {
1632
+ return fn();
1633
+ } finally {
1634
+ const finished = Date.now();
1635
+ elapsed += finished - started;
1636
+ }
1637
+ },
1638
+ warnIfExceeded() {
1639
+ if (elapsed > maxDelay) {
1640
+ console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms.
1641
+ 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.
1642
+ It is disabled in production builds, so you don't need to worry about that.`);
1643
+ }
1644
+ }
1645
+ };
1646
+ }
1647
+ function find(iterable, comparator) {
1648
+ for (const entry of iterable) {
1649
+ if (comparator(entry)) {
1650
+ return entry;
1651
+ }
1652
+ }
1653
+ return void 0;
1654
+ }
1655
+ var Tuple = class _Tuple extends Array {
1656
+ constructor(...items) {
1657
+ super(...items);
1658
+ Object.setPrototypeOf(this, _Tuple.prototype);
1659
+ }
1660
+ static get [Symbol.species]() {
1661
+ return _Tuple;
1662
+ }
1663
+ concat(...arr) {
1664
+ return super.concat.apply(this, arr);
1665
+ }
1666
+ prepend(...arr) {
1667
+ if (arr.length === 1 && Array.isArray(arr[0])) {
1668
+ return new _Tuple(...arr[0].concat(this));
1669
+ }
1670
+ return new _Tuple(...arr.concat(this));
1671
+ }
1672
+ };
1673
+ function freezeDraftable(val) {
1674
+ return isDraftable(val) ? produce(val, () => {
1675
+ }) : val;
1676
+ }
1677
+ function emplace(map, key, handler) {
1678
+ if (map.has(key)) {
1679
+ let value = map.get(key);
1680
+ if (handler.update) {
1681
+ value = handler.update(value, key, map);
1682
+ map.set(key, value);
1683
+ }
1684
+ return value;
1685
+ }
1686
+ if (!handler.insert) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(10) : "No insert provided for key not already in map");
1687
+ const inserted = handler.insert(key, map);
1688
+ map.set(key, inserted);
1689
+ return inserted;
1690
+ }
1691
+
1692
+ // src/immutableStateInvariantMiddleware.ts
1693
+ function isImmutableDefault(value) {
1694
+ return typeof value !== "object" || value == null || Object.isFrozen(value);
1695
+ }
1696
+ function trackForMutations(isImmutable, ignorePaths, obj) {
1697
+ const trackedProperties = trackProperties(isImmutable, ignorePaths, obj);
1698
+ return {
1699
+ detectMutations() {
1700
+ return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);
1701
+ }
1702
+ };
1703
+ }
1704
+ function trackProperties(isImmutable, ignorePaths = [], obj, path = "", checkedObjects = /* @__PURE__ */ new Set()) {
1705
+ const tracked = {
1706
+ value: obj
1707
+ };
1708
+ if (!isImmutable(obj) && !checkedObjects.has(obj)) {
1709
+ checkedObjects.add(obj);
1710
+ tracked.children = {};
1711
+ for (const key in obj) {
1712
+ const childPath = path ? path + "." + key : key;
1713
+ if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {
1714
+ continue;
1715
+ }
1716
+ tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);
1717
+ }
1718
+ }
1719
+ return tracked;
1720
+ }
1721
+ function detectMutations(isImmutable, ignoredPaths = [], trackedProperty, obj, sameParentRef = false, path = "") {
1722
+ const prevObj = trackedProperty ? trackedProperty.value : void 0;
1723
+ const sameRef = prevObj === obj;
1724
+ if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
1725
+ return {
1726
+ wasMutated: true,
1727
+ path
1728
+ };
1729
+ }
1730
+ if (isImmutable(prevObj) || isImmutable(obj)) {
1731
+ return {
1732
+ wasMutated: false
1733
+ };
1734
+ }
1735
+ const keysToDetect = {};
1736
+ for (let key in trackedProperty.children) {
1737
+ keysToDetect[key] = true;
1738
+ }
1739
+ for (let key in obj) {
1740
+ keysToDetect[key] = true;
1741
+ }
1742
+ const hasIgnoredPaths = ignoredPaths.length > 0;
1743
+ for (let key in keysToDetect) {
1744
+ const nestedPath = path ? path + "." + key : key;
1745
+ if (hasIgnoredPaths) {
1746
+ const hasMatches = ignoredPaths.some((ignored) => {
1747
+ if (ignored instanceof RegExp) {
1748
+ return ignored.test(nestedPath);
1749
+ }
1750
+ return nestedPath === ignored;
1751
+ });
1752
+ if (hasMatches) {
1753
+ continue;
1754
+ }
1755
+ }
1756
+ const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);
1757
+ if (result.wasMutated) {
1758
+ return result;
1759
+ }
1760
+ }
1761
+ return {
1762
+ wasMutated: false
1763
+ };
1764
+ }
1765
+ function createImmutableStateInvariantMiddleware(options = {}) {
1766
+ if (process.env.NODE_ENV === "production") {
1767
+ return () => (next) => (action) => next(action);
1768
+ } else {
1769
+ let stringify2 = function(obj, serializer, indent, decycler) {
1770
+ return JSON.stringify(obj, getSerialize2(serializer, decycler), indent);
1771
+ }, getSerialize2 = function(serializer, decycler) {
1772
+ let stack = [], keys = [];
1773
+ if (!decycler) decycler = function(_, value) {
1774
+ if (stack[0] === value) return "[Circular ~]";
1775
+ return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
1776
+ };
1777
+ return function(key, value) {
1778
+ if (stack.length > 0) {
1779
+ var thisPos = stack.indexOf(this);
1780
+ ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
1781
+ ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
1782
+ if (~stack.indexOf(value)) value = decycler.call(this, key, value);
1783
+ } else stack.push(value);
1784
+ return serializer == null ? value : serializer.call(this, key, value);
1785
+ };
1786
+ };
1787
+ let {
1788
+ isImmutable = isImmutableDefault,
1789
+ ignoredPaths,
1790
+ warnAfter = 32
1791
+ } = options;
1792
+ const track = trackForMutations.bind(null, isImmutable, ignoredPaths);
1793
+ return ({
1794
+ getState
1795
+ }) => {
1796
+ let state = getState();
1797
+ let tracker = track(state);
1798
+ let result;
1799
+ return (next) => (action) => {
1800
+ const measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
1801
+ measureUtils.measureTime(() => {
1802
+ state = getState();
1803
+ result = tracker.detectMutations();
1804
+ tracker = track(state);
1805
+ if (result.wasMutated) {
1806
+ 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)`);
1807
+ }
1808
+ });
1809
+ const dispatchedAction = next(action);
1810
+ measureUtils.measureTime(() => {
1811
+ state = getState();
1812
+ result = tracker.detectMutations();
1813
+ tracker = track(state);
1814
+ if (result.wasMutated) {
1815
+ 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)`);
1816
+ }
1817
+ });
1818
+ measureUtils.warnIfExceeded();
1819
+ return dispatchedAction;
1820
+ };
1821
+ };
1822
+ }
1823
+ }
1824
+ function isPlain(val) {
1825
+ const type = typeof val;
1826
+ return val == null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || isPlainObject$1(val);
1827
+ }
1828
+ function findNonSerializableValue(value, path = "", isSerializable = isPlain, getEntries, ignoredPaths = [], cache) {
1829
+ let foundNestedSerializable;
1830
+ if (!isSerializable(value)) {
1831
+ return {
1832
+ keyPath: path || "<root>",
1833
+ value
1834
+ };
1835
+ }
1836
+ if (typeof value !== "object" || value === null) {
1837
+ return false;
1838
+ }
1839
+ if (cache?.has(value)) return false;
1840
+ const entries = getEntries != null ? getEntries(value) : Object.entries(value);
1841
+ const hasIgnoredPaths = ignoredPaths.length > 0;
1842
+ for (const [key, nestedValue] of entries) {
1843
+ const nestedPath = path ? path + "." + key : key;
1844
+ if (hasIgnoredPaths) {
1845
+ const hasMatches = ignoredPaths.some((ignored) => {
1846
+ if (ignored instanceof RegExp) {
1847
+ return ignored.test(nestedPath);
1848
+ }
1849
+ return nestedPath === ignored;
1850
+ });
1851
+ if (hasMatches) {
1852
+ continue;
1853
+ }
1854
+ }
1855
+ if (!isSerializable(nestedValue)) {
1856
+ return {
1857
+ keyPath: nestedPath,
1858
+ value: nestedValue
1859
+ };
1860
+ }
1861
+ if (typeof nestedValue === "object") {
1862
+ foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);
1863
+ if (foundNestedSerializable) {
1864
+ return foundNestedSerializable;
1865
+ }
1866
+ }
1867
+ }
1868
+ if (cache && isNestedFrozen(value)) cache.add(value);
1869
+ return false;
1870
+ }
1871
+ function isNestedFrozen(value) {
1872
+ if (!Object.isFrozen(value)) return false;
1873
+ for (const nestedValue of Object.values(value)) {
1874
+ if (typeof nestedValue !== "object" || nestedValue === null) continue;
1875
+ if (!isNestedFrozen(nestedValue)) return false;
1876
+ }
1877
+ return true;
1878
+ }
1879
+ function createSerializableStateInvariantMiddleware(options = {}) {
1880
+ if (process.env.NODE_ENV === "production") {
1881
+ return () => (next) => (action) => next(action);
1882
+ } else {
1883
+ const {
1884
+ isSerializable = isPlain,
1885
+ getEntries,
1886
+ ignoredActions = [],
1887
+ ignoredActionPaths = ["meta.arg", "meta.baseQueryMeta"],
1888
+ ignoredPaths = [],
1889
+ warnAfter = 32,
1890
+ ignoreState = false,
1891
+ ignoreActions = false,
1892
+ disableCache = false
1893
+ } = options;
1894
+ const cache = !disableCache && WeakSet ? /* @__PURE__ */ new WeakSet() : void 0;
1895
+ return (storeAPI) => (next) => (action) => {
1896
+ if (!isAction(action)) {
1897
+ return next(action);
1898
+ }
1899
+ const result = next(action);
1900
+ const measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
1901
+ if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {
1902
+ measureUtils.measureTime(() => {
1903
+ const foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths, cache);
1904
+ if (foundActionNonSerializableValue) {
1905
+ const {
1906
+ keyPath,
1907
+ value
1908
+ } = foundActionNonSerializableValue;
1909
+ 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)");
1910
+ }
1911
+ });
1912
+ }
1913
+ if (!ignoreState) {
1914
+ measureUtils.measureTime(() => {
1915
+ const state = storeAPI.getState();
1916
+ const foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths, cache);
1917
+ if (foundStateNonSerializableValue) {
1918
+ const {
1919
+ keyPath,
1920
+ value
1921
+ } = foundStateNonSerializableValue;
1922
+ console.error(`A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`, value, `
1923
+ Take a look at the reducer(s) handling this action type: ${action.type}.
1924
+ (See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);
1925
+ }
1926
+ });
1927
+ measureUtils.warnIfExceeded();
1928
+ }
1929
+ return result;
1930
+ };
1931
+ }
1932
+ }
1933
+
1934
+ // src/getDefaultMiddleware.ts
1935
+ function isBoolean(x) {
1936
+ return typeof x === "boolean";
1937
+ }
1938
+ var buildGetDefaultMiddleware = () => function getDefaultMiddleware(options) {
1939
+ const {
1940
+ thunk: thunk$1 = true,
1941
+ immutableCheck = true,
1942
+ serializableCheck = true,
1943
+ actionCreatorCheck = true
1944
+ } = options ?? {};
1945
+ let middlewareArray = new Tuple();
1946
+ if (thunk$1) {
1947
+ if (isBoolean(thunk$1)) {
1948
+ middlewareArray.push(thunk);
1949
+ } else {
1950
+ middlewareArray.push(withExtraArgument(thunk$1.extraArgument));
1951
+ }
1952
+ }
1953
+ if (process.env.NODE_ENV !== "production") {
1954
+ if (immutableCheck) {
1955
+ let immutableOptions = {};
1956
+ if (!isBoolean(immutableCheck)) {
1957
+ immutableOptions = immutableCheck;
1958
+ }
1959
+ middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
1960
+ }
1961
+ if (serializableCheck) {
1962
+ let serializableOptions = {};
1963
+ if (!isBoolean(serializableCheck)) {
1964
+ serializableOptions = serializableCheck;
1965
+ }
1966
+ middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
1967
+ }
1968
+ if (actionCreatorCheck) {
1969
+ let actionCreatorOptions = {};
1970
+ if (!isBoolean(actionCreatorCheck)) {
1971
+ actionCreatorOptions = actionCreatorCheck;
1972
+ }
1973
+ middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));
1974
+ }
1975
+ }
1976
+ return middlewareArray;
1977
+ };
1978
+
1979
+ // src/autoBatchEnhancer.ts
1980
+ var SHOULD_AUTOBATCH = "RTK_autoBatch";
1981
+ var prepareAutoBatched = () => (payload) => ({
1982
+ payload,
1983
+ meta: {
1984
+ [SHOULD_AUTOBATCH]: true
1985
+ }
1986
+ });
1987
+ var createQueueWithTimer = (timeout) => {
1988
+ return (notify) => {
1989
+ setTimeout(notify, timeout);
1990
+ };
1991
+ };
1992
+ var rAF = typeof window !== "undefined" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10);
1993
+ var autoBatchEnhancer = (options = {
1994
+ type: "raf"
1995
+ }) => (next) => (...args) => {
1996
+ const store = next(...args);
1997
+ let notifying = true;
1998
+ let shouldNotifyAtEndOfTick = false;
1999
+ let notificationQueued = false;
2000
+ const listeners = /* @__PURE__ */ new Set();
2001
+ const queueCallback = options.type === "tick" ? queueMicrotask : options.type === "raf" ? rAF : options.type === "callback" ? options.queueNotification : createQueueWithTimer(options.timeout);
2002
+ const notifyListeners = () => {
2003
+ notificationQueued = false;
2004
+ if (shouldNotifyAtEndOfTick) {
2005
+ shouldNotifyAtEndOfTick = false;
2006
+ listeners.forEach((l) => l());
2007
+ }
2008
+ };
2009
+ return Object.assign({}, store, {
2010
+ // Override the base `store.subscribe` method to keep original listeners
2011
+ // from running if we're delaying notifications
2012
+ subscribe(listener2) {
2013
+ const wrappedListener = () => notifying && listener2();
2014
+ const unsubscribe = store.subscribe(wrappedListener);
2015
+ listeners.add(listener2);
2016
+ return () => {
2017
+ unsubscribe();
2018
+ listeners.delete(listener2);
2019
+ };
2020
+ },
2021
+ // Override the base `store.dispatch` method so that we can check actions
2022
+ // for the `shouldAutoBatch` flag and determine if batching is active
2023
+ dispatch(action) {
2024
+ try {
2025
+ notifying = !action?.meta?.[SHOULD_AUTOBATCH];
2026
+ shouldNotifyAtEndOfTick = !notifying;
2027
+ if (shouldNotifyAtEndOfTick) {
2028
+ if (!notificationQueued) {
2029
+ notificationQueued = true;
2030
+ queueCallback(notifyListeners);
2031
+ }
2032
+ }
2033
+ return store.dispatch(action);
2034
+ } finally {
2035
+ notifying = true;
2036
+ }
2037
+ }
2038
+ });
2039
+ };
2040
+
2041
+ // src/getDefaultEnhancers.ts
2042
+ var buildGetDefaultEnhancers = (middlewareEnhancer) => function getDefaultEnhancers(options) {
2043
+ const {
2044
+ autoBatch = true
2045
+ } = options ?? {};
2046
+ let enhancerArray = new Tuple(middlewareEnhancer);
2047
+ if (autoBatch) {
2048
+ enhancerArray.push(autoBatchEnhancer(typeof autoBatch === "object" ? autoBatch : void 0));
2049
+ }
2050
+ return enhancerArray;
2051
+ };
2052
+
2053
+ // src/configureStore.ts
2054
+ function configureStore(options) {
2055
+ const getDefaultMiddleware = buildGetDefaultMiddleware();
2056
+ const {
2057
+ reducer = void 0,
2058
+ middleware,
2059
+ devTools = true,
2060
+ preloadedState = void 0,
2061
+ enhancers = void 0
2062
+ } = options || {};
2063
+ let rootReducer;
2064
+ if (typeof reducer === "function") {
2065
+ rootReducer = reducer;
2066
+ } else if (isPlainObject$1(reducer)) {
2067
+ rootReducer = combineReducers(reducer);
2068
+ } else {
2069
+ 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");
2070
+ }
2071
+ if (process.env.NODE_ENV !== "production" && middleware && typeof middleware !== "function") {
2072
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(2) : "`middleware` field must be a callback");
2073
+ }
2074
+ let finalMiddleware;
2075
+ if (typeof middleware === "function") {
2076
+ finalMiddleware = middleware(getDefaultMiddleware);
2077
+ if (process.env.NODE_ENV !== "production" && !Array.isArray(finalMiddleware)) {
2078
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(3) : "when using a middleware builder function, an array of middleware must be returned");
2079
+ }
2080
+ } else {
2081
+ finalMiddleware = getDefaultMiddleware();
2082
+ }
2083
+ if (process.env.NODE_ENV !== "production" && finalMiddleware.some((item) => typeof item !== "function")) {
2084
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(4) : "each middleware provided to configureStore must be a function");
2085
+ }
2086
+ let finalCompose = compose;
2087
+ if (devTools) {
2088
+ finalCompose = composeWithDevTools({
2089
+ // Enable capture of stack traces for dispatched Redux actions
2090
+ trace: process.env.NODE_ENV !== "production",
2091
+ ...typeof devTools === "object" && devTools
2092
+ });
2093
+ }
2094
+ const middlewareEnhancer = applyMiddleware(...finalMiddleware);
2095
+ const getDefaultEnhancers = buildGetDefaultEnhancers(middlewareEnhancer);
2096
+ if (process.env.NODE_ENV !== "production" && enhancers && typeof enhancers !== "function") {
2097
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(5) : "`enhancers` field must be a callback");
2098
+ }
2099
+ let storeEnhancers = typeof enhancers === "function" ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();
2100
+ if (process.env.NODE_ENV !== "production" && !Array.isArray(storeEnhancers)) {
2101
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(6) : "`enhancers` callback must return an array");
2102
+ }
2103
+ if (process.env.NODE_ENV !== "production" && storeEnhancers.some((item) => typeof item !== "function")) {
2104
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(7) : "each enhancer provided to configureStore must be a function");
2105
+ }
2106
+ if (process.env.NODE_ENV !== "production" && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {
2107
+ console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");
2108
+ }
2109
+ const composedEnhancer = finalCompose(...storeEnhancers);
2110
+ return createStore(rootReducer, preloadedState, composedEnhancer);
2111
+ }
2112
+
2113
+ // src/mapBuilders.ts
2114
+ function executeReducerBuilderCallback(builderCallback) {
2115
+ const actionsMap = {};
2116
+ const actionMatchers = [];
2117
+ let defaultCaseReducer;
2118
+ const builder = {
2119
+ addCase(typeOrActionCreator, reducer) {
2120
+ if (process.env.NODE_ENV !== "production") {
2121
+ if (actionMatchers.length > 0) {
2122
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(26) : "`builder.addCase` should only be called before calling `builder.addMatcher`");
2123
+ }
2124
+ if (defaultCaseReducer) {
2125
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(27) : "`builder.addCase` should only be called before calling `builder.addDefaultCase`");
2126
+ }
2127
+ }
2128
+ const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
2129
+ if (!type) {
2130
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(28) : "`builder.addCase` cannot be called with an empty action type");
2131
+ }
2132
+ if (type in actionsMap) {
2133
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(29) : `\`builder.addCase\` cannot be called with two reducers for the same action type '${type}'`);
2134
+ }
2135
+ actionsMap[type] = reducer;
2136
+ return builder;
2137
+ },
2138
+ addMatcher(matcher, reducer) {
2139
+ if (process.env.NODE_ENV !== "production") {
2140
+ if (defaultCaseReducer) {
2141
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(30) : "`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
2142
+ }
2143
+ }
2144
+ actionMatchers.push({
2145
+ matcher,
2146
+ reducer
2147
+ });
2148
+ return builder;
2149
+ },
2150
+ addDefaultCase(reducer) {
2151
+ if (process.env.NODE_ENV !== "production") {
2152
+ if (defaultCaseReducer) {
2153
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(31) : "`builder.addDefaultCase` can only be called once");
2154
+ }
2155
+ }
2156
+ defaultCaseReducer = reducer;
2157
+ return builder;
2158
+ }
2159
+ };
2160
+ builderCallback(builder);
2161
+ return [actionsMap, actionMatchers, defaultCaseReducer];
2162
+ }
2163
+
2164
+ // src/createReducer.ts
2165
+ function isStateFunction(x) {
2166
+ return typeof x === "function";
2167
+ }
2168
+ function createReducer(initialState, mapOrBuilderCallback) {
2169
+ if (process.env.NODE_ENV !== "production") {
2170
+ if (typeof mapOrBuilderCallback === "object") {
2171
+ 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");
2172
+ }
2173
+ }
2174
+ let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);
2175
+ let getInitialState;
2176
+ if (isStateFunction(initialState)) {
2177
+ getInitialState = () => freezeDraftable(initialState());
2178
+ } else {
2179
+ const frozenInitialState = freezeDraftable(initialState);
2180
+ getInitialState = () => frozenInitialState;
2181
+ }
2182
+ function reducer(state = getInitialState(), action) {
2183
+ let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({
2184
+ matcher
2185
+ }) => matcher(action)).map(({
2186
+ reducer: reducer2
2187
+ }) => reducer2)];
2188
+ if (caseReducers.filter((cr) => !!cr).length === 0) {
2189
+ caseReducers = [finalDefaultCaseReducer];
2190
+ }
2191
+ return caseReducers.reduce((previousState, caseReducer) => {
2192
+ if (caseReducer) {
2193
+ if (isDraft(previousState)) {
2194
+ const draft = previousState;
2195
+ const result = caseReducer(draft, action);
2196
+ if (result === void 0) {
2197
+ return previousState;
2198
+ }
2199
+ return result;
2200
+ } else if (!isDraftable(previousState)) {
2201
+ const result = caseReducer(previousState, action);
2202
+ if (result === void 0) {
2203
+ if (previousState === null) {
2204
+ return previousState;
2205
+ }
2206
+ throw Error("A case reducer on a non-draftable value must not return undefined");
2207
+ }
2208
+ return result;
2209
+ } else {
2210
+ return produce(previousState, (draft) => {
2211
+ return caseReducer(draft, action);
2212
+ });
2213
+ }
2214
+ }
2215
+ return previousState;
2216
+ }, state);
2217
+ }
2218
+ reducer.getInitialState = getInitialState;
2219
+ return reducer;
2220
+ }
2221
+
2222
+ // src/matchers.ts
2223
+ var matches = (matcher, action) => {
2224
+ if (hasMatchFunction(matcher)) {
2225
+ return matcher.match(action);
2226
+ } else {
2227
+ return matcher(action);
2228
+ }
2229
+ };
2230
+ function isAnyOf(...matchers) {
2231
+ return (action) => {
2232
+ return matchers.some((matcher) => matches(matcher, action));
2233
+ };
2234
+ }
2235
+ function isAllOf(...matchers) {
2236
+ return (action) => {
2237
+ return matchers.every((matcher) => matches(matcher, action));
2238
+ };
2239
+ }
2240
+ function hasExpectedRequestMetadata(action, validStatus) {
2241
+ if (!action || !action.meta) return false;
2242
+ const hasValidRequestId = typeof action.meta.requestId === "string";
2243
+ const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
2244
+ return hasValidRequestId && hasValidRequestStatus;
2245
+ }
2246
+ function isAsyncThunkArray(a) {
2247
+ return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
2248
+ }
2249
+ function isPending(...asyncThunks) {
2250
+ if (asyncThunks.length === 0) {
2251
+ return (action) => hasExpectedRequestMetadata(action, ["pending"]);
2252
+ }
2253
+ if (!isAsyncThunkArray(asyncThunks)) {
2254
+ return isPending()(asyncThunks[0]);
2255
+ }
2256
+ return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.pending));
2257
+ }
2258
+ function isRejected(...asyncThunks) {
2259
+ if (asyncThunks.length === 0) {
2260
+ return (action) => hasExpectedRequestMetadata(action, ["rejected"]);
2261
+ }
2262
+ if (!isAsyncThunkArray(asyncThunks)) {
2263
+ return isRejected()(asyncThunks[0]);
2264
+ }
2265
+ return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.rejected));
2266
+ }
2267
+ function isRejectedWithValue(...asyncThunks) {
2268
+ const hasFlag = (action) => {
2269
+ return action && action.meta && action.meta.rejectedWithValue;
2270
+ };
2271
+ if (asyncThunks.length === 0) {
2272
+ return isAllOf(isRejected(...asyncThunks), hasFlag);
2273
+ }
2274
+ if (!isAsyncThunkArray(asyncThunks)) {
2275
+ return isRejectedWithValue()(asyncThunks[0]);
2276
+ }
2277
+ return isAllOf(isRejected(...asyncThunks), hasFlag);
2278
+ }
2279
+ function isFulfilled(...asyncThunks) {
2280
+ if (asyncThunks.length === 0) {
2281
+ return (action) => hasExpectedRequestMetadata(action, ["fulfilled"]);
2282
+ }
2283
+ if (!isAsyncThunkArray(asyncThunks)) {
2284
+ return isFulfilled()(asyncThunks[0]);
2285
+ }
2286
+ return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.fulfilled));
2287
+ }
2288
+ function isAsyncThunkAction(...asyncThunks) {
2289
+ if (asyncThunks.length === 0) {
2290
+ return (action) => hasExpectedRequestMetadata(action, ["pending", "fulfilled", "rejected"]);
2291
+ }
2292
+ if (!isAsyncThunkArray(asyncThunks)) {
2293
+ return isAsyncThunkAction()(asyncThunks[0]);
2294
+ }
2295
+ return isAnyOf(...asyncThunks.flatMap((asyncThunk) => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));
2296
+ }
2297
+
2298
+ // src/nanoid.ts
2299
+ var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
2300
+ var nanoid = (size = 21) => {
2301
+ let id = "";
2302
+ let i = size;
2303
+ while (i--) {
2304
+ id += urlAlphabet[Math.random() * 64 | 0];
2305
+ }
2306
+ return id;
2307
+ };
2308
+
2309
+ // src/createAsyncThunk.ts
2310
+ var commonProperties = ["name", "message", "stack", "code"];
2311
+ var RejectWithValue = class {
2312
+ constructor(payload, meta) {
2313
+ this.payload = payload;
2314
+ this.meta = meta;
2315
+ }
2316
+ /*
2317
+ type-only property to distinguish between RejectWithValue and FulfillWithMeta
2318
+ does not exist at runtime
2319
+ */
2320
+ _type;
2321
+ };
2322
+ var FulfillWithMeta = class {
2323
+ constructor(payload, meta) {
2324
+ this.payload = payload;
2325
+ this.meta = meta;
2326
+ }
2327
+ /*
2328
+ type-only property to distinguish between RejectWithValue and FulfillWithMeta
2329
+ does not exist at runtime
2330
+ */
2331
+ _type;
2332
+ };
2333
+ var miniSerializeError = (value) => {
2334
+ if (typeof value === "object" && value !== null) {
2335
+ const simpleError = {};
2336
+ for (const property of commonProperties) {
2337
+ if (typeof value[property] === "string") {
2338
+ simpleError[property] = value[property];
2339
+ }
2340
+ }
2341
+ return simpleError;
2342
+ }
2343
+ return {
2344
+ message: String(value)
2345
+ };
2346
+ };
2347
+ var createAsyncThunk = /* @__PURE__ */ (() => {
2348
+ function createAsyncThunk2(typePrefix, payloadCreator, options) {
2349
+ const fulfilled = createAction(typePrefix + "/fulfilled", (payload, requestId, arg, meta) => ({
2350
+ payload,
2351
+ meta: {
2352
+ ...meta || {},
2353
+ arg,
2354
+ requestId,
2355
+ requestStatus: "fulfilled"
2356
+ }
2357
+ }));
2358
+ const pending = createAction(typePrefix + "/pending", (requestId, arg, meta) => ({
2359
+ payload: void 0,
2360
+ meta: {
2361
+ ...meta || {},
2362
+ arg,
2363
+ requestId,
2364
+ requestStatus: "pending"
2365
+ }
2366
+ }));
2367
+ const rejected = createAction(typePrefix + "/rejected", (error, requestId, arg, payload, meta) => ({
2368
+ payload,
2369
+ error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
2370
+ meta: {
2371
+ ...meta || {},
2372
+ arg,
2373
+ requestId,
2374
+ rejectedWithValue: !!payload,
2375
+ requestStatus: "rejected",
2376
+ aborted: error?.name === "AbortError",
2377
+ condition: error?.name === "ConditionError"
2378
+ }
2379
+ }));
2380
+ function actionCreator(arg) {
2381
+ return (dispatch, getState, extra) => {
2382
+ const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();
2383
+ const abortController = new AbortController();
2384
+ let abortHandler;
2385
+ let abortReason;
2386
+ function abort(reason) {
2387
+ abortReason = reason;
2388
+ abortController.abort();
2389
+ }
2390
+ const promise = async function() {
2391
+ let finalAction;
2392
+ try {
2393
+ let conditionResult = options?.condition?.(arg, {
2394
+ getState,
2395
+ extra
2396
+ });
2397
+ if (isThenable(conditionResult)) {
2398
+ conditionResult = await conditionResult;
2399
+ }
2400
+ if (conditionResult === false || abortController.signal.aborted) {
2401
+ throw {
2402
+ name: "ConditionError",
2403
+ message: "Aborted due to condition callback returning false."
2404
+ };
2405
+ }
2406
+ const abortedPromise = new Promise((_, reject) => {
2407
+ abortHandler = () => {
2408
+ reject({
2409
+ name: "AbortError",
2410
+ message: abortReason || "Aborted"
2411
+ });
2412
+ };
2413
+ abortController.signal.addEventListener("abort", abortHandler);
2414
+ });
2415
+ dispatch(pending(requestId, arg, options?.getPendingMeta?.({
2416
+ requestId,
2417
+ arg
2418
+ }, {
2419
+ getState,
2420
+ extra
2421
+ })));
2422
+ finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {
2423
+ dispatch,
2424
+ getState,
2425
+ extra,
2426
+ requestId,
2427
+ signal: abortController.signal,
2428
+ abort,
2429
+ rejectWithValue: (value, meta) => {
2430
+ return new RejectWithValue(value, meta);
2431
+ },
2432
+ fulfillWithValue: (value, meta) => {
2433
+ return new FulfillWithMeta(value, meta);
2434
+ }
2435
+ })).then((result) => {
2436
+ if (result instanceof RejectWithValue) {
2437
+ throw result;
2438
+ }
2439
+ if (result instanceof FulfillWithMeta) {
2440
+ return fulfilled(result.payload, requestId, arg, result.meta);
2441
+ }
2442
+ return fulfilled(result, requestId, arg);
2443
+ })]);
2444
+ } catch (err) {
2445
+ finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);
2446
+ } finally {
2447
+ if (abortHandler) {
2448
+ abortController.signal.removeEventListener("abort", abortHandler);
2449
+ }
2450
+ }
2451
+ const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;
2452
+ if (!skipDispatch) {
2453
+ dispatch(finalAction);
2454
+ }
2455
+ return finalAction;
2456
+ }();
2457
+ return Object.assign(promise, {
2458
+ abort,
2459
+ requestId,
2460
+ arg,
2461
+ unwrap() {
2462
+ return promise.then(unwrapResult);
2463
+ }
2464
+ });
2465
+ };
2466
+ }
2467
+ return Object.assign(actionCreator, {
2468
+ pending,
2469
+ rejected,
2470
+ fulfilled,
2471
+ settled: isAnyOf(rejected, fulfilled),
2472
+ typePrefix
2473
+ });
2474
+ }
2475
+ createAsyncThunk2.withTypes = () => createAsyncThunk2;
2476
+ return createAsyncThunk2;
2477
+ })();
2478
+ function unwrapResult(action) {
2479
+ if (action.meta && action.meta.rejectedWithValue) {
2480
+ throw action.payload;
2481
+ }
2482
+ if (action.error) {
2483
+ throw action.error;
2484
+ }
2485
+ return action.payload;
2486
+ }
2487
+ function isThenable(value) {
2488
+ return value !== null && typeof value === "object" && typeof value.then === "function";
2489
+ }
2490
+
2491
+ // src/createSlice.ts
2492
+ var asyncThunkSymbol = /* @__PURE__ */ Symbol.for("rtk-slice-createasyncthunk");
2493
+ var asyncThunkCreator = {
2494
+ [asyncThunkSymbol]: createAsyncThunk
2495
+ };
2496
+ var ReducerType = /* @__PURE__ */ ((ReducerType2) => {
2497
+ ReducerType2["reducer"] = "reducer";
2498
+ ReducerType2["reducerWithPrepare"] = "reducerWithPrepare";
2499
+ ReducerType2["asyncThunk"] = "asyncThunk";
2500
+ return ReducerType2;
2501
+ })(ReducerType || {});
2502
+ function getType(slice, actionKey) {
2503
+ return `${slice}/${actionKey}`;
2504
+ }
2505
+ function buildCreateSlice({
2506
+ creators
2507
+ } = {}) {
2508
+ const cAT = creators?.asyncThunk?.[asyncThunkSymbol];
2509
+ return function createSlice2(options) {
2510
+ const {
2511
+ name,
2512
+ reducerPath = name
2513
+ } = options;
2514
+ if (!name) {
2515
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(11) : "`name` is a required option for createSlice");
2516
+ }
2517
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
2518
+ if (options.initialState === void 0) {
2519
+ console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");
2520
+ }
2521
+ }
2522
+ const reducers = (typeof options.reducers === "function" ? options.reducers(buildReducerCreators()) : options.reducers) || {};
2523
+ const reducerNames = Object.keys(reducers);
2524
+ const context = {
2525
+ sliceCaseReducersByName: {},
2526
+ sliceCaseReducersByType: {},
2527
+ actionCreators: {},
2528
+ sliceMatchers: []
2529
+ };
2530
+ const contextMethods = {
2531
+ addCase(typeOrActionCreator, reducer2) {
2532
+ const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
2533
+ if (!type) {
2534
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(12) : "`context.addCase` cannot be called with an empty action type");
2535
+ }
2536
+ if (type in context.sliceCaseReducersByType) {
2537
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(13) : "`context.addCase` cannot be called with two reducers for the same action type: " + type);
2538
+ }
2539
+ context.sliceCaseReducersByType[type] = reducer2;
2540
+ return contextMethods;
2541
+ },
2542
+ addMatcher(matcher, reducer2) {
2543
+ context.sliceMatchers.push({
2544
+ matcher,
2545
+ reducer: reducer2
2546
+ });
2547
+ return contextMethods;
2548
+ },
2549
+ exposeAction(name2, actionCreator) {
2550
+ context.actionCreators[name2] = actionCreator;
2551
+ return contextMethods;
2552
+ },
2553
+ exposeCaseReducer(name2, reducer2) {
2554
+ context.sliceCaseReducersByName[name2] = reducer2;
2555
+ return contextMethods;
2556
+ }
2557
+ };
2558
+ reducerNames.forEach((reducerName) => {
2559
+ const reducerDefinition = reducers[reducerName];
2560
+ const reducerDetails = {
2561
+ reducerName,
2562
+ type: getType(name, reducerName),
2563
+ createNotation: typeof options.reducers === "function"
2564
+ };
2565
+ if (isAsyncThunkSliceReducerDefinition(reducerDefinition)) {
2566
+ handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);
2567
+ } else {
2568
+ handleNormalReducerDefinition(reducerDetails, reducerDefinition, contextMethods);
2569
+ }
2570
+ });
2571
+ function buildReducer() {
2572
+ if (process.env.NODE_ENV !== "production") {
2573
+ if (typeof options.extraReducers === "object") {
2574
+ 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");
2575
+ }
2576
+ }
2577
+ const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];
2578
+ const finalCaseReducers = {
2579
+ ...extraReducers,
2580
+ ...context.sliceCaseReducersByType
2581
+ };
2582
+ return createReducer(options.initialState, (builder) => {
2583
+ for (let key in finalCaseReducers) {
2584
+ builder.addCase(key, finalCaseReducers[key]);
2585
+ }
2586
+ for (let sM of context.sliceMatchers) {
2587
+ builder.addMatcher(sM.matcher, sM.reducer);
2588
+ }
2589
+ for (let m of actionMatchers) {
2590
+ builder.addMatcher(m.matcher, m.reducer);
2591
+ }
2592
+ if (defaultCaseReducer) {
2593
+ builder.addDefaultCase(defaultCaseReducer);
2594
+ }
2595
+ });
2596
+ }
2597
+ const selectSelf = (state) => state;
2598
+ const injectedSelectorCache = /* @__PURE__ */ new Map();
2599
+ let _reducer;
2600
+ function reducer(state, action) {
2601
+ if (!_reducer) _reducer = buildReducer();
2602
+ return _reducer(state, action);
2603
+ }
2604
+ function getInitialState() {
2605
+ if (!_reducer) _reducer = buildReducer();
2606
+ return _reducer.getInitialState();
2607
+ }
2608
+ function makeSelectorProps(reducerPath2, injected = false) {
2609
+ function selectSlice(state) {
2610
+ let sliceState = state[reducerPath2];
2611
+ if (typeof sliceState === "undefined") {
2612
+ if (injected) {
2613
+ sliceState = getInitialState();
2614
+ } else if (process.env.NODE_ENV !== "production") {
2615
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(15) : "selectSlice returned undefined for an uninjected slice reducer");
2616
+ }
2617
+ }
2618
+ return sliceState;
2619
+ }
2620
+ function getSelectors(selectState = selectSelf) {
2621
+ const selectorCache = emplace(injectedSelectorCache, injected, {
2622
+ insert: () => /* @__PURE__ */ new WeakMap()
2623
+ });
2624
+ return emplace(selectorCache, selectState, {
2625
+ insert: () => {
2626
+ const map = {};
2627
+ for (const [name2, selector] of Object.entries(options.selectors ?? {})) {
2628
+ map[name2] = wrapSelector(selector, selectState, getInitialState, injected);
2629
+ }
2630
+ return map;
2631
+ }
2632
+ });
2633
+ }
2634
+ return {
2635
+ reducerPath: reducerPath2,
2636
+ getSelectors,
2637
+ get selectors() {
2638
+ return getSelectors(selectSlice);
2639
+ },
2640
+ selectSlice
2641
+ };
2642
+ }
2643
+ const slice = {
2644
+ name,
2645
+ reducer,
2646
+ actions: context.actionCreators,
2647
+ caseReducers: context.sliceCaseReducersByName,
2648
+ getInitialState,
2649
+ ...makeSelectorProps(reducerPath),
2650
+ injectInto(injectable, {
2651
+ reducerPath: pathOpt,
2652
+ ...config
2653
+ } = {}) {
2654
+ const newReducerPath = pathOpt ?? reducerPath;
2655
+ injectable.inject({
2656
+ reducerPath: newReducerPath,
2657
+ reducer
2658
+ }, config);
2659
+ return {
2660
+ ...slice,
2661
+ ...makeSelectorProps(newReducerPath, true)
2662
+ };
2663
+ }
2664
+ };
2665
+ return slice;
2666
+ };
2667
+ }
2668
+ function wrapSelector(selector, selectState, getInitialState, injected) {
2669
+ function wrapper(rootState, ...args) {
2670
+ let sliceState = selectState(rootState);
2671
+ if (typeof sliceState === "undefined") {
2672
+ if (injected) {
2673
+ sliceState = getInitialState();
2674
+ } else if (process.env.NODE_ENV !== "production") {
2675
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(16) : "selectState returned undefined for an uninjected slice reducer");
2676
+ }
2677
+ }
2678
+ return selector(sliceState, ...args);
2679
+ }
2680
+ wrapper.unwrapped = selector;
2681
+ return wrapper;
2682
+ }
2683
+ var createSlice = /* @__PURE__ */ buildCreateSlice();
2684
+ function buildReducerCreators() {
2685
+ function asyncThunk(payloadCreator, config) {
2686
+ return {
2687
+ _reducerDefinitionType: "asyncThunk" /* asyncThunk */,
2688
+ payloadCreator,
2689
+ ...config
2690
+ };
2691
+ }
2692
+ asyncThunk.withTypes = () => asyncThunk;
2693
+ return {
2694
+ reducer(caseReducer) {
2695
+ return Object.assign({
2696
+ // hack so the wrapping function has the same name as the original
2697
+ // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original
2698
+ [caseReducer.name](...args) {
2699
+ return caseReducer(...args);
2700
+ }
2701
+ }[caseReducer.name], {
2702
+ _reducerDefinitionType: "reducer" /* reducer */
2703
+ });
2704
+ },
2705
+ preparedReducer(prepare, reducer) {
2706
+ return {
2707
+ _reducerDefinitionType: "reducerWithPrepare" /* reducerWithPrepare */,
2708
+ prepare,
2709
+ reducer
2710
+ };
2711
+ },
2712
+ asyncThunk
2713
+ };
2714
+ }
2715
+ function handleNormalReducerDefinition({
2716
+ type,
2717
+ reducerName,
2718
+ createNotation
2719
+ }, maybeReducerWithPrepare, context) {
2720
+ let caseReducer;
2721
+ let prepareCallback;
2722
+ if ("reducer" in maybeReducerWithPrepare) {
2723
+ if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {
2724
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(17) : "Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");
2725
+ }
2726
+ caseReducer = maybeReducerWithPrepare.reducer;
2727
+ prepareCallback = maybeReducerWithPrepare.prepare;
2728
+ } else {
2729
+ caseReducer = maybeReducerWithPrepare;
2730
+ }
2731
+ context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));
2732
+ }
2733
+ function isAsyncThunkSliceReducerDefinition(reducerDefinition) {
2734
+ return reducerDefinition._reducerDefinitionType === "asyncThunk" /* asyncThunk */;
2735
+ }
2736
+ function isCaseReducerWithPrepareDefinition(reducerDefinition) {
2737
+ return reducerDefinition._reducerDefinitionType === "reducerWithPrepare" /* reducerWithPrepare */;
2738
+ }
2739
+ function handleThunkCaseReducerDefinition({
2740
+ type,
2741
+ reducerName
2742
+ }, reducerDefinition, context, cAT) {
2743
+ if (!cAT) {
2744
+ 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`.");
2745
+ }
2746
+ const {
2747
+ payloadCreator,
2748
+ fulfilled,
2749
+ pending,
2750
+ rejected,
2751
+ settled,
2752
+ options
2753
+ } = reducerDefinition;
2754
+ const thunk = cAT(type, payloadCreator, options);
2755
+ context.exposeAction(reducerName, thunk);
2756
+ if (fulfilled) {
2757
+ context.addCase(thunk.fulfilled, fulfilled);
2758
+ }
2759
+ if (pending) {
2760
+ context.addCase(thunk.pending, pending);
2761
+ }
2762
+ if (rejected) {
2763
+ context.addCase(thunk.rejected, rejected);
2764
+ }
2765
+ if (settled) {
2766
+ context.addMatcher(thunk.settled, settled);
2767
+ }
2768
+ context.exposeCaseReducer(reducerName, {
2769
+ fulfilled: fulfilled || noop,
2770
+ pending: pending || noop,
2771
+ rejected: rejected || noop,
2772
+ settled: settled || noop
2773
+ });
2774
+ }
2775
+ function noop() {
2776
+ }
2777
+
2778
+ // src/entities/entity_state.ts
2779
+ function getInitialEntityState() {
2780
+ return {
2781
+ ids: [],
2782
+ entities: {}
2783
+ };
2784
+ }
2785
+ function createInitialStateFactory(stateAdapter) {
2786
+ function getInitialState(additionalState = {}, entities) {
2787
+ const state = Object.assign(getInitialEntityState(), additionalState);
2788
+ return entities ? stateAdapter.setAll(state, entities) : state;
2789
+ }
2790
+ return {
2791
+ getInitialState
2792
+ };
2793
+ }
2794
+
2795
+ // src/entities/state_selectors.ts
2796
+ function createSelectorsFactory() {
2797
+ function getSelectors(selectState, options = {}) {
2798
+ const {
2799
+ createSelector: createSelector2 = createDraftSafeSelector
2800
+ } = options;
2801
+ const selectIds = (state) => state.ids;
2802
+ const selectEntities = (state) => state.entities;
2803
+ const selectAll = createSelector2(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));
2804
+ const selectId = (_, id) => id;
2805
+ const selectById = (entities, id) => entities[id];
2806
+ const selectTotal = createSelector2(selectIds, (ids) => ids.length);
2807
+ if (!selectState) {
2808
+ return {
2809
+ selectIds,
2810
+ selectEntities,
2811
+ selectAll,
2812
+ selectTotal,
2813
+ selectById: createSelector2(selectEntities, selectId, selectById)
2814
+ };
2815
+ }
2816
+ const selectGlobalizedEntities = createSelector2(selectState, selectEntities);
2817
+ return {
2818
+ selectIds: createSelector2(selectState, selectIds),
2819
+ selectEntities: selectGlobalizedEntities,
2820
+ selectAll: createSelector2(selectState, selectAll),
2821
+ selectTotal: createSelector2(selectState, selectTotal),
2822
+ selectById: createSelector2(selectGlobalizedEntities, selectId, selectById)
2823
+ };
2824
+ }
2825
+ return {
2826
+ getSelectors
2827
+ };
2828
+ }
2829
+ var isDraftTyped = isDraft;
2830
+ function createSingleArgumentStateOperator(mutator) {
2831
+ const operator = createStateOperator((_, state) => mutator(state));
2832
+ return function operation(state) {
2833
+ return operator(state, void 0);
2834
+ };
2835
+ }
2836
+ function createStateOperator(mutator) {
2837
+ return function operation(state, arg) {
2838
+ function isPayloadActionArgument(arg2) {
2839
+ return isFSA(arg2);
2840
+ }
2841
+ const runMutator = (draft) => {
2842
+ if (isPayloadActionArgument(arg)) {
2843
+ mutator(arg.payload, draft);
2844
+ } else {
2845
+ mutator(arg, draft);
2846
+ }
2847
+ };
2848
+ if (isDraftTyped(state)) {
2849
+ runMutator(state);
2850
+ return state;
2851
+ }
2852
+ return produce(state, runMutator);
2853
+ };
2854
+ }
2855
+ function selectIdValue(entity, selectId) {
2856
+ const key = selectId(entity);
2857
+ if (process.env.NODE_ENV !== "production" && key === void 0) {
2858
+ 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());
2859
+ }
2860
+ return key;
2861
+ }
2862
+ function ensureEntitiesArray(entities) {
2863
+ if (!Array.isArray(entities)) {
2864
+ entities = Object.values(entities);
2865
+ }
2866
+ return entities;
2867
+ }
2868
+ function getCurrent(value) {
2869
+ return isDraft(value) ? current(value) : value;
2870
+ }
2871
+ function splitAddedUpdatedEntities(newEntities, selectId, state) {
2872
+ newEntities = ensureEntitiesArray(newEntities);
2873
+ const existingIdsArray = getCurrent(state.ids);
2874
+ const existingIds = new Set(existingIdsArray);
2875
+ const added = [];
2876
+ const updated = [];
2877
+ for (const entity of newEntities) {
2878
+ const id = selectIdValue(entity, selectId);
2879
+ if (existingIds.has(id)) {
2880
+ updated.push({
2881
+ id,
2882
+ changes: entity
2883
+ });
2884
+ } else {
2885
+ added.push(entity);
2886
+ }
2887
+ }
2888
+ return [added, updated, existingIdsArray];
2889
+ }
2890
+
2891
+ // src/entities/unsorted_state_adapter.ts
2892
+ function createUnsortedStateAdapter(selectId) {
2893
+ function addOneMutably(entity, state) {
2894
+ const key = selectIdValue(entity, selectId);
2895
+ if (key in state.entities) {
2896
+ return;
2897
+ }
2898
+ state.ids.push(key);
2899
+ state.entities[key] = entity;
2900
+ }
2901
+ function addManyMutably(newEntities, state) {
2902
+ newEntities = ensureEntitiesArray(newEntities);
2903
+ for (const entity of newEntities) {
2904
+ addOneMutably(entity, state);
2905
+ }
2906
+ }
2907
+ function setOneMutably(entity, state) {
2908
+ const key = selectIdValue(entity, selectId);
2909
+ if (!(key in state.entities)) {
2910
+ state.ids.push(key);
2911
+ }
2912
+ state.entities[key] = entity;
2913
+ }
2914
+ function setManyMutably(newEntities, state) {
2915
+ newEntities = ensureEntitiesArray(newEntities);
2916
+ for (const entity of newEntities) {
2917
+ setOneMutably(entity, state);
2918
+ }
2919
+ }
2920
+ function setAllMutably(newEntities, state) {
2921
+ newEntities = ensureEntitiesArray(newEntities);
2922
+ state.ids = [];
2923
+ state.entities = {};
2924
+ addManyMutably(newEntities, state);
2925
+ }
2926
+ function removeOneMutably(key, state) {
2927
+ return removeManyMutably([key], state);
2928
+ }
2929
+ function removeManyMutably(keys, state) {
2930
+ let didMutate = false;
2931
+ keys.forEach((key) => {
2932
+ if (key in state.entities) {
2933
+ delete state.entities[key];
2934
+ didMutate = true;
2935
+ }
2936
+ });
2937
+ if (didMutate) {
2938
+ state.ids = state.ids.filter((id) => id in state.entities);
2939
+ }
2940
+ }
2941
+ function removeAllMutably(state) {
2942
+ Object.assign(state, {
2943
+ ids: [],
2944
+ entities: {}
2945
+ });
2946
+ }
2947
+ function takeNewKey(keys, update, state) {
2948
+ const original3 = state.entities[update.id];
2949
+ if (original3 === void 0) {
2950
+ return false;
2951
+ }
2952
+ const updated = Object.assign({}, original3, update.changes);
2953
+ const newKey = selectIdValue(updated, selectId);
2954
+ const hasNewKey = newKey !== update.id;
2955
+ if (hasNewKey) {
2956
+ keys[update.id] = newKey;
2957
+ delete state.entities[update.id];
2958
+ }
2959
+ state.entities[newKey] = updated;
2960
+ return hasNewKey;
2961
+ }
2962
+ function updateOneMutably(update, state) {
2963
+ return updateManyMutably([update], state);
2964
+ }
2965
+ function updateManyMutably(updates, state) {
2966
+ const newKeys = {};
2967
+ const updatesPerEntity = {};
2968
+ updates.forEach((update) => {
2969
+ if (update.id in state.entities) {
2970
+ updatesPerEntity[update.id] = {
2971
+ id: update.id,
2972
+ // Spreads ignore falsy values, so this works even if there isn't
2973
+ // an existing update already at this key
2974
+ changes: {
2975
+ ...updatesPerEntity[update.id]?.changes,
2976
+ ...update.changes
2977
+ }
2978
+ };
2979
+ }
2980
+ });
2981
+ updates = Object.values(updatesPerEntity);
2982
+ const didMutateEntities = updates.length > 0;
2983
+ if (didMutateEntities) {
2984
+ const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0;
2985
+ if (didMutateIds) {
2986
+ state.ids = Object.values(state.entities).map((e) => selectIdValue(e, selectId));
2987
+ }
2988
+ }
2989
+ }
2990
+ function upsertOneMutably(entity, state) {
2991
+ return upsertManyMutably([entity], state);
2992
+ }
2993
+ function upsertManyMutably(newEntities, state) {
2994
+ const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
2995
+ updateManyMutably(updated, state);
2996
+ addManyMutably(added, state);
2997
+ }
2998
+ return {
2999
+ removeAll: createSingleArgumentStateOperator(removeAllMutably),
3000
+ addOne: createStateOperator(addOneMutably),
3001
+ addMany: createStateOperator(addManyMutably),
3002
+ setOne: createStateOperator(setOneMutably),
3003
+ setMany: createStateOperator(setManyMutably),
3004
+ setAll: createStateOperator(setAllMutably),
3005
+ updateOne: createStateOperator(updateOneMutably),
3006
+ updateMany: createStateOperator(updateManyMutably),
3007
+ upsertOne: createStateOperator(upsertOneMutably),
3008
+ upsertMany: createStateOperator(upsertManyMutably),
3009
+ removeOne: createStateOperator(removeOneMutably),
3010
+ removeMany: createStateOperator(removeManyMutably)
3011
+ };
3012
+ }
3013
+
3014
+ // src/entities/sorted_state_adapter.ts
3015
+ function findInsertIndex(sortedItems, item, comparisonFunction) {
3016
+ let lowIndex = 0;
3017
+ let highIndex = sortedItems.length;
3018
+ while (lowIndex < highIndex) {
3019
+ let middleIndex = lowIndex + highIndex >>> 1;
3020
+ const currentItem = sortedItems[middleIndex];
3021
+ const res = comparisonFunction(item, currentItem);
3022
+ if (res >= 0) {
3023
+ lowIndex = middleIndex + 1;
3024
+ } else {
3025
+ highIndex = middleIndex;
3026
+ }
3027
+ }
3028
+ return lowIndex;
3029
+ }
3030
+ function insert(sortedItems, item, comparisonFunction) {
3031
+ const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);
3032
+ sortedItems.splice(insertAtIndex, 0, item);
3033
+ return sortedItems;
3034
+ }
3035
+ function createSortedStateAdapter(selectId, comparer) {
3036
+ const {
3037
+ removeOne,
3038
+ removeMany,
3039
+ removeAll
3040
+ } = createUnsortedStateAdapter(selectId);
3041
+ function addOneMutably(entity, state) {
3042
+ return addManyMutably([entity], state);
3043
+ }
3044
+ function addManyMutably(newEntities, state, existingIds) {
3045
+ newEntities = ensureEntitiesArray(newEntities);
3046
+ const existingKeys = new Set(existingIds ?? getCurrent(state.ids));
3047
+ const models = newEntities.filter((model) => !existingKeys.has(selectIdValue(model, selectId)));
3048
+ if (models.length !== 0) {
3049
+ mergeFunction(state, models);
3050
+ }
3051
+ }
3052
+ function setOneMutably(entity, state) {
3053
+ return setManyMutably([entity], state);
3054
+ }
3055
+ function setManyMutably(newEntities, state) {
3056
+ newEntities = ensureEntitiesArray(newEntities);
3057
+ if (newEntities.length !== 0) {
3058
+ for (const item of newEntities) {
3059
+ delete state.entities[selectId(item)];
3060
+ }
3061
+ mergeFunction(state, newEntities);
3062
+ }
3063
+ }
3064
+ function setAllMutably(newEntities, state) {
3065
+ newEntities = ensureEntitiesArray(newEntities);
3066
+ state.entities = {};
3067
+ state.ids = [];
3068
+ addManyMutably(newEntities, state, []);
3069
+ }
3070
+ function updateOneMutably(update, state) {
3071
+ return updateManyMutably([update], state);
3072
+ }
3073
+ function updateManyMutably(updates, state) {
3074
+ let appliedUpdates = false;
3075
+ let replacedIds = false;
3076
+ for (let update of updates) {
3077
+ const entity = state.entities[update.id];
3078
+ if (!entity) {
3079
+ continue;
3080
+ }
3081
+ appliedUpdates = true;
3082
+ Object.assign(entity, update.changes);
3083
+ const newId = selectId(entity);
3084
+ if (update.id !== newId) {
3085
+ replacedIds = true;
3086
+ delete state.entities[update.id];
3087
+ const oldIndex = state.ids.indexOf(update.id);
3088
+ state.ids[oldIndex] = newId;
3089
+ state.entities[newId] = entity;
3090
+ }
3091
+ }
3092
+ if (appliedUpdates) {
3093
+ mergeFunction(state, [], appliedUpdates, replacedIds);
3094
+ }
3095
+ }
3096
+ function upsertOneMutably(entity, state) {
3097
+ return upsertManyMutably([entity], state);
3098
+ }
3099
+ function upsertManyMutably(newEntities, state) {
3100
+ const [added, updated, existingIdsArray] = splitAddedUpdatedEntities(newEntities, selectId, state);
3101
+ if (updated.length) {
3102
+ updateManyMutably(updated, state);
3103
+ }
3104
+ if (added.length) {
3105
+ addManyMutably(added, state, existingIdsArray);
3106
+ }
3107
+ }
3108
+ function areArraysEqual(a, b) {
3109
+ if (a.length !== b.length) {
3110
+ return false;
3111
+ }
3112
+ for (let i = 0; i < a.length; i++) {
3113
+ if (a[i] === b[i]) {
3114
+ continue;
3115
+ }
3116
+ return false;
3117
+ }
3118
+ return true;
3119
+ }
3120
+ const mergeFunction = (state, addedItems, appliedUpdates, replacedIds) => {
3121
+ const currentEntities = getCurrent(state.entities);
3122
+ const currentIds = getCurrent(state.ids);
3123
+ const stateEntities = state.entities;
3124
+ let ids = currentIds;
3125
+ if (replacedIds) {
3126
+ ids = new Set(currentIds);
3127
+ }
3128
+ let sortedEntities = [];
3129
+ for (const id of ids) {
3130
+ const entity = currentEntities[id];
3131
+ if (entity) {
3132
+ sortedEntities.push(entity);
3133
+ }
3134
+ }
3135
+ const wasPreviouslyEmpty = sortedEntities.length === 0;
3136
+ for (const item of addedItems) {
3137
+ stateEntities[selectId(item)] = item;
3138
+ if (!wasPreviouslyEmpty) {
3139
+ insert(sortedEntities, item, comparer);
3140
+ }
3141
+ }
3142
+ if (wasPreviouslyEmpty) {
3143
+ sortedEntities = addedItems.slice().sort(comparer);
3144
+ } else if (appliedUpdates) {
3145
+ sortedEntities.sort(comparer);
3146
+ }
3147
+ const newSortedIds = sortedEntities.map(selectId);
3148
+ if (!areArraysEqual(currentIds, newSortedIds)) {
3149
+ state.ids = newSortedIds;
3150
+ }
3151
+ };
3152
+ return {
3153
+ removeOne,
3154
+ removeMany,
3155
+ removeAll,
3156
+ addOne: createStateOperator(addOneMutably),
3157
+ updateOne: createStateOperator(updateOneMutably),
3158
+ upsertOne: createStateOperator(upsertOneMutably),
3159
+ setOne: createStateOperator(setOneMutably),
3160
+ setMany: createStateOperator(setManyMutably),
3161
+ setAll: createStateOperator(setAllMutably),
3162
+ addMany: createStateOperator(addManyMutably),
3163
+ updateMany: createStateOperator(updateManyMutably),
3164
+ upsertMany: createStateOperator(upsertManyMutably)
3165
+ };
3166
+ }
3167
+
3168
+ // src/entities/create_adapter.ts
3169
+ function createEntityAdapter(options = {}) {
3170
+ const {
3171
+ selectId,
3172
+ sortComparer
3173
+ } = {
3174
+ sortComparer: false,
3175
+ selectId: (instance) => instance.id,
3176
+ ...options
3177
+ };
3178
+ const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
3179
+ const stateFactory = createInitialStateFactory(stateAdapter);
3180
+ const selectorsFactory = createSelectorsFactory();
3181
+ return {
3182
+ selectId,
3183
+ sortComparer,
3184
+ ...stateFactory,
3185
+ ...selectorsFactory,
3186
+ ...stateAdapter
3187
+ };
3188
+ }
3189
+
3190
+ // src/listenerMiddleware/exceptions.ts
3191
+ var task = "task";
3192
+ var listener = "listener";
3193
+ var completed = "completed";
3194
+ var cancelled = "cancelled";
3195
+ var taskCancelled = `task-${cancelled}`;
3196
+ var taskCompleted = `task-${completed}`;
3197
+ var listenerCancelled = `${listener}-${cancelled}`;
3198
+ var listenerCompleted = `${listener}-${completed}`;
3199
+ var TaskAbortError = class {
3200
+ constructor(code) {
3201
+ this.code = code;
3202
+ this.message = `${task} ${cancelled} (reason: ${code})`;
3203
+ }
3204
+ name = "TaskAbortError";
3205
+ message;
3206
+ };
3207
+
3208
+ // src/listenerMiddleware/utils.ts
3209
+ var assertFunction = (func, expected) => {
3210
+ if (typeof func !== "function") {
3211
+ throw new TypeError(process.env.NODE_ENV === "production" ? formatProdErrorMessage(32) : `${expected} is not a function`);
3212
+ }
3213
+ };
3214
+ var noop2 = () => {
3215
+ };
3216
+ var catchRejection = (promise, onError = noop2) => {
3217
+ promise.catch(onError);
3218
+ return promise;
3219
+ };
3220
+ var addAbortSignalListener = (abortSignal, callback) => {
3221
+ abortSignal.addEventListener("abort", callback, {
3222
+ once: true
3223
+ });
3224
+ return () => abortSignal.removeEventListener("abort", callback);
3225
+ };
3226
+ var abortControllerWithReason = (abortController, reason) => {
3227
+ const signal = abortController.signal;
3228
+ if (signal.aborted) {
3229
+ return;
3230
+ }
3231
+ if (!("reason" in signal)) {
3232
+ Object.defineProperty(signal, "reason", {
3233
+ enumerable: true,
3234
+ value: reason,
3235
+ configurable: true,
3236
+ writable: true
3237
+ });
3238
+ }
3239
+ abortController.abort(reason);
3240
+ };
3241
+
3242
+ // src/listenerMiddleware/task.ts
3243
+ var validateActive = (signal) => {
3244
+ if (signal.aborted) {
3245
+ const {
3246
+ reason
3247
+ } = signal;
3248
+ throw new TaskAbortError(reason);
3249
+ }
3250
+ };
3251
+ function raceWithSignal(signal, promise) {
3252
+ let cleanup = noop2;
3253
+ return new Promise((resolve, reject) => {
3254
+ const notifyRejection = () => reject(new TaskAbortError(signal.reason));
3255
+ if (signal.aborted) {
3256
+ notifyRejection();
3257
+ return;
3258
+ }
3259
+ cleanup = addAbortSignalListener(signal, notifyRejection);
3260
+ promise.finally(() => cleanup()).then(resolve, reject);
3261
+ }).finally(() => {
3262
+ cleanup = noop2;
3263
+ });
3264
+ }
3265
+ var runTask = async (task2, cleanUp) => {
3266
+ try {
3267
+ await Promise.resolve();
3268
+ const value = await task2();
3269
+ return {
3270
+ status: "ok",
3271
+ value
3272
+ };
3273
+ } catch (error) {
3274
+ return {
3275
+ status: error instanceof TaskAbortError ? "cancelled" : "rejected",
3276
+ error
3277
+ };
3278
+ } finally {
3279
+ cleanUp?.();
3280
+ }
3281
+ };
3282
+ var createPause = (signal) => {
3283
+ return (promise) => {
3284
+ return catchRejection(raceWithSignal(signal, promise).then((output) => {
3285
+ validateActive(signal);
3286
+ return output;
3287
+ }));
3288
+ };
3289
+ };
3290
+ var createDelay = (signal) => {
3291
+ const pause = createPause(signal);
3292
+ return (timeoutMs) => {
3293
+ return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)));
3294
+ };
3295
+ };
3296
+
3297
+ // src/listenerMiddleware/index.ts
3298
+ var {
3299
+ assign
3300
+ } = Object;
3301
+ var INTERNAL_NIL_TOKEN = {};
3302
+ var alm = "listenerMiddleware";
3303
+ var createFork = (parentAbortSignal, parentBlockingPromises) => {
3304
+ const linkControllers = (controller) => addAbortSignalListener(parentAbortSignal, () => abortControllerWithReason(controller, parentAbortSignal.reason));
3305
+ return (taskExecutor, opts) => {
3306
+ assertFunction(taskExecutor, "taskExecutor");
3307
+ const childAbortController = new AbortController();
3308
+ linkControllers(childAbortController);
3309
+ const result = runTask(async () => {
3310
+ validateActive(parentAbortSignal);
3311
+ validateActive(childAbortController.signal);
3312
+ const result2 = await taskExecutor({
3313
+ pause: createPause(childAbortController.signal),
3314
+ delay: createDelay(childAbortController.signal),
3315
+ signal: childAbortController.signal
3316
+ });
3317
+ validateActive(childAbortController.signal);
3318
+ return result2;
3319
+ }, () => abortControllerWithReason(childAbortController, taskCompleted));
3320
+ if (opts?.autoJoin) {
3321
+ parentBlockingPromises.push(result.catch(noop2));
3322
+ }
3323
+ return {
3324
+ result: createPause(parentAbortSignal)(result),
3325
+ cancel() {
3326
+ abortControllerWithReason(childAbortController, taskCancelled);
3327
+ }
3328
+ };
3329
+ };
3330
+ };
3331
+ var createTakePattern = (startListening, signal) => {
3332
+ const take = async (predicate, timeout) => {
3333
+ validateActive(signal);
3334
+ let unsubscribe = () => {
3335
+ };
3336
+ const tuplePromise = new Promise((resolve, reject) => {
3337
+ let stopListening = startListening({
3338
+ predicate,
3339
+ effect: (action, listenerApi) => {
3340
+ listenerApi.unsubscribe();
3341
+ resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);
3342
+ }
3343
+ });
3344
+ unsubscribe = () => {
3345
+ stopListening();
3346
+ reject();
3347
+ };
3348
+ });
3349
+ const promises = [tuplePromise];
3350
+ if (timeout != null) {
3351
+ promises.push(new Promise((resolve) => setTimeout(resolve, timeout, null)));
3352
+ }
3353
+ try {
3354
+ const output = await raceWithSignal(signal, Promise.race(promises));
3355
+ validateActive(signal);
3356
+ return output;
3357
+ } finally {
3358
+ unsubscribe();
3359
+ }
3360
+ };
3361
+ return (predicate, timeout) => catchRejection(take(predicate, timeout));
3362
+ };
3363
+ var getListenerEntryPropsFrom = (options) => {
3364
+ let {
3365
+ type,
3366
+ actionCreator,
3367
+ matcher,
3368
+ predicate,
3369
+ effect
3370
+ } = options;
3371
+ if (type) {
3372
+ predicate = createAction(type).match;
3373
+ } else if (actionCreator) {
3374
+ type = actionCreator.type;
3375
+ predicate = actionCreator.match;
3376
+ } else if (matcher) {
3377
+ predicate = matcher;
3378
+ } else if (predicate) ; else {
3379
+ 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");
3380
+ }
3381
+ assertFunction(effect, "options.listener");
3382
+ return {
3383
+ predicate,
3384
+ type,
3385
+ effect
3386
+ };
3387
+ };
3388
+ var createListenerEntry = /* @__PURE__ */ assign((options) => {
3389
+ const {
3390
+ type,
3391
+ predicate,
3392
+ effect
3393
+ } = getListenerEntryPropsFrom(options);
3394
+ const id = nanoid();
3395
+ const entry = {
3396
+ id,
3397
+ effect,
3398
+ type,
3399
+ predicate,
3400
+ pending: /* @__PURE__ */ new Set(),
3401
+ unsubscribe: () => {
3402
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(22) : "Unsubscribe not initialized");
3403
+ }
3404
+ };
3405
+ return entry;
3406
+ }, {
3407
+ withTypes: () => createListenerEntry
3408
+ });
3409
+ var cancelActiveListeners = (entry) => {
3410
+ entry.pending.forEach((controller) => {
3411
+ abortControllerWithReason(controller, listenerCancelled);
3412
+ });
3413
+ };
3414
+ var createClearListenerMiddleware = (listenerMap) => {
3415
+ return () => {
3416
+ listenerMap.forEach(cancelActiveListeners);
3417
+ listenerMap.clear();
3418
+ };
3419
+ };
3420
+ var safelyNotifyError = (errorHandler, errorToNotify, errorInfo) => {
3421
+ try {
3422
+ errorHandler(errorToNotify, errorInfo);
3423
+ } catch (errorHandlerError) {
3424
+ setTimeout(() => {
3425
+ throw errorHandlerError;
3426
+ }, 0);
3427
+ }
3428
+ };
3429
+ var addListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/add`), {
3430
+ withTypes: () => addListener
3431
+ });
3432
+ var clearAllListeners = /* @__PURE__ */ createAction(`${alm}/removeAll`);
3433
+ var removeListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/remove`), {
3434
+ withTypes: () => removeListener
3435
+ });
3436
+ var defaultErrorHandler = (...args) => {
3437
+ console.error(`${alm}/error`, ...args);
3438
+ };
3439
+ var createListenerMiddleware = (middlewareOptions = {}) => {
3440
+ const listenerMap = /* @__PURE__ */ new Map();
3441
+ const {
3442
+ extra,
3443
+ onError = defaultErrorHandler
3444
+ } = middlewareOptions;
3445
+ assertFunction(onError, "onError");
3446
+ const insertEntry = (entry) => {
3447
+ entry.unsubscribe = () => listenerMap.delete(entry.id);
3448
+ listenerMap.set(entry.id, entry);
3449
+ return (cancelOptions) => {
3450
+ entry.unsubscribe();
3451
+ if (cancelOptions?.cancelActive) {
3452
+ cancelActiveListeners(entry);
3453
+ }
3454
+ };
3455
+ };
3456
+ const startListening = (options) => {
3457
+ let entry = find(Array.from(listenerMap.values()), (existingEntry) => existingEntry.effect === options.effect);
3458
+ if (!entry) {
3459
+ entry = createListenerEntry(options);
3460
+ }
3461
+ return insertEntry(entry);
3462
+ };
3463
+ assign(startListening, {
3464
+ withTypes: () => startListening
3465
+ });
3466
+ const stopListening = (options) => {
3467
+ const {
3468
+ type,
3469
+ effect,
3470
+ predicate
3471
+ } = getListenerEntryPropsFrom(options);
3472
+ const entry = find(Array.from(listenerMap.values()), (entry2) => {
3473
+ const matchPredicateOrType = typeof type === "string" ? entry2.type === type : entry2.predicate === predicate;
3474
+ return matchPredicateOrType && entry2.effect === effect;
3475
+ });
3476
+ if (entry) {
3477
+ entry.unsubscribe();
3478
+ if (options.cancelActive) {
3479
+ cancelActiveListeners(entry);
3480
+ }
3481
+ }
3482
+ return !!entry;
3483
+ };
3484
+ assign(stopListening, {
3485
+ withTypes: () => stopListening
3486
+ });
3487
+ const notifyListener = async (entry, action, api, getOriginalState) => {
3488
+ const internalTaskController = new AbortController();
3489
+ const take = createTakePattern(startListening, internalTaskController.signal);
3490
+ const autoJoinPromises = [];
3491
+ try {
3492
+ entry.pending.add(internalTaskController);
3493
+ await Promise.resolve(entry.effect(
3494
+ action,
3495
+ // Use assign() rather than ... to avoid extra helper functions added to bundle
3496
+ assign({}, api, {
3497
+ getOriginalState,
3498
+ condition: (predicate, timeout) => take(predicate, timeout).then(Boolean),
3499
+ take,
3500
+ delay: createDelay(internalTaskController.signal),
3501
+ pause: createPause(internalTaskController.signal),
3502
+ extra,
3503
+ signal: internalTaskController.signal,
3504
+ fork: createFork(internalTaskController.signal, autoJoinPromises),
3505
+ unsubscribe: entry.unsubscribe,
3506
+ subscribe: () => {
3507
+ listenerMap.set(entry.id, entry);
3508
+ },
3509
+ cancelActiveListeners: () => {
3510
+ entry.pending.forEach((controller, _, set) => {
3511
+ if (controller !== internalTaskController) {
3512
+ abortControllerWithReason(controller, listenerCancelled);
3513
+ set.delete(controller);
3514
+ }
3515
+ });
3516
+ },
3517
+ cancel: () => {
3518
+ abortControllerWithReason(internalTaskController, listenerCancelled);
3519
+ entry.pending.delete(internalTaskController);
3520
+ },
3521
+ throwIfCancelled: () => {
3522
+ validateActive(internalTaskController.signal);
3523
+ }
3524
+ })
3525
+ ));
3526
+ } catch (listenerError) {
3527
+ if (!(listenerError instanceof TaskAbortError)) {
3528
+ safelyNotifyError(onError, listenerError, {
3529
+ raisedBy: "effect"
3530
+ });
3531
+ }
3532
+ } finally {
3533
+ await Promise.all(autoJoinPromises);
3534
+ abortControllerWithReason(internalTaskController, listenerCompleted);
3535
+ entry.pending.delete(internalTaskController);
3536
+ }
3537
+ };
3538
+ const clearListenerMiddleware = createClearListenerMiddleware(listenerMap);
3539
+ const middleware = (api) => (next) => (action) => {
3540
+ if (!isAction(action)) {
3541
+ return next(action);
3542
+ }
3543
+ if (addListener.match(action)) {
3544
+ return startListening(action.payload);
3545
+ }
3546
+ if (clearAllListeners.match(action)) {
3547
+ clearListenerMiddleware();
3548
+ return;
3549
+ }
3550
+ if (removeListener.match(action)) {
3551
+ return stopListening(action.payload);
3552
+ }
3553
+ let originalState = api.getState();
3554
+ const getOriginalState = () => {
3555
+ if (originalState === INTERNAL_NIL_TOKEN) {
3556
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(23) : `${alm}: getOriginalState can only be called synchronously`);
3557
+ }
3558
+ return originalState;
3559
+ };
3560
+ let result;
3561
+ try {
3562
+ result = next(action);
3563
+ if (listenerMap.size > 0) {
3564
+ const currentState = api.getState();
3565
+ const listenerEntries = Array.from(listenerMap.values());
3566
+ for (const entry of listenerEntries) {
3567
+ let runListener = false;
3568
+ try {
3569
+ runListener = entry.predicate(action, currentState, originalState);
3570
+ } catch (predicateError) {
3571
+ runListener = false;
3572
+ safelyNotifyError(onError, predicateError, {
3573
+ raisedBy: "predicate"
3574
+ });
3575
+ }
3576
+ if (!runListener) {
3577
+ continue;
3578
+ }
3579
+ notifyListener(entry, action, api, getOriginalState);
3580
+ }
3581
+ }
3582
+ } finally {
3583
+ originalState = INTERNAL_NIL_TOKEN;
3584
+ }
3585
+ return result;
3586
+ };
3587
+ return {
3588
+ middleware,
3589
+ startListening,
3590
+ stopListening,
3591
+ clearListeners: clearListenerMiddleware
3592
+ };
3593
+ };
3594
+ var createMiddlewareEntry = (middleware) => ({
3595
+ id: nanoid(),
3596
+ middleware,
3597
+ applied: /* @__PURE__ */ new Map()
3598
+ });
3599
+ var matchInstance = (instanceId) => (action) => action?.meta?.instanceId === instanceId;
3600
+ var createDynamicMiddleware = () => {
3601
+ const instanceId = nanoid();
3602
+ const middlewareMap = /* @__PURE__ */ new Map();
3603
+ const withMiddleware = Object.assign(createAction("dynamicMiddleware/add", (...middlewares) => ({
3604
+ payload: middlewares,
3605
+ meta: {
3606
+ instanceId
3607
+ }
3608
+ })), {
3609
+ withTypes: () => withMiddleware
3610
+ });
3611
+ const addMiddleware = Object.assign(function addMiddleware2(...middlewares) {
3612
+ middlewares.forEach((middleware2) => {
3613
+ let entry = find(Array.from(middlewareMap.values()), (entry2) => entry2.middleware === middleware2);
3614
+ if (!entry) {
3615
+ entry = createMiddlewareEntry(middleware2);
3616
+ }
3617
+ middlewareMap.set(entry.id, entry);
3618
+ });
3619
+ }, {
3620
+ withTypes: () => addMiddleware
3621
+ });
3622
+ const getFinalMiddleware = (api) => {
3623
+ const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) => emplace(entry.applied, api, {
3624
+ insert: () => entry.middleware(api)
3625
+ }));
3626
+ return compose(...appliedMiddleware);
3627
+ };
3628
+ const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));
3629
+ const middleware = (api) => (next) => (action) => {
3630
+ if (isWithMiddleware(action)) {
3631
+ addMiddleware(...action.payload);
3632
+ return api.dispatch;
3633
+ }
3634
+ return getFinalMiddleware(api)(next)(action);
3635
+ };
3636
+ return {
3637
+ middleware,
3638
+ addMiddleware,
3639
+ withMiddleware,
3640
+ instanceId
3641
+ };
3642
+ };
3643
+ var isSliceLike = (maybeSliceLike) => "reducerPath" in maybeSliceLike && typeof maybeSliceLike.reducerPath === "string";
3644
+ var getReducers = (slices) => slices.flatMap((sliceOrMap) => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));
3645
+ var ORIGINAL_STATE = Symbol.for("rtk-state-proxy-original");
3646
+ var isStateProxy = (value) => !!value && !!value[ORIGINAL_STATE];
3647
+ var stateProxyMap = /* @__PURE__ */ new WeakMap();
3648
+ var createStateProxy = (state, reducerMap) => emplace(stateProxyMap, state, {
3649
+ insert: () => new Proxy(state, {
3650
+ get: (target, prop, receiver) => {
3651
+ if (prop === ORIGINAL_STATE) return target;
3652
+ const result = Reflect.get(target, prop, receiver);
3653
+ if (typeof result === "undefined") {
3654
+ const reducer = reducerMap[prop.toString()];
3655
+ if (reducer) {
3656
+ const reducerResult = reducer(void 0, {
3657
+ type: nanoid()
3658
+ });
3659
+ if (typeof reducerResult === "undefined") {
3660
+ 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.`);
3661
+ }
3662
+ return reducerResult;
3663
+ }
3664
+ }
3665
+ return result;
3666
+ }
3667
+ })
3668
+ });
3669
+ var original = (state) => {
3670
+ if (!isStateProxy(state)) {
3671
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(25) : "original must be used on state Proxy");
3672
+ }
3673
+ return state[ORIGINAL_STATE];
3674
+ };
3675
+ var noopReducer = (state = {}) => state;
3676
+ function combineSlices(...slices) {
3677
+ const reducerMap = Object.fromEntries(getReducers(slices));
3678
+ const getReducer = () => Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer;
3679
+ let reducer = getReducer();
3680
+ function combinedReducer(state, action) {
3681
+ return reducer(state, action);
3682
+ }
3683
+ combinedReducer.withLazyLoadedSlices = () => combinedReducer;
3684
+ const inject = (slice, config = {}) => {
3685
+ const {
3686
+ reducerPath,
3687
+ reducer: reducerToInject
3688
+ } = slice;
3689
+ const currentReducer = reducerMap[reducerPath];
3690
+ if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {
3691
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
3692
+ console.error(`called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``);
3693
+ }
3694
+ return combinedReducer;
3695
+ }
3696
+ reducerMap[reducerPath] = reducerToInject;
3697
+ reducer = getReducer();
3698
+ return combinedReducer;
3699
+ };
3700
+ const selector = Object.assign(function makeSelector(selectorFn, selectState) {
3701
+ return function selector2(state, ...args) {
3702
+ return selectorFn(createStateProxy(selectState ? selectState(state, ...args) : state, reducerMap), ...args);
3703
+ };
3704
+ }, {
3705
+ original
3706
+ });
3707
+ return Object.assign(combinedReducer, {
3708
+ inject,
3709
+ selector
3710
+ });
3711
+ }
3712
+
3713
+ // src/formatProdErrorMessage.ts
3714
+ function formatProdErrorMessage(code) {
3715
+ 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. `;
3716
+ }
3717
+
3718
+ export { ReducerType, SHOULD_AUTOBATCH, TaskAbortError, Tuple, actionTypes_default as __DO_NOT_USE__ActionTypes, addListener, applyMiddleware, asyncThunkCreator, autoBatchEnhancer, bindActionCreators, buildCreateSlice, clearAllListeners, combineReducers, combineSlices, compose, configureStore, createAction, createActionCreatorInvariantMiddleware, createAsyncThunk, createDraftSafeSelector, createDraftSafeSelectorCreator, createDynamicMiddleware, createEntityAdapter, createImmutableStateInvariantMiddleware, createListenerMiddleware, produce as createNextState, createReducer, createSelector, createSelectorCreator, createSerializableStateInvariantMiddleware, createSlice, createStore, current, findNonSerializableValue, formatProdErrorMessage, freeze, isAction, isActionCreator, isAllOf, isAnyOf, isAsyncThunkAction, isDraft, isFSA as isFluxStandardAction, isFulfilled, isImmutableDefault, isPending, isPlain, isPlainObject$1 as isPlainObject, isRejected, isRejectedWithValue, legacy_createStore, lruMemoize, miniSerializeError, nanoid, original$1 as original, prepareAutoBatched, removeListener, unwrapResult, weakMapMemoize };
2
3719
  //# sourceMappingURL=index.es.js.map