UNPKG

47 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 (noop) {
46 return noop;
47 };
48};
49// src/isPlainObject.ts
50function isPlainObject(value) {
51 if (typeof value !== "object" || value === null)
52 return false;
53 let proto = value;
54 while (Object.getPrototypeOf(proto) !== null) {
55 proto = Object.getPrototypeOf(proto);
56 }
57 return Object.getPrototypeOf(value) === proto;
58}
59// src/getDefaultMiddleware.ts
60import thunkMiddleware from "redux-thunk";
61// src/utils.ts
62function getTimeMeasureUtils(maxDelay, fnName) {
63 let elapsed = 0;
64 return {
65 measureTime(fn) {
66 const started = Date.now();
67 try {
68 return fn();
69 }
70 finally {
71 const finished = Date.now();
72 elapsed += finished - started;
73 }
74 },
75 warnIfExceeded() {
76 if (elapsed > maxDelay) {
77 console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms.
78If 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.
79It is disabled in production builds, so you don't need to worry about that.`);
80 }
81 }
82 };
83}
84var MiddlewareArray = class extends Array {
85 constructor(...args) {
86 super(...args);
87 Object.setPrototypeOf(this, MiddlewareArray.prototype);
88 }
89 static get [Symbol.species]() {
90 return MiddlewareArray;
91 }
92 concat(...arr) {
93 return super.concat.apply(this, arr);
94 }
95 prepend(...arr) {
96 if (arr.length === 1 && Array.isArray(arr[0])) {
97 return new MiddlewareArray(...arr[0].concat(this));
98 }
99 return new MiddlewareArray(...arr.concat(this));
100 }
101};
102// src/immutableStateInvariantMiddleware.ts
103var isProduction = process.env.NODE_ENV === "production";
104var prefix = "Invariant failed";
105function invariant(condition, message) {
106 if (condition) {
107 return;
108 }
109 if (isProduction) {
110 throw new Error(prefix);
111 }
112 throw new Error(`${prefix}: ${message || ""}`);
113}
114function stringify(obj, serializer, indent, decycler) {
115 return JSON.stringify(obj, getSerialize(serializer, decycler), indent);
116}
117function getSerialize(serializer, decycler) {
118 let stack = [], keys = [];
119 if (!decycler)
120 decycler = function (_, value) {
121 if (stack[0] === value)
122 return "[Circular ~]";
123 return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
124 };
125 return function (key, value) {
126 if (stack.length > 0) {
127 var thisPos = stack.indexOf(this);
128 ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
129 ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
130 if (~stack.indexOf(value))
131 value = decycler.call(this, key, value);
132 }
133 else
134 stack.push(value);
135 return serializer == null ? value : serializer.call(this, key, value);
136 };
137}
138function isImmutableDefault(value) {
139 return typeof value !== "object" || value === null || typeof value === "undefined" || Object.isFrozen(value);
140}
141function trackForMutations(isImmutable, ignorePaths, obj) {
142 const trackedProperties = trackProperties(isImmutable, ignorePaths, obj);
143 return {
144 detectMutations() {
145 return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);
146 }
147 };
148}
149function trackProperties(isImmutable, ignorePaths = [], obj, path = "") {
150 const tracked = { value: obj };
151 if (!isImmutable(obj)) {
152 tracked.children = {};
153 for (const key in obj) {
154 const childPath = path ? path + "." + key : key;
155 if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {
156 continue;
157 }
158 tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);
159 }
160 }
161 return tracked;
162}
163function detectMutations(isImmutable, ignorePaths = [], trackedProperty, obj, sameParentRef = false, path = "") {
164 const prevObj = trackedProperty ? trackedProperty.value : void 0;
165 const sameRef = prevObj === obj;
166 if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
167 return { wasMutated: true, path };
168 }
169 if (isImmutable(prevObj) || isImmutable(obj)) {
170 return { wasMutated: false };
171 }
172 const keysToDetect = {};
173 for (let key in trackedProperty.children) {
174 keysToDetect[key] = true;
175 }
176 for (let key in obj) {
177 keysToDetect[key] = true;
178 }
179 for (let key in keysToDetect) {
180 const childPath = path ? path + "." + key : key;
181 if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {
182 continue;
183 }
184 const result = detectMutations(isImmutable, ignorePaths, trackedProperty.children[key], obj[key], sameRef, childPath);
185 if (result.wasMutated) {
186 return result;
187 }
188 }
189 return { wasMutated: false };
190}
191function createImmutableStateInvariantMiddleware(options = {}) {
192 if (process.env.NODE_ENV === "production") {
193 return () => (next) => (action) => next(action);
194 }
195 let { isImmutable = isImmutableDefault, ignoredPaths, warnAfter = 32, ignore } = options;
196 ignoredPaths = ignoredPaths || ignore;
197 const track = trackForMutations.bind(null, isImmutable, ignoredPaths);
198 return ({ getState }) => {
199 let state = getState();
200 let tracker = track(state);
201 let result;
202 return (next) => (action) => {
203 const measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
204 measureUtils.measureTime(() => {
205 state = getState();
206 result = tracker.detectMutations();
207 tracker = track(state);
208 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)`);
209 });
210 const dispatchedAction = next(action);
211 measureUtils.measureTime(() => {
212 state = getState();
213 result = tracker.detectMutations();
214 tracker = track(state);
215 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)`);
216 });
217 measureUtils.warnIfExceeded();
218 return dispatchedAction;
219 };
220 };
221}
222// src/serializableStateInvariantMiddleware.ts
223function isPlain(val) {
224 const type = typeof val;
225 return type === "undefined" || val === null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || isPlainObject(val);
226}
227function findNonSerializableValue(value, path = "", isSerializable = isPlain, getEntries, ignoredPaths = []) {
228 let foundNestedSerializable;
229 if (!isSerializable(value)) {
230 return {
231 keyPath: path || "<root>",
232 value
233 };
234 }
235 if (typeof value !== "object" || value === null) {
236 return false;
237 }
238 const entries = getEntries != null ? getEntries(value) : Object.entries(value);
239 const hasIgnoredPaths = ignoredPaths.length > 0;
240 for (const [key, nestedValue] of entries) {
241 const nestedPath = path ? path + "." + key : key;
242 if (hasIgnoredPaths && ignoredPaths.indexOf(nestedPath) >= 0) {
243 continue;
244 }
245 if (!isSerializable(nestedValue)) {
246 return {
247 keyPath: nestedPath,
248 value: nestedValue
249 };
250 }
251 if (typeof nestedValue === "object") {
252 foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths);
253 if (foundNestedSerializable) {
254 return foundNestedSerializable;
255 }
256 }
257 }
258 return false;
259}
260function createSerializableStateInvariantMiddleware(options = {}) {
261 if (process.env.NODE_ENV === "production") {
262 return () => (next) => (action) => next(action);
263 }
264 const { isSerializable = isPlain, getEntries, ignoredActions = [], ignoredActionPaths = ["meta.arg", "meta.baseQueryMeta"], ignoredPaths = [], warnAfter = 32, ignoreState = false } = options;
265 return (storeAPI) => (next) => (action) => {
266 if (ignoredActions.length && ignoredActions.indexOf(action.type) !== -1) {
267 return next(action);
268 }
269 const measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
270 measureUtils.measureTime(() => {
271 const foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths);
272 if (foundActionNonSerializableValue) {
273 const { keyPath, value } = foundActionNonSerializableValue;
274 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)");
275 }
276 });
277 const result = next(action);
278 if (!ignoreState) {
279 measureUtils.measureTime(() => {
280 const state = storeAPI.getState();
281 const foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths);
282 if (foundStateNonSerializableValue) {
283 const { keyPath, value } = foundStateNonSerializableValue;
284 console.error(`A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`, value, `
285Take a look at the reducer(s) handling this action type: ${action.type}.
286(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);
287 }
288 });
289 measureUtils.warnIfExceeded();
290 }
291 return result;
292 };
293}
294// src/getDefaultMiddleware.ts
295function isBoolean(x) {
296 return typeof x === "boolean";
297}
298function curryGetDefaultMiddleware() {
299 return function curriedGetDefaultMiddleware(options) {
300 return getDefaultMiddleware(options);
301 };
302}
303function getDefaultMiddleware(options = {}) {
304 const { thunk = true, immutableCheck = true, serializableCheck = true } = options;
305 let middlewareArray = new MiddlewareArray();
306 if (thunk) {
307 if (isBoolean(thunk)) {
308 middlewareArray.push(thunkMiddleware);
309 }
310 else {
311 middlewareArray.push(thunkMiddleware.withExtraArgument(thunk.extraArgument));
312 }
313 }
314 if (process.env.NODE_ENV !== "production") {
315 if (immutableCheck) {
316 let immutableOptions = {};
317 if (!isBoolean(immutableCheck)) {
318 immutableOptions = immutableCheck;
319 }
320 middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
321 }
322 if (serializableCheck) {
323 let serializableOptions = {};
324 if (!isBoolean(serializableCheck)) {
325 serializableOptions = serializableCheck;
326 }
327 middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
328 }
329 }
330 return middlewareArray;
331}
332// src/configureStore.ts
333var IS_PRODUCTION = process.env.NODE_ENV === "production";
334function configureStore(options) {
335 const curriedGetDefaultMiddleware = curryGetDefaultMiddleware();
336 const { reducer = void 0, middleware = curriedGetDefaultMiddleware(), devTools = true, preloadedState = void 0, enhancers = void 0 } = options || {};
337 let rootReducer;
338 if (typeof reducer === "function") {
339 rootReducer = reducer;
340 }
341 else if (isPlainObject(reducer)) {
342 rootReducer = combineReducers(reducer);
343 }
344 else {
345 throw new Error('"reducer" is a required argument, and must be a function or an object of functions that can be passed to combineReducers');
346 }
347 let finalMiddleware = middleware;
348 if (typeof finalMiddleware === "function") {
349 finalMiddleware = finalMiddleware(curriedGetDefaultMiddleware);
350 if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {
351 throw new Error("when using a middleware builder function, an array of middleware must be returned");
352 }
353 }
354 if (!IS_PRODUCTION && finalMiddleware.some((item) => typeof item !== "function")) {
355 throw new Error("each middleware provided to configureStore must be a function");
356 }
357 const middlewareEnhancer = applyMiddleware(...finalMiddleware);
358 let finalCompose = compose2;
359 if (devTools) {
360 finalCompose = composeWithDevTools(__spreadValues({
361 trace: !IS_PRODUCTION
362 }, typeof devTools === "object" && devTools));
363 }
364 let storeEnhancers = [middlewareEnhancer];
365 if (Array.isArray(enhancers)) {
366 storeEnhancers = [middlewareEnhancer, ...enhancers];
367 }
368 else if (typeof enhancers === "function") {
369 storeEnhancers = enhancers(storeEnhancers);
370 }
371 const composedEnhancer = finalCompose(...storeEnhancers);
372 return createStore(rootReducer, preloadedState, composedEnhancer);
373}
374// src/createAction.ts
375function createAction(type, prepareAction) {
376 function actionCreator(...args) {
377 if (prepareAction) {
378 let prepared = prepareAction(...args);
379 if (!prepared) {
380 throw new Error("prepareAction did not return an object");
381 }
382 return __spreadValues(__spreadValues({
383 type,
384 payload: prepared.payload
385 }, "meta" in prepared && { meta: prepared.meta }), "error" in prepared && { error: prepared.error });
386 }
387 return { type, payload: args[0] };
388 }
389 actionCreator.toString = () => `${type}`;
390 actionCreator.type = type;
391 actionCreator.match = (action) => action.type === type;
392 return actionCreator;
393}
394function isFSA(action) {
395 return isPlainObject(action) && typeof action.type === "string" && Object.keys(action).every(isValidKey);
396}
397function isValidKey(key) {
398 return ["type", "payload", "error", "meta"].indexOf(key) > -1;
399}
400function getType(actionCreator) {
401 return `${actionCreator}`;
402}
403// src/createReducer.ts
404import createNextState, { isDraft as isDraft2, isDraftable } from "immer";
405// src/mapBuilders.ts
406function executeReducerBuilderCallback(builderCallback) {
407 const actionsMap = {};
408 const actionMatchers = [];
409 let defaultCaseReducer;
410 const builder = {
411 addCase(typeOrActionCreator, reducer) {
412 if (process.env.NODE_ENV !== "production") {
413 if (actionMatchers.length > 0) {
414 throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");
415 }
416 if (defaultCaseReducer) {
417 throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`");
418 }
419 }
420 const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
421 if (type in actionsMap) {
422 throw new Error("addCase cannot be called with two reducers for the same action type");
423 }
424 actionsMap[type] = reducer;
425 return builder;
426 },
427 addMatcher(matcher, reducer) {
428 if (process.env.NODE_ENV !== "production") {
429 if (defaultCaseReducer) {
430 throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
431 }
432 }
433 actionMatchers.push({ matcher, reducer });
434 return builder;
435 },
436 addDefaultCase(reducer) {
437 if (process.env.NODE_ENV !== "production") {
438 if (defaultCaseReducer) {
439 throw new Error("`builder.addDefaultCase` can only be called once");
440 }
441 }
442 defaultCaseReducer = reducer;
443 return builder;
444 }
445 };
446 builderCallback(builder);
447 return [actionsMap, actionMatchers, defaultCaseReducer];
448}
449// src/createReducer.ts
450function createReducer(initialState, mapOrBuilderCallback, actionMatchers = [], defaultCaseReducer) {
451 let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = typeof mapOrBuilderCallback === "function" ? executeReducerBuilderCallback(mapOrBuilderCallback) : [mapOrBuilderCallback, actionMatchers, defaultCaseReducer];
452 const frozenInitialState = createNextState(initialState, () => {
453 });
454 return function (state = frozenInitialState, action) {
455 let caseReducers = [
456 actionsMap[action.type],
457 ...finalActionMatchers.filter(({ matcher }) => matcher(action)).map(({ reducer }) => reducer)
458 ];
459 if (caseReducers.filter((cr) => !!cr).length === 0) {
460 caseReducers = [finalDefaultCaseReducer];
461 }
462 return caseReducers.reduce((previousState, caseReducer) => {
463 if (caseReducer) {
464 if (isDraft2(previousState)) {
465 const draft = previousState;
466 const result = caseReducer(draft, action);
467 if (typeof result === "undefined") {
468 return previousState;
469 }
470 return result;
471 }
472 else if (!isDraftable(previousState)) {
473 const result = caseReducer(previousState, action);
474 if (typeof result === "undefined") {
475 if (previousState === null) {
476 return previousState;
477 }
478 throw Error("A case reducer on a non-draftable value must not return undefined");
479 }
480 return result;
481 }
482 else {
483 return createNextState(previousState, (draft) => {
484 return caseReducer(draft, action);
485 });
486 }
487 }
488 return previousState;
489 }, state);
490 };
491}
492// src/createSlice.ts
493function getType2(slice, actionKey) {
494 return `${slice}/${actionKey}`;
495}
496function createSlice(options) {
497 const { name, initialState } = options;
498 if (!name) {
499 throw new Error("`name` is a required option for createSlice");
500 }
501 const reducers = options.reducers || {};
502 const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];
503 const reducerNames = Object.keys(reducers);
504 const sliceCaseReducersByName = {};
505 const sliceCaseReducersByType = {};
506 const actionCreators = {};
507 reducerNames.forEach((reducerName) => {
508 const maybeReducerWithPrepare = reducers[reducerName];
509 const type = getType2(name, reducerName);
510 let caseReducer;
511 let prepareCallback;
512 if ("reducer" in maybeReducerWithPrepare) {
513 caseReducer = maybeReducerWithPrepare.reducer;
514 prepareCallback = maybeReducerWithPrepare.prepare;
515 }
516 else {
517 caseReducer = maybeReducerWithPrepare;
518 }
519 sliceCaseReducersByName[reducerName] = caseReducer;
520 sliceCaseReducersByType[type] = caseReducer;
521 actionCreators[reducerName] = prepareCallback ? createAction(type, prepareCallback) : createAction(type);
522 });
523 const finalCaseReducers = __spreadValues(__spreadValues({}, extraReducers), sliceCaseReducersByType);
524 const reducer = createReducer(initialState, finalCaseReducers, actionMatchers, defaultCaseReducer);
525 return {
526 name,
527 reducer,
528 actions: actionCreators,
529 caseReducers: sliceCaseReducersByName
530 };
531}
532// src/entities/entity_state.ts
533function getInitialEntityState() {
534 return {
535 ids: [],
536 entities: {}
537 };
538}
539function createInitialStateFactory() {
540 function getInitialState(additionalState = {}) {
541 return Object.assign(getInitialEntityState(), additionalState);
542 }
543 return { getInitialState };
544}
545// src/entities/state_selectors.ts
546function createSelectorsFactory() {
547 function getSelectors(selectState) {
548 const selectIds = (state) => state.ids;
549 const selectEntities = (state) => state.entities;
550 const selectAll = createDraftSafeSelector(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));
551 const selectId = (_, id) => id;
552 const selectById = (entities, id) => entities[id];
553 const selectTotal = createDraftSafeSelector(selectIds, (ids) => ids.length);
554 if (!selectState) {
555 return {
556 selectIds,
557 selectEntities,
558 selectAll,
559 selectTotal,
560 selectById: createDraftSafeSelector(selectEntities, selectId, selectById)
561 };
562 }
563 const selectGlobalizedEntities = createDraftSafeSelector(selectState, selectEntities);
564 return {
565 selectIds: createDraftSafeSelector(selectState, selectIds),
566 selectEntities: selectGlobalizedEntities,
567 selectAll: createDraftSafeSelector(selectState, selectAll),
568 selectTotal: createDraftSafeSelector(selectState, selectTotal),
569 selectById: createDraftSafeSelector(selectGlobalizedEntities, selectId, selectById)
570 };
571 }
572 return { getSelectors };
573}
574// src/entities/state_adapter.ts
575import createNextState2, { isDraft as isDraft3 } from "immer";
576function createSingleArgumentStateOperator(mutator) {
577 const operator = createStateOperator((_, state) => mutator(state));
578 return function operation(state) {
579 return operator(state, void 0);
580 };
581}
582function createStateOperator(mutator) {
583 return function operation(state, arg) {
584 function isPayloadActionArgument(arg2) {
585 return isFSA(arg2);
586 }
587 const runMutator = (draft) => {
588 if (isPayloadActionArgument(arg)) {
589 mutator(arg.payload, draft);
590 }
591 else {
592 mutator(arg, draft);
593 }
594 };
595 if (isDraft3(state)) {
596 runMutator(state);
597 return state;
598 }
599 else {
600 return createNextState2(state, runMutator);
601 }
602 };
603}
604// src/entities/utils.ts
605function selectIdValue(entity, selectId) {
606 const key = selectId(entity);
607 if (process.env.NODE_ENV !== "production" && key === void 0) {
608 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());
609 }
610 return key;
611}
612function ensureEntitiesArray(entities) {
613 if (!Array.isArray(entities)) {
614 entities = Object.values(entities);
615 }
616 return entities;
617}
618function splitAddedUpdatedEntities(newEntities, selectId, state) {
619 newEntities = ensureEntitiesArray(newEntities);
620 const added = [];
621 const updated = [];
622 for (const entity of newEntities) {
623 const id = selectIdValue(entity, selectId);
624 if (id in state.entities) {
625 updated.push({ id, changes: entity });
626 }
627 else {
628 added.push(entity);
629 }
630 }
631 return [added, updated];
632}
633// src/entities/unsorted_state_adapter.ts
634function createUnsortedStateAdapter(selectId) {
635 function addOneMutably(entity, state) {
636 const key = selectIdValue(entity, selectId);
637 if (key in state.entities) {
638 return;
639 }
640 state.ids.push(key);
641 state.entities[key] = entity;
642 }
643 function addManyMutably(newEntities, state) {
644 newEntities = ensureEntitiesArray(newEntities);
645 for (const entity of newEntities) {
646 addOneMutably(entity, state);
647 }
648 }
649 function setOneMutably(entity, state) {
650 const key = selectIdValue(entity, selectId);
651 if (!(key in state.entities)) {
652 state.ids.push(key);
653 }
654 state.entities[key] = entity;
655 }
656 function setManyMutably(newEntities, state) {
657 newEntities = ensureEntitiesArray(newEntities);
658 for (const entity of newEntities) {
659 setOneMutably(entity, state);
660 }
661 }
662 function setAllMutably(newEntities, state) {
663 newEntities = ensureEntitiesArray(newEntities);
664 state.ids = [];
665 state.entities = {};
666 addManyMutably(newEntities, state);
667 }
668 function removeOneMutably(key, state) {
669 return removeManyMutably([key], state);
670 }
671 function removeManyMutably(keys, state) {
672 let didMutate = false;
673 keys.forEach((key) => {
674 if (key in state.entities) {
675 delete state.entities[key];
676 didMutate = true;
677 }
678 });
679 if (didMutate) {
680 state.ids = state.ids.filter((id) => id in state.entities);
681 }
682 }
683 function removeAllMutably(state) {
684 Object.assign(state, {
685 ids: [],
686 entities: {}
687 });
688 }
689 function takeNewKey(keys, update, state) {
690 const original2 = state.entities[update.id];
691 const updated = Object.assign({}, original2, update.changes);
692 const newKey = selectIdValue(updated, selectId);
693 const hasNewKey = newKey !== update.id;
694 if (hasNewKey) {
695 keys[update.id] = newKey;
696 delete state.entities[update.id];
697 }
698 state.entities[newKey] = updated;
699 return hasNewKey;
700 }
701 function updateOneMutably(update, state) {
702 return updateManyMutably([update], state);
703 }
704 function updateManyMutably(updates, state) {
705 const newKeys = {};
706 const updatesPerEntity = {};
707 updates.forEach((update) => {
708 if (update.id in state.entities) {
709 updatesPerEntity[update.id] = {
710 id: update.id,
711 changes: __spreadValues(__spreadValues({}, updatesPerEntity[update.id] ? updatesPerEntity[update.id].changes : null), update.changes)
712 };
713 }
714 });
715 updates = Object.values(updatesPerEntity);
716 const didMutateEntities = updates.length > 0;
717 if (didMutateEntities) {
718 const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0;
719 if (didMutateIds) {
720 state.ids = state.ids.map((id) => newKeys[id] || id);
721 }
722 }
723 }
724 function upsertOneMutably(entity, state) {
725 return upsertManyMutably([entity], state);
726 }
727 function upsertManyMutably(newEntities, state) {
728 const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
729 updateManyMutably(updated, state);
730 addManyMutably(added, state);
731 }
732 return {
733 removeAll: createSingleArgumentStateOperator(removeAllMutably),
734 addOne: createStateOperator(addOneMutably),
735 addMany: createStateOperator(addManyMutably),
736 setOne: createStateOperator(setOneMutably),
737 setMany: createStateOperator(setManyMutably),
738 setAll: createStateOperator(setAllMutably),
739 updateOne: createStateOperator(updateOneMutably),
740 updateMany: createStateOperator(updateManyMutably),
741 upsertOne: createStateOperator(upsertOneMutably),
742 upsertMany: createStateOperator(upsertManyMutably),
743 removeOne: createStateOperator(removeOneMutably),
744 removeMany: createStateOperator(removeManyMutably)
745 };
746}
747// src/entities/sorted_state_adapter.ts
748function createSortedStateAdapter(selectId, sort) {
749 const { removeOne, removeMany, removeAll } = createUnsortedStateAdapter(selectId);
750 function addOneMutably(entity, state) {
751 return addManyMutably([entity], state);
752 }
753 function addManyMutably(newEntities, state) {
754 newEntities = ensureEntitiesArray(newEntities);
755 const models = newEntities.filter((model) => !(selectIdValue(model, selectId) in state.entities));
756 if (models.length !== 0) {
757 merge(models, state);
758 }
759 }
760 function setOneMutably(entity, state) {
761 return setManyMutably([entity], state);
762 }
763 function setManyMutably(newEntities, state) {
764 newEntities = ensureEntitiesArray(newEntities);
765 if (newEntities.length !== 0) {
766 merge(newEntities, state);
767 }
768 }
769 function setAllMutably(newEntities, state) {
770 newEntities = ensureEntitiesArray(newEntities);
771 state.entities = {};
772 state.ids = [];
773 addManyMutably(newEntities, state);
774 }
775 function updateOneMutably(update, state) {
776 return updateManyMutably([update], state);
777 }
778 function takeUpdatedModel(models, update, state) {
779 if (!(update.id in state.entities)) {
780 return false;
781 }
782 const original2 = state.entities[update.id];
783 const updated = Object.assign({}, original2, update.changes);
784 const newKey = selectIdValue(updated, selectId);
785 delete state.entities[update.id];
786 models.push(updated);
787 return newKey !== update.id;
788 }
789 function updateManyMutably(updates, state) {
790 const models = [];
791 updates.forEach((update) => takeUpdatedModel(models, update, state));
792 if (models.length !== 0) {
793 merge(models, state);
794 }
795 }
796 function upsertOneMutably(entity, state) {
797 return upsertManyMutably([entity], state);
798 }
799 function upsertManyMutably(newEntities, state) {
800 const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
801 updateManyMutably(updated, state);
802 addManyMutably(added, state);
803 }
804 function areArraysEqual(a, b) {
805 if (a.length !== b.length) {
806 return false;
807 }
808 for (let i = 0; i < a.length && i < b.length; i++) {
809 if (a[i] === b[i]) {
810 continue;
811 }
812 return false;
813 }
814 return true;
815 }
816 function merge(models, state) {
817 models.forEach((model) => {
818 state.entities[selectId(model)] = model;
819 });
820 const allEntities = Object.values(state.entities);
821 allEntities.sort(sort);
822 const newSortedIds = allEntities.map(selectId);
823 const { ids } = state;
824 if (!areArraysEqual(ids, newSortedIds)) {
825 state.ids = newSortedIds;
826 }
827 }
828 return {
829 removeOne,
830 removeMany,
831 removeAll,
832 addOne: createStateOperator(addOneMutably),
833 updateOne: createStateOperator(updateOneMutably),
834 upsertOne: createStateOperator(upsertOneMutably),
835 setOne: createStateOperator(setOneMutably),
836 setMany: createStateOperator(setManyMutably),
837 setAll: createStateOperator(setAllMutably),
838 addMany: createStateOperator(addManyMutably),
839 updateMany: createStateOperator(updateManyMutably),
840 upsertMany: createStateOperator(upsertManyMutably)
841 };
842}
843// src/entities/create_adapter.ts
844function createEntityAdapter(options = {}) {
845 const { selectId, sortComparer } = __spreadValues({
846 sortComparer: false,
847 selectId: (instance) => instance.id
848 }, options);
849 const stateFactory = createInitialStateFactory();
850 const selectorsFactory = createSelectorsFactory();
851 const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
852 return __spreadValues(__spreadValues(__spreadValues({
853 selectId,
854 sortComparer
855 }, stateFactory), selectorsFactory), stateAdapter);
856}
857// src/nanoid.ts
858var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
859var nanoid = (size = 21) => {
860 let id = "";
861 let i = size;
862 while (i--) {
863 id += urlAlphabet[Math.random() * 64 | 0];
864 }
865 return id;
866};
867// src/createAsyncThunk.ts
868var commonProperties = [
869 "name",
870 "message",
871 "stack",
872 "code"
873];
874var RejectWithValue = class {
875 constructor(payload, meta) {
876 this.payload = payload;
877 this.meta = meta;
878 }
879};
880var FulfillWithMeta = class {
881 constructor(payload, meta) {
882 this.payload = payload;
883 this.meta = meta;
884 }
885};
886var miniSerializeError = (value) => {
887 if (typeof value === "object" && value !== null) {
888 const simpleError = {};
889 for (const property of commonProperties) {
890 if (typeof value[property] === "string") {
891 simpleError[property] = value[property];
892 }
893 }
894 return simpleError;
895 }
896 return { message: String(value) };
897};
898function createAsyncThunk(typePrefix, payloadCreator, options) {
899 const fulfilled = createAction(typePrefix + "/fulfilled", (payload, requestId, arg, meta) => ({
900 payload,
901 meta: __spreadProps(__spreadValues({}, meta || {}), {
902 arg,
903 requestId,
904 requestStatus: "fulfilled"
905 })
906 }));
907 const pending = createAction(typePrefix + "/pending", (requestId, arg, meta) => ({
908 payload: void 0,
909 meta: __spreadProps(__spreadValues({}, meta || {}), {
910 arg,
911 requestId,
912 requestStatus: "pending"
913 })
914 }));
915 const rejected = createAction(typePrefix + "/rejected", (error, requestId, arg, payload, meta) => ({
916 payload,
917 error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
918 meta: __spreadProps(__spreadValues({}, meta || {}), {
919 arg,
920 requestId,
921 rejectedWithValue: !!payload,
922 requestStatus: "rejected",
923 aborted: (error == null ? void 0 : error.name) === "AbortError",
924 condition: (error == null ? void 0 : error.name) === "ConditionError"
925 })
926 }));
927 let displayedWarning = false;
928 const AC = typeof AbortController !== "undefined" ? AbortController : class {
929 constructor() {
930 this.signal = {
931 aborted: false,
932 addEventListener() {
933 },
934 dispatchEvent() {
935 return false;
936 },
937 onabort() {
938 },
939 removeEventListener() {
940 }
941 };
942 }
943 abort() {
944 if (process.env.NODE_ENV !== "production") {
945 if (!displayedWarning) {
946 displayedWarning = true;
947 console.info(`This platform does not implement AbortController.
948If you want to use the AbortController to react to \`abort\` events, please consider importing a polyfill like 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'.`);
949 }
950 }
951 }
952 };
953 function actionCreator(arg) {
954 return (dispatch, getState, extra) => {
955 var _a;
956 const requestId = ((_a = options == null ? void 0 : options.idGenerator) != null ? _a : nanoid)();
957 const abortController = new AC();
958 let abortReason;
959 const abortedPromise = new Promise((_, reject) => abortController.signal.addEventListener("abort", () => reject({ name: "AbortError", message: abortReason || "Aborted" })));
960 let started = false;
961 function abort(reason) {
962 if (started) {
963 abortReason = reason;
964 abortController.abort();
965 }
966 }
967 const promise = async function () {
968 var _a2;
969 let finalAction;
970 try {
971 if (options && options.condition && options.condition(arg, { getState, extra }) === false) {
972 throw {
973 name: "ConditionError",
974 message: "Aborted due to condition callback returning false."
975 };
976 }
977 started = true;
978 dispatch(pending(requestId, arg, (_a2 = options == null ? void 0 : options.getPendingMeta) == null ? void 0 : _a2.call(options, { requestId, arg }, { getState, extra })));
979 finalAction = await Promise.race([
980 abortedPromise,
981 Promise.resolve(payloadCreator(arg, {
982 dispatch,
983 getState,
984 extra,
985 requestId,
986 signal: abortController.signal,
987 rejectWithValue: (value, meta) => {
988 return new RejectWithValue(value, meta);
989 },
990 fulfillWithValue: (value, meta) => {
991 return new FulfillWithMeta(value, meta);
992 }
993 })).then((result) => {
994 if (result instanceof RejectWithValue) {
995 throw result;
996 }
997 if (result instanceof FulfillWithMeta) {
998 return fulfilled(result.payload, requestId, arg, result.meta);
999 }
1000 return fulfilled(result, requestId, arg);
1001 })
1002 ]);
1003 }
1004 catch (err) {
1005 finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);
1006 }
1007 const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;
1008 if (!skipDispatch) {
1009 dispatch(finalAction);
1010 }
1011 return finalAction;
1012 }();
1013 return Object.assign(promise, {
1014 abort,
1015 requestId,
1016 arg,
1017 unwrap() {
1018 return promise.then(unwrapResult);
1019 }
1020 });
1021 };
1022 }
1023 return Object.assign(actionCreator, {
1024 pending,
1025 rejected,
1026 fulfilled,
1027 typePrefix
1028 });
1029}
1030function unwrapResult(action) {
1031 if (action.meta && action.meta.rejectedWithValue) {
1032 throw action.payload;
1033 }
1034 if (action.error) {
1035 throw action.error;
1036 }
1037 return action.payload;
1038}
1039// src/tsHelpers.ts
1040var hasMatchFunction = (v) => {
1041 return v && typeof v.match === "function";
1042};
1043// src/matchers.ts
1044var matches = (matcher, action) => {
1045 if (hasMatchFunction(matcher)) {
1046 return matcher.match(action);
1047 }
1048 else {
1049 return matcher(action);
1050 }
1051};
1052function isAnyOf(...matchers) {
1053 return (action) => {
1054 return matchers.some((matcher) => matches(matcher, action));
1055 };
1056}
1057function isAllOf(...matchers) {
1058 return (action) => {
1059 return matchers.every((matcher) => matches(matcher, action));
1060 };
1061}
1062function hasExpectedRequestMetadata(action, validStatus) {
1063 if (!action || !action.meta)
1064 return false;
1065 const hasValidRequestId = typeof action.meta.requestId === "string";
1066 const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
1067 return hasValidRequestId && hasValidRequestStatus;
1068}
1069function isAsyncThunkArray(a) {
1070 return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
1071}
1072function isPending(...asyncThunks) {
1073 if (asyncThunks.length === 0) {
1074 return (action) => hasExpectedRequestMetadata(action, ["pending"]);
1075 }
1076 if (!isAsyncThunkArray(asyncThunks)) {
1077 return isPending()(asyncThunks[0]);
1078 }
1079 return (action) => {
1080 const matchers = asyncThunks.map((asyncThunk) => asyncThunk.pending);
1081 const combinedMatcher = isAnyOf(...matchers);
1082 return combinedMatcher(action);
1083 };
1084}
1085function isRejected(...asyncThunks) {
1086 if (asyncThunks.length === 0) {
1087 return (action) => hasExpectedRequestMetadata(action, ["rejected"]);
1088 }
1089 if (!isAsyncThunkArray(asyncThunks)) {
1090 return isRejected()(asyncThunks[0]);
1091 }
1092 return (action) => {
1093 const matchers = asyncThunks.map((asyncThunk) => asyncThunk.rejected);
1094 const combinedMatcher = isAnyOf(...matchers);
1095 return combinedMatcher(action);
1096 };
1097}
1098function isRejectedWithValue(...asyncThunks) {
1099 const hasFlag = (action) => {
1100 return action && action.meta && action.meta.rejectedWithValue;
1101 };
1102 if (asyncThunks.length === 0) {
1103 return (action) => {
1104 const combinedMatcher = isAllOf(isRejected(...asyncThunks), hasFlag);
1105 return combinedMatcher(action);
1106 };
1107 }
1108 if (!isAsyncThunkArray(asyncThunks)) {
1109 return isRejectedWithValue()(asyncThunks[0]);
1110 }
1111 return (action) => {
1112 const combinedMatcher = isAllOf(isRejected(...asyncThunks), hasFlag);
1113 return combinedMatcher(action);
1114 };
1115}
1116function isFulfilled(...asyncThunks) {
1117 if (asyncThunks.length === 0) {
1118 return (action) => hasExpectedRequestMetadata(action, ["fulfilled"]);
1119 }
1120 if (!isAsyncThunkArray(asyncThunks)) {
1121 return isFulfilled()(asyncThunks[0]);
1122 }
1123 return (action) => {
1124 const matchers = asyncThunks.map((asyncThunk) => asyncThunk.fulfilled);
1125 const combinedMatcher = isAnyOf(...matchers);
1126 return combinedMatcher(action);
1127 };
1128}
1129function isAsyncThunkAction(...asyncThunks) {
1130 if (asyncThunks.length === 0) {
1131 return (action) => hasExpectedRequestMetadata(action, ["pending", "fulfilled", "rejected"]);
1132 }
1133 if (!isAsyncThunkArray(asyncThunks)) {
1134 return isAsyncThunkAction()(asyncThunks[0]);
1135 }
1136 return (action) => {
1137 const matchers = [];
1138 for (const asyncThunk of asyncThunks) {
1139 matchers.push(asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled);
1140 }
1141 const combinedMatcher = isAnyOf(...matchers);
1142 return combinedMatcher(action);
1143 };
1144}
1145// src/index.ts
1146enableES5();
1147export { MiddlewareArray, configureStore, createAction, createAsyncThunk, createDraftSafeSelector, createEntityAdapter, createImmutableStateInvariantMiddleware, 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, unwrapResult };
1148//# sourceMappingURL=module.js.map
\No newline at end of file