UNPKG

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