@depup/reduxjs__toolkit 2.12.0-depup.29 → 2.13.0-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +2 -2
  2. package/changes.json +1 -1
  3. package/dist/cjs/redux-toolkit.development.cjs +1755 -2247
  4. package/dist/cjs/redux-toolkit.development.cjs.map +1 -1
  5. package/dist/cjs/redux-toolkit.production.min.cjs +1 -2
  6. package/dist/cjs/redux-toolkit.production.min.cjs.map +1 -1
  7. package/dist/index.d.mts +1496 -1525
  8. package/dist/index.d.ts +1496 -1525
  9. package/dist/query/cjs/rtk-query.development.cjs +2059 -2990
  10. package/dist/query/cjs/rtk-query.development.cjs.map +1 -1
  11. package/dist/query/cjs/rtk-query.production.min.cjs +1 -1
  12. package/dist/query/cjs/rtk-query.production.min.cjs.map +1 -1
  13. package/dist/query/index.d.mts +2300 -2308
  14. package/dist/query/index.d.ts +2300 -2308
  15. package/dist/query/react/cjs/rtk-query-react.development.cjs +609 -714
  16. package/dist/query/react/cjs/rtk-query-react.development.cjs.map +1 -1
  17. package/dist/query/react/cjs/rtk-query-react.production.min.cjs +1 -1
  18. package/dist/query/react/cjs/rtk-query-react.production.min.cjs.map +1 -1
  19. package/dist/query/react/index.d.mts +516 -523
  20. package/dist/query/react/index.d.ts +516 -523
  21. package/dist/query/react/rtk-query-react.browser.mjs +1 -1
  22. package/dist/query/react/rtk-query-react.browser.mjs.map +1 -1
  23. package/dist/query/react/rtk-query-react.legacy-esm.js +672 -714
  24. package/dist/query/react/rtk-query-react.legacy-esm.js.map +1 -1
  25. package/dist/query/react/rtk-query-react.modern.mjs +586 -679
  26. package/dist/query/react/rtk-query-react.modern.mjs.map +1 -1
  27. package/dist/query/rtk-query.browser.mjs +1 -1
  28. package/dist/query/rtk-query.browser.mjs.map +1 -1
  29. package/dist/query/rtk-query.legacy-esm.js +2175 -3014
  30. package/dist/query/rtk-query.legacy-esm.js.map +1 -1
  31. package/dist/query/rtk-query.modern.mjs +2052 -2949
  32. package/dist/query/rtk-query.modern.mjs.map +1 -1
  33. package/dist/react/cjs/redux-toolkit-react.development.cjs +30 -51
  34. package/dist/react/cjs/redux-toolkit-react.development.cjs.map +1 -1
  35. package/dist/react/cjs/redux-toolkit-react.production.min.cjs +1 -1
  36. package/dist/react/cjs/redux-toolkit-react.production.min.cjs.map +1 -1
  37. package/dist/react/index.d.mts +12 -15
  38. package/dist/react/index.d.ts +12 -15
  39. package/dist/react/redux-toolkit-react.browser.mjs +1 -1
  40. package/dist/react/redux-toolkit-react.browser.mjs.map +1 -1
  41. package/dist/react/redux-toolkit-react.legacy-esm.js +83 -44
  42. package/dist/react/redux-toolkit-react.legacy-esm.js.map +1 -1
  43. package/dist/react/redux-toolkit-react.modern.mjs +23 -25
  44. package/dist/react/redux-toolkit-react.modern.mjs.map +1 -1
  45. package/dist/redux-toolkit.browser.mjs +1 -2
  46. package/dist/redux-toolkit.browser.mjs.map +1 -1
  47. package/dist/redux-toolkit.legacy-esm.js +1748 -2201
  48. package/dist/redux-toolkit.legacy-esm.js.map +1 -1
  49. package/dist/redux-toolkit.modern.mjs +1670 -2171
  50. package/dist/redux-toolkit.modern.mjs.map +1 -1
  51. package/package.json +13 -29
  52. package/skills/build-modern-redux-apps/modern-redux/SKILL.md +23 -14
  53. package/skills/build-modern-redux-apps/modern-redux/references/store-lifetime.md +6 -6
  54. package/skills/build-modern-redux-apps/redux-dataflow/SKILL.md +13 -10
  55. package/skills/evolve-and-diagnose-redux-apps/debug-redux-toolkit-apps/SKILL.md +6 -6
  56. package/skills/evolve-and-diagnose-redux-apps/migrate-to-modern-redux/SKILL.md +7 -8
  57. package/skills/manage-server-data/adopt-rtk-query/SKILL.md +13 -11
  58. package/skills/model-redux-state/build-slices-and-selectors/SKILL.md +26 -14
  59. package/skills/model-redux-state/design-state-ownership/SKILL.md +11 -12
  60. package/skills/model-redux-state/design-state-ownership/references/state-ownership.md +6 -6
  61. package/skills/orchestrate-side-effects/handle-side-effects/SKILL.md +27 -23
  62. package/skills/orchestrate-side-effects/handle-side-effects/references/listener-workflows.md +4 -4
  63. package/src/autoBatchEnhancer.ts +5 -3
  64. package/src/combineSlices.ts +5 -5
  65. package/src/createAction.ts +11 -6
  66. package/src/createAsyncThunk.ts +14 -2
  67. package/src/createReducer.ts +1 -1
  68. package/src/createSlice.ts +9 -4
  69. package/src/dynamicMiddleware/index.ts +21 -5
  70. package/src/entities/models.ts +2 -1
  71. package/src/entities/sorted_state_adapter.ts +35 -24
  72. package/src/entities/unsorted_state_adapter.ts +1 -1
  73. package/src/immutableStateInvariantMiddleware.ts +34 -5
  74. package/src/listenerMiddleware/types.ts +10 -10
  75. package/src/mapBuilders.ts +2 -5
  76. package/src/matchers.ts +7 -1
  77. package/src/query/core/apiState.ts +1 -1
  78. package/src/query/core/buildInitiate.ts +19 -15
  79. package/src/query/core/buildMiddleware/cacheLifecycle.ts +3 -1
  80. package/src/query/core/buildMiddleware/index.ts +1 -1
  81. package/src/query/core/buildMiddleware/invalidationByTags.ts +4 -1
  82. package/src/query/core/buildMiddleware/polling.ts +12 -3
  83. package/src/query/core/buildMiddleware/types.ts +5 -2
  84. package/src/query/core/buildSlice.ts +2 -2
  85. package/src/query/core/buildThunks.ts +19 -0
  86. package/src/query/core/module.ts +9 -3
  87. package/src/query/createApi.ts +4 -1
  88. package/src/query/endpointDefinitions.ts +15 -9
  89. package/src/query/fetchBaseQuery.ts +1 -1
  90. package/src/query/react/buildHooks.ts +54 -51
  91. package/src/query/react/namedHooks.ts +28 -24
  92. package/src/query/utils/isAbsoluteUrl.ts +8 -3
  93. package/src/serializableStateInvariantMiddleware.ts +1 -1
@@ -1,2351 +1,1898 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __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
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __objRest = (source, exclude) => {
21
- var target = {};
22
- for (var prop in source)
23
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
- target[prop] = source[prop];
25
- if (source != null && __getOwnPropSymbols)
26
- for (var prop of __getOwnPropSymbols(source)) {
27
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
- target[prop] = source[prop];
29
- }
30
- return target;
31
- };
32
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
33
-
34
- // src/index.ts
1
+ import { applyMiddleware, combineReducers, combineReducers as combineReducers$1, compose, createStore, isAction, isPlainObject } from "redux";
2
+ import { current, freeze, isDraft, isDraftable, original, produce as createNextState } from "immer";
3
+ import { createSelector, createSelectorCreator, lruMemoize, weakMapMemoize } from "reselect";
4
+ import { thunk, withExtraArgument } from "redux-thunk";
35
5
  export * from "redux";
36
- import { freeze, original as original2 } from "immer";
37
-
38
- // src/immerImports.ts
39
- import { current, isDraft, produce, isDraftable, setUseStrictIteration } from "immer";
40
-
41
- // src/index.ts
42
- import { createSelector, lruMemoize } from "reselect";
43
-
44
- // src/reselectImports.ts
45
- import { createSelectorCreator, weakMapMemoize } from "reselect";
46
-
47
- // src/createDraftSafeSelector.ts
48
- var createDraftSafeSelectorCreator = (...args) => {
49
- const createSelector2 = createSelectorCreator(...args);
50
- const createDraftSafeSelector2 = Object.assign((...args2) => {
51
- const selector = createSelector2(...args2);
52
- const wrappedSelector = (value, ...rest) => selector(isDraft(value) ? current(value) : value, ...rest);
53
- Object.assign(wrappedSelector, selector);
54
- return wrappedSelector;
55
- }, {
56
- withTypes: () => createDraftSafeSelector2
57
- });
58
- return createDraftSafeSelector2;
6
+ //#region src/createDraftSafeSelector.ts
7
+ const createDraftSafeSelectorCreator = (...args) => {
8
+ const createSelector = createSelectorCreator(...args);
9
+ const createDraftSafeSelector = Object.assign((...args) => {
10
+ const selector = createSelector(...args);
11
+ const wrappedSelector = (value, ...rest) => selector(isDraft(value) ? current(value) : value, ...rest);
12
+ Object.assign(wrappedSelector, selector);
13
+ return wrappedSelector;
14
+ }, { withTypes: () => createDraftSafeSelector });
15
+ return createDraftSafeSelector;
59
16
  };
60
- var createDraftSafeSelector = /* @__PURE__ */ createDraftSafeSelectorCreator(weakMapMemoize);
61
-
62
- // src/reduxImports.ts
63
- import { createStore, combineReducers, applyMiddleware, compose, isPlainObject, isAction } from "redux";
64
-
65
- // src/devtoolsExtension.ts
66
- var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() {
67
- if (arguments.length === 0) return void 0;
68
- if (typeof arguments[0] === "object") return compose;
69
- return compose.apply(null, arguments);
17
+ const createDraftSafeSelector = /* @__PURE__ */ createDraftSafeSelectorCreator(weakMapMemoize);
18
+ //#endregion
19
+ //#region src/devtoolsExtension.ts
20
+ const composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() {
21
+ if (arguments.length === 0) return void 0;
22
+ if (typeof arguments[0] === "object") return compose;
23
+ return compose.apply(null, arguments);
70
24
  };
71
- var devToolsEnhancer = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function() {
72
- return function(noop3) {
73
- return noop3;
74
- };
25
+ typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__;
26
+ //#endregion
27
+ //#region src/tsHelpers.ts
28
+ const hasMatchFunction = (v) => {
29
+ return v && typeof v.match === "function";
75
30
  };
76
-
77
- // src/getDefaultMiddleware.ts
78
- import { thunk as thunkMiddleware, withExtraArgument } from "redux-thunk";
79
-
80
- // src/tsHelpers.ts
81
- var hasMatchFunction = (v) => {
82
- return v && typeof v.match === "function";
83
- };
84
-
85
- // src/createAction.ts
31
+ //#endregion
32
+ //#region \0@oxc-project+runtime@0.144.0/helpers/esm/typeof.js
33
+ function _typeof(o) {
34
+ "@babel/helpers - typeof";
35
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
36
+ return typeof o;
37
+ } : function(o) {
38
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
39
+ }, _typeof(o);
40
+ }
41
+ //#endregion
42
+ //#region \0@oxc-project+runtime@0.144.0/helpers/esm/toPrimitive.js
43
+ function toPrimitive(t, r) {
44
+ if ("object" != _typeof(t) || !t) return t;
45
+ var e = t[Symbol.toPrimitive];
46
+ if (void 0 !== e) {
47
+ var i = e.call(t, r || "default");
48
+ if ("object" != _typeof(i)) return i;
49
+ throw new TypeError("@@toPrimitive must return a primitive value.");
50
+ }
51
+ return ("string" === r ? String : Number)(t);
52
+ }
53
+ //#endregion
54
+ //#region \0@oxc-project+runtime@0.144.0/helpers/esm/toPropertyKey.js
55
+ function toPropertyKey(t) {
56
+ var i = toPrimitive(t, "string");
57
+ return "symbol" == _typeof(i) ? i : i + "";
58
+ }
59
+ //#endregion
60
+ //#region \0@oxc-project+runtime@0.144.0/helpers/esm/defineProperty.js
61
+ function _defineProperty(e, r, t) {
62
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
63
+ value: t,
64
+ enumerable: !0,
65
+ configurable: !0,
66
+ writable: !0
67
+ }) : e[r] = t, e;
68
+ }
69
+ //#endregion
70
+ //#region \0@oxc-project+runtime@0.144.0/helpers/esm/objectSpread2.js
71
+ function ownKeys(e, r) {
72
+ var t = Object.keys(e);
73
+ if (Object.getOwnPropertySymbols) {
74
+ var o = Object.getOwnPropertySymbols(e);
75
+ r && (o = o.filter(function(r) {
76
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
77
+ })), t.push.apply(t, o);
78
+ }
79
+ return t;
80
+ }
81
+ function _objectSpread2(e) {
82
+ for (var r = 1; r < arguments.length; r++) {
83
+ var t = null != arguments[r] ? arguments[r] : {};
84
+ r % 2 ? ownKeys(Object(t), !0).forEach(function(r) {
85
+ _defineProperty(e, r, t[r]);
86
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {
87
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
88
+ });
89
+ }
90
+ return e;
91
+ }
92
+ //#endregion
93
+ //#region src/createAction.ts
86
94
  function createAction(type, prepareAction) {
87
- function actionCreator(...args) {
88
- if (prepareAction) {
89
- let prepared = prepareAction(...args);
90
- if (!prepared) {
91
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(0) : "prepareAction did not return an object");
92
- }
93
- return __spreadValues(__spreadValues({
94
- type,
95
- payload: prepared.payload
96
- }, "meta" in prepared && {
97
- meta: prepared.meta
98
- }), "error" in prepared && {
99
- error: prepared.error
100
- });
101
- }
102
- return {
103
- type,
104
- payload: args[0]
105
- };
106
- }
107
- actionCreator.toString = () => `${type}`;
108
- actionCreator.type = type;
109
- actionCreator.match = (action) => isAction(action) && action.type === type;
110
- return actionCreator;
95
+ function actionCreator(...args) {
96
+ if (prepareAction) {
97
+ let prepared = prepareAction(...args);
98
+ if (!prepared) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(0) : "prepareAction did not return an object");
99
+ return _objectSpread2(_objectSpread2({
100
+ type,
101
+ payload: prepared.payload
102
+ }, "meta" in prepared && { meta: prepared.meta }), "error" in prepared && { error: prepared.error });
103
+ }
104
+ return {
105
+ type,
106
+ payload: args[0]
107
+ };
108
+ }
109
+ actionCreator.toString = () => `${type}`;
110
+ actionCreator.type = type;
111
+ actionCreator.match = (action) => isAction(action) && action.type === type;
112
+ return actionCreator;
111
113
  }
112
114
  function isActionCreator(action) {
113
- return typeof action === "function" && "type" in action && // hasMatchFunction only wants Matchers but I don't see the point in rewriting it
114
- hasMatchFunction(action);
115
+ return typeof action === "function" && "type" in action && hasMatchFunction(action);
115
116
  }
116
117
  function isFSA(action) {
117
- return isAction(action) && Object.keys(action).every(isValidKey);
118
+ return isAction(action) && Object.keys(action).every(isValidKey);
118
119
  }
119
120
  function isValidKey(key) {
120
- return ["type", "payload", "error", "meta"].indexOf(key) > -1;
121
+ return [
122
+ "type",
123
+ "payload",
124
+ "error",
125
+ "meta"
126
+ ].indexOf(key) > -1;
121
127
  }
122
-
123
- // src/actionCreatorInvariantMiddleware.ts
128
+ //#endregion
129
+ //#region src/actionCreatorInvariantMiddleware.ts
124
130
  function getMessage(type) {
125
- const splitType = type ? `${type}`.split("/") : [];
126
- const actionName = splitType[splitType.length - 1] || "actionCreator";
127
- return `Detected an action creator with type "${type || "unknown"}" being dispatched.
131
+ const splitType = type ? `${type}`.split("/") : [];
132
+ const actionName = splitType[splitType.length - 1] || "actionCreator";
133
+ return `Detected an action creator with type "${type || "unknown"}" being dispatched.
128
134
  Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${actionName}())\` instead of \`dispatch(${actionName})\`. This is necessary even if the action has no payload.`;
129
135
  }
130
136
  function createActionCreatorInvariantMiddleware(options = {}) {
131
- if (process.env.NODE_ENV === "production") {
132
- return () => (next) => (action) => next(action);
133
- }
134
- const {
135
- isActionCreator: isActionCreator2 = isActionCreator
136
- } = options;
137
- return () => (next) => (action) => {
138
- if (isActionCreator2(action)) {
139
- console.warn(getMessage(action.type));
140
- }
141
- return next(action);
142
- };
137
+ if (process.env.NODE_ENV === "production") return () => (next) => (action) => next(action);
138
+ const { isActionCreator: isActionCreator$1 = isActionCreator } = options;
139
+ return () => (next) => (action) => {
140
+ if (isActionCreator$1(action)) console.warn(getMessage(action.type));
141
+ return next(action);
142
+ };
143
143
  }
144
-
145
- // src/utils.ts
144
+ //#endregion
145
+ //#region src/utils.ts
146
146
  function getTimeMeasureUtils(maxDelay, fnName) {
147
- let elapsed = 0;
148
- return {
149
- measureTime(fn) {
150
- const started = Date.now();
151
- try {
152
- return fn();
153
- } finally {
154
- const finished = Date.now();
155
- elapsed += finished - started;
156
- }
157
- },
158
- warnIfExceeded() {
159
- if (elapsed > maxDelay) {
160
- console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms.
147
+ let elapsed = 0;
148
+ return {
149
+ measureTime(fn) {
150
+ const started = Date.now();
151
+ try {
152
+ return fn();
153
+ } finally {
154
+ elapsed += Date.now() - started;
155
+ }
156
+ },
157
+ warnIfExceeded() {
158
+ if (elapsed > maxDelay) console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms.
161
159
  If your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.
162
160
  It is disabled in production builds, so you don't need to worry about that.`);
163
- }
164
- }
165
- };
166
- }
167
- var Tuple = class _Tuple extends Array {
168
- constructor(...items) {
169
- super(...items);
170
- Object.setPrototypeOf(this, _Tuple.prototype);
171
- }
172
- static get [Symbol.species]() {
173
- return _Tuple;
174
- }
175
- concat(...arr) {
176
- return super.concat.apply(this, arr);
177
- }
178
- prepend(...arr) {
179
- if (arr.length === 1 && Array.isArray(arr[0])) {
180
- return new _Tuple(...arr[0].concat(this));
181
- }
182
- return new _Tuple(...arr.concat(this));
183
- }
161
+ }
162
+ };
163
+ }
164
+ var Tuple = class Tuple extends Array {
165
+ constructor(...items) {
166
+ super(...items);
167
+ Object.setPrototypeOf(this, Tuple.prototype);
168
+ }
169
+ static get [Symbol.species]() {
170
+ return Tuple;
171
+ }
172
+ concat(...arr) {
173
+ return super.concat.apply(this, arr);
174
+ }
175
+ prepend(...arr) {
176
+ if (arr.length === 1 && Array.isArray(arr[0])) return new Tuple(...arr[0].concat(this));
177
+ return new Tuple(...arr.concat(this));
178
+ }
184
179
  };
185
180
  function freezeDraftable(val) {
186
- return isDraftable(val) ? produce(val, () => {
187
- }) : val;
181
+ return isDraftable(val) ? createNextState(val, () => {}) : val;
188
182
  }
189
183
  function getOrInsertComputed(map, key, compute) {
190
- if (map.has(key)) return map.get(key);
191
- return map.set(key, compute(key)).get(key);
184
+ if (map.has(key)) return map.get(key);
185
+ return map.set(key, compute(key)).get(key);
192
186
  }
193
-
194
- // src/immutableStateInvariantMiddleware.ts
187
+ //#endregion
188
+ //#region src/immutableStateInvariantMiddleware.ts
195
189
  function isImmutableDefault(value) {
196
- return typeof value !== "object" || value == null || Object.isFrozen(value);
190
+ return typeof value !== "object" || value == null || Object.isFrozen(value);
197
191
  }
198
192
  function trackForMutations(isImmutable, ignoredPaths, obj) {
199
- const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj);
200
- return {
201
- detectMutations() {
202
- return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj);
203
- }
204
- };
205
- }
206
- function trackProperties(isImmutable, ignoredPaths = [], obj, path = "", checkedObjects = /* @__PURE__ */ new Set()) {
207
- const tracked = {
208
- value: obj
209
- };
210
- if (!isImmutable(obj) && !checkedObjects.has(obj)) {
211
- checkedObjects.add(obj);
212
- tracked.children = {};
213
- const hasIgnoredPaths = ignoredPaths.length > 0;
214
- for (const key in obj) {
215
- const nestedPath = path ? path + "." + key : key;
216
- if (hasIgnoredPaths) {
217
- const hasMatches = ignoredPaths.some((ignored) => {
218
- if (ignored instanceof RegExp) {
219
- return ignored.test(nestedPath);
220
- }
221
- return nestedPath === ignored;
222
- });
223
- if (hasMatches) {
224
- continue;
225
- }
226
- }
227
- tracked.children[key] = trackProperties(isImmutable, ignoredPaths, obj[key], nestedPath);
228
- }
229
- }
230
- return tracked;
231
- }
232
- function detectMutations(isImmutable, ignoredPaths = [], trackedProperty, obj, sameParentRef = false, path = "") {
233
- const prevObj = trackedProperty ? trackedProperty.value : void 0;
234
- const sameRef = prevObj === obj;
235
- if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
236
- return {
237
- wasMutated: true,
238
- path
239
- };
240
- }
241
- if (isImmutable(prevObj) || isImmutable(obj)) {
242
- return {
243
- wasMutated: false
244
- };
245
- }
246
- const keysToDetect = {};
247
- for (let key in trackedProperty.children) {
248
- keysToDetect[key] = true;
249
- }
250
- for (let key in obj) {
251
- keysToDetect[key] = true;
252
- }
253
- const hasIgnoredPaths = ignoredPaths.length > 0;
254
- for (let key in keysToDetect) {
255
- const nestedPath = path ? path + "." + key : key;
256
- if (hasIgnoredPaths) {
257
- const hasMatches = ignoredPaths.some((ignored) => {
258
- if (ignored instanceof RegExp) {
259
- return ignored.test(nestedPath);
260
- }
261
- return nestedPath === ignored;
262
- });
263
- if (hasMatches) {
264
- continue;
265
- }
266
- }
267
- const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);
268
- if (result.wasMutated) {
269
- return result;
270
- }
271
- }
272
- return {
273
- wasMutated: false
274
- };
193
+ const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj);
194
+ return { detectMutations() {
195
+ return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj);
196
+ } };
197
+ }
198
+ function trackProperties(isImmutable, ignoredPaths = [], obj, path = "", inProgress = /* @__PURE__ */ new Map()) {
199
+ const tracked = { value: obj };
200
+ if (!isImmutable(obj)) {
201
+ const alreadyInProgress = inProgress.get(obj);
202
+ if (alreadyInProgress) return alreadyInProgress;
203
+ tracked.children = {};
204
+ inProgress.set(obj, tracked);
205
+ const hasIgnoredPaths = ignoredPaths.length > 0;
206
+ for (const key in obj) {
207
+ const nestedPath = path ? path + "." + key : key;
208
+ if (hasIgnoredPaths) {
209
+ if (ignoredPaths.some((ignored) => {
210
+ if (ignored instanceof RegExp) return ignored.test(nestedPath);
211
+ return nestedPath === ignored;
212
+ })) continue;
213
+ }
214
+ tracked.children[key] = trackProperties(isImmutable, ignoredPaths, obj[key], nestedPath, inProgress);
215
+ }
216
+ inProgress.delete(obj);
217
+ }
218
+ return tracked;
219
+ }
220
+ function detectMutations(isImmutable, ignoredPaths = [], trackedProperty, obj, sameParentRef = false, path = "", seen = /* @__PURE__ */ new Map()) {
221
+ const prevObj = trackedProperty ? trackedProperty.value : void 0;
222
+ const sameRef = prevObj === obj;
223
+ if (sameParentRef && !sameRef && !Number.isNaN(obj)) return {
224
+ wasMutated: true,
225
+ path
226
+ };
227
+ if (isImmutable(prevObj) || isImmutable(obj)) return { wasMutated: false };
228
+ let seenValues = seen.get(trackedProperty);
229
+ if (!seenValues) {
230
+ seenValues = /* @__PURE__ */ new Set();
231
+ seen.set(trackedProperty, seenValues);
232
+ } else if (seenValues.has(obj)) return { wasMutated: false };
233
+ seenValues.add(obj);
234
+ const keysToDetect = {};
235
+ for (let key in trackedProperty.children) keysToDetect[key] = true;
236
+ for (let key in obj) keysToDetect[key] = true;
237
+ const hasIgnoredPaths = ignoredPaths.length > 0;
238
+ for (let key in keysToDetect) {
239
+ const nestedPath = path ? path + "." + key : key;
240
+ if (hasIgnoredPaths) {
241
+ if (ignoredPaths.some((ignored) => {
242
+ if (ignored instanceof RegExp) return ignored.test(nestedPath);
243
+ return nestedPath === ignored;
244
+ })) continue;
245
+ }
246
+ const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath, seen);
247
+ if (result.wasMutated) return result;
248
+ }
249
+ return { wasMutated: false };
275
250
  }
276
251
  function createImmutableStateInvariantMiddleware(options = {}) {
277
- if (process.env.NODE_ENV === "production") {
278
- return () => (next) => (action) => next(action);
279
- } else {
280
- let stringify2 = function(obj, serializer, indent, decycler) {
281
- return JSON.stringify(obj, getSerialize2(serializer, decycler), indent);
282
- }, getSerialize2 = function(serializer, decycler) {
283
- let stack = [], keys = [];
284
- if (!decycler) decycler = function(_, value) {
285
- if (stack[0] === value) return "[Circular ~]";
286
- return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
287
- };
288
- return function(key, value) {
289
- if (stack.length > 0) {
290
- var thisPos = stack.indexOf(this);
291
- ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
292
- ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
293
- if (~stack.indexOf(value)) value = decycler.call(this, key, value);
294
- } else stack.push(value);
295
- return serializer == null ? value : serializer.call(this, key, value);
296
- };
297
- };
298
- var stringify = stringify2, getSerialize = getSerialize2;
299
- let {
300
- isImmutable = isImmutableDefault,
301
- ignoredPaths,
302
- warnAfter = 32
303
- } = options;
304
- const track = trackForMutations.bind(null, isImmutable, ignoredPaths);
305
- return ({
306
- getState
307
- }) => {
308
- let state = getState();
309
- let tracker = track(state);
310
- let result;
311
- return (next) => (action) => {
312
- const measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
313
- measureUtils.measureTime(() => {
314
- state = getState();
315
- result = tracker.detectMutations();
316
- tracker = track(state);
317
- if (result.wasMutated) {
318
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || ""}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
319
- }
320
- });
321
- const dispatchedAction = next(action);
322
- measureUtils.measureTime(() => {
323
- state = getState();
324
- result = tracker.detectMutations();
325
- tracker = track(state);
326
- if (result.wasMutated) {
327
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || ""}. Take a look at the reducer(s) handling the action ${stringify2(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
328
- }
329
- });
330
- measureUtils.warnIfExceeded();
331
- return dispatchedAction;
332
- };
333
- };
334
- }
252
+ if (process.env.NODE_ENV === "production") return () => (next) => (action) => next(action);
253
+ else {
254
+ function stringify(obj, serializer, indent, decycler) {
255
+ return JSON.stringify(obj, getSerialize(serializer, decycler), indent);
256
+ }
257
+ function getSerialize(serializer, decycler) {
258
+ let stack = [], keys = [];
259
+ if (!decycler) decycler = function(_, value) {
260
+ if (stack[0] === value) return "[Circular ~]";
261
+ return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
262
+ };
263
+ return function(key, value) {
264
+ if (stack.length > 0) {
265
+ var thisPos = stack.indexOf(this);
266
+ if (~thisPos) {
267
+ stack.splice(thisPos + 1);
268
+ keys.splice(thisPos, Infinity, key);
269
+ } else {
270
+ stack.push(this);
271
+ keys.push(key);
272
+ }
273
+ if (~stack.indexOf(value)) value = decycler.call(this, key, value);
274
+ } else stack.push(value);
275
+ return serializer == null ? value : serializer.call(this, key, value);
276
+ };
277
+ }
278
+ let { isImmutable = isImmutableDefault, ignoredPaths, warnAfter = 32 } = options;
279
+ const track = trackForMutations.bind(null, isImmutable, ignoredPaths);
280
+ return ({ getState }) => {
281
+ let state = getState();
282
+ let tracker = track(state);
283
+ let result;
284
+ return (next) => (action) => {
285
+ const measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
286
+ measureUtils.measureTime(() => {
287
+ state = getState();
288
+ result = tracker.detectMutations();
289
+ tracker = track(state);
290
+ if (result.wasMutated) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || ""}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
291
+ });
292
+ const dispatchedAction = next(action);
293
+ measureUtils.measureTime(() => {
294
+ state = getState();
295
+ result = tracker.detectMutations();
296
+ tracker = track(state);
297
+ if (result.wasMutated) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || ""}. Take a look at the reducer(s) handling the action ${stringify(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);
298
+ });
299
+ measureUtils.warnIfExceeded();
300
+ return dispatchedAction;
301
+ };
302
+ };
303
+ }
335
304
  }
336
-
337
- // src/serializableStateInvariantMiddleware.ts
305
+ //#endregion
306
+ //#region src/serializableStateInvariantMiddleware.ts
338
307
  function isPlain(val) {
339
- const type = typeof val;
340
- return val == null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || isPlainObject(val);
308
+ const type = typeof val;
309
+ return val == null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || isPlainObject(val);
341
310
  }
342
311
  function findNonSerializableValue(value, path = "", isSerializable = isPlain, getEntries, ignoredPaths = [], cache) {
343
- let foundNestedSerializable;
344
- if (!isSerializable(value)) {
345
- return {
346
- keyPath: path || "<root>",
347
- value
348
- };
349
- }
350
- if (typeof value !== "object" || value === null) {
351
- return false;
352
- }
353
- if (cache == null ? void 0 : cache.has(value)) return false;
354
- const entries = getEntries != null ? getEntries(value) : Object.entries(value);
355
- const hasIgnoredPaths = ignoredPaths.length > 0;
356
- for (const [key, nestedValue] of entries) {
357
- const nestedPath = path ? path + "." + key : key;
358
- if (hasIgnoredPaths) {
359
- const hasMatches = ignoredPaths.some((ignored) => {
360
- if (ignored instanceof RegExp) {
361
- return ignored.test(nestedPath);
362
- }
363
- return nestedPath === ignored;
364
- });
365
- if (hasMatches) {
366
- continue;
367
- }
368
- }
369
- if (!isSerializable(nestedValue)) {
370
- return {
371
- keyPath: nestedPath,
372
- value: nestedValue
373
- };
374
- }
375
- if (typeof nestedValue === "object") {
376
- foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);
377
- if (foundNestedSerializable) {
378
- return foundNestedSerializable;
379
- }
380
- }
381
- }
382
- if (cache && isNestedFrozen(value)) cache.add(value);
383
- return false;
312
+ let foundNestedSerializable;
313
+ if (!isSerializable(value)) return {
314
+ keyPath: path || "<root>",
315
+ value
316
+ };
317
+ if (typeof value !== "object" || value === null) return false;
318
+ if (cache === null || cache === void 0 ? void 0 : cache.has(value)) return false;
319
+ const entries = getEntries != null ? getEntries(value) : Object.entries(value);
320
+ const hasIgnoredPaths = ignoredPaths.length > 0;
321
+ for (const [key, nestedValue] of entries) {
322
+ const nestedPath = path ? path + "." + key : key;
323
+ if (hasIgnoredPaths) {
324
+ if (ignoredPaths.some((ignored) => {
325
+ if (ignored instanceof RegExp) return ignored.test(nestedPath);
326
+ return nestedPath === ignored;
327
+ })) continue;
328
+ }
329
+ if (!isSerializable(nestedValue)) return {
330
+ keyPath: nestedPath,
331
+ value: nestedValue
332
+ };
333
+ if (typeof nestedValue === "object") {
334
+ foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);
335
+ if (foundNestedSerializable) return foundNestedSerializable;
336
+ }
337
+ }
338
+ if (cache && isNestedFrozen(value)) cache.add(value);
339
+ return false;
384
340
  }
385
341
  function isNestedFrozen(value) {
386
- if (!Object.isFrozen(value)) return false;
387
- for (const nestedValue of Object.values(value)) {
388
- if (typeof nestedValue !== "object" || nestedValue === null) continue;
389
- if (!isNestedFrozen(nestedValue)) return false;
390
- }
391
- return true;
342
+ if (!Object.isFrozen(value)) return false;
343
+ for (const nestedValue of Object.values(value)) {
344
+ if (typeof nestedValue !== "object" || nestedValue === null) continue;
345
+ if (!isNestedFrozen(nestedValue)) return false;
346
+ }
347
+ return true;
392
348
  }
393
349
  function createSerializableStateInvariantMiddleware(options = {}) {
394
- if (process.env.NODE_ENV === "production") {
395
- return () => (next) => (action) => next(action);
396
- } else {
397
- const {
398
- isSerializable = isPlain,
399
- getEntries,
400
- ignoredActions = [],
401
- ignoredActionPaths = ["meta.arg", "meta.baseQueryMeta"],
402
- ignoredPaths = [],
403
- warnAfter = 32,
404
- ignoreState = false,
405
- ignoreActions = false,
406
- disableCache = false
407
- } = options;
408
- const cache = !disableCache && WeakSet ? /* @__PURE__ */ new WeakSet() : void 0;
409
- return (storeAPI) => (next) => (action) => {
410
- if (!isAction(action)) {
411
- return next(action);
412
- }
413
- const result = next(action);
414
- const measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
415
- if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {
416
- measureUtils.measureTime(() => {
417
- const foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths, cache);
418
- if (foundActionNonSerializableValue) {
419
- const {
420
- keyPath,
421
- value
422
- } = foundActionNonSerializableValue;
423
- 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)");
424
- }
425
- });
426
- }
427
- if (!ignoreState) {
428
- measureUtils.measureTime(() => {
429
- const state = storeAPI.getState();
430
- const foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths, cache);
431
- if (foundStateNonSerializableValue) {
432
- const {
433
- keyPath,
434
- value
435
- } = foundStateNonSerializableValue;
436
- console.error(`A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`, value, `
350
+ if (process.env.NODE_ENV === "production") return () => (next) => (action) => next(action);
351
+ else {
352
+ const { isSerializable = isPlain, getEntries, ignoredActions = [], ignoredActionPaths = ["meta.arg", "meta.baseQueryMeta"], ignoredPaths = [], warnAfter = 32, ignoreState = false, ignoreActions = false, disableCache = false } = options;
353
+ const cache = !disableCache && WeakSet ? /* @__PURE__ */ new WeakSet() : void 0;
354
+ return (storeAPI) => (next) => (action) => {
355
+ if (!isAction(action)) return next(action);
356
+ const result = next(action);
357
+ const measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
358
+ if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) measureUtils.measureTime(() => {
359
+ const foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths, cache);
360
+ if (foundActionNonSerializableValue) {
361
+ const { keyPath, value } = foundActionNonSerializableValue;
362
+ 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-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)");
363
+ }
364
+ });
365
+ if (!ignoreState) {
366
+ measureUtils.measureTime(() => {
367
+ const foundStateNonSerializableValue = findNonSerializableValue(storeAPI.getState(), "", isSerializable, getEntries, ignoredPaths, cache);
368
+ if (foundStateNonSerializableValue) {
369
+ const { keyPath, value } = foundStateNonSerializableValue;
370
+ console.error(`A non-serializable value was detected in the state, in the path: \`${keyPath}\`. Value:`, value, `
437
371
  Take a look at the reducer(s) handling this action type: ${action.type}.
438
372
  (See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);
439
- }
440
- });
441
- measureUtils.warnIfExceeded();
442
- }
443
- return result;
444
- };
445
- }
373
+ }
374
+ });
375
+ measureUtils.warnIfExceeded();
376
+ }
377
+ return result;
378
+ };
379
+ }
446
380
  }
447
-
448
- // src/getDefaultMiddleware.ts
381
+ //#endregion
382
+ //#region src/getDefaultMiddleware.ts
449
383
  function isBoolean(x) {
450
- return typeof x === "boolean";
451
- }
452
- var buildGetDefaultMiddleware = () => function getDefaultMiddleware(options) {
453
- const {
454
- thunk = true,
455
- immutableCheck = true,
456
- serializableCheck = true,
457
- actionCreatorCheck = true
458
- } = options != null ? options : {};
459
- let middlewareArray = new Tuple();
460
- if (thunk) {
461
- if (isBoolean(thunk)) {
462
- middlewareArray.push(thunkMiddleware);
463
- } else {
464
- middlewareArray.push(withExtraArgument(thunk.extraArgument));
465
- }
466
- }
467
- if (process.env.NODE_ENV !== "production") {
468
- if (immutableCheck) {
469
- let immutableOptions = {};
470
- if (!isBoolean(immutableCheck)) {
471
- immutableOptions = immutableCheck;
472
- }
473
- middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
474
- }
475
- if (serializableCheck) {
476
- let serializableOptions = {};
477
- if (!isBoolean(serializableCheck)) {
478
- serializableOptions = serializableCheck;
479
- }
480
- middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
481
- }
482
- if (actionCreatorCheck) {
483
- let actionCreatorOptions = {};
484
- if (!isBoolean(actionCreatorCheck)) {
485
- actionCreatorOptions = actionCreatorCheck;
486
- }
487
- middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));
488
- }
489
- }
490
- return middlewareArray;
384
+ return typeof x === "boolean";
385
+ }
386
+ const buildGetDefaultMiddleware = () => function getDefaultMiddleware(options) {
387
+ const { thunk: thunk$1 = true, immutableCheck = true, serializableCheck = true, actionCreatorCheck = true } = options !== null && options !== void 0 ? options : {};
388
+ let middlewareArray = new Tuple();
389
+ if (thunk$1) {
390
+ if (isBoolean(thunk$1)) middlewareArray.push(thunk);
391
+ else middlewareArray.push(withExtraArgument(thunk$1.extraArgument));
392
+ }
393
+ if (process.env.NODE_ENV !== "production") {
394
+ if (immutableCheck) {
395
+ let immutableOptions = {};
396
+ if (!isBoolean(immutableCheck)) immutableOptions = immutableCheck;
397
+ middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
398
+ }
399
+ if (serializableCheck) {
400
+ let serializableOptions = {};
401
+ if (!isBoolean(serializableCheck)) serializableOptions = serializableCheck;
402
+ middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
403
+ }
404
+ if (actionCreatorCheck) {
405
+ let actionCreatorOptions = {};
406
+ if (!isBoolean(actionCreatorCheck)) actionCreatorOptions = actionCreatorCheck;
407
+ middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));
408
+ }
409
+ }
410
+ return middlewareArray;
491
411
  };
492
-
493
- // src/autoBatchEnhancer.ts
494
- var SHOULD_AUTOBATCH = "RTK_autoBatch";
495
- var prepareAutoBatched = () => (payload) => ({
496
- payload,
497
- meta: {
498
- [SHOULD_AUTOBATCH]: true
499
- }
412
+ //#endregion
413
+ //#region src/autoBatchEnhancer.ts
414
+ const SHOULD_AUTOBATCH = "RTK_autoBatch";
415
+ const prepareAutoBatched = () => (payload) => ({
416
+ payload,
417
+ meta: { [SHOULD_AUTOBATCH]: true }
500
418
  });
501
- var createQueueWithTimer = (timeout) => {
502
- return (notify) => {
503
- setTimeout(notify, timeout);
504
- };
419
+ const createQueueWithTimer = (timeout) => {
420
+ return (notify) => {
421
+ setTimeout(notify, timeout);
422
+ };
505
423
  };
506
- var createRafWithFallbackTimer = (raf, timeout) => {
507
- return (notify) => {
508
- let called = false;
509
- const callback = () => {
510
- if (called) return;
511
- called = true;
512
- cancelAnimationFrame(rafId);
513
- clearTimeout(timerId);
514
- notify();
515
- };
516
- const rafId = raf(callback);
517
- const timerId = setTimeout(callback, timeout);
518
- };
424
+ const createRafWithFallbackTimer = (raf, timeout) => {
425
+ return (notify) => {
426
+ let called = false;
427
+ let rafId;
428
+ let timerId;
429
+ const callback = () => {
430
+ if (called) return;
431
+ called = true;
432
+ cancelAnimationFrame(rafId);
433
+ clearTimeout(timerId);
434
+ notify();
435
+ };
436
+ rafId = raf(callback);
437
+ timerId = setTimeout(callback, timeout);
438
+ };
519
439
  };
520
- var autoBatchEnhancer = (options = {
521
- type: "raf"
522
- }) => (next) => (...args) => {
523
- const store = next(...args);
524
- let notifying = true;
525
- let shouldNotifyAtEndOfTick = false;
526
- let notificationQueued = false;
527
- const listeners = /* @__PURE__ */ new Set();
528
- const queueCallback = options.type === "tick" ? queueMicrotask : options.type === "raf" ? (
529
- // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.
530
- typeof window !== "undefined" && window.requestAnimationFrame ? createRafWithFallbackTimer(window.requestAnimationFrame, 100) : createQueueWithTimer(10)
531
- ) : options.type === "callback" ? options.queueNotification : createQueueWithTimer(options.timeout);
532
- const notifyListeners = () => {
533
- notificationQueued = false;
534
- if (shouldNotifyAtEndOfTick) {
535
- shouldNotifyAtEndOfTick = false;
536
- listeners.forEach((l) => l());
537
- }
538
- };
539
- return Object.assign({}, store, {
540
- // Override the base `store.subscribe` method to keep original listeners
541
- // from running if we're delaying notifications
542
- subscribe(listener2) {
543
- const wrappedListener = () => notifying && listener2();
544
- const unsubscribe = store.subscribe(wrappedListener);
545
- listeners.add(listener2);
546
- return () => {
547
- unsubscribe();
548
- listeners.delete(listener2);
549
- };
550
- },
551
- // Override the base `store.dispatch` method so that we can check actions
552
- // for the `shouldAutoBatch` flag and determine if batching is active
553
- dispatch(action) {
554
- var _a;
555
- try {
556
- notifying = !((_a = action == null ? void 0 : action.meta) == null ? void 0 : _a[SHOULD_AUTOBATCH]);
557
- shouldNotifyAtEndOfTick = !notifying;
558
- if (shouldNotifyAtEndOfTick) {
559
- if (!notificationQueued) {
560
- notificationQueued = true;
561
- queueCallback(notifyListeners);
562
- }
563
- }
564
- return store.dispatch(action);
565
- } finally {
566
- notifying = true;
567
- }
568
- }
569
- });
440
+ const autoBatchEnhancer = (options = { type: "raf" }) => (next) => (...args) => {
441
+ const store = next(...args);
442
+ let notifying = true;
443
+ let shouldNotifyAtEndOfTick = false;
444
+ let notificationQueued = false;
445
+ const listeners = /* @__PURE__ */ new Set();
446
+ const queueCallback = options.type === "tick" ? queueMicrotask : options.type === "raf" ? typeof window !== "undefined" && window.requestAnimationFrame ? createRafWithFallbackTimer(window.requestAnimationFrame, 100) : createQueueWithTimer(10) : options.type === "callback" ? options.queueNotification : createQueueWithTimer(options.timeout);
447
+ const notifyListeners = () => {
448
+ notificationQueued = false;
449
+ if (shouldNotifyAtEndOfTick) {
450
+ shouldNotifyAtEndOfTick = false;
451
+ listeners.forEach((l) => l());
452
+ }
453
+ };
454
+ return Object.assign({}, store, {
455
+ subscribe(listener) {
456
+ const wrappedListener = () => notifying && listener();
457
+ const unsubscribe = store.subscribe(wrappedListener);
458
+ listeners.add(listener);
459
+ return () => {
460
+ unsubscribe();
461
+ listeners.delete(listener);
462
+ };
463
+ },
464
+ dispatch(action) {
465
+ try {
466
+ var _action$meta;
467
+ notifying = !(action === null || action === void 0 || (_action$meta = action.meta) === null || _action$meta === void 0 ? void 0 : _action$meta[SHOULD_AUTOBATCH]);
468
+ shouldNotifyAtEndOfTick = !notifying;
469
+ if (shouldNotifyAtEndOfTick) {
470
+ if (!notificationQueued) {
471
+ notificationQueued = true;
472
+ queueCallback(notifyListeners);
473
+ }
474
+ }
475
+ return store.dispatch(action);
476
+ } finally {
477
+ notifying = true;
478
+ }
479
+ }
480
+ });
570
481
  };
571
-
572
- // src/getDefaultEnhancers.ts
573
- var buildGetDefaultEnhancers = (middlewareEnhancer) => function getDefaultEnhancers(options) {
574
- const {
575
- autoBatch = true
576
- } = options != null ? options : {};
577
- let enhancerArray = new Tuple(middlewareEnhancer);
578
- if (autoBatch) {
579
- enhancerArray.push(autoBatchEnhancer(typeof autoBatch === "object" ? autoBatch : void 0));
580
- }
581
- return enhancerArray;
482
+ //#endregion
483
+ //#region src/getDefaultEnhancers.ts
484
+ const buildGetDefaultEnhancers = (middlewareEnhancer) => function getDefaultEnhancers(options) {
485
+ const { autoBatch = true } = options !== null && options !== void 0 ? options : {};
486
+ let enhancerArray = new Tuple(middlewareEnhancer);
487
+ if (autoBatch) enhancerArray.push(autoBatchEnhancer(typeof autoBatch === "object" ? autoBatch : void 0));
488
+ return enhancerArray;
582
489
  };
583
-
584
- // src/configureStore.ts
490
+ //#endregion
491
+ //#region src/configureStore.ts
585
492
  function configureStore(options) {
586
- const getDefaultMiddleware = buildGetDefaultMiddleware();
587
- const {
588
- reducer = void 0,
589
- middleware,
590
- devTools = true,
591
- duplicateMiddlewareCheck = true,
592
- preloadedState = void 0,
593
- enhancers = void 0
594
- } = options || {};
595
- let rootReducer;
596
- if (typeof reducer === "function") {
597
- rootReducer = reducer;
598
- } else if (isPlainObject(reducer)) {
599
- rootReducer = combineReducers(reducer);
600
- } else {
601
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(1) : "`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");
602
- }
603
- if (process.env.NODE_ENV !== "production" && middleware && typeof middleware !== "function") {
604
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(2) : "`middleware` field must be a callback");
605
- }
606
- let finalMiddleware;
607
- if (typeof middleware === "function") {
608
- finalMiddleware = middleware(getDefaultMiddleware);
609
- if (process.env.NODE_ENV !== "production" && !Array.isArray(finalMiddleware)) {
610
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(3) : "when using a middleware builder function, an array of middleware must be returned");
611
- }
612
- } else {
613
- finalMiddleware = getDefaultMiddleware();
614
- }
615
- if (process.env.NODE_ENV !== "production" && finalMiddleware.some((item) => typeof item !== "function")) {
616
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(4) : "each middleware provided to configureStore must be a function");
617
- }
618
- if (process.env.NODE_ENV !== "production" && duplicateMiddlewareCheck) {
619
- let middlewareReferences = /* @__PURE__ */ new Set();
620
- finalMiddleware.forEach((middleware2) => {
621
- if (middlewareReferences.has(middleware2)) {
622
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(42) : "Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.");
623
- }
624
- middlewareReferences.add(middleware2);
625
- });
626
- }
627
- let finalCompose = compose;
628
- if (devTools) {
629
- finalCompose = composeWithDevTools(__spreadValues({
630
- // Enable capture of stack traces for dispatched Redux actions
631
- trace: process.env.NODE_ENV !== "production"
632
- }, typeof devTools === "object" && devTools));
633
- }
634
- const middlewareEnhancer = applyMiddleware(...finalMiddleware);
635
- const getDefaultEnhancers = buildGetDefaultEnhancers(middlewareEnhancer);
636
- if (process.env.NODE_ENV !== "production" && enhancers && typeof enhancers !== "function") {
637
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(5) : "`enhancers` field must be a callback");
638
- }
639
- let storeEnhancers = typeof enhancers === "function" ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();
640
- if (process.env.NODE_ENV !== "production" && !Array.isArray(storeEnhancers)) {
641
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(6) : "`enhancers` callback must return an array");
642
- }
643
- if (process.env.NODE_ENV !== "production" && storeEnhancers.some((item) => typeof item !== "function")) {
644
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(7) : "each enhancer provided to configureStore must be a function");
645
- }
646
- if (process.env.NODE_ENV !== "production" && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {
647
- console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");
648
- }
649
- const composedEnhancer = finalCompose(...storeEnhancers);
650
- return createStore(rootReducer, preloadedState, composedEnhancer);
493
+ const getDefaultMiddleware = buildGetDefaultMiddleware();
494
+ const { reducer = void 0, middleware, devTools = true, duplicateMiddlewareCheck = true, preloadedState = void 0, enhancers = void 0 } = options || {};
495
+ let rootReducer;
496
+ if (typeof reducer === "function") rootReducer = reducer;
497
+ else if (isPlainObject(reducer)) rootReducer = combineReducers$1(reducer);
498
+ else throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(1) : "`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");
499
+ if (process.env.NODE_ENV !== "production" && middleware && typeof middleware !== "function") throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(2) : "`middleware` field must be a callback");
500
+ let finalMiddleware;
501
+ if (typeof middleware === "function") {
502
+ finalMiddleware = middleware(getDefaultMiddleware);
503
+ if (process.env.NODE_ENV !== "production" && !Array.isArray(finalMiddleware)) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(3) : "when using a middleware builder function, an array of middleware must be returned");
504
+ } else finalMiddleware = getDefaultMiddleware();
505
+ if (process.env.NODE_ENV !== "production" && finalMiddleware.some((item) => typeof item !== "function")) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(4) : "each middleware provided to configureStore must be a function");
506
+ if (process.env.NODE_ENV !== "production" && duplicateMiddlewareCheck) {
507
+ let middlewareReferences = /* @__PURE__ */ new Set();
508
+ finalMiddleware.forEach((middleware) => {
509
+ if (middlewareReferences.has(middleware)) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(42) : "Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.");
510
+ middlewareReferences.add(middleware);
511
+ });
512
+ }
513
+ let finalCompose = compose;
514
+ if (devTools) finalCompose = composeWithDevTools(_objectSpread2({ trace: process.env.NODE_ENV !== "production" }, typeof devTools === "object" && devTools));
515
+ const middlewareEnhancer = applyMiddleware(...finalMiddleware);
516
+ const getDefaultEnhancers = buildGetDefaultEnhancers(middlewareEnhancer);
517
+ if (process.env.NODE_ENV !== "production" && enhancers && typeof enhancers !== "function") throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(5) : "`enhancers` field must be a callback");
518
+ let storeEnhancers = typeof enhancers === "function" ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();
519
+ if (process.env.NODE_ENV !== "production" && !Array.isArray(storeEnhancers)) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(6) : "`enhancers` callback must return an array");
520
+ if (process.env.NODE_ENV !== "production" && storeEnhancers.some((item) => typeof item !== "function")) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(7) : "each enhancer provided to configureStore must be a function");
521
+ if (process.env.NODE_ENV !== "production" && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");
522
+ const composedEnhancer = finalCompose(...storeEnhancers);
523
+ return createStore(rootReducer, preloadedState, composedEnhancer);
651
524
  }
652
-
653
- // src/mapBuilders.ts
525
+ //#endregion
526
+ //#region src/mapBuilders.ts
654
527
  function executeReducerBuilderCallback(builderCallback) {
655
- const actionsMap = {};
656
- const actionMatchers = [];
657
- let defaultCaseReducer;
658
- const builder = {
659
- addCase(typeOrActionCreator, reducer) {
660
- if (process.env.NODE_ENV !== "production") {
661
- if (actionMatchers.length > 0) {
662
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(26) : "`builder.addCase` should only be called before calling `builder.addMatcher`");
663
- }
664
- if (defaultCaseReducer) {
665
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(27) : "`builder.addCase` should only be called before calling `builder.addDefaultCase`");
666
- }
667
- }
668
- const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
669
- if (!type) {
670
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(28) : "`builder.addCase` cannot be called with an empty action type");
671
- }
672
- if (type in actionsMap) {
673
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(29) : `\`builder.addCase\` cannot be called with two reducers for the same action type '${type}'`);
674
- }
675
- actionsMap[type] = reducer;
676
- return builder;
677
- },
678
- addAsyncThunk(asyncThunk, reducers) {
679
- if (process.env.NODE_ENV !== "production") {
680
- if (defaultCaseReducer) {
681
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(43) : "`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`");
682
- }
683
- }
684
- if (reducers.pending) actionsMap[asyncThunk.pending.type] = reducers.pending;
685
- if (reducers.rejected) actionsMap[asyncThunk.rejected.type] = reducers.rejected;
686
- if (reducers.fulfilled) actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled;
687
- if (reducers.settled) actionMatchers.push({
688
- matcher: asyncThunk.settled,
689
- reducer: reducers.settled
690
- });
691
- return builder;
692
- },
693
- addMatcher(matcher, reducer) {
694
- if (process.env.NODE_ENV !== "production") {
695
- if (defaultCaseReducer) {
696
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(30) : "`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
697
- }
698
- }
699
- actionMatchers.push({
700
- matcher,
701
- reducer
702
- });
703
- return builder;
704
- },
705
- addDefaultCase(reducer) {
706
- if (process.env.NODE_ENV !== "production") {
707
- if (defaultCaseReducer) {
708
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(31) : "`builder.addDefaultCase` can only be called once");
709
- }
710
- }
711
- defaultCaseReducer = reducer;
712
- return builder;
713
- }
714
- };
715
- builderCallback(builder);
716
- return [actionsMap, actionMatchers, defaultCaseReducer];
528
+ const actionsMap = {};
529
+ const actionMatchers = [];
530
+ let defaultCaseReducer;
531
+ const builder = {
532
+ addCase(typeOrActionCreator, reducer) {
533
+ if (process.env.NODE_ENV !== "production") {
534
+ if (actionMatchers.length > 0) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(26) : "`builder.addCase` should only be called before calling `builder.addMatcher`");
535
+ if (defaultCaseReducer) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(27) : "`builder.addCase` should only be called before calling `builder.addDefaultCase`");
536
+ }
537
+ const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
538
+ if (!type) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(28) : "`builder.addCase` cannot be called with an empty action type");
539
+ if (type in actionsMap) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(29) : `\`builder.addCase\` cannot be called with two reducers for the same action type '${type}'`);
540
+ actionsMap[type] = reducer;
541
+ return builder;
542
+ },
543
+ addAsyncThunk(asyncThunk, reducers) {
544
+ if (process.env.NODE_ENV !== "production") {
545
+ if (defaultCaseReducer) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(43) : "`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`");
546
+ }
547
+ if (reducers.pending) actionsMap[asyncThunk.pending.type] = reducers.pending;
548
+ if (reducers.rejected) actionsMap[asyncThunk.rejected.type] = reducers.rejected;
549
+ if (reducers.fulfilled) actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled;
550
+ if (reducers.settled) actionMatchers.push({
551
+ matcher: asyncThunk.settled,
552
+ reducer: reducers.settled
553
+ });
554
+ return builder;
555
+ },
556
+ addMatcher(matcher, reducer) {
557
+ if (process.env.NODE_ENV !== "production") {
558
+ if (defaultCaseReducer) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(30) : "`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
559
+ }
560
+ actionMatchers.push({
561
+ matcher,
562
+ reducer
563
+ });
564
+ return builder;
565
+ },
566
+ addDefaultCase(reducer) {
567
+ if (process.env.NODE_ENV !== "production") {
568
+ if (defaultCaseReducer) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(31) : "`builder.addDefaultCase` can only be called once");
569
+ }
570
+ defaultCaseReducer = reducer;
571
+ return builder;
572
+ }
573
+ };
574
+ builderCallback(builder);
575
+ return [
576
+ actionsMap,
577
+ actionMatchers,
578
+ defaultCaseReducer
579
+ ];
717
580
  }
718
-
719
- // src/createReducer.ts
581
+ //#endregion
582
+ //#region src/createReducer.ts
720
583
  function isStateFunction(x) {
721
- return typeof x === "function";
584
+ return typeof x === "function";
722
585
  }
723
586
  function createReducer(initialState, mapOrBuilderCallback) {
724
- if (process.env.NODE_ENV !== "production") {
725
- if (typeof mapOrBuilderCallback === "object") {
726
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(8) : "The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");
727
- }
728
- }
729
- let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);
730
- let getInitialState;
731
- if (isStateFunction(initialState)) {
732
- getInitialState = () => freezeDraftable(initialState());
733
- } else {
734
- const frozenInitialState = freezeDraftable(initialState);
735
- getInitialState = () => frozenInitialState;
736
- }
737
- function reducer(state = getInitialState(), action) {
738
- let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({
739
- matcher
740
- }) => matcher(action)).map(({
741
- reducer: reducer2
742
- }) => reducer2)];
743
- if (caseReducers.filter((cr) => !!cr).length === 0) {
744
- caseReducers = [finalDefaultCaseReducer];
745
- }
746
- return caseReducers.reduce((previousState, caseReducer) => {
747
- if (caseReducer) {
748
- if (isDraft(previousState)) {
749
- const draft = previousState;
750
- const result = caseReducer(draft, action);
751
- if (result === void 0) {
752
- return previousState;
753
- }
754
- return result;
755
- } else if (!isDraftable(previousState)) {
756
- const result = caseReducer(previousState, action);
757
- if (result === void 0) {
758
- if (previousState === null) {
759
- return previousState;
760
- }
761
- throw Error("A case reducer on a non-draftable value must not return undefined");
762
- }
763
- return result;
764
- } else {
765
- return produce(previousState, (draft) => {
766
- return caseReducer(draft, action);
767
- });
768
- }
769
- }
770
- return previousState;
771
- }, state);
772
- }
773
- reducer.getInitialState = getInitialState;
774
- return reducer;
587
+ if (process.env.NODE_ENV !== "production") {
588
+ if (typeof mapOrBuilderCallback === "object") throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(8) : "The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");
589
+ }
590
+ let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);
591
+ let getInitialState;
592
+ if (isStateFunction(initialState)) getInitialState = () => freezeDraftable(initialState());
593
+ else {
594
+ const frozenInitialState = freezeDraftable(initialState);
595
+ getInitialState = () => frozenInitialState;
596
+ }
597
+ function reducer(state = getInitialState(), action) {
598
+ let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({ matcher }) => matcher(action)).map(({ reducer }) => reducer)];
599
+ if (caseReducers.filter((cr) => !!cr).length === 0) caseReducers = [finalDefaultCaseReducer];
600
+ return caseReducers.reduce((previousState, caseReducer) => {
601
+ if (caseReducer) {
602
+ if (isDraft(previousState)) {
603
+ const result = caseReducer(previousState, action);
604
+ if (result === void 0) return previousState;
605
+ return result;
606
+ } else if (!isDraftable(previousState)) {
607
+ const result = caseReducer(previousState, action);
608
+ if (result === void 0) {
609
+ if (previousState === null) return previousState;
610
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(9) : "A case reducer on a non-draftable value must not return undefined");
611
+ }
612
+ return result;
613
+ } else return createNextState(previousState, (draft) => {
614
+ return caseReducer(draft, action);
615
+ });
616
+ }
617
+ return previousState;
618
+ }, state);
619
+ }
620
+ reducer.getInitialState = getInitialState;
621
+ return reducer;
775
622
  }
776
-
777
- // src/matchers.ts
778
- var matches = (matcher, action) => {
779
- if (hasMatchFunction(matcher)) {
780
- return matcher.match(action);
781
- } else {
782
- return matcher(action);
783
- }
623
+ //#endregion
624
+ //#region src/matchers.ts
625
+ const matches = (matcher, action) => {
626
+ if (hasMatchFunction(matcher)) return matcher.match(action);
627
+ else return matcher(action);
784
628
  };
785
629
  function isAnyOf(...matchers) {
786
- return (action) => {
787
- return matchers.some((matcher) => matches(matcher, action));
788
- };
630
+ return (action) => {
631
+ return matchers.some((matcher) => matches(matcher, action));
632
+ };
789
633
  }
790
634
  function isAllOf(...matchers) {
791
- return (action) => {
792
- return matchers.every((matcher) => matches(matcher, action));
793
- };
635
+ return (action) => {
636
+ return matchers.every((matcher) => matches(matcher, action));
637
+ };
794
638
  }
795
639
  function hasExpectedRequestMetadata(action, validStatus) {
796
- if (!action || !action.meta) return false;
797
- const hasValidRequestId = typeof action.meta.requestId === "string";
798
- const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
799
- return hasValidRequestId && hasValidRequestStatus;
640
+ if (!action || !action.meta) return false;
641
+ const hasValidRequestId = typeof action.meta.requestId === "string";
642
+ const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
643
+ return hasValidRequestId && hasValidRequestStatus;
800
644
  }
801
645
  function isAsyncThunkArray(a) {
802
- return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
646
+ return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
803
647
  }
804
648
  function isPending(...asyncThunks) {
805
- if (asyncThunks.length === 0) {
806
- return (action) => hasExpectedRequestMetadata(action, ["pending"]);
807
- }
808
- if (!isAsyncThunkArray(asyncThunks)) {
809
- return isPending()(asyncThunks[0]);
810
- }
811
- return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.pending));
649
+ if (asyncThunks.length === 0) return (action) => hasExpectedRequestMetadata(action, ["pending"]);
650
+ if (!isAsyncThunkArray(asyncThunks)) return isPending()(asyncThunks[0]);
651
+ return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.pending));
812
652
  }
813
653
  function isRejected(...asyncThunks) {
814
- if (asyncThunks.length === 0) {
815
- return (action) => hasExpectedRequestMetadata(action, ["rejected"]);
816
- }
817
- if (!isAsyncThunkArray(asyncThunks)) {
818
- return isRejected()(asyncThunks[0]);
819
- }
820
- return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.rejected));
654
+ if (asyncThunks.length === 0) return (action) => hasExpectedRequestMetadata(action, ["rejected"]);
655
+ if (!isAsyncThunkArray(asyncThunks)) return isRejected()(asyncThunks[0]);
656
+ return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.rejected));
821
657
  }
822
658
  function isRejectedWithValue(...asyncThunks) {
823
- const hasFlag = (action) => {
824
- return action && action.meta && action.meta.rejectedWithValue;
825
- };
826
- if (asyncThunks.length === 0) {
827
- return isAllOf(isRejected(...asyncThunks), hasFlag);
828
- }
829
- if (!isAsyncThunkArray(asyncThunks)) {
830
- return isRejectedWithValue()(asyncThunks[0]);
831
- }
832
- return isAllOf(isRejected(...asyncThunks), hasFlag);
659
+ const hasFlag = (action) => {
660
+ return action && action.meta && action.meta.rejectedWithValue;
661
+ };
662
+ if (asyncThunks.length === 0) return isAllOf(isRejected(...asyncThunks), hasFlag);
663
+ if (!isAsyncThunkArray(asyncThunks)) return isRejectedWithValue()(asyncThunks[0]);
664
+ return isAllOf(isRejected(...asyncThunks), hasFlag);
833
665
  }
834
666
  function isFulfilled(...asyncThunks) {
835
- if (asyncThunks.length === 0) {
836
- return (action) => hasExpectedRequestMetadata(action, ["fulfilled"]);
837
- }
838
- if (!isAsyncThunkArray(asyncThunks)) {
839
- return isFulfilled()(asyncThunks[0]);
840
- }
841
- return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.fulfilled));
667
+ if (asyncThunks.length === 0) return (action) => hasExpectedRequestMetadata(action, ["fulfilled"]);
668
+ if (!isAsyncThunkArray(asyncThunks)) return isFulfilled()(asyncThunks[0]);
669
+ return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.fulfilled));
842
670
  }
843
671
  function isAsyncThunkAction(...asyncThunks) {
844
- if (asyncThunks.length === 0) {
845
- return (action) => hasExpectedRequestMetadata(action, ["pending", "fulfilled", "rejected"]);
846
- }
847
- if (!isAsyncThunkArray(asyncThunks)) {
848
- return isAsyncThunkAction()(asyncThunks[0]);
849
- }
850
- return isAnyOf(...asyncThunks.flatMap((asyncThunk) => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));
672
+ if (asyncThunks.length === 0) return (action) => hasExpectedRequestMetadata(action, [
673
+ "pending",
674
+ "fulfilled",
675
+ "rejected"
676
+ ]);
677
+ if (!isAsyncThunkArray(asyncThunks)) return isAsyncThunkAction()(asyncThunks[0]);
678
+ return isAnyOf(...asyncThunks.flatMap((asyncThunk) => [
679
+ asyncThunk.pending,
680
+ asyncThunk.rejected,
681
+ asyncThunk.fulfilled
682
+ ]));
851
683
  }
852
-
853
- // src/nanoid.ts
854
- var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
855
- var nanoid = (size = 21) => {
856
- let id = "";
857
- let i = size;
858
- while (i--) {
859
- id += urlAlphabet[Math.random() * 64 | 0];
860
- }
861
- return id;
684
+ //#endregion
685
+ //#region src/nanoid.ts
686
+ let urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
687
+ let nanoid = (size = 21) => {
688
+ let id = "";
689
+ let i = size;
690
+ while (i--) id += urlAlphabet[Math.random() * 64 | 0];
691
+ return id;
862
692
  };
863
-
864
- // src/createAsyncThunk.ts
865
- var commonProperties = ["name", "message", "stack", "code"];
693
+ //#endregion
694
+ //#region src/createAsyncThunk.ts
695
+ const commonProperties = [
696
+ "name",
697
+ "message",
698
+ "stack",
699
+ "code"
700
+ ];
866
701
  var RejectWithValue = class {
867
- constructor(payload, meta) {
868
- __publicField(this, "payload", payload);
869
- __publicField(this, "meta", meta);
870
- /*
871
- type-only property to distinguish between RejectWithValue and FulfillWithMeta
872
- does not exist at runtime
873
- */
874
- __publicField(this, "_type");
875
- }
702
+ constructor(payload, meta) {
703
+ this.payload = payload;
704
+ this.meta = meta;
705
+ _defineProperty(this, "_type", void 0);
706
+ }
876
707
  };
877
708
  var FulfillWithMeta = class {
878
- constructor(payload, meta) {
879
- __publicField(this, "payload", payload);
880
- __publicField(this, "meta", meta);
881
- /*
882
- type-only property to distinguish between RejectWithValue and FulfillWithMeta
883
- does not exist at runtime
884
- */
885
- __publicField(this, "_type");
886
- }
709
+ constructor(payload, meta) {
710
+ this.payload = payload;
711
+ this.meta = meta;
712
+ _defineProperty(this, "_type", void 0);
713
+ }
887
714
  };
888
- var miniSerializeError = (value) => {
889
- if (typeof value === "object" && value !== null) {
890
- const simpleError = {};
891
- for (const property of commonProperties) {
892
- if (typeof value[property] === "string") {
893
- simpleError[property] = value[property];
894
- }
895
- }
896
- return simpleError;
897
- }
898
- return {
899
- message: String(value)
900
- };
715
+ const miniSerializeError = (value) => {
716
+ if (typeof value === "object" && value !== null) {
717
+ const simpleError = {};
718
+ for (const property of commonProperties) if (typeof value[property] === "string") simpleError[property] = value[property];
719
+ return simpleError;
720
+ }
721
+ return { message: String(value) };
901
722
  };
902
- var externalAbortMessage = "External signal was aborted";
903
- var createAsyncThunk = /* @__PURE__ */ (() => {
904
- function createAsyncThunk2(typePrefix, payloadCreator, options) {
905
- const fulfilled = createAction(typePrefix + "/fulfilled", (payload, requestId, arg, meta) => ({
906
- payload,
907
- meta: __spreadProps(__spreadValues({}, meta || {}), {
908
- arg,
909
- requestId,
910
- requestStatus: "fulfilled"
911
- })
912
- }));
913
- const pending = createAction(typePrefix + "/pending", (requestId, arg, meta) => ({
914
- payload: void 0,
915
- meta: __spreadProps(__spreadValues({}, meta || {}), {
916
- arg,
917
- requestId,
918
- requestStatus: "pending"
919
- })
920
- }));
921
- const rejected = createAction(typePrefix + "/rejected", (error, requestId, arg, payload, meta) => ({
922
- payload,
923
- error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
924
- meta: __spreadProps(__spreadValues({}, meta || {}), {
925
- arg,
926
- requestId,
927
- rejectedWithValue: !!payload,
928
- requestStatus: "rejected",
929
- aborted: (error == null ? void 0 : error.name) === "AbortError",
930
- condition: (error == null ? void 0 : error.name) === "ConditionError"
931
- })
932
- }));
933
- function actionCreator(arg, {
934
- signal
935
- } = {}) {
936
- return (dispatch, getState, extra) => {
937
- const requestId = (options == null ? void 0 : options.idGenerator) ? options.idGenerator(arg) : nanoid();
938
- const abortController = new AbortController();
939
- let abortHandler;
940
- let abortReason;
941
- function abort(reason) {
942
- abortReason = reason;
943
- abortController.abort();
944
- }
945
- if (signal) {
946
- if (signal.aborted) {
947
- abort(externalAbortMessage);
948
- } else {
949
- signal.addEventListener("abort", () => abort(externalAbortMessage), {
950
- once: true
951
- });
952
- }
953
- }
954
- const promise = (async function() {
955
- var _a, _b;
956
- let finalAction;
957
- try {
958
- let conditionResult = (_a = options == null ? void 0 : options.condition) == null ? void 0 : _a.call(options, arg, {
959
- getState,
960
- extra
961
- });
962
- if (isThenable(conditionResult)) {
963
- conditionResult = await conditionResult;
964
- }
965
- if (conditionResult === false || abortController.signal.aborted) {
966
- throw {
967
- name: "ConditionError",
968
- message: "Aborted due to condition callback returning false."
969
- };
970
- }
971
- const abortedPromise = new Promise((_, reject) => {
972
- abortHandler = () => {
973
- reject({
974
- name: "AbortError",
975
- message: abortReason || "Aborted"
976
- });
977
- };
978
- abortController.signal.addEventListener("abort", abortHandler, {
979
- once: true
980
- });
981
- });
982
- dispatch(pending(requestId, arg, (_b = options == null ? void 0 : options.getPendingMeta) == null ? void 0 : _b.call(options, {
983
- requestId,
984
- arg
985
- }, {
986
- getState,
987
- extra
988
- })));
989
- finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {
990
- dispatch,
991
- getState,
992
- extra,
993
- requestId,
994
- signal: abortController.signal,
995
- abort,
996
- rejectWithValue: ((value, meta) => {
997
- return new RejectWithValue(value, meta);
998
- }),
999
- fulfillWithValue: ((value, meta) => {
1000
- return new FulfillWithMeta(value, meta);
1001
- })
1002
- })).then((result) => {
1003
- if (result instanceof RejectWithValue) {
1004
- throw result;
1005
- }
1006
- if (result instanceof FulfillWithMeta) {
1007
- return fulfilled(result.payload, requestId, arg, result.meta);
1008
- }
1009
- return fulfilled(result, requestId, arg);
1010
- })]);
1011
- } catch (err) {
1012
- finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);
1013
- } finally {
1014
- if (abortHandler) {
1015
- abortController.signal.removeEventListener("abort", abortHandler);
1016
- }
1017
- }
1018
- const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;
1019
- if (!skipDispatch) {
1020
- dispatch(finalAction);
1021
- }
1022
- return finalAction;
1023
- })();
1024
- return Object.assign(promise, {
1025
- abort,
1026
- requestId,
1027
- arg,
1028
- unwrap() {
1029
- return promise.then(unwrapResult);
1030
- }
1031
- });
1032
- };
1033
- }
1034
- return Object.assign(actionCreator, {
1035
- pending,
1036
- rejected,
1037
- fulfilled,
1038
- settled: isAnyOf(rejected, fulfilled),
1039
- typePrefix
1040
- });
1041
- }
1042
- createAsyncThunk2.withTypes = () => createAsyncThunk2;
1043
- return createAsyncThunk2;
723
+ const externalAbortMessage = "External signal was aborted";
724
+ const createAsyncThunk = /* @__PURE__ */ (() => {
725
+ function createAsyncThunk(typePrefix, payloadCreator, options) {
726
+ const fulfilled = createAction(typePrefix + "/fulfilled", (payload, requestId, arg, meta) => ({
727
+ payload,
728
+ meta: _objectSpread2(_objectSpread2({}, meta || {}), {}, {
729
+ arg,
730
+ requestId,
731
+ requestStatus: "fulfilled"
732
+ })
733
+ }));
734
+ const pending = createAction(typePrefix + "/pending", (requestId, arg, meta) => ({
735
+ payload: void 0,
736
+ meta: _objectSpread2(_objectSpread2({}, meta || {}), {}, {
737
+ arg,
738
+ requestId,
739
+ requestStatus: "pending"
740
+ })
741
+ }));
742
+ const rejected = createAction(typePrefix + "/rejected", (error, requestId, arg, payload, meta) => ({
743
+ payload,
744
+ error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
745
+ meta: _objectSpread2(_objectSpread2({}, meta || {}), {}, {
746
+ arg,
747
+ requestId,
748
+ rejectedWithValue: payload !== void 0,
749
+ requestStatus: "rejected",
750
+ aborted: (error === null || error === void 0 ? void 0 : error.name) === "AbortError",
751
+ condition: (error === null || error === void 0 ? void 0 : error.name) === "ConditionError"
752
+ })
753
+ }));
754
+ function actionCreator(arg, { signal } = {}) {
755
+ return (dispatch, getState, extra) => {
756
+ const requestId = (options === null || options === void 0 ? void 0 : options.idGenerator) ? options.idGenerator(arg) : nanoid();
757
+ const abortController = new AbortController();
758
+ let abortHandler;
759
+ let abortReason;
760
+ function abort(reason) {
761
+ abortReason = reason;
762
+ abortController.abort();
763
+ }
764
+ if (signal) {
765
+ if (signal.aborted) abort(externalAbortMessage);
766
+ else signal.addEventListener("abort", () => abort(externalAbortMessage), { once: true });
767
+ }
768
+ const promise = async function() {
769
+ let finalAction;
770
+ try {
771
+ var _options$condition, _options$getPendingMe;
772
+ let conditionResult = options === null || options === void 0 || (_options$condition = options.condition) === null || _options$condition === void 0 ? void 0 : _options$condition.call(options, arg, {
773
+ getState,
774
+ extra
775
+ });
776
+ if (isThenable(conditionResult)) conditionResult = await conditionResult;
777
+ if (conditionResult === false) throw {
778
+ name: "ConditionError",
779
+ message: "Aborted due to condition callback returning false."
780
+ };
781
+ if (abortController.signal.aborted) throw {
782
+ name: "AbortError",
783
+ message: abortReason || "Aborted"
784
+ };
785
+ const abortedPromise = new Promise((_, reject) => {
786
+ abortHandler = () => {
787
+ reject({
788
+ name: "AbortError",
789
+ message: abortReason || "Aborted"
790
+ });
791
+ };
792
+ abortController.signal.addEventListener("abort", abortHandler, { once: true });
793
+ });
794
+ dispatch(pending(requestId, arg, options === null || options === void 0 || (_options$getPendingMe = options.getPendingMeta) === null || _options$getPendingMe === void 0 ? void 0 : _options$getPendingMe.call(options, {
795
+ requestId,
796
+ arg
797
+ }, {
798
+ getState,
799
+ extra
800
+ })));
801
+ finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {
802
+ dispatch,
803
+ getState,
804
+ extra,
805
+ requestId,
806
+ signal: abortController.signal,
807
+ abort,
808
+ rejectWithValue: ((value, meta) => {
809
+ return new RejectWithValue(value, meta);
810
+ }),
811
+ fulfillWithValue: ((value, meta) => {
812
+ return new FulfillWithMeta(value, meta);
813
+ })
814
+ })).then((result) => {
815
+ if (result instanceof RejectWithValue) throw result;
816
+ if (result instanceof FulfillWithMeta) return fulfilled(result.payload, requestId, arg, result.meta);
817
+ return fulfilled(result, requestId, arg);
818
+ })]);
819
+ } catch (err) {
820
+ finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);
821
+ } finally {
822
+ if (abortHandler) abortController.signal.removeEventListener("abort", abortHandler);
823
+ }
824
+ if (!(options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition)) dispatch(finalAction);
825
+ return finalAction;
826
+ }();
827
+ return Object.assign(promise, {
828
+ abort,
829
+ requestId,
830
+ arg,
831
+ unwrap() {
832
+ return promise.then(unwrapResult);
833
+ }
834
+ });
835
+ };
836
+ }
837
+ return Object.assign(actionCreator, {
838
+ pending,
839
+ rejected,
840
+ fulfilled,
841
+ settled: isAnyOf(rejected, fulfilled),
842
+ typePrefix
843
+ });
844
+ }
845
+ createAsyncThunk.withTypes = () => createAsyncThunk;
846
+ return createAsyncThunk;
1044
847
  })();
1045
848
  function unwrapResult(action) {
1046
- if (action.meta && action.meta.rejectedWithValue) {
1047
- throw action.payload;
1048
- }
1049
- if (action.error) {
1050
- throw action.error;
1051
- }
1052
- return action.payload;
849
+ if (action.meta && action.meta.rejectedWithValue) throw action.payload;
850
+ if (action.error) throw action.error;
851
+ return action.payload;
1053
852
  }
1054
853
  function isThenable(value) {
1055
- return value !== null && typeof value === "object" && typeof value.then === "function";
854
+ return value !== null && typeof value === "object" && typeof value.then === "function";
1056
855
  }
1057
-
1058
- // src/createSlice.ts
1059
- var asyncThunkSymbol = /* @__PURE__ */ Symbol.for("rtk-slice-createasyncthunk");
1060
- var asyncThunkCreator = {
1061
- [asyncThunkSymbol]: createAsyncThunk
1062
- };
1063
- var ReducerType = /* @__PURE__ */ ((ReducerType2) => {
1064
- ReducerType2["reducer"] = "reducer";
1065
- ReducerType2["reducerWithPrepare"] = "reducerWithPrepare";
1066
- ReducerType2["asyncThunk"] = "asyncThunk";
1067
- return ReducerType2;
1068
- })(ReducerType || {});
856
+ //#endregion
857
+ //#region \0@oxc-project+runtime@0.144.0/helpers/esm/objectWithoutPropertiesLoose.js
858
+ function _objectWithoutPropertiesLoose(r, e) {
859
+ if (null == r) return {};
860
+ var t = {};
861
+ for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
862
+ if (e.includes(n)) continue;
863
+ t[n] = r[n];
864
+ }
865
+ return t;
866
+ }
867
+ //#endregion
868
+ //#region \0@oxc-project+runtime@0.144.0/helpers/esm/objectWithoutProperties.js
869
+ function _objectWithoutProperties(e, t) {
870
+ if (null == e) return {};
871
+ var o, r, i = _objectWithoutPropertiesLoose(e, t);
872
+ if (Object.getOwnPropertySymbols) {
873
+ var s = Object.getOwnPropertySymbols(e);
874
+ for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
875
+ }
876
+ return i;
877
+ }
878
+ //#endregion
879
+ //#region src/createSlice.ts
880
+ const _excluded = ["reducerPath"];
881
+ const asyncThunkSymbol = /* @__PURE__ */ Symbol.for("rtk-slice-createasyncthunk");
882
+ const asyncThunkCreator = { [asyncThunkSymbol]: createAsyncThunk };
883
+ let ReducerType = /* @__PURE__ */ function(ReducerType) {
884
+ ReducerType["reducer"] = "reducer";
885
+ ReducerType["reducerWithPrepare"] = "reducerWithPrepare";
886
+ ReducerType["asyncThunk"] = "asyncThunk";
887
+ return ReducerType;
888
+ }({});
1069
889
  function getType(slice, actionKey) {
1070
- return `${slice}/${actionKey}`;
1071
- }
1072
- function buildCreateSlice({
1073
- creators
1074
- } = {}) {
1075
- var _a;
1076
- const cAT = (_a = creators == null ? void 0 : creators.asyncThunk) == null ? void 0 : _a[asyncThunkSymbol];
1077
- return function createSlice2(options) {
1078
- const {
1079
- name,
1080
- reducerPath = name
1081
- } = options;
1082
- if (!name) {
1083
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(11) : "`name` is a required option for createSlice");
1084
- }
1085
- if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
1086
- if (options.initialState === void 0) {
1087
- console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");
1088
- }
1089
- }
1090
- const reducers = (typeof options.reducers === "function" ? options.reducers(buildReducerCreators()) : options.reducers) || {};
1091
- const reducerNames = Object.keys(reducers);
1092
- const context = {
1093
- sliceCaseReducersByName: {},
1094
- sliceCaseReducersByType: {},
1095
- actionCreators: {},
1096
- sliceMatchers: []
1097
- };
1098
- const contextMethods = {
1099
- addCase(typeOrActionCreator, reducer2) {
1100
- const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
1101
- if (!type) {
1102
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(12) : "`context.addCase` cannot be called with an empty action type");
1103
- }
1104
- if (type in context.sliceCaseReducersByType) {
1105
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(13) : "`context.addCase` cannot be called with two reducers for the same action type: " + type);
1106
- }
1107
- context.sliceCaseReducersByType[type] = reducer2;
1108
- return contextMethods;
1109
- },
1110
- addMatcher(matcher, reducer2) {
1111
- context.sliceMatchers.push({
1112
- matcher,
1113
- reducer: reducer2
1114
- });
1115
- return contextMethods;
1116
- },
1117
- exposeAction(name2, actionCreator) {
1118
- context.actionCreators[name2] = actionCreator;
1119
- return contextMethods;
1120
- },
1121
- exposeCaseReducer(name2, reducer2) {
1122
- context.sliceCaseReducersByName[name2] = reducer2;
1123
- return contextMethods;
1124
- }
1125
- };
1126
- reducerNames.forEach((reducerName) => {
1127
- const reducerDefinition = reducers[reducerName];
1128
- const reducerDetails = {
1129
- reducerName,
1130
- type: getType(name, reducerName),
1131
- createNotation: typeof options.reducers === "function"
1132
- };
1133
- if (isAsyncThunkSliceReducerDefinition(reducerDefinition)) {
1134
- handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);
1135
- } else {
1136
- handleNormalReducerDefinition(reducerDetails, reducerDefinition, contextMethods);
1137
- }
1138
- });
1139
- function buildReducer() {
1140
- if (process.env.NODE_ENV !== "production") {
1141
- if (typeof options.extraReducers === "object") {
1142
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(14) : "The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");
1143
- }
1144
- }
1145
- const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];
1146
- const finalCaseReducers = __spreadValues(__spreadValues({}, extraReducers), context.sliceCaseReducersByType);
1147
- return createReducer(options.initialState, (builder) => {
1148
- for (let key in finalCaseReducers) {
1149
- builder.addCase(key, finalCaseReducers[key]);
1150
- }
1151
- for (let sM of context.sliceMatchers) {
1152
- builder.addMatcher(sM.matcher, sM.reducer);
1153
- }
1154
- for (let m of actionMatchers) {
1155
- builder.addMatcher(m.matcher, m.reducer);
1156
- }
1157
- if (defaultCaseReducer) {
1158
- builder.addDefaultCase(defaultCaseReducer);
1159
- }
1160
- });
1161
- }
1162
- const selectSelf = (state) => state;
1163
- const injectedSelectorCache = /* @__PURE__ */ new Map();
1164
- const injectedStateCache = /* @__PURE__ */ new WeakMap();
1165
- let _reducer;
1166
- function reducer(state, action) {
1167
- if (!_reducer) _reducer = buildReducer();
1168
- return _reducer(state, action);
1169
- }
1170
- function getInitialState() {
1171
- if (!_reducer) _reducer = buildReducer();
1172
- return _reducer.getInitialState();
1173
- }
1174
- function makeSelectorProps(reducerPath2, injected = false) {
1175
- function selectSlice(state) {
1176
- let sliceState = state[reducerPath2];
1177
- if (typeof sliceState === "undefined") {
1178
- if (injected) {
1179
- sliceState = getOrInsertComputed(injectedStateCache, selectSlice, getInitialState);
1180
- } else if (process.env.NODE_ENV !== "production") {
1181
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(15) : "selectSlice returned undefined for an uninjected slice reducer");
1182
- }
1183
- }
1184
- return sliceState;
1185
- }
1186
- function getSelectors(selectState = selectSelf) {
1187
- const selectorCache = getOrInsertComputed(injectedSelectorCache, injected, () => /* @__PURE__ */ new WeakMap());
1188
- return getOrInsertComputed(selectorCache, selectState, () => {
1189
- var _a2;
1190
- const map = {};
1191
- for (const [name2, selector] of Object.entries((_a2 = options.selectors) != null ? _a2 : {})) {
1192
- map[name2] = wrapSelector(selector, selectState, () => getOrInsertComputed(injectedStateCache, selectState, getInitialState), injected);
1193
- }
1194
- return map;
1195
- });
1196
- }
1197
- return {
1198
- reducerPath: reducerPath2,
1199
- getSelectors,
1200
- get selectors() {
1201
- return getSelectors(selectSlice);
1202
- },
1203
- selectSlice
1204
- };
1205
- }
1206
- const slice = __spreadProps(__spreadValues({
1207
- name,
1208
- reducer,
1209
- actions: context.actionCreators,
1210
- caseReducers: context.sliceCaseReducersByName,
1211
- getInitialState
1212
- }, makeSelectorProps(reducerPath)), {
1213
- injectInto(injectable, _a2 = {}) {
1214
- var _b = _a2, {
1215
- reducerPath: pathOpt
1216
- } = _b, config = __objRest(_b, [
1217
- "reducerPath"
1218
- ]);
1219
- const newReducerPath = pathOpt != null ? pathOpt : reducerPath;
1220
- injectable.inject({
1221
- reducerPath: newReducerPath,
1222
- reducer
1223
- }, config);
1224
- return __spreadValues(__spreadValues({}, slice), makeSelectorProps(newReducerPath, true));
1225
- }
1226
- });
1227
- return slice;
1228
- };
890
+ return `${slice}/${actionKey}`;
891
+ }
892
+ function buildCreateSlice({ creators } = {}) {
893
+ var _creators$asyncThunk;
894
+ const cAT = creators === null || creators === void 0 || (_creators$asyncThunk = creators.asyncThunk) === null || _creators$asyncThunk === void 0 ? void 0 : _creators$asyncThunk[asyncThunkSymbol];
895
+ return function createSlice(options) {
896
+ const { name, reducerPath = name } = options;
897
+ if (!name) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(11) : "`name` is a required option for createSlice");
898
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
899
+ if (options.initialState === void 0) console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");
900
+ }
901
+ const reducers = (typeof options.reducers === "function" ? options.reducers(buildReducerCreators()) : options.reducers) || {};
902
+ const reducerNames = Object.keys(reducers);
903
+ const context = {
904
+ sliceCaseReducersByName: {},
905
+ sliceCaseReducersByType: {},
906
+ actionCreators: {},
907
+ sliceMatchers: []
908
+ };
909
+ const contextMethods = {
910
+ addCase(typeOrActionCreator, reducer) {
911
+ const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
912
+ if (!type) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(12) : "`context.addCase` cannot be called with an empty action type");
913
+ if (type in context.sliceCaseReducersByType) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(13) : "`context.addCase` cannot be called with two reducers for the same action type: " + type);
914
+ context.sliceCaseReducersByType[type] = reducer;
915
+ return contextMethods;
916
+ },
917
+ addMatcher(matcher, reducer) {
918
+ context.sliceMatchers.push({
919
+ matcher,
920
+ reducer
921
+ });
922
+ return contextMethods;
923
+ },
924
+ exposeAction(name, actionCreator) {
925
+ context.actionCreators[name] = actionCreator;
926
+ return contextMethods;
927
+ },
928
+ exposeCaseReducer(name, reducer) {
929
+ context.sliceCaseReducersByName[name] = reducer;
930
+ return contextMethods;
931
+ }
932
+ };
933
+ reducerNames.forEach((reducerName) => {
934
+ const reducerDefinition = reducers[reducerName];
935
+ const reducerDetails = {
936
+ reducerName,
937
+ type: getType(name, reducerName),
938
+ createNotation: typeof options.reducers === "function"
939
+ };
940
+ if (isAsyncThunkSliceReducerDefinition(reducerDefinition)) handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);
941
+ else handleNormalReducerDefinition(reducerDetails, reducerDefinition, contextMethods);
942
+ });
943
+ function buildReducer() {
944
+ if (process.env.NODE_ENV !== "production") {
945
+ if (typeof options.extraReducers === "object") throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(14) : "The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");
946
+ }
947
+ const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];
948
+ const finalCaseReducers = _objectSpread2(_objectSpread2({}, extraReducers), context.sliceCaseReducersByType);
949
+ return createReducer(options.initialState, (builder) => {
950
+ for (let key in finalCaseReducers) builder.addCase(key, finalCaseReducers[key]);
951
+ for (let sM of context.sliceMatchers) builder.addMatcher(sM.matcher, sM.reducer);
952
+ for (let m of actionMatchers) builder.addMatcher(m.matcher, m.reducer);
953
+ if (defaultCaseReducer) builder.addDefaultCase(defaultCaseReducer);
954
+ });
955
+ }
956
+ const selectSelf = (state) => state;
957
+ const injectedSelectorCache = /* @__PURE__ */ new Map();
958
+ const injectedStateCache = /* @__PURE__ */ new WeakMap();
959
+ let _reducer;
960
+ function reducer(state, action) {
961
+ if (!_reducer) _reducer = buildReducer();
962
+ return _reducer(state, action);
963
+ }
964
+ function getInitialState() {
965
+ if (!_reducer) _reducer = buildReducer();
966
+ return _reducer.getInitialState();
967
+ }
968
+ function makeSelectorProps(reducerPath, injected = false) {
969
+ function selectSlice(state) {
970
+ let sliceState = state[reducerPath];
971
+ if (typeof sliceState === "undefined") {
972
+ if (injected) sliceState = getOrInsertComputed(injectedStateCache, selectSlice, getInitialState);
973
+ else if (process.env.NODE_ENV !== "production") throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(15) : "selectSlice returned undefined for an uninjected slice reducer");
974
+ }
975
+ return sliceState;
976
+ }
977
+ function getSelectors(selectState = selectSelf) {
978
+ return getOrInsertComputed(getOrInsertComputed(injectedSelectorCache, injected, () => /* @__PURE__ */ new WeakMap()), selectState, () => {
979
+ var _options$selectors;
980
+ const map = {};
981
+ for (const [name, selector] of Object.entries((_options$selectors = options.selectors) !== null && _options$selectors !== void 0 ? _options$selectors : {})) map[name] = wrapSelector(selector, selectState, () => getOrInsertComputed(injectedStateCache, selectState, getInitialState), injected);
982
+ return map;
983
+ });
984
+ }
985
+ return {
986
+ reducerPath,
987
+ getSelectors,
988
+ get selectors() {
989
+ return getSelectors(selectSlice);
990
+ },
991
+ selectSlice
992
+ };
993
+ }
994
+ const slice = _objectSpread2(_objectSpread2({
995
+ name,
996
+ reducer,
997
+ actions: context.actionCreators,
998
+ caseReducers: context.sliceCaseReducersByName,
999
+ getInitialState
1000
+ }, makeSelectorProps(reducerPath)), {}, { injectInto(injectable, _ref = {}) {
1001
+ let { reducerPath: pathOpt } = _ref, config = _objectWithoutProperties(_ref, _excluded);
1002
+ const newReducerPath = pathOpt !== null && pathOpt !== void 0 ? pathOpt : reducerPath;
1003
+ injectable.inject({
1004
+ reducerPath: newReducerPath,
1005
+ reducer
1006
+ }, config);
1007
+ return _objectSpread2(_objectSpread2({}, slice), makeSelectorProps(newReducerPath, true));
1008
+ } });
1009
+ return slice;
1010
+ };
1229
1011
  }
1230
1012
  function wrapSelector(selector, selectState, getInitialState, injected) {
1231
- function wrapper(rootState, ...args) {
1232
- let sliceState = selectState(rootState);
1233
- if (typeof sliceState === "undefined") {
1234
- if (injected) {
1235
- sliceState = getInitialState();
1236
- } else if (process.env.NODE_ENV !== "production") {
1237
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(16) : "selectState returned undefined for an uninjected slice reducer");
1238
- }
1239
- }
1240
- return selector(sliceState, ...args);
1241
- }
1242
- wrapper.unwrapped = selector;
1243
- return wrapper;
1244
- }
1245
- var createSlice = /* @__PURE__ */ buildCreateSlice();
1013
+ function wrapper(rootState, ...args) {
1014
+ let sliceState = selectState(rootState);
1015
+ if (typeof sliceState === "undefined") {
1016
+ if (injected) sliceState = getInitialState();
1017
+ else if (process.env.NODE_ENV !== "production") throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(16) : "selectState returned undefined for an uninjected slice reducer");
1018
+ }
1019
+ return selector(sliceState, ...args);
1020
+ }
1021
+ wrapper.unwrapped = selector;
1022
+ return wrapper;
1023
+ }
1024
+ const createSlice = /* @__PURE__ */ buildCreateSlice();
1246
1025
  function buildReducerCreators() {
1247
- function asyncThunk(payloadCreator, config) {
1248
- return __spreadValues({
1249
- _reducerDefinitionType: "asyncThunk" /* asyncThunk */,
1250
- payloadCreator
1251
- }, config);
1252
- }
1253
- asyncThunk.withTypes = () => asyncThunk;
1254
- return {
1255
- reducer(caseReducer) {
1256
- return Object.assign({
1257
- // hack so the wrapping function has the same name as the original
1258
- // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original
1259
- [caseReducer.name](...args) {
1260
- return caseReducer(...args);
1261
- }
1262
- }[caseReducer.name], {
1263
- _reducerDefinitionType: "reducer" /* reducer */
1264
- });
1265
- },
1266
- preparedReducer(prepare, reducer) {
1267
- return {
1268
- _reducerDefinitionType: "reducerWithPrepare" /* reducerWithPrepare */,
1269
- prepare,
1270
- reducer
1271
- };
1272
- },
1273
- asyncThunk
1274
- };
1275
- }
1276
- function handleNormalReducerDefinition({
1277
- type,
1278
- reducerName,
1279
- createNotation
1280
- }, maybeReducerWithPrepare, context) {
1281
- let caseReducer;
1282
- let prepareCallback;
1283
- if ("reducer" in maybeReducerWithPrepare) {
1284
- if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {
1285
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(17) : "Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");
1286
- }
1287
- caseReducer = maybeReducerWithPrepare.reducer;
1288
- prepareCallback = maybeReducerWithPrepare.prepare;
1289
- } else {
1290
- caseReducer = maybeReducerWithPrepare;
1291
- }
1292
- context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));
1026
+ function asyncThunk(payloadCreator, config) {
1027
+ return _objectSpread2({
1028
+ _reducerDefinitionType: "asyncThunk",
1029
+ payloadCreator
1030
+ }, config);
1031
+ }
1032
+ asyncThunk.withTypes = () => asyncThunk;
1033
+ return {
1034
+ reducer(caseReducer) {
1035
+ return Object.assign({ [caseReducer.name](...args) {
1036
+ return caseReducer(...args);
1037
+ } }[caseReducer.name], { _reducerDefinitionType: "reducer" });
1038
+ },
1039
+ preparedReducer(prepare, reducer) {
1040
+ return {
1041
+ _reducerDefinitionType: "reducerWithPrepare",
1042
+ prepare,
1043
+ reducer
1044
+ };
1045
+ },
1046
+ asyncThunk
1047
+ };
1048
+ }
1049
+ function handleNormalReducerDefinition({ type, reducerName, createNotation }, maybeReducerWithPrepare, context) {
1050
+ let caseReducer;
1051
+ let prepareCallback;
1052
+ if ("reducer" in maybeReducerWithPrepare) {
1053
+ if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(17) : "Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");
1054
+ caseReducer = maybeReducerWithPrepare.reducer;
1055
+ prepareCallback = maybeReducerWithPrepare.prepare;
1056
+ } else caseReducer = maybeReducerWithPrepare;
1057
+ context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));
1293
1058
  }
1294
1059
  function isAsyncThunkSliceReducerDefinition(reducerDefinition) {
1295
- return reducerDefinition._reducerDefinitionType === "asyncThunk" /* asyncThunk */;
1060
+ return reducerDefinition._reducerDefinitionType === "asyncThunk";
1296
1061
  }
1297
1062
  function isCaseReducerWithPrepareDefinition(reducerDefinition) {
1298
- return reducerDefinition._reducerDefinitionType === "reducerWithPrepare" /* reducerWithPrepare */;
1299
- }
1300
- function handleThunkCaseReducerDefinition({
1301
- type,
1302
- reducerName
1303
- }, reducerDefinition, context, cAT) {
1304
- if (!cAT) {
1305
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(18) : "Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");
1306
- }
1307
- const {
1308
- payloadCreator,
1309
- fulfilled,
1310
- pending,
1311
- rejected,
1312
- settled,
1313
- options
1314
- } = reducerDefinition;
1315
- const thunk = cAT(type, payloadCreator, options);
1316
- context.exposeAction(reducerName, thunk);
1317
- if (fulfilled) {
1318
- context.addCase(thunk.fulfilled, fulfilled);
1319
- }
1320
- if (pending) {
1321
- context.addCase(thunk.pending, pending);
1322
- }
1323
- if (rejected) {
1324
- context.addCase(thunk.rejected, rejected);
1325
- }
1326
- if (settled) {
1327
- context.addMatcher(thunk.settled, settled);
1328
- }
1329
- context.exposeCaseReducer(reducerName, {
1330
- fulfilled: fulfilled || noop,
1331
- pending: pending || noop,
1332
- rejected: rejected || noop,
1333
- settled: settled || noop
1334
- });
1335
- }
1336
- function noop() {
1063
+ return reducerDefinition._reducerDefinitionType === "reducerWithPrepare";
1337
1064
  }
1338
-
1339
- // src/entities/entity_state.ts
1065
+ function handleThunkCaseReducerDefinition({ type, reducerName }, reducerDefinition, context, cAT) {
1066
+ if (!cAT) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(18) : "Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");
1067
+ const { payloadCreator, fulfilled, pending, rejected, settled, options } = reducerDefinition;
1068
+ const thunk = cAT(type, payloadCreator, options);
1069
+ context.exposeAction(reducerName, thunk);
1070
+ if (fulfilled) context.addCase(thunk.fulfilled, fulfilled);
1071
+ if (pending) context.addCase(thunk.pending, pending);
1072
+ if (rejected) context.addCase(thunk.rejected, rejected);
1073
+ if (settled) context.addMatcher(thunk.settled, settled);
1074
+ context.exposeCaseReducer(reducerName, {
1075
+ fulfilled: fulfilled || noop$1,
1076
+ pending: pending || noop$1,
1077
+ rejected: rejected || noop$1,
1078
+ settled: settled || noop$1
1079
+ });
1080
+ }
1081
+ function noop$1() {}
1082
+ //#endregion
1083
+ //#region src/entities/entity_state.ts
1340
1084
  function getInitialEntityState() {
1341
- return {
1342
- ids: [],
1343
- entities: {}
1344
- };
1085
+ return {
1086
+ ids: [],
1087
+ entities: {}
1088
+ };
1345
1089
  }
1346
1090
  function createInitialStateFactory(stateAdapter) {
1347
- function getInitialState(additionalState = {}, entities) {
1348
- const state = Object.assign(getInitialEntityState(), additionalState);
1349
- return entities ? stateAdapter.setAll(state, entities) : state;
1350
- }
1351
- return {
1352
- getInitialState
1353
- };
1091
+ function getInitialState(additionalState = {}, entities) {
1092
+ const state = Object.assign(getInitialEntityState(), additionalState);
1093
+ return entities ? stateAdapter.setAll(state, entities) : state;
1094
+ }
1095
+ return { getInitialState };
1354
1096
  }
1355
-
1356
- // src/entities/state_selectors.ts
1097
+ //#endregion
1098
+ //#region src/entities/state_selectors.ts
1357
1099
  function createSelectorsFactory() {
1358
- function getSelectors(selectState, options = {}) {
1359
- const {
1360
- createSelector: createSelector2 = createDraftSafeSelector
1361
- } = options;
1362
- const selectIds = (state) => state.ids;
1363
- const selectEntities = (state) => state.entities;
1364
- const selectAll = createSelector2(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));
1365
- const selectId = (_, id) => id;
1366
- const selectById = (entities, id) => entities[id];
1367
- const selectTotal = createSelector2(selectIds, (ids) => ids.length);
1368
- if (!selectState) {
1369
- return {
1370
- selectIds,
1371
- selectEntities,
1372
- selectAll,
1373
- selectTotal,
1374
- selectById: createSelector2(selectEntities, selectId, selectById)
1375
- };
1376
- }
1377
- const selectGlobalizedEntities = createSelector2(selectState, selectEntities);
1378
- return {
1379
- selectIds: createSelector2(selectState, selectIds),
1380
- selectEntities: selectGlobalizedEntities,
1381
- selectAll: createSelector2(selectState, selectAll),
1382
- selectTotal: createSelector2(selectState, selectTotal),
1383
- selectById: createSelector2(selectGlobalizedEntities, selectId, selectById)
1384
- };
1385
- }
1386
- return {
1387
- getSelectors
1388
- };
1100
+ function getSelectors(selectState, options = {}) {
1101
+ const { createSelector = createDraftSafeSelector } = options;
1102
+ const selectIds = (state) => state.ids;
1103
+ const selectEntities = (state) => state.entities;
1104
+ const selectAll = createSelector(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));
1105
+ const selectId = (_, id) => id;
1106
+ const selectById = (entities, id) => entities[id];
1107
+ const selectTotal = createSelector(selectIds, (ids) => ids.length);
1108
+ if (!selectState) return {
1109
+ selectIds,
1110
+ selectEntities,
1111
+ selectAll,
1112
+ selectTotal,
1113
+ selectById: createSelector(selectEntities, selectId, selectById)
1114
+ };
1115
+ const selectGlobalizedEntities = createSelector(selectState, selectEntities);
1116
+ return {
1117
+ selectIds: createSelector(selectState, selectIds),
1118
+ selectEntities: selectGlobalizedEntities,
1119
+ selectAll: createSelector(selectState, selectAll),
1120
+ selectTotal: createSelector(selectState, selectTotal),
1121
+ selectById: createSelector(selectGlobalizedEntities, selectId, selectById)
1122
+ };
1123
+ }
1124
+ return { getSelectors };
1389
1125
  }
1390
-
1391
- // src/entities/state_adapter.ts
1392
- var isDraftTyped = isDraft;
1126
+ //#endregion
1127
+ //#region src/entities/state_adapter.ts
1128
+ const isDraftTyped = isDraft;
1393
1129
  function createSingleArgumentStateOperator(mutator) {
1394
- const operator = createStateOperator((_, state) => mutator(state));
1395
- return function operation(state) {
1396
- return operator(state, void 0);
1397
- };
1130
+ const operator = createStateOperator((_, state) => mutator(state));
1131
+ return function operation(state) {
1132
+ return operator(state, void 0);
1133
+ };
1398
1134
  }
1399
1135
  function createStateOperator(mutator) {
1400
- return function operation(state, arg) {
1401
- function isPayloadActionArgument(arg2) {
1402
- return isFSA(arg2);
1403
- }
1404
- const runMutator = (draft) => {
1405
- if (isPayloadActionArgument(arg)) {
1406
- mutator(arg.payload, draft);
1407
- } else {
1408
- mutator(arg, draft);
1409
- }
1410
- };
1411
- if (isDraftTyped(state)) {
1412
- runMutator(state);
1413
- return state;
1414
- }
1415
- return produce(state, runMutator);
1416
- };
1136
+ return function operation(state, arg) {
1137
+ function isPayloadActionArgument(arg) {
1138
+ return isFSA(arg);
1139
+ }
1140
+ const runMutator = (draft) => {
1141
+ if (isPayloadActionArgument(arg)) mutator(arg.payload, draft);
1142
+ else mutator(arg, draft);
1143
+ };
1144
+ if (isDraftTyped(state)) {
1145
+ runMutator(state);
1146
+ return state;
1147
+ }
1148
+ return createNextState(state, runMutator);
1149
+ };
1417
1150
  }
1418
-
1419
- // src/entities/utils.ts
1151
+ //#endregion
1152
+ //#region src/entities/utils.ts
1420
1153
  function selectIdValue(entity, selectId) {
1421
- const key = selectId(entity);
1422
- if (process.env.NODE_ENV !== "production" && key === void 0) {
1423
- 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());
1424
- }
1425
- return key;
1154
+ const key = selectId(entity);
1155
+ if (process.env.NODE_ENV !== "production" && key === void 0) 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());
1156
+ return key;
1426
1157
  }
1427
1158
  function ensureEntitiesArray(entities) {
1428
- if (!Array.isArray(entities)) {
1429
- entities = Object.values(entities);
1430
- }
1431
- return entities;
1159
+ if (!Array.isArray(entities)) entities = Object.values(entities);
1160
+ return entities;
1432
1161
  }
1433
1162
  function getCurrent(value) {
1434
- return isDraft(value) ? current(value) : value;
1163
+ return isDraft(value) ? current(value) : value;
1435
1164
  }
1436
1165
  function splitAddedUpdatedEntities(newEntities, selectId, state) {
1437
- newEntities = ensureEntitiesArray(newEntities);
1438
- const existingIdsArray = getCurrent(state.ids);
1439
- const existingIds = new Set(existingIdsArray);
1440
- const added = [];
1441
- const addedIds = /* @__PURE__ */ new Set([]);
1442
- const updated = [];
1443
- for (const entity of newEntities) {
1444
- const id = selectIdValue(entity, selectId);
1445
- if (existingIds.has(id) || addedIds.has(id)) {
1446
- updated.push({
1447
- id,
1448
- changes: entity
1449
- });
1450
- } else {
1451
- addedIds.add(id);
1452
- added.push(entity);
1453
- }
1454
- }
1455
- return [added, updated, existingIdsArray];
1166
+ newEntities = ensureEntitiesArray(newEntities);
1167
+ const existingIdsArray = getCurrent(state.ids);
1168
+ const existingIds = new Set(existingIdsArray);
1169
+ const added = [];
1170
+ const addedIds = /* @__PURE__ */ new Set([]);
1171
+ const updated = [];
1172
+ for (const entity of newEntities) {
1173
+ const id = selectIdValue(entity, selectId);
1174
+ if (existingIds.has(id) || addedIds.has(id)) updated.push({
1175
+ id,
1176
+ changes: entity
1177
+ });
1178
+ else {
1179
+ addedIds.add(id);
1180
+ added.push(entity);
1181
+ }
1182
+ }
1183
+ return [
1184
+ added,
1185
+ updated,
1186
+ existingIdsArray
1187
+ ];
1456
1188
  }
1457
-
1458
- // src/entities/unsorted_state_adapter.ts
1189
+ //#endregion
1190
+ //#region src/entities/unsorted_state_adapter.ts
1459
1191
  function createUnsortedStateAdapter(selectId) {
1460
- function addOneMutably(entity, state) {
1461
- const key = selectIdValue(entity, selectId);
1462
- if (key in state.entities) {
1463
- return;
1464
- }
1465
- state.ids.push(key);
1466
- state.entities[key] = entity;
1467
- }
1468
- function addManyMutably(newEntities, state) {
1469
- newEntities = ensureEntitiesArray(newEntities);
1470
- for (const entity of newEntities) {
1471
- addOneMutably(entity, state);
1472
- }
1473
- }
1474
- function setOneMutably(entity, state) {
1475
- const key = selectIdValue(entity, selectId);
1476
- if (!(key in state.entities)) {
1477
- state.ids.push(key);
1478
- }
1479
- ;
1480
- state.entities[key] = entity;
1481
- }
1482
- function setManyMutably(newEntities, state) {
1483
- newEntities = ensureEntitiesArray(newEntities);
1484
- for (const entity of newEntities) {
1485
- setOneMutably(entity, state);
1486
- }
1487
- }
1488
- function setAllMutably(newEntities, state) {
1489
- newEntities = ensureEntitiesArray(newEntities);
1490
- state.ids = [];
1491
- state.entities = {};
1492
- addManyMutably(newEntities, state);
1493
- }
1494
- function removeOneMutably(key, state) {
1495
- return removeManyMutably([key], state);
1496
- }
1497
- function removeManyMutably(keys, state) {
1498
- let didMutate = false;
1499
- keys.forEach((key) => {
1500
- if (key in state.entities) {
1501
- delete state.entities[key];
1502
- didMutate = true;
1503
- }
1504
- });
1505
- if (didMutate) {
1506
- state.ids = state.ids.filter((id) => id in state.entities);
1507
- }
1508
- }
1509
- function removeAllMutably(state) {
1510
- Object.assign(state, {
1511
- ids: [],
1512
- entities: {}
1513
- });
1514
- }
1515
- function takeNewKey(keys, update, state) {
1516
- const original3 = state.entities[update.id];
1517
- if (original3 === void 0) {
1518
- return false;
1519
- }
1520
- const updated = Object.assign({}, original3, update.changes);
1521
- const newKey = selectIdValue(updated, selectId);
1522
- const hasNewKey = newKey !== update.id;
1523
- if (hasNewKey) {
1524
- keys[update.id] = newKey;
1525
- delete state.entities[update.id];
1526
- }
1527
- ;
1528
- state.entities[newKey] = updated;
1529
- return hasNewKey;
1530
- }
1531
- function updateOneMutably(update, state) {
1532
- return updateManyMutably([update], state);
1533
- }
1534
- function updateManyMutably(updates, state) {
1535
- const newKeys = {};
1536
- const updatesPerEntity = {};
1537
- updates.forEach((update) => {
1538
- var _a;
1539
- if (update.id in state.entities) {
1540
- updatesPerEntity[update.id] = {
1541
- id: update.id,
1542
- // Spreads ignore falsy values, so this works even if there isn't
1543
- // an existing update already at this key
1544
- changes: __spreadValues(__spreadValues({}, (_a = updatesPerEntity[update.id]) == null ? void 0 : _a.changes), update.changes)
1545
- };
1546
- }
1547
- });
1548
- updates = Object.values(updatesPerEntity);
1549
- const didMutateEntities = updates.length > 0;
1550
- if (didMutateEntities) {
1551
- const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0;
1552
- if (didMutateIds) {
1553
- state.ids = Object.values(state.entities).map((e) => selectIdValue(e, selectId));
1554
- }
1555
- }
1556
- }
1557
- function upsertOneMutably(entity, state) {
1558
- return upsertManyMutably([entity], state);
1559
- }
1560
- function upsertManyMutably(newEntities, state) {
1561
- const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
1562
- addManyMutably(added, state);
1563
- updateManyMutably(updated, state);
1564
- }
1565
- return {
1566
- removeAll: createSingleArgumentStateOperator(removeAllMutably),
1567
- addOne: createStateOperator(addOneMutably),
1568
- addMany: createStateOperator(addManyMutably),
1569
- setOne: createStateOperator(setOneMutably),
1570
- setMany: createStateOperator(setManyMutably),
1571
- setAll: createStateOperator(setAllMutably),
1572
- updateOne: createStateOperator(updateOneMutably),
1573
- updateMany: createStateOperator(updateManyMutably),
1574
- upsertOne: createStateOperator(upsertOneMutably),
1575
- upsertMany: createStateOperator(upsertManyMutably),
1576
- removeOne: createStateOperator(removeOneMutably),
1577
- removeMany: createStateOperator(removeManyMutably)
1578
- };
1192
+ function addOneMutably(entity, state) {
1193
+ const key = selectIdValue(entity, selectId);
1194
+ if (key in state.entities) return;
1195
+ state.ids.push(key);
1196
+ state.entities[key] = entity;
1197
+ }
1198
+ function addManyMutably(newEntities, state) {
1199
+ newEntities = ensureEntitiesArray(newEntities);
1200
+ for (const entity of newEntities) addOneMutably(entity, state);
1201
+ }
1202
+ function setOneMutably(entity, state) {
1203
+ const key = selectIdValue(entity, selectId);
1204
+ if (!(key in state.entities)) state.ids.push(key);
1205
+ state.entities[key] = entity;
1206
+ }
1207
+ function setManyMutably(newEntities, state) {
1208
+ newEntities = ensureEntitiesArray(newEntities);
1209
+ for (const entity of newEntities) setOneMutably(entity, state);
1210
+ }
1211
+ function setAllMutably(newEntities, state) {
1212
+ newEntities = ensureEntitiesArray(newEntities);
1213
+ state.ids = [];
1214
+ state.entities = {};
1215
+ setManyMutably(newEntities, state);
1216
+ }
1217
+ function removeOneMutably(key, state) {
1218
+ return removeManyMutably([key], state);
1219
+ }
1220
+ function removeManyMutably(keys, state) {
1221
+ let didMutate = false;
1222
+ keys.forEach((key) => {
1223
+ if (key in state.entities) {
1224
+ delete state.entities[key];
1225
+ didMutate = true;
1226
+ }
1227
+ });
1228
+ if (didMutate) state.ids = state.ids.filter((id) => id in state.entities);
1229
+ }
1230
+ function removeAllMutably(state) {
1231
+ Object.assign(state, {
1232
+ ids: [],
1233
+ entities: {}
1234
+ });
1235
+ }
1236
+ function takeNewKey(keys, update, state) {
1237
+ const original = state.entities[update.id];
1238
+ if (original === void 0) return false;
1239
+ const updated = Object.assign({}, original, update.changes);
1240
+ const newKey = selectIdValue(updated, selectId);
1241
+ const hasNewKey = newKey !== update.id;
1242
+ if (hasNewKey) {
1243
+ keys[update.id] = newKey;
1244
+ delete state.entities[update.id];
1245
+ }
1246
+ state.entities[newKey] = updated;
1247
+ return hasNewKey;
1248
+ }
1249
+ function updateOneMutably(update, state) {
1250
+ return updateManyMutably([update], state);
1251
+ }
1252
+ function updateManyMutably(updates, state) {
1253
+ const newKeys = {};
1254
+ const updatesPerEntity = {};
1255
+ updates.forEach((update) => {
1256
+ if (update.id in state.entities) {
1257
+ var _updatesPerEntity$upd;
1258
+ updatesPerEntity[update.id] = {
1259
+ id: update.id,
1260
+ changes: _objectSpread2(_objectSpread2({}, (_updatesPerEntity$upd = updatesPerEntity[update.id]) === null || _updatesPerEntity$upd === void 0 ? void 0 : _updatesPerEntity$upd.changes), update.changes)
1261
+ };
1262
+ }
1263
+ });
1264
+ updates = Object.values(updatesPerEntity);
1265
+ if (updates.length > 0) {
1266
+ if (updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0) state.ids = Object.values(state.entities).map((e) => selectIdValue(e, selectId));
1267
+ }
1268
+ }
1269
+ function upsertOneMutably(entity, state) {
1270
+ return upsertManyMutably([entity], state);
1271
+ }
1272
+ function upsertManyMutably(newEntities, state) {
1273
+ const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);
1274
+ addManyMutably(added, state);
1275
+ updateManyMutably(updated, state);
1276
+ }
1277
+ return {
1278
+ removeAll: createSingleArgumentStateOperator(removeAllMutably),
1279
+ addOne: createStateOperator(addOneMutably),
1280
+ addMany: createStateOperator(addManyMutably),
1281
+ setOne: createStateOperator(setOneMutably),
1282
+ setMany: createStateOperator(setManyMutably),
1283
+ setAll: createStateOperator(setAllMutably),
1284
+ updateOne: createStateOperator(updateOneMutably),
1285
+ updateMany: createStateOperator(updateManyMutably),
1286
+ upsertOne: createStateOperator(upsertOneMutably),
1287
+ upsertMany: createStateOperator(upsertManyMutably),
1288
+ removeOne: createStateOperator(removeOneMutably),
1289
+ removeMany: createStateOperator(removeManyMutably)
1290
+ };
1579
1291
  }
1580
-
1581
- // src/entities/sorted_state_adapter.ts
1292
+ //#endregion
1293
+ //#region src/entities/sorted_state_adapter.ts
1582
1294
  function findInsertIndex(sortedItems, item, comparisonFunction) {
1583
- let lowIndex = 0;
1584
- let highIndex = sortedItems.length;
1585
- while (lowIndex < highIndex) {
1586
- let middleIndex = lowIndex + highIndex >>> 1;
1587
- const currentItem = sortedItems[middleIndex];
1588
- const res = comparisonFunction(item, currentItem);
1589
- if (res >= 0) {
1590
- lowIndex = middleIndex + 1;
1591
- } else {
1592
- highIndex = middleIndex;
1593
- }
1594
- }
1595
- return lowIndex;
1295
+ let lowIndex = 0;
1296
+ let highIndex = sortedItems.length;
1297
+ while (lowIndex < highIndex) {
1298
+ let middleIndex = lowIndex + highIndex >>> 1;
1299
+ const currentItem = sortedItems[middleIndex];
1300
+ if (comparisonFunction(item, currentItem) >= 0) lowIndex = middleIndex + 1;
1301
+ else highIndex = middleIndex;
1302
+ }
1303
+ return lowIndex;
1596
1304
  }
1597
1305
  function insert(sortedItems, item, comparisonFunction) {
1598
- const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);
1599
- sortedItems.splice(insertAtIndex, 0, item);
1600
- return sortedItems;
1306
+ const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);
1307
+ sortedItems.splice(insertAtIndex, 0, item);
1308
+ return sortedItems;
1601
1309
  }
1602
1310
  function createSortedStateAdapter(selectId, comparer) {
1603
- const {
1604
- removeOne,
1605
- removeMany,
1606
- removeAll
1607
- } = createUnsortedStateAdapter(selectId);
1608
- function addOneMutably(entity, state) {
1609
- return addManyMutably([entity], state);
1610
- }
1611
- function addManyMutably(newEntities, state, existingIds) {
1612
- newEntities = ensureEntitiesArray(newEntities);
1613
- const existingKeys = new Set(existingIds != null ? existingIds : getCurrent(state.ids));
1614
- const addedKeys = /* @__PURE__ */ new Set();
1615
- const models = newEntities.filter((model) => {
1616
- const modelId = selectIdValue(model, selectId);
1617
- const notAdded = !addedKeys.has(modelId);
1618
- if (notAdded) addedKeys.add(modelId);
1619
- return !existingKeys.has(modelId) && notAdded;
1620
- });
1621
- if (models.length !== 0) {
1622
- mergeFunction(state, models);
1623
- }
1624
- }
1625
- function setOneMutably(entity, state) {
1626
- return setManyMutably([entity], state);
1627
- }
1628
- function setManyMutably(newEntities, state) {
1629
- let deduplicatedEntities = {};
1630
- newEntities = ensureEntitiesArray(newEntities);
1631
- if (newEntities.length !== 0) {
1632
- for (const item of newEntities) {
1633
- const entityId = selectId(item);
1634
- deduplicatedEntities[entityId] = item;
1635
- delete state.entities[entityId];
1636
- }
1637
- newEntities = ensureEntitiesArray(deduplicatedEntities);
1638
- mergeFunction(state, newEntities);
1639
- }
1640
- }
1641
- function setAllMutably(newEntities, state) {
1642
- newEntities = ensureEntitiesArray(newEntities);
1643
- state.entities = {};
1644
- state.ids = [];
1645
- addManyMutably(newEntities, state, []);
1646
- }
1647
- function updateOneMutably(update, state) {
1648
- return updateManyMutably([update], state);
1649
- }
1650
- function updateManyMutably(updates, state) {
1651
- let appliedUpdates = false;
1652
- let replacedIds = false;
1653
- for (let update of updates) {
1654
- const entity = state.entities[update.id];
1655
- if (!entity) {
1656
- continue;
1657
- }
1658
- appliedUpdates = true;
1659
- Object.assign(entity, update.changes);
1660
- const newId = selectId(entity);
1661
- if (update.id !== newId) {
1662
- replacedIds = true;
1663
- delete state.entities[update.id];
1664
- const oldIndex = state.ids.indexOf(update.id);
1665
- state.ids[oldIndex] = newId;
1666
- state.entities[newId] = entity;
1667
- }
1668
- }
1669
- if (appliedUpdates) {
1670
- mergeFunction(state, [], appliedUpdates, replacedIds);
1671
- }
1672
- }
1673
- function upsertOneMutably(entity, state) {
1674
- return upsertManyMutably([entity], state);
1675
- }
1676
- function upsertManyMutably(newEntities, state) {
1677
- const [added, updated, existingIdsArray] = splitAddedUpdatedEntities(newEntities, selectId, state);
1678
- if (added.length) {
1679
- addManyMutably(added, state, existingIdsArray);
1680
- }
1681
- if (updated.length) {
1682
- updateManyMutably(updated, state);
1683
- }
1684
- }
1685
- function areArraysEqual(a, b) {
1686
- if (a.length !== b.length) {
1687
- return false;
1688
- }
1689
- for (let i = 0; i < a.length; i++) {
1690
- if (a[i] === b[i]) {
1691
- continue;
1692
- }
1693
- return false;
1694
- }
1695
- return true;
1696
- }
1697
- const mergeFunction = (state, addedItems, appliedUpdates, replacedIds) => {
1698
- const currentEntities = getCurrent(state.entities);
1699
- const currentIds = getCurrent(state.ids);
1700
- const stateEntities = state.entities;
1701
- let ids = currentIds;
1702
- if (replacedIds) {
1703
- ids = new Set(currentIds);
1704
- }
1705
- let sortedEntities = [];
1706
- for (const id of ids) {
1707
- const entity = currentEntities[id];
1708
- if (entity) {
1709
- sortedEntities.push(entity);
1710
- }
1711
- }
1712
- const wasPreviouslyEmpty = sortedEntities.length === 0;
1713
- for (const item of addedItems) {
1714
- stateEntities[selectId(item)] = item;
1715
- if (!wasPreviouslyEmpty) {
1716
- insert(sortedEntities, item, comparer);
1717
- }
1718
- }
1719
- if (wasPreviouslyEmpty) {
1720
- sortedEntities = addedItems.slice().sort(comparer);
1721
- } else if (appliedUpdates) {
1722
- sortedEntities.sort(comparer);
1723
- }
1724
- const newSortedIds = sortedEntities.map(selectId);
1725
- if (!areArraysEqual(currentIds, newSortedIds)) {
1726
- state.ids = newSortedIds;
1727
- }
1728
- };
1729
- return {
1730
- removeOne,
1731
- removeMany,
1732
- removeAll,
1733
- addOne: createStateOperator(addOneMutably),
1734
- updateOne: createStateOperator(updateOneMutably),
1735
- upsertOne: createStateOperator(upsertOneMutably),
1736
- setOne: createStateOperator(setOneMutably),
1737
- setMany: createStateOperator(setManyMutably),
1738
- setAll: createStateOperator(setAllMutably),
1739
- addMany: createStateOperator(addManyMutably),
1740
- updateMany: createStateOperator(updateManyMutably),
1741
- upsertMany: createStateOperator(upsertManyMutably)
1742
- };
1311
+ const { removeOne, removeMany, removeAll } = createUnsortedStateAdapter(selectId);
1312
+ function addOneMutably(entity, state) {
1313
+ return addManyMutably([entity], state);
1314
+ }
1315
+ function addManyMutably(newEntities, state, existingIds) {
1316
+ newEntities = ensureEntitiesArray(newEntities);
1317
+ const existingKeys = new Set(existingIds !== null && existingIds !== void 0 ? existingIds : getCurrent(state.ids));
1318
+ const addedKeys = /* @__PURE__ */ new Set();
1319
+ const models = newEntities.filter((model) => {
1320
+ const modelId = selectIdValue(model, selectId);
1321
+ const notAdded = !addedKeys.has(modelId);
1322
+ if (notAdded) addedKeys.add(modelId);
1323
+ return !existingKeys.has(modelId) && notAdded;
1324
+ });
1325
+ if (models.length !== 0) mergeFunction(state, models);
1326
+ }
1327
+ function setOneMutably(entity, state) {
1328
+ return setManyMutably([entity], state);
1329
+ }
1330
+ function setManyMutably(newEntities, state) {
1331
+ let deduplicatedEntities = {};
1332
+ newEntities = ensureEntitiesArray(newEntities);
1333
+ if (newEntities.length !== 0) {
1334
+ for (const item of newEntities) {
1335
+ const entityId = selectId(item);
1336
+ deduplicatedEntities[entityId] = item;
1337
+ delete state.entities[entityId];
1338
+ }
1339
+ newEntities = ensureEntitiesArray(deduplicatedEntities);
1340
+ mergeFunction(state, newEntities);
1341
+ }
1342
+ }
1343
+ function setAllMutably(newEntities, state) {
1344
+ newEntities = ensureEntitiesArray(newEntities);
1345
+ state.entities = {};
1346
+ state.ids = [];
1347
+ setManyMutably(newEntities, state);
1348
+ }
1349
+ function updateOneMutably(update, state) {
1350
+ return updateManyMutably([update], state);
1351
+ }
1352
+ function updateManyMutably(updates, state) {
1353
+ let appliedUpdates = false;
1354
+ let replacedIds = false;
1355
+ const updatesPerEntity = {};
1356
+ for (const update of updates) if (update.id in state.entities) {
1357
+ var _updatesPerEntity$upd;
1358
+ updatesPerEntity[update.id] = {
1359
+ id: update.id,
1360
+ changes: _objectSpread2(_objectSpread2({}, (_updatesPerEntity$upd = updatesPerEntity[update.id]) === null || _updatesPerEntity$upd === void 0 ? void 0 : _updatesPerEntity$upd.changes), update.changes)
1361
+ };
1362
+ }
1363
+ for (const update of Object.values(updatesPerEntity)) {
1364
+ const entity = state.entities[update.id];
1365
+ if (!entity) continue;
1366
+ appliedUpdates = true;
1367
+ Object.assign(entity, update.changes);
1368
+ const newId = selectId(entity);
1369
+ if (update.id !== newId) {
1370
+ replacedIds = true;
1371
+ delete state.entities[update.id];
1372
+ const oldIndex = state.ids.indexOf(update.id);
1373
+ state.ids[oldIndex] = newId;
1374
+ state.entities[newId] = entity;
1375
+ }
1376
+ }
1377
+ if (appliedUpdates) mergeFunction(state, [], appliedUpdates, replacedIds);
1378
+ }
1379
+ function upsertOneMutably(entity, state) {
1380
+ return upsertManyMutably([entity], state);
1381
+ }
1382
+ function upsertManyMutably(newEntities, state) {
1383
+ const [added, updated, existingIdsArray] = splitAddedUpdatedEntities(newEntities, selectId, state);
1384
+ if (added.length) addManyMutably(added, state, existingIdsArray);
1385
+ if (updated.length) updateManyMutably(updated, state);
1386
+ }
1387
+ function areArraysEqual(a, b) {
1388
+ if (a.length !== b.length) return false;
1389
+ for (let i = 0; i < a.length; i++) {
1390
+ if (a[i] === b[i]) continue;
1391
+ return false;
1392
+ }
1393
+ return true;
1394
+ }
1395
+ function mergeFunction(state, addedItems, appliedUpdates, replacedIds) {
1396
+ const currentEntities = getCurrent(state.entities);
1397
+ const currentIds = getCurrent(state.ids);
1398
+ const stateEntities = state.entities;
1399
+ let ids = currentIds;
1400
+ if (replacedIds) ids = new Set(currentIds);
1401
+ let sortedEntities = [];
1402
+ for (const id of ids) {
1403
+ const entity = currentEntities[id];
1404
+ if (entity) sortedEntities.push(entity);
1405
+ }
1406
+ const wasPreviouslyEmpty = sortedEntities.length === 0;
1407
+ for (const item of addedItems) {
1408
+ stateEntities[selectId(item)] = item;
1409
+ if (!wasPreviouslyEmpty) insert(sortedEntities, item, comparer);
1410
+ }
1411
+ if (wasPreviouslyEmpty) sortedEntities = addedItems.slice().sort(comparer);
1412
+ else if (appliedUpdates) sortedEntities.sort(comparer);
1413
+ const newSortedIds = sortedEntities.map(selectId);
1414
+ if (!areArraysEqual(currentIds, newSortedIds)) state.ids = newSortedIds;
1415
+ }
1416
+ return {
1417
+ removeOne,
1418
+ removeMany,
1419
+ removeAll,
1420
+ addOne: createStateOperator(addOneMutably),
1421
+ updateOne: createStateOperator(updateOneMutably),
1422
+ upsertOne: createStateOperator(upsertOneMutably),
1423
+ setOne: createStateOperator(setOneMutably),
1424
+ setMany: createStateOperator(setManyMutably),
1425
+ setAll: createStateOperator(setAllMutably),
1426
+ addMany: createStateOperator(addManyMutably),
1427
+ updateMany: createStateOperator(updateManyMutably),
1428
+ upsertMany: createStateOperator(upsertManyMutably)
1429
+ };
1743
1430
  }
1744
-
1745
- // src/entities/create_adapter.ts
1431
+ //#endregion
1432
+ //#region src/entities/create_adapter.ts
1746
1433
  function createEntityAdapter(options = {}) {
1747
- const {
1748
- selectId,
1749
- sortComparer
1750
- } = __spreadValues({
1751
- sortComparer: false,
1752
- selectId: (instance) => instance.id
1753
- }, options);
1754
- const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
1755
- const stateFactory = createInitialStateFactory(stateAdapter);
1756
- const selectorsFactory = createSelectorsFactory();
1757
- return __spreadValues(__spreadValues(__spreadValues({
1758
- selectId,
1759
- sortComparer
1760
- }, stateFactory), selectorsFactory), stateAdapter);
1434
+ const { selectId, sortComparer } = _objectSpread2({
1435
+ sortComparer: false,
1436
+ selectId: (instance) => instance.id
1437
+ }, options);
1438
+ const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
1439
+ const stateFactory = createInitialStateFactory(stateAdapter);
1440
+ const selectorsFactory = createSelectorsFactory();
1441
+ return _objectSpread2(_objectSpread2(_objectSpread2({
1442
+ selectId,
1443
+ sortComparer
1444
+ }, stateFactory), selectorsFactory), stateAdapter);
1761
1445
  }
1762
-
1763
- // src/listenerMiddleware/exceptions.ts
1764
- var task = "task";
1765
- var listener = "listener";
1766
- var completed = "completed";
1767
- var cancelled = "cancelled";
1768
- var taskCancelled = `task-${cancelled}`;
1769
- var taskCompleted = `task-${completed}`;
1770
- var listenerCancelled = `${listener}-${cancelled}`;
1771
- var listenerCompleted = `${listener}-${completed}`;
1446
+ //#endregion
1447
+ //#region src/listenerMiddleware/exceptions.ts
1448
+ const task = "task";
1449
+ const listener = "listener";
1450
+ const completed = "completed";
1451
+ const cancelled = "cancelled";
1452
+ const taskCancelled = `task-${cancelled}`;
1453
+ const taskCompleted = `task-${completed}`;
1454
+ const listenerCancelled = `${listener}-${cancelled}`;
1455
+ const listenerCompleted = `${listener}-${completed}`;
1772
1456
  var TaskAbortError = class {
1773
- constructor(code) {
1774
- __publicField(this, "code", code);
1775
- __publicField(this, "name", "TaskAbortError");
1776
- __publicField(this, "message");
1777
- this.message = `${task} ${cancelled} (reason: ${code})`;
1778
- }
1779
- };
1780
-
1781
- // src/listenerMiddleware/utils.ts
1782
- var assertFunction = (func, expected) => {
1783
- if (typeof func !== "function") {
1784
- throw new TypeError(process.env.NODE_ENV === "production" ? formatProdErrorMessage(32) : `${expected} is not a function`);
1785
- }
1457
+ constructor(code) {
1458
+ this.code = code;
1459
+ _defineProperty(this, "name", "TaskAbortError");
1460
+ _defineProperty(this, "message", void 0);
1461
+ this.message = `${task} ${cancelled} (reason: ${code})`;
1462
+ }
1786
1463
  };
1787
- var noop2 = () => {
1464
+ //#endregion
1465
+ //#region src/listenerMiddleware/utils.ts
1466
+ const assertFunction = (func, expected) => {
1467
+ if (typeof func !== "function") throw new TypeError(process.env.NODE_ENV === "production" ? formatProdErrorMessage(32) : `${expected} is not a function`);
1788
1468
  };
1789
- var catchRejection = (promise, onError = noop2) => {
1790
- promise.catch(onError);
1791
- return promise;
1469
+ const noop = () => {};
1470
+ const catchRejection = (promise, onError = noop) => {
1471
+ promise.catch(onError);
1472
+ return promise;
1792
1473
  };
1793
- var addAbortSignalListener = (abortSignal, callback) => {
1794
- abortSignal.addEventListener("abort", callback, {
1795
- once: true
1796
- });
1797
- return () => abortSignal.removeEventListener("abort", callback);
1474
+ const addAbortSignalListener = (abortSignal, callback) => {
1475
+ abortSignal.addEventListener("abort", callback, { once: true });
1476
+ return () => abortSignal.removeEventListener("abort", callback);
1798
1477
  };
1799
-
1800
- // src/listenerMiddleware/task.ts
1801
- var validateActive = (signal) => {
1802
- if (signal.aborted) {
1803
- throw new TaskAbortError(signal.reason);
1804
- }
1478
+ //#endregion
1479
+ //#region src/listenerMiddleware/task.ts
1480
+ const validateActive = (signal) => {
1481
+ if (signal.aborted) throw new TaskAbortError(signal.reason);
1805
1482
  };
1806
1483
  function raceWithSignal(signal, promise) {
1807
- let cleanup = noop2;
1808
- return new Promise((resolve, reject) => {
1809
- const notifyRejection = () => reject(new TaskAbortError(signal.reason));
1810
- if (signal.aborted) {
1811
- notifyRejection();
1812
- return;
1813
- }
1814
- cleanup = addAbortSignalListener(signal, notifyRejection);
1815
- promise.finally(() => cleanup()).then(resolve, reject);
1816
- }).finally(() => {
1817
- cleanup = noop2;
1818
- });
1819
- }
1820
- var runTask = async (task2, cleanUp) => {
1821
- try {
1822
- await Promise.resolve();
1823
- const value = await task2();
1824
- return {
1825
- status: "ok",
1826
- value
1827
- };
1828
- } catch (error) {
1829
- return {
1830
- status: error instanceof TaskAbortError ? "cancelled" : "rejected",
1831
- error
1832
- };
1833
- } finally {
1834
- cleanUp == null ? void 0 : cleanUp();
1835
- }
1484
+ let cleanup = noop;
1485
+ return new Promise((resolve, reject) => {
1486
+ const notifyRejection = () => reject(new TaskAbortError(signal.reason));
1487
+ if (signal.aborted) {
1488
+ notifyRejection();
1489
+ return;
1490
+ }
1491
+ cleanup = addAbortSignalListener(signal, notifyRejection);
1492
+ promise.finally(() => cleanup()).then(resolve, reject);
1493
+ }).finally(() => {
1494
+ cleanup = noop;
1495
+ });
1496
+ }
1497
+ const runTask = async (task, cleanUp) => {
1498
+ try {
1499
+ await Promise.resolve();
1500
+ return {
1501
+ status: "ok",
1502
+ value: await task()
1503
+ };
1504
+ } catch (error) {
1505
+ return {
1506
+ status: error instanceof TaskAbortError ? "cancelled" : "rejected",
1507
+ error
1508
+ };
1509
+ } finally {
1510
+ cleanUp === null || cleanUp === void 0 || cleanUp();
1511
+ }
1836
1512
  };
1837
- var createPause = (signal) => {
1838
- return (promise) => {
1839
- return catchRejection(raceWithSignal(signal, promise).then((output) => {
1840
- validateActive(signal);
1841
- return output;
1842
- }));
1843
- };
1513
+ const createPause = (signal) => {
1514
+ return (promise) => {
1515
+ return catchRejection(raceWithSignal(signal, promise).then((output) => {
1516
+ validateActive(signal);
1517
+ return output;
1518
+ }));
1519
+ };
1844
1520
  };
1845
- var createDelay = (signal) => {
1846
- const pause = createPause(signal);
1847
- return (timeoutMs) => {
1848
- return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)));
1849
- };
1521
+ const createDelay = (signal) => {
1522
+ const pause = createPause(signal);
1523
+ return (timeoutMs) => {
1524
+ return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)));
1525
+ };
1850
1526
  };
1851
-
1852
- // src/listenerMiddleware/index.ts
1853
- var {
1854
- assign
1855
- } = Object;
1856
- var INTERNAL_NIL_TOKEN = {};
1857
- var alm = "listenerMiddleware";
1858
- var createFork = (parentAbortSignal, parentBlockingPromises) => {
1859
- const linkControllers = (controller) => addAbortSignalListener(parentAbortSignal, () => controller.abort(parentAbortSignal.reason));
1860
- return (taskExecutor, opts) => {
1861
- assertFunction(taskExecutor, "taskExecutor");
1862
- const childAbortController = new AbortController();
1863
- linkControllers(childAbortController);
1864
- const result = runTask(async () => {
1865
- validateActive(parentAbortSignal);
1866
- validateActive(childAbortController.signal);
1867
- const result2 = await taskExecutor({
1868
- pause: createPause(childAbortController.signal),
1869
- delay: createDelay(childAbortController.signal),
1870
- signal: childAbortController.signal
1871
- });
1872
- validateActive(childAbortController.signal);
1873
- return result2;
1874
- }, () => childAbortController.abort(taskCompleted));
1875
- if (opts == null ? void 0 : opts.autoJoin) {
1876
- parentBlockingPromises.push(result.catch(noop2));
1877
- }
1878
- return {
1879
- result: createPause(parentAbortSignal)(result),
1880
- cancel() {
1881
- childAbortController.abort(taskCancelled);
1882
- }
1883
- };
1884
- };
1527
+ //#endregion
1528
+ //#region src/listenerMiddleware/index.ts
1529
+ const { assign } = Object;
1530
+ const INTERNAL_NIL_TOKEN = {};
1531
+ const alm = "listenerMiddleware";
1532
+ const createFork = (parentAbortSignal, parentBlockingPromises) => {
1533
+ const linkControllers = (controller) => addAbortSignalListener(parentAbortSignal, () => controller.abort(parentAbortSignal.reason));
1534
+ return (taskExecutor, opts) => {
1535
+ assertFunction(taskExecutor, "taskExecutor");
1536
+ const childAbortController = new AbortController();
1537
+ linkControllers(childAbortController);
1538
+ const result = runTask(async () => {
1539
+ validateActive(parentAbortSignal);
1540
+ validateActive(childAbortController.signal);
1541
+ const result = await taskExecutor({
1542
+ pause: createPause(childAbortController.signal),
1543
+ delay: createDelay(childAbortController.signal),
1544
+ signal: childAbortController.signal
1545
+ });
1546
+ validateActive(childAbortController.signal);
1547
+ return result;
1548
+ }, () => childAbortController.abort(taskCompleted));
1549
+ if (opts === null || opts === void 0 ? void 0 : opts.autoJoin) parentBlockingPromises.push(result.catch(noop));
1550
+ return {
1551
+ result: createPause(parentAbortSignal)(result),
1552
+ cancel() {
1553
+ childAbortController.abort(taskCancelled);
1554
+ }
1555
+ };
1556
+ };
1885
1557
  };
1886
- var createTakePattern = (startListening, signal) => {
1887
- const take = async (predicate, timeout) => {
1888
- validateActive(signal);
1889
- let unsubscribe = () => {
1890
- };
1891
- const tuplePromise = new Promise((resolve, reject) => {
1892
- let stopListening = startListening({
1893
- predicate,
1894
- effect: (action, listenerApi) => {
1895
- listenerApi.unsubscribe();
1896
- resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);
1897
- }
1898
- });
1899
- unsubscribe = () => {
1900
- stopListening();
1901
- reject();
1902
- };
1903
- });
1904
- const promises = [tuplePromise];
1905
- if (timeout != null) {
1906
- promises.push(new Promise((resolve) => setTimeout(resolve, timeout, null)));
1907
- }
1908
- try {
1909
- const output = await raceWithSignal(signal, Promise.race(promises));
1910
- validateActive(signal);
1911
- return output;
1912
- } finally {
1913
- unsubscribe();
1914
- }
1915
- };
1916
- return ((predicate, timeout) => catchRejection(take(predicate, timeout)));
1558
+ const createTakePattern = (startListening, signal) => {
1559
+ const take = async (predicate, timeout) => {
1560
+ validateActive(signal);
1561
+ let unsubscribe = () => {};
1562
+ const promises = [new Promise((resolve, reject) => {
1563
+ let stopListening = startListening({
1564
+ predicate,
1565
+ effect: (action, listenerApi) => {
1566
+ listenerApi.unsubscribe();
1567
+ resolve([
1568
+ action,
1569
+ listenerApi.getState(),
1570
+ listenerApi.getOriginalState()
1571
+ ]);
1572
+ }
1573
+ });
1574
+ unsubscribe = () => {
1575
+ stopListening();
1576
+ reject();
1577
+ };
1578
+ })];
1579
+ if (timeout != null) promises.push(new Promise((resolve) => setTimeout(resolve, timeout, null)));
1580
+ try {
1581
+ const output = await raceWithSignal(signal, Promise.race(promises));
1582
+ validateActive(signal);
1583
+ return output;
1584
+ } finally {
1585
+ unsubscribe();
1586
+ }
1587
+ };
1588
+ return ((predicate, timeout) => catchRejection(take(predicate, timeout)));
1917
1589
  };
1918
- var getListenerEntryPropsFrom = (options) => {
1919
- let {
1920
- type,
1921
- actionCreator,
1922
- matcher,
1923
- predicate,
1924
- effect
1925
- } = options;
1926
- if (type) {
1927
- predicate = createAction(type).match;
1928
- } else if (actionCreator) {
1929
- type = actionCreator.type;
1930
- predicate = actionCreator.match;
1931
- } else if (matcher) {
1932
- predicate = matcher;
1933
- } else if (predicate) {
1934
- } else {
1935
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(21) : "Creating or removing a listener requires one of the known fields for matching an action");
1936
- }
1937
- assertFunction(effect, "options.listener");
1938
- return {
1939
- predicate,
1940
- type,
1941
- effect
1942
- };
1590
+ const getListenerEntryPropsFrom = (options) => {
1591
+ let { type, actionCreator, matcher, predicate, effect } = options;
1592
+ if (type) predicate = createAction(type).match;
1593
+ else if (actionCreator) {
1594
+ type = actionCreator.type;
1595
+ predicate = actionCreator.match;
1596
+ } else if (matcher) predicate = matcher;
1597
+ else if (predicate) {} else throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(21) : "Creating or removing a listener requires one of the known fields for matching an action");
1598
+ assertFunction(effect, "options.listener");
1599
+ return {
1600
+ predicate,
1601
+ type,
1602
+ effect
1603
+ };
1943
1604
  };
1944
- var createListenerEntry = /* @__PURE__ */ assign((options) => {
1945
- const {
1946
- type,
1947
- predicate,
1948
- effect
1949
- } = getListenerEntryPropsFrom(options);
1950
- const entry = {
1951
- id: nanoid(),
1952
- effect,
1953
- type,
1954
- predicate,
1955
- pending: /* @__PURE__ */ new Set(),
1956
- unsubscribe: () => {
1957
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(22) : "Unsubscribe not initialized");
1958
- }
1959
- };
1960
- return entry;
1961
- }, {
1962
- withTypes: () => createListenerEntry
1963
- });
1964
- var findListenerEntry = (listenerMap, options) => {
1965
- const {
1966
- type,
1967
- effect,
1968
- predicate
1969
- } = getListenerEntryPropsFrom(options);
1970
- return Array.from(listenerMap.values()).find((entry) => {
1971
- const matchPredicateOrType = typeof type === "string" ? entry.type === type : entry.predicate === predicate;
1972
- return matchPredicateOrType && entry.effect === effect;
1973
- });
1605
+ const createListenerEntry = /* @__PURE__ */ assign((options) => {
1606
+ const { type, predicate, effect } = getListenerEntryPropsFrom(options);
1607
+ return {
1608
+ id: nanoid(),
1609
+ effect,
1610
+ type,
1611
+ predicate,
1612
+ pending: /* @__PURE__ */ new Set(),
1613
+ unsubscribe: () => {
1614
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(22) : "Unsubscribe not initialized");
1615
+ }
1616
+ };
1617
+ }, { withTypes: () => createListenerEntry });
1618
+ const findListenerEntry = (listenerMap, options) => {
1619
+ const { type, effect, predicate } = getListenerEntryPropsFrom(options);
1620
+ return Array.from(listenerMap.values()).find((entry) => {
1621
+ return (typeof type === "string" ? entry.type === type : entry.predicate === predicate) && entry.effect === effect;
1622
+ });
1974
1623
  };
1975
- var cancelActiveListeners = (entry) => {
1976
- entry.pending.forEach((controller) => {
1977
- controller.abort(listenerCancelled);
1978
- });
1624
+ const cancelActiveListeners = (entry) => {
1625
+ entry.pending.forEach((controller) => {
1626
+ controller.abort(listenerCancelled);
1627
+ });
1979
1628
  };
1980
- var createClearListenerMiddleware = (listenerMap, executingListeners) => {
1981
- return () => {
1982
- for (const listener2 of executingListeners.keys()) {
1983
- cancelActiveListeners(listener2);
1984
- }
1985
- listenerMap.clear();
1986
- };
1629
+ const createClearListenerMiddleware = (listenerMap, executingListeners) => {
1630
+ return () => {
1631
+ for (const listener of executingListeners.keys()) cancelActiveListeners(listener);
1632
+ listenerMap.clear();
1633
+ };
1987
1634
  };
1988
- var safelyNotifyError = (errorHandler, errorToNotify, errorInfo) => {
1989
- try {
1990
- errorHandler(errorToNotify, errorInfo);
1991
- } catch (errorHandlerError) {
1992
- setTimeout(() => {
1993
- throw errorHandlerError;
1994
- }, 0);
1995
- }
1635
+ const safelyNotifyError = (errorHandler, errorToNotify, errorInfo) => {
1636
+ try {
1637
+ errorHandler(errorToNotify, errorInfo);
1638
+ } catch (errorHandlerError) {
1639
+ setTimeout(() => {
1640
+ throw errorHandlerError;
1641
+ }, 0);
1642
+ }
1996
1643
  };
1997
- var addListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/add`), {
1998
- withTypes: () => addListener
1999
- });
2000
- var clearAllListeners = /* @__PURE__ */ createAction(`${alm}/removeAll`);
2001
- var removeListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/remove`), {
2002
- withTypes: () => removeListener
2003
- });
2004
- var defaultErrorHandler = (...args) => {
2005
- console.error(`${alm}/error`, ...args);
1644
+ const addListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/add`), { withTypes: () => addListener });
1645
+ const clearAllListeners = /* @__PURE__ */ createAction(`${alm}/removeAll`);
1646
+ const removeListener = /* @__PURE__ */ assign(/* @__PURE__ */ createAction(`${alm}/remove`), { withTypes: () => removeListener });
1647
+ const defaultErrorHandler = (...args) => {
1648
+ console.error(`${alm}/error`, ...args);
2006
1649
  };
2007
- var createListenerMiddleware = (middlewareOptions = {}) => {
2008
- const listenerMap = /* @__PURE__ */ new Map();
2009
- const executingListeners = /* @__PURE__ */ new Map();
2010
- const trackExecutingListener = (entry) => {
2011
- var _a;
2012
- const count = (_a = executingListeners.get(entry)) != null ? _a : 0;
2013
- executingListeners.set(entry, count + 1);
2014
- };
2015
- const untrackExecutingListener = (entry) => {
2016
- var _a;
2017
- const count = (_a = executingListeners.get(entry)) != null ? _a : 1;
2018
- if (count === 1) {
2019
- executingListeners.delete(entry);
2020
- } else {
2021
- executingListeners.set(entry, count - 1);
2022
- }
2023
- };
2024
- const {
2025
- extra,
2026
- onError = defaultErrorHandler
2027
- } = middlewareOptions;
2028
- assertFunction(onError, "onError");
2029
- const insertEntry = (entry) => {
2030
- entry.unsubscribe = () => listenerMap.delete(entry.id);
2031
- listenerMap.set(entry.id, entry);
2032
- return (cancelOptions) => {
2033
- entry.unsubscribe();
2034
- if (cancelOptions == null ? void 0 : cancelOptions.cancelActive) {
2035
- cancelActiveListeners(entry);
2036
- }
2037
- };
2038
- };
2039
- const startListening = ((options) => {
2040
- var _a;
2041
- const entry = (_a = findListenerEntry(listenerMap, options)) != null ? _a : createListenerEntry(options);
2042
- return insertEntry(entry);
2043
- });
2044
- assign(startListening, {
2045
- withTypes: () => startListening
2046
- });
2047
- const stopListening = (options) => {
2048
- const entry = findListenerEntry(listenerMap, options);
2049
- if (entry) {
2050
- entry.unsubscribe();
2051
- if (options.cancelActive) {
2052
- cancelActiveListeners(entry);
2053
- }
2054
- }
2055
- return !!entry;
2056
- };
2057
- assign(stopListening, {
2058
- withTypes: () => stopListening
2059
- });
2060
- const notifyListener = async (entry, action, api, getOriginalState) => {
2061
- const internalTaskController = new AbortController();
2062
- const take = createTakePattern(startListening, internalTaskController.signal);
2063
- const autoJoinPromises = [];
2064
- try {
2065
- entry.pending.add(internalTaskController);
2066
- trackExecutingListener(entry);
2067
- await Promise.resolve(entry.effect(
2068
- action,
2069
- // Use assign() rather than ... to avoid extra helper functions added to bundle
2070
- assign({}, api, {
2071
- getOriginalState,
2072
- condition: (predicate, timeout) => take(predicate, timeout).then(Boolean),
2073
- take,
2074
- delay: createDelay(internalTaskController.signal),
2075
- pause: createPause(internalTaskController.signal),
2076
- extra,
2077
- signal: internalTaskController.signal,
2078
- fork: createFork(internalTaskController.signal, autoJoinPromises),
2079
- unsubscribe: entry.unsubscribe,
2080
- subscribe: () => {
2081
- listenerMap.set(entry.id, entry);
2082
- },
2083
- cancelActiveListeners: () => {
2084
- entry.pending.forEach((controller, _, set) => {
2085
- if (controller !== internalTaskController) {
2086
- controller.abort(listenerCancelled);
2087
- set.delete(controller);
2088
- }
2089
- });
2090
- },
2091
- cancel: () => {
2092
- internalTaskController.abort(listenerCancelled);
2093
- entry.pending.delete(internalTaskController);
2094
- },
2095
- throwIfCancelled: () => {
2096
- validateActive(internalTaskController.signal);
2097
- }
2098
- })
2099
- ));
2100
- } catch (listenerError) {
2101
- if (!(listenerError instanceof TaskAbortError)) {
2102
- safelyNotifyError(onError, listenerError, {
2103
- raisedBy: "effect"
2104
- });
2105
- }
2106
- } finally {
2107
- await Promise.all(autoJoinPromises);
2108
- internalTaskController.abort(listenerCompleted);
2109
- untrackExecutingListener(entry);
2110
- entry.pending.delete(internalTaskController);
2111
- }
2112
- };
2113
- const clearListenerMiddleware = createClearListenerMiddleware(listenerMap, executingListeners);
2114
- const middleware = (api) => (next) => (action) => {
2115
- if (!isAction(action)) {
2116
- return next(action);
2117
- }
2118
- if (addListener.match(action)) {
2119
- return startListening(action.payload);
2120
- }
2121
- if (clearAllListeners.match(action)) {
2122
- clearListenerMiddleware();
2123
- return;
2124
- }
2125
- if (removeListener.match(action)) {
2126
- return stopListening(action.payload);
2127
- }
2128
- let originalState = api.getState();
2129
- const getOriginalState = () => {
2130
- if (originalState === INTERNAL_NIL_TOKEN) {
2131
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(23) : `${alm}: getOriginalState can only be called synchronously`);
2132
- }
2133
- return originalState;
2134
- };
2135
- let result;
2136
- try {
2137
- result = next(action);
2138
- if (listenerMap.size > 0) {
2139
- const currentState = api.getState();
2140
- const listenerEntries = Array.from(listenerMap.values());
2141
- for (const entry of listenerEntries) {
2142
- let runListener = false;
2143
- try {
2144
- runListener = entry.predicate(action, currentState, originalState);
2145
- } catch (predicateError) {
2146
- runListener = false;
2147
- safelyNotifyError(onError, predicateError, {
2148
- raisedBy: "predicate"
2149
- });
2150
- }
2151
- if (!runListener) {
2152
- continue;
2153
- }
2154
- notifyListener(entry, action, api, getOriginalState);
2155
- }
2156
- }
2157
- } finally {
2158
- originalState = INTERNAL_NIL_TOKEN;
2159
- }
2160
- return result;
2161
- };
2162
- return {
2163
- middleware,
2164
- startListening,
2165
- stopListening,
2166
- clearListeners: clearListenerMiddleware
2167
- };
1650
+ const createListenerMiddleware = (middlewareOptions = {}) => {
1651
+ const listenerMap = /* @__PURE__ */ new Map();
1652
+ const executingListeners = /* @__PURE__ */ new Map();
1653
+ const trackExecutingListener = (entry) => {
1654
+ var _executingListeners$g;
1655
+ const count = (_executingListeners$g = executingListeners.get(entry)) !== null && _executingListeners$g !== void 0 ? _executingListeners$g : 0;
1656
+ executingListeners.set(entry, count + 1);
1657
+ };
1658
+ const untrackExecutingListener = (entry) => {
1659
+ var _executingListeners$g2;
1660
+ const count = (_executingListeners$g2 = executingListeners.get(entry)) !== null && _executingListeners$g2 !== void 0 ? _executingListeners$g2 : 1;
1661
+ if (count === 1) executingListeners.delete(entry);
1662
+ else executingListeners.set(entry, count - 1);
1663
+ };
1664
+ const { extra, onError = defaultErrorHandler } = middlewareOptions;
1665
+ assertFunction(onError, "onError");
1666
+ const insertEntry = (entry) => {
1667
+ entry.unsubscribe = () => listenerMap.delete(entry.id);
1668
+ listenerMap.set(entry.id, entry);
1669
+ return (cancelOptions) => {
1670
+ entry.unsubscribe();
1671
+ if (cancelOptions === null || cancelOptions === void 0 ? void 0 : cancelOptions.cancelActive) cancelActiveListeners(entry);
1672
+ };
1673
+ };
1674
+ const startListening = ((options) => {
1675
+ var _findListenerEntry;
1676
+ const entry = (_findListenerEntry = findListenerEntry(listenerMap, options)) !== null && _findListenerEntry !== void 0 ? _findListenerEntry : createListenerEntry(options);
1677
+ return insertEntry(entry);
1678
+ });
1679
+ assign(startListening, { withTypes: () => startListening });
1680
+ const stopListening = (options) => {
1681
+ const entry = findListenerEntry(listenerMap, options);
1682
+ if (entry) {
1683
+ entry.unsubscribe();
1684
+ if (options.cancelActive) cancelActiveListeners(entry);
1685
+ }
1686
+ return !!entry;
1687
+ };
1688
+ assign(stopListening, { withTypes: () => stopListening });
1689
+ const notifyListener = async (entry, action, api, getOriginalState) => {
1690
+ const internalTaskController = new AbortController();
1691
+ const take = createTakePattern(startListening, internalTaskController.signal);
1692
+ const autoJoinPromises = [];
1693
+ try {
1694
+ entry.pending.add(internalTaskController);
1695
+ trackExecutingListener(entry);
1696
+ await Promise.resolve(entry.effect(action, assign({}, api, {
1697
+ getOriginalState,
1698
+ condition: (predicate, timeout) => take(predicate, timeout).then(Boolean),
1699
+ take,
1700
+ delay: createDelay(internalTaskController.signal),
1701
+ pause: createPause(internalTaskController.signal),
1702
+ extra,
1703
+ signal: internalTaskController.signal,
1704
+ fork: createFork(internalTaskController.signal, autoJoinPromises),
1705
+ unsubscribe: entry.unsubscribe,
1706
+ subscribe: () => {
1707
+ listenerMap.set(entry.id, entry);
1708
+ },
1709
+ cancelActiveListeners: () => {
1710
+ entry.pending.forEach((controller, _, set) => {
1711
+ if (controller !== internalTaskController) {
1712
+ controller.abort(listenerCancelled);
1713
+ set.delete(controller);
1714
+ }
1715
+ });
1716
+ },
1717
+ cancel: () => {
1718
+ internalTaskController.abort(listenerCancelled);
1719
+ entry.pending.delete(internalTaskController);
1720
+ },
1721
+ throwIfCancelled: () => {
1722
+ validateActive(internalTaskController.signal);
1723
+ }
1724
+ })));
1725
+ } catch (listenerError) {
1726
+ if (!(listenerError instanceof TaskAbortError)) safelyNotifyError(onError, listenerError, { raisedBy: "effect" });
1727
+ } finally {
1728
+ await Promise.all(autoJoinPromises);
1729
+ internalTaskController.abort(listenerCompleted);
1730
+ untrackExecutingListener(entry);
1731
+ entry.pending.delete(internalTaskController);
1732
+ }
1733
+ };
1734
+ const clearListenerMiddleware = createClearListenerMiddleware(listenerMap, executingListeners);
1735
+ const middleware = (api) => (next) => (action) => {
1736
+ if (!isAction(action)) return next(action);
1737
+ if (addListener.match(action)) return startListening(action.payload);
1738
+ if (clearAllListeners.match(action)) {
1739
+ clearListenerMiddleware();
1740
+ return;
1741
+ }
1742
+ if (removeListener.match(action)) return stopListening(action.payload);
1743
+ let originalState = api.getState();
1744
+ const getOriginalState = () => {
1745
+ if (originalState === INTERNAL_NIL_TOKEN) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(23) : `${alm}: getOriginalState can only be called synchronously`);
1746
+ return originalState;
1747
+ };
1748
+ let result;
1749
+ try {
1750
+ result = next(action);
1751
+ if (listenerMap.size > 0) {
1752
+ const currentState = api.getState();
1753
+ const listenerEntries = Array.from(listenerMap.values());
1754
+ for (const entry of listenerEntries) {
1755
+ let runListener = false;
1756
+ try {
1757
+ runListener = entry.predicate(action, currentState, originalState);
1758
+ } catch (predicateError) {
1759
+ runListener = false;
1760
+ safelyNotifyError(onError, predicateError, { raisedBy: "predicate" });
1761
+ }
1762
+ if (!runListener) continue;
1763
+ notifyListener(entry, action, api, getOriginalState);
1764
+ }
1765
+ }
1766
+ } finally {
1767
+ originalState = INTERNAL_NIL_TOKEN;
1768
+ }
1769
+ return result;
1770
+ };
1771
+ return {
1772
+ middleware,
1773
+ startListening,
1774
+ stopListening,
1775
+ clearListeners: clearListenerMiddleware
1776
+ };
2168
1777
  };
2169
-
2170
- // src/dynamicMiddleware/index.ts
2171
- var createMiddlewareEntry = (middleware) => ({
2172
- middleware,
2173
- applied: /* @__PURE__ */ new Map()
1778
+ //#endregion
1779
+ //#region src/dynamicMiddleware/index.ts
1780
+ const createMiddlewareEntry = (middleware) => ({
1781
+ middleware,
1782
+ applied: /* @__PURE__ */ new Map()
2174
1783
  });
2175
- var matchInstance = (instanceId) => (action) => {
2176
- var _a;
2177
- return ((_a = action == null ? void 0 : action.meta) == null ? void 0 : _a.instanceId) === instanceId;
1784
+ const matchInstance = (instanceId) => (action) => {
1785
+ var _action$meta;
1786
+ return (action === null || action === void 0 || (_action$meta = action.meta) === null || _action$meta === void 0 ? void 0 : _action$meta.instanceId) === instanceId;
2178
1787
  };
2179
- var createDynamicMiddleware = () => {
2180
- const instanceId = nanoid();
2181
- const middlewareMap = /* @__PURE__ */ new Map();
2182
- const withMiddleware = Object.assign(createAction("dynamicMiddleware/add", (...middlewares) => ({
2183
- payload: middlewares,
2184
- meta: {
2185
- instanceId
2186
- }
2187
- })), {
2188
- withTypes: () => withMiddleware
2189
- });
2190
- const addMiddleware = Object.assign(function addMiddleware2(...middlewares) {
2191
- middlewares.forEach((middleware2) => {
2192
- getOrInsertComputed(middlewareMap, middleware2, createMiddlewareEntry);
2193
- });
2194
- }, {
2195
- withTypes: () => addMiddleware
2196
- });
2197
- const getFinalMiddleware = (api) => {
2198
- const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) => getOrInsertComputed(entry.applied, api, entry.middleware));
2199
- return compose(...appliedMiddleware);
2200
- };
2201
- const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));
2202
- const middleware = (api) => (next) => (action) => {
2203
- if (isWithMiddleware(action)) {
2204
- addMiddleware(...action.payload);
2205
- return api.dispatch;
2206
- }
2207
- return getFinalMiddleware(api)(next)(action);
2208
- };
2209
- return {
2210
- middleware,
2211
- addMiddleware,
2212
- withMiddleware,
2213
- instanceId
2214
- };
1788
+ const createDynamicMiddleware = () => {
1789
+ const instanceId = nanoid();
1790
+ const middlewareMap = /* @__PURE__ */ new Map();
1791
+ let middlewareVersion = 0;
1792
+ const withMiddleware = Object.assign(createAction("dynamicMiddleware/add", (...middlewares) => ({
1793
+ payload: middlewares,
1794
+ meta: { instanceId }
1795
+ })), { withTypes: () => withMiddleware });
1796
+ const addMiddleware = Object.assign(function addMiddleware(...middlewares) {
1797
+ const previousSize = middlewareMap.size;
1798
+ middlewares.forEach((middleware) => {
1799
+ getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry);
1800
+ });
1801
+ if (middlewareMap.size !== previousSize) middlewareVersion++;
1802
+ }, { withTypes: () => addMiddleware });
1803
+ const getFinalMiddleware = (api) => {
1804
+ const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) => getOrInsertComputed(entry.applied, api, entry.middleware));
1805
+ return compose(...appliedMiddleware);
1806
+ };
1807
+ const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));
1808
+ const middleware = (api) => (next) => {
1809
+ let appliedVersion = -1;
1810
+ let dispatch = next;
1811
+ return (action) => {
1812
+ if (isWithMiddleware(action)) {
1813
+ addMiddleware(...action.payload);
1814
+ return api.dispatch;
1815
+ }
1816
+ if (appliedVersion !== middlewareVersion) {
1817
+ dispatch = getFinalMiddleware(api)(next);
1818
+ appliedVersion = middlewareVersion;
1819
+ }
1820
+ return dispatch(action);
1821
+ };
1822
+ };
1823
+ return {
1824
+ middleware,
1825
+ addMiddleware,
1826
+ withMiddleware,
1827
+ instanceId
1828
+ };
2215
1829
  };
2216
-
2217
- // src/combineSlices.ts
2218
- import { combineReducers as combineReducers2 } from "redux";
2219
- var isSliceLike = (maybeSliceLike) => "reducerPath" in maybeSliceLike && typeof maybeSliceLike.reducerPath === "string";
2220
- var getReducers = (slices) => slices.flatMap((sliceOrMap) => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));
2221
- var ORIGINAL_STATE = /* @__PURE__ */ Symbol.for("rtk-state-proxy-original");
2222
- var isStateProxy = (value) => !!value && !!value[ORIGINAL_STATE];
2223
- var stateProxyMap = /* @__PURE__ */ new WeakMap();
2224
- var createStateProxy = (state, reducerMap, initialStateCache) => getOrInsertComputed(stateProxyMap, state, () => new Proxy(state, {
2225
- get: (target, prop, receiver) => {
2226
- if (prop === ORIGINAL_STATE) return target;
2227
- const result = Reflect.get(target, prop, receiver);
2228
- if (typeof result === "undefined") {
2229
- const cached = initialStateCache[prop];
2230
- if (typeof cached !== "undefined") return cached;
2231
- const reducer = reducerMap[prop];
2232
- if (reducer) {
2233
- const reducerResult = reducer(void 0, {
2234
- type: nanoid()
2235
- });
2236
- if (typeof reducerResult === "undefined") {
2237
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(24) : `The slice reducer for key "${prop.toString()}" returned undefined when called for selector(). If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);
2238
- }
2239
- initialStateCache[prop] = reducerResult;
2240
- return reducerResult;
2241
- }
2242
- }
2243
- return result;
2244
- }
2245
- }));
2246
- var original = (state) => {
2247
- if (!isStateProxy(state)) {
2248
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(25) : "original must be used on state Proxy");
2249
- }
2250
- return state[ORIGINAL_STATE];
1830
+ //#endregion
1831
+ //#region src/combineSlices.ts
1832
+ const isSliceLike = (maybeSliceLike) => "reducerPath" in maybeSliceLike && typeof maybeSliceLike.reducerPath === "string";
1833
+ const getReducers = (slices) => slices.flatMap((sliceOrMap) => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));
1834
+ const ORIGINAL_STATE = Symbol.for("rtk-state-proxy-original");
1835
+ const isStateProxy = (value) => !!value && !!value[ORIGINAL_STATE];
1836
+ const createStateProxy = (stateProxyMap, state, reducerMap, initialStateCache) => getOrInsertComputed(stateProxyMap, state, () => new Proxy(state, { get: (target, prop, receiver) => {
1837
+ if (prop === ORIGINAL_STATE) return target;
1838
+ const result = Reflect.get(target, prop, receiver);
1839
+ if (typeof result === "undefined") {
1840
+ const cached = initialStateCache[prop];
1841
+ if (typeof cached !== "undefined") return cached;
1842
+ const reducer = reducerMap[prop];
1843
+ if (reducer) {
1844
+ const reducerResult = reducer(void 0, { type: nanoid() });
1845
+ if (typeof reducerResult === "undefined") throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(24) : `The slice reducer for key "${prop.toString()}" returned undefined when called for selector(). If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);
1846
+ initialStateCache[prop] = reducerResult;
1847
+ return reducerResult;
1848
+ }
1849
+ }
1850
+ return result;
1851
+ } }));
1852
+ const original$1 = (state) => {
1853
+ if (!isStateProxy(state)) throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(25) : "original must be used on state Proxy");
1854
+ return state[ORIGINAL_STATE];
2251
1855
  };
2252
- var emptyObject = {};
2253
- var noopReducer = (state = emptyObject) => state;
1856
+ const emptyObject = {};
1857
+ const noopReducer = (state = emptyObject) => state;
2254
1858
  function combineSlices(...slices) {
2255
- const reducerMap = Object.fromEntries(getReducers(slices));
2256
- const getReducer = () => Object.keys(reducerMap).length ? combineReducers2(reducerMap) : noopReducer;
2257
- let reducer = getReducer();
2258
- function combinedReducer(state, action) {
2259
- return reducer(state, action);
2260
- }
2261
- combinedReducer.withLazyLoadedSlices = () => combinedReducer;
2262
- const initialStateCache = {};
2263
- const inject = (slice, config = {}) => {
2264
- const {
2265
- reducerPath,
2266
- reducer: reducerToInject
2267
- } = slice;
2268
- const currentReducer = reducerMap[reducerPath];
2269
- if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {
2270
- if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
2271
- console.error(`called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``);
2272
- }
2273
- return combinedReducer;
2274
- }
2275
- if (config.overrideExisting && currentReducer !== reducerToInject) {
2276
- delete initialStateCache[reducerPath];
2277
- }
2278
- reducerMap[reducerPath] = reducerToInject;
2279
- reducer = getReducer();
2280
- return combinedReducer;
2281
- };
2282
- const selector = Object.assign(function makeSelector(selectorFn, selectState) {
2283
- return function selector2(state, ...args) {
2284
- return selectorFn(createStateProxy(selectState ? selectState(state, ...args) : state, reducerMap, initialStateCache), ...args);
2285
- };
2286
- }, {
2287
- original
2288
- });
2289
- return Object.assign(combinedReducer, {
2290
- inject,
2291
- selector
2292
- });
1859
+ const stateProxyMap = /* @__PURE__ */ new WeakMap();
1860
+ const reducerMap = Object.fromEntries(getReducers(slices));
1861
+ const getReducer = () => Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer;
1862
+ let reducer = getReducer();
1863
+ function combinedReducer(state, action) {
1864
+ return reducer(state, action);
1865
+ }
1866
+ combinedReducer.withLazyLoadedSlices = () => combinedReducer;
1867
+ const initialStateCache = {};
1868
+ const inject = (slice, config = {}) => {
1869
+ const { reducerPath, reducer: reducerToInject } = slice;
1870
+ const currentReducer = reducerMap[reducerPath];
1871
+ if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {
1872
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "development") console.error(`called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``);
1873
+ return combinedReducer;
1874
+ }
1875
+ if (config.overrideExisting && currentReducer !== reducerToInject) delete initialStateCache[reducerPath];
1876
+ reducerMap[reducerPath] = reducerToInject;
1877
+ reducer = getReducer();
1878
+ return combinedReducer;
1879
+ };
1880
+ const selector = Object.assign(function makeSelector(selectorFn, selectState) {
1881
+ return function selector(state, ...args) {
1882
+ return selectorFn(createStateProxy(stateProxyMap, selectState ? selectState(state, ...args) : state, reducerMap, initialStateCache), ...args);
1883
+ };
1884
+ }, { original: original$1 });
1885
+ return Object.assign(combinedReducer, {
1886
+ inject,
1887
+ selector
1888
+ });
2293
1889
  }
2294
-
2295
- // src/formatProdErrorMessage.ts
1890
+ //#endregion
1891
+ //#region src/formatProdErrorMessage.ts
2296
1892
  function formatProdErrorMessage(code) {
2297
- return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
2298
- }
2299
- export {
2300
- ReducerType,
2301
- SHOULD_AUTOBATCH,
2302
- TaskAbortError,
2303
- Tuple,
2304
- addListener,
2305
- asyncThunkCreator,
2306
- autoBatchEnhancer,
2307
- buildCreateSlice,
2308
- clearAllListeners,
2309
- combineSlices,
2310
- configureStore,
2311
- createAction,
2312
- createActionCreatorInvariantMiddleware,
2313
- createAsyncThunk,
2314
- createDraftSafeSelector,
2315
- createDraftSafeSelectorCreator,
2316
- createDynamicMiddleware,
2317
- createEntityAdapter,
2318
- createImmutableStateInvariantMiddleware,
2319
- createListenerMiddleware,
2320
- produce as createNextState,
2321
- createReducer,
2322
- createSelector,
2323
- createSelectorCreator,
2324
- createSerializableStateInvariantMiddleware,
2325
- createSlice,
2326
- current,
2327
- findNonSerializableValue,
2328
- formatProdErrorMessage,
2329
- freeze,
2330
- isActionCreator,
2331
- isAllOf,
2332
- isAnyOf,
2333
- isAsyncThunkAction,
2334
- isDraft,
2335
- isFSA as isFluxStandardAction,
2336
- isFulfilled,
2337
- isImmutableDefault,
2338
- isPending,
2339
- isPlain,
2340
- isRejected,
2341
- isRejectedWithValue,
2342
- lruMemoize,
2343
- miniSerializeError,
2344
- nanoid,
2345
- original2 as original,
2346
- prepareAutoBatched,
2347
- removeListener,
2348
- unwrapResult,
2349
- weakMapMemoize
2350
- };
1893
+ return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
1894
+ }
1895
+ //#endregion
1896
+ export { ReducerType, SHOULD_AUTOBATCH, TaskAbortError, Tuple, addListener, asyncThunkCreator, autoBatchEnhancer, buildCreateSlice, clearAllListeners, combineSlices, configureStore, createAction, createActionCreatorInvariantMiddleware, createAsyncThunk, createDraftSafeSelector, createDraftSafeSelectorCreator, createDynamicMiddleware, createEntityAdapter, createImmutableStateInvariantMiddleware, createListenerMiddleware, createNextState, createReducer, createSelector, createSelectorCreator, createSerializableStateInvariantMiddleware, createSlice, current, findNonSerializableValue, formatProdErrorMessage, freeze, isActionCreator, isAllOf, isAnyOf, isAsyncThunkAction, isDraft, isFSA as isFluxStandardAction, isFulfilled, isImmutableDefault, isPending, isPlain, isRejected, isRejectedWithValue, lruMemoize, miniSerializeError, nanoid, original, prepareAutoBatched, removeListener, unwrapResult, weakMapMemoize };
1897
+
2351
1898
  //# sourceMappingURL=redux-toolkit.legacy-esm.js.map