UNPKG

61.7 kBJavaScriptView Raw
1var __defProp = Object.defineProperty;
2var __defProps = Object.defineProperties;
3var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5var __hasOwnProp = Object.prototype.hasOwnProperty;
6var __propIsEnum = Object.prototype.propertyIsEnumerable;
7var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8var __spreadValues = (a, b) => {
9 for (var prop in b || (b = {}))
10 if (__hasOwnProp.call(b, prop))
11 __defNormalProp(a, prop, b[prop]);
12 if (__getOwnPropSymbols)
13 for (var prop of __getOwnPropSymbols(b)) {
14 if (__propIsEnum.call(b, prop))
15 __defNormalProp(a, prop, b[prop]);
16 }
17 return a;
18};
19var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20// src/index.ts
21import { enableES5 } from "immer";
22export * from "redux";
23import { default as default2, current as current2, freeze, original, isDraft as isDraft4 } from "immer";
24import { createSelector as createSelector2 } from "reselect";
25// src/createDraftSafeSelector.ts
26import { current, isDraft } from "immer";
27import { createSelector } from "reselect";
28var createDraftSafeSelector = (...args) => {
29 const selector = createSelector(...args);
30 const wrappedSelector = (value, ...rest) => selector(isDraft(value) ? current(value) : value, ...rest);
31 return wrappedSelector;
32};
33// src/configureStore.ts
34import { createStore, compose as compose2, applyMiddleware, combineReducers } from "redux";
35// src/devtoolsExtension.ts
36import { compose } from "redux";
37var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () {
38 if (arguments.length === 0)
39 return void 0;
40 if (typeof arguments[0] === "object")
41 return compose;
42 return compose.apply(null, arguments);
43};
44var devToolsEnhancer = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function () {
45 return function (noop2) {
46 return noop2;
47 };
48};
49// src/isPlainObject.ts
50function isPlainObject(value) {
51 if (typeof value !== "object" || value === null)
52 return false;
53 let proto = Object.getPrototypeOf(value);
54 if (proto === null)
55 return true;
56 let baseProto = proto;
57 while (Object.getPrototypeOf(baseProto) !== null) {
58 baseProto = Object.getPrototypeOf(baseProto);
59 }
60 return proto === baseProto;
61}
62// src/getDefaultMiddleware.ts
63import thunkMiddleware from "redux-thunk";
64// src/utils.ts
65import createNextState, { isDraftable } from "immer";
66function getTimeMeasureUtils(maxDelay, fnName) {
67 let elapsed = 0;
68 return {
69 measureTime(fn) {
70 const started = Date.now();
71 try {
72 return fn();
73 }
74 finally {
75 const finished = Date.now();
76 elapsed += finished - started;
77 }
78 },
79 warnIfExceeded() {
80 if (elapsed > maxDelay) {
81 console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms.
82If 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.
83It is disabled in production builds, so you don't need to worry about that.`);
84 }
85 }
86 };
87}
88var MiddlewareArray = class extends Array {
89 constructor(...args) {
90 super(...args);
91 Object.setPrototypeOf(this, MiddlewareArray.prototype);
92 }
93 static get [Symbol.species]() {
94 return MiddlewareArray;
95 }
96 concat(...arr) {
97 return super.concat.apply(this, arr);
98 }
99 prepend(...arr) {
100 if (arr.length === 1 && Array.isArray(arr[0])) {
101 return new MiddlewareArray(...arr[0].concat(this));
102 }
103 return new MiddlewareArray(...arr.concat(this));
104 }
105};
106function freezeDraftable(val) {
107 return isDraftable(val) ? createNextState(val, () => {
108 }) : val;
109}
110// src/immutableStateInvariantMiddleware.ts
111var isProduction = process.env.NODE_ENV === "production";
112var prefix = "Invariant failed";
113function invariant(condition, message) {
114 if (condition) {
115 return;
116 }
117 if (isProduction) {
118 throw new Error(prefix);
119 }
120 throw new Error(`${prefix}: ${message || ""}`);
121}
122function stringify(obj, serializer, indent, decycler) {
123 return JSON.stringify(obj, getSerialize(serializer, decycler), indent);
124}
125function getSerialize(serializer, decycler) {
126 let stack = [], keys = [];
127 if (!decycler)
128 decycler = function (_, value) {
129 if (stack[0] === value)
130 return "[Circular ~]";
131 return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
132 };
133 return function (key, value) {
134 if (stack.length > 0) {
135 var thisPos = stack.indexOf(this);
136 ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
137 ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
138 if (~stack.indexOf(value))
139 value = decycler.call(this, key, value);
140 }
141 else
142 stack.push(value);
143 return serializer == null ? value : serializer.call(this, key, value);
144 };
145}
146function isImmutableDefault(value) {
147 return typeof value !== "object" || value === null || typeof value === "undefined" || Object.isFrozen(value);
148}
149function trackForMutations(isImmutable, ignorePaths, obj) {
150 const trackedProperties = trackProperties(isImmutable, ignorePaths, obj);
151 return {
152 detectMutations() {
153 return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);
154 }
155 };
156}
157function trackProperties(isImmutable, ignorePaths = [], obj, path = "") {
158 const tracked = { value: obj };
159 if (!isImmutable(obj)) {
160 tracked.children = {};
161 for (const key in obj) {
162 const childPath = path ? path + "." + key : key;
163 if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {
164 continue;
165 }
166 tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);
167 }
168 }
169 return tracked;
170}
171function detectMutations(isImmutable, ignorePaths = [], trackedProperty, obj, sameParentRef = false, path = "") {
172 const prevObj = trackedProperty ? trackedProperty.value : void 0;
173 const sameRef = prevObj === obj;
174 if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
175 return { wasMutated: true, path };
176 }
177 if (isImmutable(prevObj) || isImmutable(obj)) {
178 return { wasMutated: false };
179 }
180 const keysToDetect = {};
181 for (let key in trackedProperty.children) {
182 keysToDetect[key] = true;
183 }
184 for (let key in obj) {
185 keysToDetect[key] = true;
186 }
187 for (let key in keysToDetect) {
188 const childPath = path ? path + "." + key : key;
189 if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {
190 continue;
191 }
192 const result = detectMutations(isImmutable, ignorePaths, trackedProperty.children[key], obj[key], sameRef, childPath);
193 if (result.wasMutated) {
194 return result;
195 }
196 }
197 return { wasMutated: false };
198}
199function createImmutableStateInvariantMiddleware(options = {}) {
200 if (process.env.NODE_ENV === "production") {
201 return () => (next) => (action) => next(action);
202 }
203 let { isImmutable = isImmutableDefault, ignoredPaths, warnAfter = 32, ignore } = options;
204 ignoredPaths = ignoredPaths || ignore;
205 const track = trackForMutations.bind(null, isImmutable, ignoredPaths);
206 return ({ getState }) => {
207 let state = getState();
208 let tracker = track(state);
209 let result;
210 return (next) => (action) => {
211 const measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
212 measureUtils.measureTime(() => {
213 state = getState();
214 result = tracker.detectMutations();
215 tracker = track(state);
216 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)`);
217 });
218 const dispatchedAction = next(action);
219 measureUtils.measureTime(() => {
220 state = getState();
221 result = tracker.detectMutations();
222 tracker = track(state);
223 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)`);
224 });
225 measureUtils.warnIfExceeded();
226 return dispatchedAction;
227 };
228 };
229}
230// src/serializableStateInvariantMiddleware.ts
231function isPlain(val) {
232 const type = typeof val;
233 return type === "undefined" || val === null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || isPlainObject(val);
234}
235function findNonSerializableValue(value, path = "", isSerializable = isPlain, getEntries, ignoredPaths = []) {
236 let foundNestedSerializable;
237 if (!isSerializable(value)) {
238 return {
239 keyPath: path || "<root>",
240 value
241 };
242 }
243 if (typeof value !== "object" || value === null) {
244 return false;
245 }
246 const entries = getEntries != null ? getEntries(value) : Object.entries(value);
247 const hasIgnoredPaths = ignoredPaths.length > 0;
248 for (const [key, nestedValue] of entries) {
249 const nestedPath = path ? path + "." + key : key;
250 if (hasIgnoredPaths && ignoredPaths.indexOf(nestedPath) >= 0) {
251 continue;
252 }
253 if (!isSerializable(nestedValue)) {
254 return {
255 keyPath: nestedPath,
256 value: nestedValue
257 };
258 }
259 if (typeof nestedValue === "object") {
260 foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths);
261 if (foundNestedSerializable) {
262 return foundNestedSerializable;
263 }
264 }
265 }
266 return false;
267}
268function createSerializableStateInvariantMiddleware(options = {}) {
269 if (process.env.NODE_ENV === "production") {
270 return () => (next) => (action) => next(action);
271 }
272 const { isSerializable = isPlain, getEntries, ignoredActions = [], ignoredActionPaths = ["meta.arg", "meta.baseQueryMeta"], ignoredPaths = [], warnAfter = 32, ignoreState = false, ignoreActions = false } = options;
273 return (storeAPI) => (next) => (action) => {
274 const result = next(action);
275 const measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
276 if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {
277 measureUtils.measureTime(() => {
278 const foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths);
279 if (foundActionNonSerializableValue) {
280 const { keyPath, value } = foundActionNonSerializableValue;
281 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)");
282 }
283 });
284 }
285 if (!ignoreState) {
286 measureUtils.measureTime(() => {
287 const state = storeAPI.getState();
288 const foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths);
289 if (foundStateNonSerializableValue) {
290 const { keyPath, value } = foundStateNonSerializableValue;
291 console.error(`A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`, value, `
292Take a look at the reducer(s) handling this action type: ${action.type}.
293(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);
294 }
295 });
296 measureUtils.warnIfExceeded();
297 }
298 return result;
299 };
300}
301// src/getDefaultMiddleware.ts
302function isBoolean(x) {
303 return typeof x === "boolean";
304}
305function curryGetDefaultMiddleware() {
306 return function curriedGetDefaultMiddleware(options) {
307 return getDefaultMiddleware(options);
308 };
309}
310function getDefaultMiddleware(options = {}) {
311 const { thunk = true, immutableCheck = true, serializableCheck = true } = options;
312 let middlewareArray = new MiddlewareArray();
313 if (thunk) {
314 if (isBoolean(thunk)) {
315 middlewareArray.push(thunkMiddleware);
316 }
317 else {
318 middlewareArray.push(thunkMiddleware.withExtraArgument(thunk.extraArgument));
319 }
320 }
321 if (process.env.NODE_ENV !== "production") {
322 if (immutableCheck) {
323 let immutableOptions = {};
324 if (!isBoolean(immutableCheck)) {
325 immutableOptions = immutableCheck;
326 }
327 middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
328 }
329 if (serializableCheck) {
330 let serializableOptions = {};
331 if (!isBoolean(serializableCheck)) {
332 serializableOptions = serializableCheck;
333 }
334 middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
335 }
336 }
337 return middlewareArray;
338}
339// src/configureStore.ts
340var IS_PRODUCTION = process.env.NODE_ENV === "production";
341function configureStore(options) {
342 const curriedGetDefaultMiddleware = curryGetDefaultMiddleware();
343 const { reducer = void 0, middleware = curriedGetDefaultMiddleware(), devTools = true, preloadedState = void 0, enhancers = void 0 } = options || {};
344 let rootReducer;
345 if (typeof reducer === "function") {
346 rootReducer = reducer;
347 }
348 else if (isPlainObject(reducer)) {
349 rootReducer = combineReducers(reducer);
350 }
351 else {
352 throw new Error('"reducer" is a required argument, and must be a function or an object of functions that can be passed to combineReducers');
353 }
354 let finalMiddleware = middleware;
355 if (typeof finalMiddleware === "function") {
356 finalMiddleware = finalMiddleware(curriedGetDefaultMiddleware);
357 if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {
358 throw new Error("when using a middleware builder function, an array of middleware must be returned");
359 }
360 }
361 if (!IS_PRODUCTION && finalMiddleware.some((item) => typeof item !== "function")) {
362 throw new Error("each middleware provided to configureStore must be a function");
363 }
364 const middlewareEnhancer = applyMiddleware(...finalMiddleware);
365 let finalCompose = compose2;
366 if (devTools) {
367 finalCompose = composeWithDevTools(__spreadValues({
368 trace: !IS_PRODUCTION
369 }, typeof devTools === "object" && devTools));
370 }
371 let storeEnhancers = [middlewareEnhancer];
372 if (Array.isArray(enhancers)) {
373 storeEnhancers = [middlewareEnhancer, ...enhancers];
374 }
375 else if (typeof enhancers === "function") {
376 storeEnhancers = enhancers(storeEnhancers);
377 }
378 const composedEnhancer = finalCompose(...storeEnhancers);
379 return createStore(rootReducer, preloadedState, composedEnhancer);
380}
381// src/createAction.ts
382function createAction(type, prepareAction) {
383 function actionCreator(...args) {
384 if (prepareAction) {
385 let prepared = prepareAction(...args);
386 if (!prepared) {
387 throw new Error("prepareAction did not return an object");
388 }
389 return __spreadValues(__spreadValues({
390 type,
391 payload: prepared.payload
392 }, "meta" in prepared && { meta: prepared.meta }), "error" in prepared && { error: prepared.error });
393 }
394 return { type, payload: args[0] };
395 }
396 actionCreator.toString = () => `${type}`;
397 actionCreator.type = type;
398 actionCreator.match = (action) => action.type === type;
399 return actionCreator;
400}
401function isFSA(action) {
402 return isPlainObject(action) && typeof action.type === "string" && Object.keys(action).every(isValidKey);
403}
404function isValidKey(key) {
405 return ["type", "payload", "error", "meta"].indexOf(key) > -1;
406}
407function getType(actionCreator) {
408 return `${actionCreator}`;
409}
410// src/createReducer.ts
411import createNextState2, { isDraft as isDraft2, isDraftable as isDraftable2 } from "immer";
412// src/mapBuilders.ts
413function executeReducerBuilderCallback(builderCallback) {
414 const actionsMap = {};
415 const actionMatchers = [];
416 let defaultCaseReducer;
417 const builder = {
418 addCase(typeOrActionCreator, reducer) {
419 if (process.env.NODE_ENV !== "production") {
420 if (actionMatchers.length > 0) {
421 throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");
422 }
423 if (defaultCaseReducer) {
424 throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`");
425 }
426 }
427 const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
428 if (type in actionsMap) {
429 throw new Error("addCase cannot be called with two reducers for the same action type");
430 }
431 actionsMap[type] = reducer;
432 return builder;
433 },
434 addMatcher(matcher, reducer) {
435 if (process.env.NODE_ENV !== "production") {
436 if (defaultCaseReducer) {
437 throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
438 }
439 }
440 actionMatchers.push({ matcher, reducer });
441 return builder;
442 },
443 addDefaultCase(reducer) {
444 if (process.env.NODE_ENV !== "production") {
445 if (defaultCaseReducer) {
446 throw new Error("`builder.addDefaultCase` can only be called once");
447 }
448 }
449 defaultCaseReducer = reducer;
450 return builder;
451 }
452 };
453 builderCallback(builder);
454 return [actionsMap, actionMatchers, defaultCaseReducer];
455}
456// src/createReducer.ts
457function isStateFunction(x) {
458 return typeof x === "function";
459}
460function createReducer(initialState, mapOrBuilderCallback, actionMatchers = [], defaultCaseReducer) {
461 let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = typeof mapOrBuilderCallback === "function" ? executeReducerBuilderCallback(mapOrBuilderCallback) : [mapOrBuilderCallback, actionMatchers, defaultCaseReducer];
462 let getInitialState;
463 if (isStateFunction(initialState)) {
464 getInitialState = () => freezeDraftable(initialState());
465 }
466 else {
467 const frozenInitialState = freezeDraftable(initialState);
468 getInitialState = () => frozenInitialState;
469 }
470 function reducer(state = getInitialState(), action) {
471 let caseReducers = [
472 actionsMap[action.type],
473 ...finalActionMatchers.filter(({ matcher }) => matcher(action)).map(({ reducer: reducer2 }) => reducer2)
474 ];
475 if (caseReducers.filter((cr) => !!cr).length === 0) {
476 caseReducers = [finalDefaultCaseReducer];
477 }
478 return caseReducers.reduce((previousState, caseReducer) => {
479 if (caseReducer) {
480 if (isDraft2(previousState)) {
481 const draft = previousState;
482 const result = caseReducer(draft, action);
483 if (typeof result === "undefined") {
484 return previousState;
485 }
486 return result;
487 }
488 else if (!isDraftable2(previousState)) {
489 const result = caseReducer(previousState, action);
490 if (typeof result === "undefined") {
491 if (previousState === null) {
492 return previousState;
493 }
494 throw Error("A case reducer on a non-draftable value must not return undefined");
495 }
496 return result;
497 }
498 else {
499 return createNextState2(previousState, (draft) => {
500 return caseReducer(draft, action);
501 });
502 }
503 }
504 return previousState;
505 }, state);
506 }
507 reducer.getInitialState = getInitialState;
508 return reducer;
509}
510// src/createSlice.ts
511function getType2(slice, actionKey) {
512 return `${slice}/${actionKey}`;
513}
514function createSlice(options) {
515 const { name } = options;
516 if (!name) {
517 throw new Error("`name` is a required option for createSlice");
518 }
519 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
520 if (options.initialState === void 0) {
521 console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");
522 }
523 }
524 const initialState = typeof options.initialState == "function" ? options.initialState : freezeDraftable(options.initialState);
525 const reducers = options.reducers || {};
526 const reducerNames = Object.keys(reducers);
527 const sliceCaseReducersByName = {};
528 const sliceCaseReducersByType = {};
529 const actionCreators = {};
530 reducerNames.forEach((reducerName) => {
531 const maybeReducerWithPrepare = reducers[reducerName];
532 const type = getType2(name, reducerName);
533 let caseReducer;
534 let prepareCallback;
535 if ("reducer" in maybeReducerWithPrepare) {
536 caseReducer = maybeReducerWithPrepare.reducer;
537 prepareCallback = maybeReducerWithPrepare.prepare;
538 }
539 else {
540 caseReducer = maybeReducerWithPrepare;
541 }
542 sliceCaseReducersByName[reducerName] = caseReducer;
543 sliceCaseReducersByType[type] = caseReducer;
544 actionCreators[reducerName] = prepareCallback ? createAction(type, prepareCallback) : createAction(type);
545 });
546 function buildReducer() {
547 const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];
548 const finalCaseReducers = __spreadValues(__spreadValues({}, extraReducers), sliceCaseReducersByType);
549 return createReducer(initialState, finalCaseReducers, actionMatchers, defaultCaseReducer);
550 }
551 let _reducer;
552 return {
553 name,
554 reducer(state, action) {
555 if (!_reducer)
556 _reducer = buildReducer();
557 return _reducer(state, action);
558 },
559 actions: actionCreators,
560 caseReducers: sliceCaseReducersByName,
561 getInitialState() {
562 if (!_reducer)
563 _reducer = buildReducer();
564 return _reducer.getInitialState();
565 }
566 };
567}
568// src/entities/entity_state.ts
569function getInitialEntityState() {
570 return {
571 ids: [],
572 entities: {}
573 };
574}
575function createInitialStateFactory() {
576 function getInitialState(additionalState = {}) {
577 return Object.assign(getInitialEntityState(), additionalState);
578 }
579 return { getInitialState };
580}
581// src/entities/state_selectors.ts
582function createSelectorsFactory() {
583 function getSelectors(selectState) {
584 const selectIds = (state) => state.ids;
585 const selectEntities = (state) => state.entities;
586 const selectAll = createDraftSafeSelector(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));
587 const selectId = (_, id) => id;
588 const selectById = (entities, id) => entities[id];
589 const selectTotal = createDraftSafeSelector(selectIds, (ids) => ids.length);
590 if (!selectState) {
591 return {
592 selectIds,
593 selectEntities,
594 selectAll,
595 selectTotal,
596 selectById: createDraftSafeSelector(selectEntities, selectId, selectById)
597 };
598 }
599 const selectGlobalizedEntities = createDraftSafeSelector(selectState, selectEntities);
600 return {
601 selectIds: createDraftSafeSelector(selectState, selectIds),
602 selectEntities: selectGlobalizedEntities,
603 selectAll: createDraftSafeSelector(selectState, selectAll),
604 selectTotal: createDraftSafeSelector(selectState, selectTotal),
605 selectById: createDraftSafeSelector(selectGlobalizedEntities, selectId, selectById)
606 };
607 }
608 return { getSelectors };
609}
610// src/entities/state_adapter.ts
611import createNextState3, { isDraft as isDraft3 } from "immer";
612function createSingleArgumentStateOperator(mutator) {
613 const operator = createStateOperator((_, state) => mutator(state));
614 return function operation(state) {
615 return operator(state, void 0);
616 };
617}
618function createStateOperator(mutator) {
619 return function operation(state, arg) {
620 function isPayloadActionArgument(arg2) {
621 return isFSA(arg2);
622 }
623 const runMutator = (draft) => {
624 if (isPayloadActionArgument(arg)) {
625 mutator(arg.payload, draft);
626 }
627 else {
628 mutator(arg, draft);
629 }
630 };
631 if (isDraft3(state)) {
632 runMutator(state);
633 return state;
634 }
635 else {
636 return createNextState3(state, runMutator);
637 }
638 };
639}
640// src/entities/utils.ts
641function selectIdValue(entity, selectId) {
642 const key = selectId(entity);
643 if (process.env.NODE_ENV !== "production" && key === void 0) {
644 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());
645 }
646 return key;
647}
648function ensureEntitiesArray(entities) {
649 if (!Array.isArray(entities)) {
650 entities = Object.values(entities);
651 }
652 return entities;
653}
654function splitAddedUpdatedEntities(newEntities, selectId, state) {
655 newEntities = ensureEntitiesArray(newEntities);
656 const added = [];
657 const updated = [];
658 for (const entity of newEntities) {
659 const id = selectIdValue(entity, selectId);
660 if (id in state.entities) {
661 updated.push({ id, changes: entity });
662 }
663 else {
664 added.push(entity);
665 }
666 }
667 return [added, updated];
668}
669// src/entities/unsorted_state_adapter.ts
670function createUnsortedStateAdapter(selectId) {
671 function addOneMutably(entity, state) {
672 const key = selectIdValue(entity, selectId);
673 if (key in state.entities) {
674 return;
675 }
676 state.ids.push(key);
677 state.entities[key] = entity;
678 }
679 function addManyMutably(newEntities, state) {
680 newEntities = ensureEntitiesArray(newEntities);
681 for (const entity of newEntities) {
682 addOneMutably(entity, state);
683 }
684 }
685 function setOneMutably(entity, state) {
686 const key = selectIdValue(entity, selectId);
687 if (!(key in state.entities)) {
688 state.ids.push(key);
689 }
690 state.entities[key] = entity;
691 }
692 function setManyMutably(newEntities, state) {
693 newEntities = ensureEntitiesArray(newEntities);
694 for (const entity of newEntities) {
695 setOneMutably(entity, state);
696 }
697 }
698 function setAllMutably(newEntities, state) {
699 newEntities = ensureEntitiesArray(newEntities);
700 state.ids = [];
701 state.entities = {};
702 addManyMutably(newEntities, state);
703 }
704 function removeOneMutably(key, state) {
705 return removeManyMutably([key], state);
706 }
707 function removeManyMutably(keys, state) {
708 let didMutate = false;
709 keys.forEach((key) => {
710 if (key in state.entities) {
711 delete state.entities[key];
712 didMutate = true;
713 }
714 });
715 if (didMutate) {
716 state.ids = state.ids.filter((id) => id in state.entities);
717 }
718 }
719 function removeAllMutably(state) {
720 Object.assign(state, {
721 ids: [],
722 entities: {}
723 });
724 }
725 function takeNewKey(keys, update, state) {
726 const original2 = state.entities[update.id];
727 const updated = Object.assign({}, original2, update.changes);
728 const newKey = selectIdValue(updated, selectId);
729 const hasNewKey = newKey !== update.id;
730 if (hasNewKey) {
731 keys[update.id] = newKey;
732 delete state.entities[update.id];
733 }
734 state.entities[newKey] = updated;
735 return hasNewKey;
736 }
737 function updateOneMutably(update, state) {
738 return updateManyMutably([update], state);
739 }
740 function updateManyMutably(updates, state) {
741 const newKeys = {};
742 const updatesPerEntity = {};
743 updates.forEach((update) => {
744 if (update.id in state.entities) {
745 updatesPerEntity[update.id] = {
746 id: update.id,
747 changes: __spreadValues(__spreadValues({}, updatesPerEntity[update.id] ? updatesPerEntity[update.id].changes : null), update.changes)
748 };
749 }
750 });
751 updates = Object.values(updatesPerEntity);
752 const didMutateEntities = updates.length > 0;
753 if (didMutateEntities) {
754 const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0;
755 if (didMutateIds) {
756 state.ids = state.ids.map((id) => newKeys[id] || id);
757 }
758 }
759 }
760 function upsertOneMutably(entity, state) {
761 return upsertManyMutably([entity], state);
762 }
763 function upsertManyMutably(newEntities, state) {
764 const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
765 updateManyMutably(updated, state);
766 addManyMutably(added, state);
767 }
768 return {
769 removeAll: createSingleArgumentStateOperator(removeAllMutably),
770 addOne: createStateOperator(addOneMutably),
771 addMany: createStateOperator(addManyMutably),
772 setOne: createStateOperator(setOneMutably),
773 setMany: createStateOperator(setManyMutably),
774 setAll: createStateOperator(setAllMutably),
775 updateOne: createStateOperator(updateOneMutably),
776 updateMany: createStateOperator(updateManyMutably),
777 upsertOne: createStateOperator(upsertOneMutably),
778 upsertMany: createStateOperator(upsertManyMutably),
779 removeOne: createStateOperator(removeOneMutably),
780 removeMany: createStateOperator(removeManyMutably)
781 };
782}
783// src/entities/sorted_state_adapter.ts
784function createSortedStateAdapter(selectId, sort) {
785 const { removeOne, removeMany, removeAll } = createUnsortedStateAdapter(selectId);
786 function addOneMutably(entity, state) {
787 return addManyMutably([entity], state);
788 }
789 function addManyMutably(newEntities, state) {
790 newEntities = ensureEntitiesArray(newEntities);
791 const models = newEntities.filter((model) => !(selectIdValue(model, selectId) in state.entities));
792 if (models.length !== 0) {
793 merge(models, state);
794 }
795 }
796 function setOneMutably(entity, state) {
797 return setManyMutably([entity], state);
798 }
799 function setManyMutably(newEntities, state) {
800 newEntities = ensureEntitiesArray(newEntities);
801 if (newEntities.length !== 0) {
802 merge(newEntities, state);
803 }
804 }
805 function setAllMutably(newEntities, state) {
806 newEntities = ensureEntitiesArray(newEntities);
807 state.entities = {};
808 state.ids = [];
809 addManyMutably(newEntities, state);
810 }
811 function updateOneMutably(update, state) {
812 return updateManyMutably([update], state);
813 }
814 function updateManyMutably(updates, state) {
815 let appliedUpdates = false;
816 for (let update of updates) {
817 const entity = state.entities[update.id];
818 if (!entity) {
819 continue;
820 }
821 appliedUpdates = true;
822 Object.assign(entity, update.changes);
823 const newId = selectId(entity);
824 if (update.id !== newId) {
825 delete state.entities[update.id];
826 state.entities[newId] = entity;
827 }
828 }
829 if (appliedUpdates) {
830 resortEntities(state);
831 }
832 }
833 function upsertOneMutably(entity, state) {
834 return upsertManyMutably([entity], state);
835 }
836 function upsertManyMutably(newEntities, state) {
837 const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
838 updateManyMutably(updated, state);
839 addManyMutably(added, state);
840 }
841 function areArraysEqual(a, b) {
842 if (a.length !== b.length) {
843 return false;
844 }
845 for (let i = 0; i < a.length && i < b.length; i++) {
846 if (a[i] === b[i]) {
847 continue;
848 }
849 return false;
850 }
851 return true;
852 }
853 function merge(models, state) {
854 models.forEach((model) => {
855 state.entities[selectId(model)] = model;
856 });
857 resortEntities(state);
858 }
859 function resortEntities(state) {
860 const allEntities = Object.values(state.entities);
861 allEntities.sort(sort);
862 const newSortedIds = allEntities.map(selectId);
863 const { ids } = state;
864 if (!areArraysEqual(ids, newSortedIds)) {
865 state.ids = newSortedIds;
866 }
867 }
868 return {
869 removeOne,
870 removeMany,
871 removeAll,
872 addOne: createStateOperator(addOneMutably),
873 updateOne: createStateOperator(updateOneMutably),
874 upsertOne: createStateOperator(upsertOneMutably),
875 setOne: createStateOperator(setOneMutably),
876 setMany: createStateOperator(setManyMutably),
877 setAll: createStateOperator(setAllMutably),
878 addMany: createStateOperator(addManyMutably),
879 updateMany: createStateOperator(updateManyMutably),
880 upsertMany: createStateOperator(upsertManyMutably)
881 };
882}
883// src/entities/create_adapter.ts
884function createEntityAdapter(options = {}) {
885 const { selectId, sortComparer } = __spreadValues({
886 sortComparer: false,
887 selectId: (instance) => instance.id
888 }, options);
889 const stateFactory = createInitialStateFactory();
890 const selectorsFactory = createSelectorsFactory();
891 const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
892 return __spreadValues(__spreadValues(__spreadValues({
893 selectId,
894 sortComparer
895 }, stateFactory), selectorsFactory), stateAdapter);
896}
897// src/nanoid.ts
898var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
899var nanoid = (size = 21) => {
900 let id = "";
901 let i = size;
902 while (i--) {
903 id += urlAlphabet[Math.random() * 64 | 0];
904 }
905 return id;
906};
907// src/createAsyncThunk.ts
908var commonProperties = [
909 "name",
910 "message",
911 "stack",
912 "code"
913];
914var RejectWithValue = class {
915 constructor(payload, meta) {
916 this.payload = payload;
917 this.meta = meta;
918 }
919};
920var FulfillWithMeta = class {
921 constructor(payload, meta) {
922 this.payload = payload;
923 this.meta = meta;
924 }
925};
926var miniSerializeError = (value) => {
927 if (typeof value === "object" && value !== null) {
928 const simpleError = {};
929 for (const property of commonProperties) {
930 if (typeof value[property] === "string") {
931 simpleError[property] = value[property];
932 }
933 }
934 return simpleError;
935 }
936 return { message: String(value) };
937};
938function createAsyncThunk(typePrefix, payloadCreator, options) {
939 const fulfilled = createAction(typePrefix + "/fulfilled", (payload, requestId, arg, meta) => ({
940 payload,
941 meta: __spreadProps(__spreadValues({}, meta || {}), {
942 arg,
943 requestId,
944 requestStatus: "fulfilled"
945 })
946 }));
947 const pending = createAction(typePrefix + "/pending", (requestId, arg, meta) => ({
948 payload: void 0,
949 meta: __spreadProps(__spreadValues({}, meta || {}), {
950 arg,
951 requestId,
952 requestStatus: "pending"
953 })
954 }));
955 const rejected = createAction(typePrefix + "/rejected", (error, requestId, arg, payload, meta) => ({
956 payload,
957 error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
958 meta: __spreadProps(__spreadValues({}, meta || {}), {
959 arg,
960 requestId,
961 rejectedWithValue: !!payload,
962 requestStatus: "rejected",
963 aborted: (error == null ? void 0 : error.name) === "AbortError",
964 condition: (error == null ? void 0 : error.name) === "ConditionError"
965 })
966 }));
967 let displayedWarning = false;
968 const AC = typeof AbortController !== "undefined" ? AbortController : class {
969 constructor() {
970 this.signal = {
971 aborted: false,
972 addEventListener() {
973 },
974 dispatchEvent() {
975 return false;
976 },
977 onabort() {
978 },
979 removeEventListener() {
980 },
981 reason: void 0,
982 throwIfAborted() {
983 }
984 };
985 }
986 abort() {
987 if (process.env.NODE_ENV !== "production") {
988 if (!displayedWarning) {
989 displayedWarning = true;
990 console.info(`This platform does not implement AbortController.
991If you want to use the AbortController to react to \`abort\` events, please consider importing a polyfill like 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'.`);
992 }
993 }
994 }
995 };
996 function actionCreator(arg) {
997 return (dispatch, getState, extra) => {
998 const requestId = (options == null ? void 0 : options.idGenerator) ? options.idGenerator(arg) : nanoid();
999 const abortController = new AC();
1000 let abortReason;
1001 const abortedPromise = new Promise((_, reject) => abortController.signal.addEventListener("abort", () => reject({ name: "AbortError", message: abortReason || "Aborted" })));
1002 let started = false;
1003 function abort(reason) {
1004 if (started) {
1005 abortReason = reason;
1006 abortController.abort();
1007 }
1008 }
1009 const promise = async function () {
1010 var _a, _b;
1011 let finalAction;
1012 try {
1013 let conditionResult = (_a = options == null ? void 0 : options.condition) == null ? void 0 : _a.call(options, arg, { getState, extra });
1014 if (isThenable(conditionResult)) {
1015 conditionResult = await conditionResult;
1016 }
1017 if (conditionResult === false) {
1018 throw {
1019 name: "ConditionError",
1020 message: "Aborted due to condition callback returning false."
1021 };
1022 }
1023 started = true;
1024 dispatch(pending(requestId, arg, (_b = options == null ? void 0 : options.getPendingMeta) == null ? void 0 : _b.call(options, { requestId, arg }, { getState, extra })));
1025 finalAction = await Promise.race([
1026 abortedPromise,
1027 Promise.resolve(payloadCreator(arg, {
1028 dispatch,
1029 getState,
1030 extra,
1031 requestId,
1032 signal: abortController.signal,
1033 rejectWithValue: (value, meta) => {
1034 return new RejectWithValue(value, meta);
1035 },
1036 fulfillWithValue: (value, meta) => {
1037 return new FulfillWithMeta(value, meta);
1038 }
1039 })).then((result) => {
1040 if (result instanceof RejectWithValue) {
1041 throw result;
1042 }
1043 if (result instanceof FulfillWithMeta) {
1044 return fulfilled(result.payload, requestId, arg, result.meta);
1045 }
1046 return fulfilled(result, requestId, arg);
1047 })
1048 ]);
1049 }
1050 catch (err) {
1051 finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);
1052 }
1053 const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;
1054 if (!skipDispatch) {
1055 dispatch(finalAction);
1056 }
1057 return finalAction;
1058 }();
1059 return Object.assign(promise, {
1060 abort,
1061 requestId,
1062 arg,
1063 unwrap() {
1064 return promise.then(unwrapResult);
1065 }
1066 });
1067 };
1068 }
1069 return Object.assign(actionCreator, {
1070 pending,
1071 rejected,
1072 fulfilled,
1073 typePrefix
1074 });
1075}
1076function unwrapResult(action) {
1077 if (action.meta && action.meta.rejectedWithValue) {
1078 throw action.payload;
1079 }
1080 if (action.error) {
1081 throw action.error;
1082 }
1083 return action.payload;
1084}
1085function isThenable(value) {
1086 return value !== null && typeof value === "object" && typeof value.then === "function";
1087}
1088// src/tsHelpers.ts
1089var hasMatchFunction = (v) => {
1090 return v && typeof v.match === "function";
1091};
1092// src/matchers.ts
1093var matches = (matcher, action) => {
1094 if (hasMatchFunction(matcher)) {
1095 return matcher.match(action);
1096 }
1097 else {
1098 return matcher(action);
1099 }
1100};
1101function isAnyOf(...matchers) {
1102 return (action) => {
1103 return matchers.some((matcher) => matches(matcher, action));
1104 };
1105}
1106function isAllOf(...matchers) {
1107 return (action) => {
1108 return matchers.every((matcher) => matches(matcher, action));
1109 };
1110}
1111function hasExpectedRequestMetadata(action, validStatus) {
1112 if (!action || !action.meta)
1113 return false;
1114 const hasValidRequestId = typeof action.meta.requestId === "string";
1115 const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
1116 return hasValidRequestId && hasValidRequestStatus;
1117}
1118function isAsyncThunkArray(a) {
1119 return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
1120}
1121function isPending(...asyncThunks) {
1122 if (asyncThunks.length === 0) {
1123 return (action) => hasExpectedRequestMetadata(action, ["pending"]);
1124 }
1125 if (!isAsyncThunkArray(asyncThunks)) {
1126 return isPending()(asyncThunks[0]);
1127 }
1128 return (action) => {
1129 const matchers = asyncThunks.map((asyncThunk) => asyncThunk.pending);
1130 const combinedMatcher = isAnyOf(...matchers);
1131 return combinedMatcher(action);
1132 };
1133}
1134function isRejected(...asyncThunks) {
1135 if (asyncThunks.length === 0) {
1136 return (action) => hasExpectedRequestMetadata(action, ["rejected"]);
1137 }
1138 if (!isAsyncThunkArray(asyncThunks)) {
1139 return isRejected()(asyncThunks[0]);
1140 }
1141 return (action) => {
1142 const matchers = asyncThunks.map((asyncThunk) => asyncThunk.rejected);
1143 const combinedMatcher = isAnyOf(...matchers);
1144 return combinedMatcher(action);
1145 };
1146}
1147function isRejectedWithValue(...asyncThunks) {
1148 const hasFlag = (action) => {
1149 return action && action.meta && action.meta.rejectedWithValue;
1150 };
1151 if (asyncThunks.length === 0) {
1152 return (action) => {
1153 const combinedMatcher = isAllOf(isRejected(...asyncThunks), hasFlag);
1154 return combinedMatcher(action);
1155 };
1156 }
1157 if (!isAsyncThunkArray(asyncThunks)) {
1158 return isRejectedWithValue()(asyncThunks[0]);
1159 }
1160 return (action) => {
1161 const combinedMatcher = isAllOf(isRejected(...asyncThunks), hasFlag);
1162 return combinedMatcher(action);
1163 };
1164}
1165function isFulfilled(...asyncThunks) {
1166 if (asyncThunks.length === 0) {
1167 return (action) => hasExpectedRequestMetadata(action, ["fulfilled"]);
1168 }
1169 if (!isAsyncThunkArray(asyncThunks)) {
1170 return isFulfilled()(asyncThunks[0]);
1171 }
1172 return (action) => {
1173 const matchers = asyncThunks.map((asyncThunk) => asyncThunk.fulfilled);
1174 const combinedMatcher = isAnyOf(...matchers);
1175 return combinedMatcher(action);
1176 };
1177}
1178function isAsyncThunkAction(...asyncThunks) {
1179 if (asyncThunks.length === 0) {
1180 return (action) => hasExpectedRequestMetadata(action, ["pending", "fulfilled", "rejected"]);
1181 }
1182 if (!isAsyncThunkArray(asyncThunks)) {
1183 return isAsyncThunkAction()(asyncThunks[0]);
1184 }
1185 return (action) => {
1186 const matchers = [];
1187 for (const asyncThunk of asyncThunks) {
1188 matchers.push(asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled);
1189 }
1190 const combinedMatcher = isAnyOf(...matchers);
1191 return combinedMatcher(action);
1192 };
1193}
1194// src/listenerMiddleware/utils.ts
1195var assertFunction = (func, expected) => {
1196 if (typeof func !== "function") {
1197 throw new TypeError(`${expected} is not a function`);
1198 }
1199};
1200var noop = () => {
1201};
1202var catchRejection = (promise, onError = noop) => {
1203 promise.catch(onError);
1204 return promise;
1205};
1206var addAbortSignalListener = (abortSignal, callback) => {
1207 abortSignal.addEventListener("abort", callback, { once: true });
1208};
1209var abortControllerWithReason = (abortController, reason) => {
1210 const signal = abortController.signal;
1211 if (signal.aborted) {
1212 return;
1213 }
1214 if (!("reason" in signal)) {
1215 Object.defineProperty(signal, "reason", {
1216 enumerable: true,
1217 value: reason,
1218 configurable: true,
1219 writable: true
1220 });
1221 }
1222 ;
1223 abortController.abort(reason);
1224};
1225// src/listenerMiddleware/exceptions.ts
1226var task = "task";
1227var listener = "listener";
1228var completed = "completed";
1229var cancelled = "cancelled";
1230var taskCancelled = `task-${cancelled}`;
1231var taskCompleted = `task-${completed}`;
1232var listenerCancelled = `${listener}-${cancelled}`;
1233var listenerCompleted = `${listener}-${completed}`;
1234var TaskAbortError = class {
1235 constructor(code) {
1236 this.code = code;
1237 this.name = "TaskAbortError";
1238 this.message = `${task} ${cancelled} (reason: ${code})`;
1239 }
1240};
1241// src/listenerMiddleware/task.ts
1242var validateActive = (signal) => {
1243 if (signal.aborted) {
1244 throw new TaskAbortError(signal.reason);
1245 }
1246};
1247var promisifyAbortSignal = (signal) => {
1248 return catchRejection(new Promise((_, reject) => {
1249 const notifyRejection = () => reject(new TaskAbortError(signal.reason));
1250 if (signal.aborted) {
1251 notifyRejection();
1252 }
1253 else {
1254 addAbortSignalListener(signal, notifyRejection);
1255 }
1256 }));
1257};
1258var runTask = async (task2, cleanUp) => {
1259 try {
1260 await Promise.resolve();
1261 const value = await task2();
1262 return {
1263 status: "ok",
1264 value
1265 };
1266 }
1267 catch (error) {
1268 return {
1269 status: error instanceof TaskAbortError ? "cancelled" : "rejected",
1270 error
1271 };
1272 }
1273 finally {
1274 cleanUp == null ? void 0 : cleanUp();
1275 }
1276};
1277var createPause = (signal) => {
1278 return (promise) => {
1279 return catchRejection(Promise.race([promisifyAbortSignal(signal), promise]).then((output) => {
1280 validateActive(signal);
1281 return output;
1282 }));
1283 };
1284};
1285var createDelay = (signal) => {
1286 const pause = createPause(signal);
1287 return (timeoutMs) => {
1288 return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)));
1289 };
1290};
1291// src/listenerMiddleware/index.ts
1292var { assign } = Object;
1293var INTERNAL_NIL_TOKEN = {};
1294var alm = "listenerMiddleware";
1295var createFork = (parentAbortSignal) => {
1296 const linkControllers = (controller) => addAbortSignalListener(parentAbortSignal, () => abortControllerWithReason(controller, parentAbortSignal.reason));
1297 return (taskExecutor) => {
1298 assertFunction(taskExecutor, "taskExecutor");
1299 const childAbortController = new AbortController();
1300 linkControllers(childAbortController);
1301 const result = runTask(async () => {
1302 validateActive(parentAbortSignal);
1303 validateActive(childAbortController.signal);
1304 const result2 = await taskExecutor({
1305 pause: createPause(childAbortController.signal),
1306 delay: createDelay(childAbortController.signal),
1307 signal: childAbortController.signal
1308 });
1309 validateActive(childAbortController.signal);
1310 return result2;
1311 }, () => abortControllerWithReason(childAbortController, taskCompleted));
1312 return {
1313 result: createPause(parentAbortSignal)(result),
1314 cancel() {
1315 abortControllerWithReason(childAbortController, taskCancelled);
1316 }
1317 };
1318 };
1319};
1320var createTakePattern = (startListening, signal) => {
1321 const take = async (predicate, timeout) => {
1322 validateActive(signal);
1323 let unsubscribe = () => {
1324 };
1325 const tuplePromise = new Promise((resolve) => {
1326 unsubscribe = startListening({
1327 predicate,
1328 effect: (action, listenerApi) => {
1329 listenerApi.unsubscribe();
1330 resolve([
1331 action,
1332 listenerApi.getState(),
1333 listenerApi.getOriginalState()
1334 ]);
1335 }
1336 });
1337 });
1338 const promises = [
1339 promisifyAbortSignal(signal),
1340 tuplePromise
1341 ];
1342 if (timeout != null) {
1343 promises.push(new Promise((resolve) => setTimeout(resolve, timeout, null)));
1344 }
1345 try {
1346 const output = await Promise.race(promises);
1347 validateActive(signal);
1348 return output;
1349 }
1350 finally {
1351 unsubscribe();
1352 }
1353 };
1354 return (predicate, timeout) => catchRejection(take(predicate, timeout));
1355};
1356var getListenerEntryPropsFrom = (options) => {
1357 let { type, actionCreator, matcher, predicate, effect } = options;
1358 if (type) {
1359 predicate = createAction(type).match;
1360 }
1361 else if (actionCreator) {
1362 type = actionCreator.type;
1363 predicate = actionCreator.match;
1364 }
1365 else if (matcher) {
1366 predicate = matcher;
1367 }
1368 else if (predicate) {
1369 }
1370 else {
1371 throw new Error("Creating or removing a listener requires one of the known fields for matching an action");
1372 }
1373 assertFunction(effect, "options.listener");
1374 return { predicate, type, effect };
1375};
1376var createListenerEntry = (options) => {
1377 const { type, predicate, effect } = getListenerEntryPropsFrom(options);
1378 const id = nanoid();
1379 const entry = {
1380 id,
1381 effect,
1382 type,
1383 predicate,
1384 pending: new Set(),
1385 unsubscribe: () => {
1386 throw new Error("Unsubscribe not initialized");
1387 }
1388 };
1389 return entry;
1390};
1391var createClearListenerMiddleware = (listenerMap) => {
1392 return () => {
1393 listenerMap.forEach(cancelActiveListeners);
1394 listenerMap.clear();
1395 };
1396};
1397var safelyNotifyError = (errorHandler, errorToNotify, errorInfo) => {
1398 try {
1399 errorHandler(errorToNotify, errorInfo);
1400 }
1401 catch (errorHandlerError) {
1402 setTimeout(() => {
1403 throw errorHandlerError;
1404 }, 0);
1405 }
1406};
1407var addListener = createAction(`${alm}/add`);
1408var clearAllListeners = createAction(`${alm}/removeAll`);
1409var removeListener = createAction(`${alm}/remove`);
1410var defaultErrorHandler = (...args) => {
1411 console.error(`${alm}/error`, ...args);
1412};
1413var cancelActiveListeners = (entry) => {
1414 entry.pending.forEach((controller) => {
1415 abortControllerWithReason(controller, listenerCancelled);
1416 });
1417};
1418function createListenerMiddleware(middlewareOptions = {}) {
1419 const listenerMap = new Map();
1420 const { extra, onError = defaultErrorHandler } = middlewareOptions;
1421 assertFunction(onError, "onError");
1422 const insertEntry = (entry) => {
1423 entry.unsubscribe = () => listenerMap.delete(entry.id);
1424 listenerMap.set(entry.id, entry);
1425 return (cancelOptions) => {
1426 entry.unsubscribe();
1427 if (cancelOptions == null ? void 0 : cancelOptions.cancelActive) {
1428 cancelActiveListeners(entry);
1429 }
1430 };
1431 };
1432 const findListenerEntry = (comparator) => {
1433 for (const entry of Array.from(listenerMap.values())) {
1434 if (comparator(entry)) {
1435 return entry;
1436 }
1437 }
1438 return void 0;
1439 };
1440 const startListening = (options) => {
1441 let entry = findListenerEntry((existingEntry) => existingEntry.effect === options.effect);
1442 if (!entry) {
1443 entry = createListenerEntry(options);
1444 }
1445 return insertEntry(entry);
1446 };
1447 const stopListening = (options) => {
1448 const { type, effect, predicate } = getListenerEntryPropsFrom(options);
1449 const entry = findListenerEntry((entry2) => {
1450 const matchPredicateOrType = typeof type === "string" ? entry2.type === type : entry2.predicate === predicate;
1451 return matchPredicateOrType && entry2.effect === effect;
1452 });
1453 if (entry) {
1454 entry.unsubscribe();
1455 if (options.cancelActive) {
1456 cancelActiveListeners(entry);
1457 }
1458 }
1459 return !!entry;
1460 };
1461 const notifyListener = async (entry, action, api, getOriginalState) => {
1462 const internalTaskController = new AbortController();
1463 const take = createTakePattern(startListening, internalTaskController.signal);
1464 try {
1465 entry.pending.add(internalTaskController);
1466 await Promise.resolve(entry.effect(action, assign({}, api, {
1467 getOriginalState,
1468 condition: (predicate, timeout) => take(predicate, timeout).then(Boolean),
1469 take,
1470 delay: createDelay(internalTaskController.signal),
1471 pause: createPause(internalTaskController.signal),
1472 extra,
1473 signal: internalTaskController.signal,
1474 fork: createFork(internalTaskController.signal),
1475 unsubscribe: entry.unsubscribe,
1476 subscribe: () => {
1477 listenerMap.set(entry.id, entry);
1478 },
1479 cancelActiveListeners: () => {
1480 entry.pending.forEach((controller, _, set) => {
1481 if (controller !== internalTaskController) {
1482 abortControllerWithReason(controller, listenerCancelled);
1483 set.delete(controller);
1484 }
1485 });
1486 }
1487 })));
1488 }
1489 catch (listenerError) {
1490 if (!(listenerError instanceof TaskAbortError)) {
1491 safelyNotifyError(onError, listenerError, {
1492 raisedBy: "effect"
1493 });
1494 }
1495 }
1496 finally {
1497 abortControllerWithReason(internalTaskController, listenerCompleted);
1498 entry.pending.delete(internalTaskController);
1499 }
1500 };
1501 const clearListenerMiddleware = createClearListenerMiddleware(listenerMap);
1502 const middleware = (api) => (next) => (action) => {
1503 if (addListener.match(action)) {
1504 return startListening(action.payload);
1505 }
1506 if (clearAllListeners.match(action)) {
1507 clearListenerMiddleware();
1508 return;
1509 }
1510 if (removeListener.match(action)) {
1511 return stopListening(action.payload);
1512 }
1513 let originalState = api.getState();
1514 const getOriginalState = () => {
1515 if (originalState === INTERNAL_NIL_TOKEN) {
1516 throw new Error(`${alm}: getOriginalState can only be called synchronously`);
1517 }
1518 return originalState;
1519 };
1520 let result;
1521 try {
1522 result = next(action);
1523 if (listenerMap.size > 0) {
1524 let currentState = api.getState();
1525 const listenerEntries = Array.from(listenerMap.values());
1526 for (let entry of listenerEntries) {
1527 let runListener = false;
1528 try {
1529 runListener = entry.predicate(action, currentState, originalState);
1530 }
1531 catch (predicateError) {
1532 runListener = false;
1533 safelyNotifyError(onError, predicateError, {
1534 raisedBy: "predicate"
1535 });
1536 }
1537 if (!runListener) {
1538 continue;
1539 }
1540 notifyListener(entry, action, api, getOriginalState);
1541 }
1542 }
1543 }
1544 finally {
1545 originalState = INTERNAL_NIL_TOKEN;
1546 }
1547 return result;
1548 };
1549 return {
1550 middleware,
1551 startListening,
1552 stopListening,
1553 clearListeners: clearListenerMiddleware
1554 };
1555}
1556// src/index.ts
1557enableES5();
1558export { MiddlewareArray, TaskAbortError, addListener, clearAllListeners, configureStore, createAction, createAsyncThunk, createDraftSafeSelector, createEntityAdapter, createImmutableStateInvariantMiddleware, createListenerMiddleware, default2 as createNextState, createReducer, createSelector2 as createSelector, createSerializableStateInvariantMiddleware, createSlice, current2 as current, findNonSerializableValue, freeze, getDefaultMiddleware, getType, isAllOf, isAnyOf, isAsyncThunkAction, isDraft4 as isDraft, isFulfilled, isImmutableDefault, isPending, isPlain, isPlainObject, isRejected, isRejectedWithValue, miniSerializeError, nanoid, original, removeListener, unwrapResult };
1559//# sourceMappingURL=redux-toolkit.modern.js.map
\No newline at end of file