UNPKG

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