@depup/reduxjs__toolkit 2.12.0-depup.28

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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/changes.json +18 -0
  4. package/dist/cjs/index.js +6 -0
  5. package/dist/cjs/redux-toolkit.development.cjs +2406 -0
  6. package/dist/cjs/redux-toolkit.development.cjs.map +1 -0
  7. package/dist/cjs/redux-toolkit.production.min.cjs +3 -0
  8. package/dist/cjs/redux-toolkit.production.min.cjs.map +1 -0
  9. package/dist/index.d.mts +2665 -0
  10. package/dist/index.d.ts +2665 -0
  11. package/dist/query/cjs/index.js +6 -0
  12. package/dist/query/cjs/rtk-query.development.cjs +3092 -0
  13. package/dist/query/cjs/rtk-query.development.cjs.map +1 -0
  14. package/dist/query/cjs/rtk-query.production.min.cjs +2 -0
  15. package/dist/query/cjs/rtk-query.production.min.cjs.map +1 -0
  16. package/dist/query/index.d.mts +3066 -0
  17. package/dist/query/index.d.ts +3066 -0
  18. package/dist/query/react/cjs/index.js +6 -0
  19. package/dist/query/react/cjs/rtk-query-react.development.cjs +748 -0
  20. package/dist/query/react/cjs/rtk-query-react.development.cjs.map +1 -0
  21. package/dist/query/react/cjs/rtk-query-react.production.min.cjs +2 -0
  22. package/dist/query/react/cjs/rtk-query-react.production.min.cjs.map +1 -0
  23. package/dist/query/react/index.d.mts +1009 -0
  24. package/dist/query/react/index.d.ts +1009 -0
  25. package/dist/query/react/rtk-query-react.browser.mjs +2 -0
  26. package/dist/query/react/rtk-query-react.browser.mjs.map +1 -0
  27. package/dist/query/react/rtk-query-react.legacy-esm.js +740 -0
  28. package/dist/query/react/rtk-query-react.legacy-esm.js.map +1 -0
  29. package/dist/query/react/rtk-query-react.modern.mjs +705 -0
  30. package/dist/query/react/rtk-query-react.modern.mjs.map +1 -0
  31. package/dist/query/rtk-query.browser.mjs +2 -0
  32. package/dist/query/rtk-query.browser.mjs.map +1 -0
  33. package/dist/query/rtk-query.legacy-esm.js +3117 -0
  34. package/dist/query/rtk-query.legacy-esm.js.map +1 -0
  35. package/dist/query/rtk-query.modern.mjs +3052 -0
  36. package/dist/query/rtk-query.modern.mjs.map +1 -0
  37. package/dist/react/cjs/index.js +6 -0
  38. package/dist/react/cjs/redux-toolkit-react.development.cjs +55 -0
  39. package/dist/react/cjs/redux-toolkit-react.development.cjs.map +1 -0
  40. package/dist/react/cjs/redux-toolkit-react.production.min.cjs +2 -0
  41. package/dist/react/cjs/redux-toolkit-react.production.min.cjs.map +1 -0
  42. package/dist/react/index.d.mts +22 -0
  43. package/dist/react/index.d.ts +22 -0
  44. package/dist/react/redux-toolkit-react.browser.mjs +2 -0
  45. package/dist/react/redux-toolkit-react.browser.mjs.map +1 -0
  46. package/dist/react/redux-toolkit-react.legacy-esm.js +47 -0
  47. package/dist/react/redux-toolkit-react.legacy-esm.js.map +1 -0
  48. package/dist/react/redux-toolkit-react.modern.mjs +28 -0
  49. package/dist/react/redux-toolkit-react.modern.mjs.map +1 -0
  50. package/dist/redux-toolkit.browser.mjs +3 -0
  51. package/dist/redux-toolkit.browser.mjs.map +1 -0
  52. package/dist/redux-toolkit.legacy-esm.js +2351 -0
  53. package/dist/redux-toolkit.legacy-esm.js.map +1 -0
  54. package/dist/redux-toolkit.modern.mjs +2330 -0
  55. package/dist/redux-toolkit.modern.mjs.map +1 -0
  56. package/dist/uncheckedindexed.ts +16 -0
  57. package/package.json +310 -0
  58. package/query/package.json +13 -0
  59. package/query/react/package.json +13 -0
  60. package/react/package.json +13 -0
  61. package/skills/build-modern-redux-apps/modern-redux/SKILL.md +304 -0
  62. package/skills/build-modern-redux-apps/modern-redux/references/store-lifetime.md +53 -0
  63. package/skills/build-modern-redux-apps/redux-dataflow/SKILL.md +264 -0
  64. package/skills/evolve-and-diagnose-redux-apps/debug-redux-toolkit-apps/SKILL.md +269 -0
  65. package/skills/evolve-and-diagnose-redux-apps/migrate-to-modern-redux/SKILL.md +226 -0
  66. package/skills/manage-server-data/adopt-rtk-query/SKILL.md +385 -0
  67. package/skills/manage-server-data/adopt-rtk-query/references/endpoint-lifecycle.md +36 -0
  68. package/skills/model-redux-state/build-slices-and-selectors/SKILL.md +364 -0
  69. package/skills/model-redux-state/build-slices-and-selectors/references/slice-patterns.md +59 -0
  70. package/skills/model-redux-state/design-state-ownership/SKILL.md +322 -0
  71. package/skills/model-redux-state/design-state-ownership/references/state-ownership.md +28 -0
  72. package/skills/orchestrate-side-effects/handle-side-effects/SKILL.md +271 -0
  73. package/skills/orchestrate-side-effects/handle-side-effects/references/listener-workflows.md +34 -0
  74. package/src/actionCreatorInvariantMiddleware.ts +34 -0
  75. package/src/autoBatchEnhancer.ts +146 -0
  76. package/src/combineSlices.ts +487 -0
  77. package/src/configureStore.ts +248 -0
  78. package/src/createAction.ts +324 -0
  79. package/src/createAsyncThunk.ts +791 -0
  80. package/src/createDraftSafeSelector.ts +30 -0
  81. package/src/createReducer.ts +217 -0
  82. package/src/createSlice.ts +1079 -0
  83. package/src/devtoolsExtension.ts +241 -0
  84. package/src/dynamicMiddleware/index.ts +93 -0
  85. package/src/dynamicMiddleware/react/index.ts +101 -0
  86. package/src/dynamicMiddleware/types.ts +82 -0
  87. package/src/entities/create_adapter.ts +47 -0
  88. package/src/entities/entity_state.ts +38 -0
  89. package/src/entities/index.ts +8 -0
  90. package/src/entities/models.ts +198 -0
  91. package/src/entities/sorted_state_adapter.ts +266 -0
  92. package/src/entities/state_adapter.ts +58 -0
  93. package/src/entities/state_selectors.ts +73 -0
  94. package/src/entities/unsorted_state_adapter.ts +204 -0
  95. package/src/entities/utils.ts +68 -0
  96. package/src/formatProdErrorMessage.ts +13 -0
  97. package/src/getDefaultEnhancers.ts +31 -0
  98. package/src/getDefaultMiddleware.ts +113 -0
  99. package/src/immerImports.ts +7 -0
  100. package/src/immutableStateInvariantMiddleware.ts +274 -0
  101. package/src/index.ts +213 -0
  102. package/src/listenerMiddleware/exceptions.ts +20 -0
  103. package/src/listenerMiddleware/index.ts +562 -0
  104. package/src/listenerMiddleware/task.ts +100 -0
  105. package/src/listenerMiddleware/types.ts +886 -0
  106. package/src/listenerMiddleware/utils.ts +30 -0
  107. package/src/mapBuilders.ts +298 -0
  108. package/src/matchers.ts +365 -0
  109. package/src/nanoid.ts +20 -0
  110. package/src/query/HandledError.ts +6 -0
  111. package/src/query/apiTypes.ts +120 -0
  112. package/src/query/baseQueryTypes.ts +101 -0
  113. package/src/query/core/apiState.ts +377 -0
  114. package/src/query/core/buildInitiate.ts +596 -0
  115. package/src/query/core/buildMiddleware/batchActions.ts +207 -0
  116. package/src/query/core/buildMiddleware/cacheCollection.ts +204 -0
  117. package/src/query/core/buildMiddleware/cacheLifecycle.ts +379 -0
  118. package/src/query/core/buildMiddleware/devMiddleware.ts +34 -0
  119. package/src/query/core/buildMiddleware/index.ts +162 -0
  120. package/src/query/core/buildMiddleware/invalidationByTags.ts +139 -0
  121. package/src/query/core/buildMiddleware/polling.ts +187 -0
  122. package/src/query/core/buildMiddleware/queryLifecycle.ts +508 -0
  123. package/src/query/core/buildMiddleware/types.ts +173 -0
  124. package/src/query/core/buildMiddleware/windowEventHandling.ts +64 -0
  125. package/src/query/core/buildSelectors.ts +413 -0
  126. package/src/query/core/buildSlice.ts +735 -0
  127. package/src/query/core/buildThunks.ts +1124 -0
  128. package/src/query/core/index.ts +58 -0
  129. package/src/query/core/module.ts +727 -0
  130. package/src/query/core/rtkImports.ts +24 -0
  131. package/src/query/core/setupListeners.ts +118 -0
  132. package/src/query/createApi.ts +506 -0
  133. package/src/query/defaultSerializeQueryArgs.ts +52 -0
  134. package/src/query/endpointDefinitions.ts +1717 -0
  135. package/src/query/fakeBaseQuery.ts +21 -0
  136. package/src/query/fetchBaseQuery.ts +385 -0
  137. package/src/query/index.ts +105 -0
  138. package/src/query/react/ApiProvider.tsx +69 -0
  139. package/src/query/react/buildHooks.ts +2297 -0
  140. package/src/query/react/constants.ts +2 -0
  141. package/src/query/react/index.ts +45 -0
  142. package/src/query/react/module.ts +275 -0
  143. package/src/query/react/namedHooks.ts +59 -0
  144. package/src/query/react/reactImports.ts +10 -0
  145. package/src/query/react/reactReduxImports.ts +1 -0
  146. package/src/query/react/rtkqImports.ts +8 -0
  147. package/src/query/react/useSerializedStableValue.ts +17 -0
  148. package/src/query/react/useShallowStableValue.ts +13 -0
  149. package/src/query/retry.ts +233 -0
  150. package/src/query/standardSchema.ts +35 -0
  151. package/src/query/tsHelpers.ts +48 -0
  152. package/src/query/utils/capitalize.ts +3 -0
  153. package/src/query/utils/copyWithStructuralSharing.ts +27 -0
  154. package/src/query/utils/countObjectKeys.ts +14 -0
  155. package/src/query/utils/filterMap.ts +27 -0
  156. package/src/query/utils/getCurrent.ts +6 -0
  157. package/src/query/utils/getOrInsert.ts +41 -0
  158. package/src/query/utils/immerImports.ts +9 -0
  159. package/src/query/utils/index.ts +11 -0
  160. package/src/query/utils/isAbsoluteUrl.ts +9 -0
  161. package/src/query/utils/isDocumentVisible.ts +12 -0
  162. package/src/query/utils/isNotNullish.ts +7 -0
  163. package/src/query/utils/isOnline.ts +12 -0
  164. package/src/query/utils/isValidUrl.ts +9 -0
  165. package/src/query/utils/joinUrls.ts +26 -0
  166. package/src/query/utils/signals.ts +33 -0
  167. package/src/react/index.ts +7 -0
  168. package/src/reduxImports.ts +8 -0
  169. package/src/reselectImports.ts +1 -0
  170. package/src/serializableStateInvariantMiddleware.ts +285 -0
  171. package/src/tsHelpers.ts +214 -0
  172. package/src/uncheckedindexed.ts +16 -0
  173. package/src/utils.ts +125 -0
@@ -0,0 +1,248 @@
1
+ import type {
2
+ Reducer,
3
+ ReducersMapObject,
4
+ Middleware,
5
+ Action,
6
+ StoreEnhancer,
7
+ Store,
8
+ UnknownAction,
9
+ } from 'redux'
10
+ import {
11
+ applyMiddleware,
12
+ createStore,
13
+ compose,
14
+ combineReducers,
15
+ isPlainObject,
16
+ } from './reduxImports'
17
+ import type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension'
18
+ import { composeWithDevTools } from './devtoolsExtension'
19
+
20
+ import type {
21
+ ThunkMiddlewareFor,
22
+ GetDefaultMiddleware,
23
+ } from './getDefaultMiddleware'
24
+ import { buildGetDefaultMiddleware } from './getDefaultMiddleware'
25
+ import type {
26
+ ExtractDispatchExtensions,
27
+ ExtractStoreExtensions,
28
+ ExtractStateExtensions,
29
+ UnknownIfNonSpecific,
30
+ } from './tsHelpers'
31
+ import type { Tuple } from './utils'
32
+ import type { GetDefaultEnhancers } from './getDefaultEnhancers'
33
+ import { buildGetDefaultEnhancers } from './getDefaultEnhancers'
34
+
35
+ /**
36
+ * Options for `configureStore()`.
37
+ *
38
+ * @public
39
+ */
40
+ export interface ConfigureStoreOptions<
41
+ S = any,
42
+ A extends Action = UnknownAction,
43
+ M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>,
44
+ E extends Tuple<Enhancers> = Tuple<Enhancers>,
45
+ P = S,
46
+ > {
47
+ /**
48
+ * A single reducer function that will be used as the root reducer, or an
49
+ * object of slice reducers that will be passed to `combineReducers()`.
50
+ */
51
+ reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>
52
+
53
+ /**
54
+ * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.
55
+ * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.
56
+ *
57
+ * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`
58
+ * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage
59
+ */
60
+ middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M
61
+
62
+ /**
63
+ * Whether to enable Redux DevTools integration. Defaults to `true`.
64
+ *
65
+ * Additional configuration can be done by passing Redux DevTools options
66
+ */
67
+ devTools?: boolean | DevToolsOptions
68
+
69
+ /**
70
+ * Whether to check for duplicate middleware instances. Defaults to `true`.
71
+ */
72
+ duplicateMiddlewareCheck?: boolean
73
+
74
+ /**
75
+ * The initial state, same as Redux's createStore.
76
+ * You may optionally specify it to hydrate the state
77
+ * from the server in universal apps, or to restore a previously serialized
78
+ * user session. If you use `combineReducers()` to produce the root reducer
79
+ * function (either directly or indirectly by passing an object as `reducer`),
80
+ * this must be an object with the same shape as the reducer map keys.
81
+ */
82
+ // we infer here, and instead complain if the reducer doesn't match
83
+ preloadedState?: P
84
+
85
+ /**
86
+ * The store enhancers to apply. See Redux's `createStore()`.
87
+ * All enhancers will be included before the DevTools Extension enhancer.
88
+ * If you need to customize the order of enhancers, supply a callback
89
+ * function that will receive a `getDefaultEnhancers` function that returns a Tuple,
90
+ * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).
91
+ * If you only need to add middleware, you can use the `middleware` parameter instead.
92
+ */
93
+ enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E
94
+ }
95
+
96
+ export type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>
97
+
98
+ type Enhancers = ReadonlyArray<StoreEnhancer>
99
+
100
+ /**
101
+ * A Redux store returned by `configureStore()`. Supports dispatching
102
+ * side-effectful _thunks_ in addition to plain actions.
103
+ *
104
+ * @public
105
+ */
106
+ export type EnhancedStore<
107
+ S = any,
108
+ A extends Action = UnknownAction,
109
+ E extends Enhancers = Enhancers,
110
+ > = ExtractStoreExtensions<E> &
111
+ Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>
112
+
113
+ /**
114
+ * A friendly abstraction over the standard Redux `createStore()` function.
115
+ *
116
+ * @param options The store configuration.
117
+ * @returns A configured Redux store.
118
+ *
119
+ * @public
120
+ */
121
+ export function configureStore<
122
+ S = any,
123
+ A extends Action = UnknownAction,
124
+ M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>,
125
+ E extends Tuple<Enhancers> = Tuple<
126
+ [StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>, StoreEnhancer]
127
+ >,
128
+ P = S,
129
+ >(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E> {
130
+ const getDefaultMiddleware = buildGetDefaultMiddleware<S>()
131
+
132
+ const {
133
+ reducer = undefined,
134
+ middleware,
135
+ devTools = true,
136
+ duplicateMiddlewareCheck = true,
137
+ preloadedState = undefined,
138
+ enhancers = undefined,
139
+ } = options || {}
140
+
141
+ let rootReducer: Reducer<S, A, P>
142
+
143
+ if (typeof reducer === 'function') {
144
+ rootReducer = reducer
145
+ } else if (isPlainObject(reducer)) {
146
+ rootReducer = combineReducers(reducer) as unknown as Reducer<S, A, P>
147
+ } else {
148
+ throw new Error(
149
+ '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers',
150
+ )
151
+ }
152
+
153
+ if (
154
+ process.env.NODE_ENV !== 'production' &&
155
+ middleware &&
156
+ typeof middleware !== 'function'
157
+ ) {
158
+ throw new Error('`middleware` field must be a callback')
159
+ }
160
+
161
+ let finalMiddleware: Tuple<Middlewares<S>>
162
+ if (typeof middleware === 'function') {
163
+ finalMiddleware = middleware(getDefaultMiddleware)
164
+
165
+ if (
166
+ process.env.NODE_ENV !== 'production' &&
167
+ !Array.isArray(finalMiddleware)
168
+ ) {
169
+ throw new Error(
170
+ 'when using a middleware builder function, an array of middleware must be returned',
171
+ )
172
+ }
173
+ } else {
174
+ finalMiddleware = getDefaultMiddleware()
175
+ }
176
+ if (
177
+ process.env.NODE_ENV !== 'production' &&
178
+ finalMiddleware.some((item: any) => typeof item !== 'function')
179
+ ) {
180
+ throw new Error(
181
+ 'each middleware provided to configureStore must be a function',
182
+ )
183
+ }
184
+
185
+ if (process.env.NODE_ENV !== 'production' && duplicateMiddlewareCheck) {
186
+ let middlewareReferences = new Set<Middleware<any, S>>()
187
+ finalMiddleware.forEach((middleware) => {
188
+ if (middlewareReferences.has(middleware)) {
189
+ throw new Error(
190
+ 'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.',
191
+ )
192
+ }
193
+ middlewareReferences.add(middleware)
194
+ })
195
+ }
196
+
197
+ let finalCompose = compose
198
+
199
+ if (devTools) {
200
+ finalCompose = composeWithDevTools({
201
+ // Enable capture of stack traces for dispatched Redux actions
202
+ trace: process.env.NODE_ENV !== 'production',
203
+ ...(typeof devTools === 'object' && devTools),
204
+ })
205
+ }
206
+
207
+ const middlewareEnhancer = applyMiddleware(...finalMiddleware)
208
+
209
+ const getDefaultEnhancers = buildGetDefaultEnhancers<M>(middlewareEnhancer)
210
+
211
+ if (
212
+ process.env.NODE_ENV !== 'production' &&
213
+ enhancers &&
214
+ typeof enhancers !== 'function'
215
+ ) {
216
+ throw new Error('`enhancers` field must be a callback')
217
+ }
218
+
219
+ let storeEnhancers =
220
+ typeof enhancers === 'function'
221
+ ? enhancers(getDefaultEnhancers)
222
+ : getDefaultEnhancers()
223
+
224
+ if (process.env.NODE_ENV !== 'production' && !Array.isArray(storeEnhancers)) {
225
+ throw new Error('`enhancers` callback must return an array')
226
+ }
227
+ if (
228
+ process.env.NODE_ENV !== 'production' &&
229
+ storeEnhancers.some((item: any) => typeof item !== 'function')
230
+ ) {
231
+ throw new Error(
232
+ 'each enhancer provided to configureStore must be a function',
233
+ )
234
+ }
235
+ if (
236
+ process.env.NODE_ENV !== 'production' &&
237
+ finalMiddleware.length &&
238
+ !storeEnhancers.includes(middlewareEnhancer)
239
+ ) {
240
+ console.error(
241
+ 'middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`',
242
+ )
243
+ }
244
+
245
+ const composedEnhancer: StoreEnhancer<any> = finalCompose(...storeEnhancers)
246
+
247
+ return createStore(rootReducer, preloadedState as P, composedEnhancer)
248
+ }
@@ -0,0 +1,324 @@
1
+ import { isAction } from './reduxImports'
2
+ import type {
3
+ IsUnknownOrNonInferrable,
4
+ IfMaybeUndefined,
5
+ IfVoid,
6
+ IsAny,
7
+ } from './tsHelpers'
8
+ import { hasMatchFunction } from './tsHelpers'
9
+
10
+ /**
11
+ * An action with a string type and an associated payload. This is the
12
+ * type of action returned by `createAction()` action creators.
13
+ *
14
+ * @template P The type of the action's payload.
15
+ * @template T the type used for the action type.
16
+ * @template M The type of the action's meta (optional)
17
+ * @template E The type of the action's error (optional)
18
+ *
19
+ * @public
20
+ */
21
+ export type PayloadAction<
22
+ P = void,
23
+ T extends string = string,
24
+ M = never,
25
+ E = never,
26
+ > = {
27
+ payload: P
28
+ type: T
29
+ } & ([M] extends [never]
30
+ ? {}
31
+ : {
32
+ meta: M
33
+ }) &
34
+ ([E] extends [never]
35
+ ? {}
36
+ : {
37
+ error: E
38
+ })
39
+
40
+ /**
41
+ * A "prepare" method to be used as the second parameter of `createAction`.
42
+ * Takes any number of arguments and returns a Flux Standard Action without
43
+ * type (will be added later) that *must* contain a payload (might be undefined).
44
+ *
45
+ * @public
46
+ */
47
+ export type PrepareAction<P> =
48
+ | ((...args: any[]) => { payload: P })
49
+ | ((...args: any[]) => { payload: P; meta: any })
50
+ | ((...args: any[]) => { payload: P; error: any })
51
+ | ((...args: any[]) => { payload: P; meta: any; error: any })
52
+
53
+ /**
54
+ * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.
55
+ *
56
+ * @internal
57
+ */
58
+ export type _ActionCreatorWithPreparedPayload<
59
+ PA extends PrepareAction<any> | void,
60
+ T extends string = string,
61
+ > =
62
+ PA extends PrepareAction<infer P>
63
+ ? ActionCreatorWithPreparedPayload<
64
+ Parameters<PA>,
65
+ P,
66
+ T,
67
+ ReturnType<PA> extends {
68
+ error: infer E
69
+ }
70
+ ? E
71
+ : never,
72
+ ReturnType<PA> extends {
73
+ meta: infer M
74
+ }
75
+ ? M
76
+ : never
77
+ >
78
+ : void
79
+
80
+ /**
81
+ * Basic type for all action creators.
82
+ *
83
+ * @inheritdoc {redux#ActionCreator}
84
+ */
85
+ export type BaseActionCreator<P, T extends string, M = never, E = never> = {
86
+ type: T
87
+ match: (action: unknown) => action is PayloadAction<P, T, M, E>
88
+ }
89
+
90
+ /**
91
+ * An action creator that takes multiple arguments that are passed
92
+ * to a `PrepareAction` method to create the final Action.
93
+ * @typeParam Args arguments for the action creator function
94
+ * @typeParam P `payload` type
95
+ * @typeParam T `type` name
96
+ * @typeParam E optional `error` type
97
+ * @typeParam M optional `meta` type
98
+ *
99
+ * @inheritdoc {redux#ActionCreator}
100
+ *
101
+ * @public
102
+ */
103
+ export interface ActionCreatorWithPreparedPayload<
104
+ Args extends unknown[],
105
+ P,
106
+ T extends string = string,
107
+ E = never,
108
+ M = never,
109
+ > extends BaseActionCreator<P, T, M, E> {
110
+ /**
111
+ * Calling this {@link redux#ActionCreator} with `Args` will return
112
+ * an Action with a payload of type `P` and (depending on the `PrepareAction`
113
+ * method used) a `meta`- and `error` property of types `M` and `E` respectively.
114
+ */
115
+ (...args: Args): PayloadAction<P, T, M, E>
116
+ }
117
+
118
+ /**
119
+ * An action creator of type `T` that takes an optional payload of type `P`.
120
+ *
121
+ * @inheritdoc {redux#ActionCreator}
122
+ *
123
+ * @public
124
+ */
125
+ export interface ActionCreatorWithOptionalPayload<P, T extends string = string>
126
+ extends BaseActionCreator<P, T> {
127
+ /**
128
+ * Calling this {@link redux#ActionCreator} with an argument will
129
+ * return a {@link PayloadAction} of type `T` with a payload of `P`.
130
+ * Calling it without an argument will return a PayloadAction with a payload of `undefined`.
131
+ */
132
+ (payload?: P): PayloadAction<P, T>
133
+ }
134
+
135
+ /**
136
+ * An action creator of type `T` that takes no payload.
137
+ *
138
+ * @inheritdoc {redux#ActionCreator}
139
+ *
140
+ * @public
141
+ */
142
+ export interface ActionCreatorWithoutPayload<T extends string = string>
143
+ extends BaseActionCreator<undefined, T> {
144
+ /**
145
+ * Calling this {@link redux#ActionCreator} will
146
+ * return a {@link PayloadAction} of type `T` with a payload of `undefined`
147
+ */
148
+ (noArgument: void): PayloadAction<undefined, T>
149
+ }
150
+
151
+ /**
152
+ * An action creator of type `T` that requires a payload of type P.
153
+ *
154
+ * @inheritdoc {redux#ActionCreator}
155
+ *
156
+ * @public
157
+ */
158
+ export interface ActionCreatorWithPayload<P, T extends string = string>
159
+ extends BaseActionCreator<P, T> {
160
+ /**
161
+ * Calling this {@link redux#ActionCreator} with an argument will
162
+ * return a {@link PayloadAction} of type `T` with a payload of `P`
163
+ */
164
+ (payload: P): PayloadAction<P, T>
165
+ }
166
+
167
+ /**
168
+ * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.
169
+ *
170
+ * @inheritdoc {redux#ActionCreator}
171
+ *
172
+ * @public
173
+ */
174
+ export interface ActionCreatorWithNonInferrablePayload<
175
+ T extends string = string,
176
+ > extends BaseActionCreator<unknown, T> {
177
+ /**
178
+ * Calling this {@link redux#ActionCreator} with an argument will
179
+ * return a {@link PayloadAction} of type `T` with a payload
180
+ * of exactly the type of the argument.
181
+ */
182
+ <PT extends unknown>(payload: PT): PayloadAction<PT, T>
183
+ }
184
+
185
+ /**
186
+ * An action creator that produces actions with a `payload` attribute.
187
+ *
188
+ * @typeParam P the `payload` type
189
+ * @typeParam T the `type` of the resulting action
190
+ * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.
191
+ *
192
+ * @public
193
+ */
194
+ export type PayloadActionCreator<
195
+ P = void,
196
+ T extends string = string,
197
+ PA extends PrepareAction<P> | void = void,
198
+ > = IfPrepareActionMethodProvided<
199
+ PA,
200
+ _ActionCreatorWithPreparedPayload<PA, T>,
201
+ // else
202
+ IsAny<
203
+ P,
204
+ ActionCreatorWithPayload<any, T>,
205
+ IsUnknownOrNonInferrable<
206
+ P,
207
+ ActionCreatorWithNonInferrablePayload<T>,
208
+ // else
209
+ IfVoid<
210
+ P,
211
+ ActionCreatorWithoutPayload<T>,
212
+ // else
213
+ IfMaybeUndefined<
214
+ P,
215
+ ActionCreatorWithOptionalPayload<P, T>,
216
+ // else
217
+ ActionCreatorWithPayload<P, T>
218
+ >
219
+ >
220
+ >
221
+ >
222
+ >
223
+
224
+ /**
225
+ * A utility function to create an action creator for the given action type
226
+ * string. The action creator accepts a single argument, which will be included
227
+ * in the action object as a field called payload. The action creator function
228
+ * will also have its toString() overridden so that it returns the action type.
229
+ *
230
+ * @param type The action type to use for created actions.
231
+ * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
232
+ * If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
233
+ *
234
+ * @public
235
+ */
236
+ export function createAction<P = void, T extends string = string>(
237
+ type: T,
238
+ ): PayloadActionCreator<P, T>
239
+
240
+ /**
241
+ * A utility function to create an action creator for the given action type
242
+ * string. The action creator accepts a single argument, which will be included
243
+ * in the action object as a field called payload. The action creator function
244
+ * will also have its toString() overridden so that it returns the action type.
245
+ *
246
+ * @param type The action type to use for created actions.
247
+ * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
248
+ * If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
249
+ *
250
+ * @public
251
+ */
252
+ export function createAction<
253
+ PA extends PrepareAction<any>,
254
+ T extends string = string,
255
+ >(
256
+ type: T,
257
+ prepareAction: PA,
258
+ ): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>
259
+
260
+ export function createAction(type: string, prepareAction?: Function): any {
261
+ function actionCreator(...args: any[]) {
262
+ if (prepareAction) {
263
+ let prepared = prepareAction(...args)
264
+ if (!prepared) {
265
+ throw new Error('prepareAction did not return an object')
266
+ }
267
+
268
+ return {
269
+ type,
270
+ payload: prepared.payload,
271
+ ...('meta' in prepared && { meta: prepared.meta }),
272
+ ...('error' in prepared && { error: prepared.error }),
273
+ }
274
+ }
275
+ return { type, payload: args[0] }
276
+ }
277
+
278
+ actionCreator.toString = () => `${type}`
279
+
280
+ actionCreator.type = type
281
+
282
+ actionCreator.match = (action: unknown): action is PayloadAction =>
283
+ isAction(action) && action.type === type
284
+
285
+ return actionCreator
286
+ }
287
+
288
+ /**
289
+ * Returns true if value is an RTK-like action creator, with a static type property and match method.
290
+ */
291
+ export function isActionCreator(
292
+ action: unknown,
293
+ ): action is BaseActionCreator<unknown, string> & Function {
294
+ return (
295
+ typeof action === 'function' &&
296
+ 'type' in action &&
297
+ // hasMatchFunction only wants Matchers but I don't see the point in rewriting it
298
+ hasMatchFunction(action as any)
299
+ )
300
+ }
301
+
302
+ /**
303
+ * Returns true if value is an action with a string type and valid Flux Standard Action keys.
304
+ */
305
+ export function isFSA(action: unknown): action is {
306
+ type: string
307
+ payload?: unknown
308
+ error?: unknown
309
+ meta?: unknown
310
+ } {
311
+ return isAction(action) && Object.keys(action).every(isValidKey)
312
+ }
313
+
314
+ function isValidKey(key: string) {
315
+ return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1
316
+ }
317
+
318
+ // helper types for more readable typings
319
+
320
+ type IfPrepareActionMethodProvided<
321
+ PA extends PrepareAction<any> | void,
322
+ True,
323
+ False,
324
+ > = PA extends (...args: any[]) => any ? True : False