@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,24 @@
1
+ // This file exists to consolidate all of the imports from the `@reduxjs/toolkit` package.
2
+ // ESBuild does not de-duplicate imports, so this file is used to ensure that each method
3
+ // imported is only listed once, and there's only one mention of the `@reduxjs/toolkit` package.
4
+
5
+ export {
6
+ createAction,
7
+ createSlice,
8
+ createSelector,
9
+ createAsyncThunk,
10
+ combineReducers,
11
+ createNextState,
12
+ isAnyOf,
13
+ isAllOf,
14
+ isAction,
15
+ isPending,
16
+ isRejected,
17
+ isFulfilled,
18
+ isRejectedWithValue,
19
+ isAsyncThunkAction,
20
+ prepareAutoBatched,
21
+ SHOULD_AUTOBATCH,
22
+ isPlainObject,
23
+ nanoid,
24
+ } from '@reduxjs/toolkit'
@@ -0,0 +1,118 @@
1
+ import type {
2
+ ThunkDispatch,
3
+ ActionCreatorWithoutPayload, // Workaround for API-Extractor
4
+ } from '@reduxjs/toolkit'
5
+ import { createAction } from './rtkImports'
6
+
7
+ export const INTERNAL_PREFIX = '__rtkq/'
8
+
9
+ const ONLINE = 'online'
10
+ const OFFLINE = 'offline'
11
+ const FOCUS = 'focus'
12
+ const FOCUSED = 'focused'
13
+ const VISIBILITYCHANGE = 'visibilitychange'
14
+
15
+ export const onFocus = /* @__PURE__ */ createAction(
16
+ `${INTERNAL_PREFIX}${FOCUSED}`,
17
+ )
18
+ export const onFocusLost = /* @__PURE__ */ createAction(
19
+ `${INTERNAL_PREFIX}un${FOCUSED}`,
20
+ )
21
+ export const onOnline = /* @__PURE__ */ createAction(
22
+ `${INTERNAL_PREFIX}${ONLINE}`,
23
+ )
24
+ export const onOffline = /* @__PURE__ */ createAction(
25
+ `${INTERNAL_PREFIX}${OFFLINE}`,
26
+ )
27
+
28
+ const actions = {
29
+ onFocus,
30
+ onFocusLost,
31
+ onOnline,
32
+ onOffline,
33
+ }
34
+
35
+ let initialized = false
36
+
37
+ /**
38
+ * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.
39
+ * It requires the dispatch method from your store.
40
+ * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,
41
+ * but you have the option of providing a callback for more granular control.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * setupListeners(store.dispatch)
46
+ * ```
47
+ *
48
+ * @param dispatch - The dispatch method from your store
49
+ * @param customHandler - An optional callback for more granular control over listener behavior
50
+ * @returns Return value of the handler.
51
+ * The default handler returns an `unsubscribe` method that can be called to remove the listeners.
52
+ */
53
+ export function setupListeners(
54
+ dispatch: ThunkDispatch<any, any, any>,
55
+ customHandler?: (
56
+ dispatch: ThunkDispatch<any, any, any>,
57
+ actions: {
58
+ onFocus: typeof onFocus
59
+ onFocusLost: typeof onFocusLost
60
+ onOnline: typeof onOnline
61
+ onOffline: typeof onOffline
62
+ },
63
+ ) => () => void,
64
+ ) {
65
+ function defaultHandler() {
66
+ const [handleFocus, handleFocusLost, handleOnline, handleOffline] = [
67
+ onFocus,
68
+ onFocusLost,
69
+ onOnline,
70
+ onOffline,
71
+ ].map((action) => () => dispatch(action()))
72
+
73
+ const handleVisibilityChange = () => {
74
+ if (window.document.visibilityState === 'visible') {
75
+ handleFocus()
76
+ } else {
77
+ handleFocusLost()
78
+ }
79
+ }
80
+
81
+ let unsubscribe = () => {
82
+ initialized = false
83
+ }
84
+
85
+ if (!initialized) {
86
+ if (typeof window !== 'undefined' && window.addEventListener) {
87
+ const handlers = {
88
+ [FOCUS]: handleFocus,
89
+ [VISIBILITYCHANGE]: handleVisibilityChange,
90
+ [ONLINE]: handleOnline,
91
+ [OFFLINE]: handleOffline,
92
+ }
93
+
94
+ function updateListeners(add: boolean) {
95
+ Object.entries(handlers).forEach(([event, handler]) => {
96
+ if (add) {
97
+ window.addEventListener(event, handler, false)
98
+ } else {
99
+ window.removeEventListener(event, handler)
100
+ }
101
+ })
102
+ }
103
+ // Handle focus events
104
+ updateListeners(true)
105
+ initialized = true
106
+
107
+ unsubscribe = () => {
108
+ updateListeners(false)
109
+ initialized = false
110
+ }
111
+ }
112
+ }
113
+
114
+ return unsubscribe
115
+ }
116
+
117
+ return customHandler ? customHandler(dispatch, actions) : defaultHandler()
118
+ }
@@ -0,0 +1,506 @@
1
+ import type { UnknownAction } from '@reduxjs/toolkit'
2
+ import { weakMapMemoize } from 'reselect'
3
+ import type { Api, ApiContext, Module, ModuleName } from './apiTypes'
4
+ import { getEndpointDefinition } from './apiTypes'
5
+ import type { BaseQueryFn } from './baseQueryTypes'
6
+ import type { CombinedState } from './core/index'
7
+ import { nanoid } from './core/rtkImports'
8
+ import type { SerializeQueryArgs } from './defaultSerializeQueryArgs'
9
+ import { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs'
10
+ import type {
11
+ EndpointBuilder,
12
+ EndpointDefinitions,
13
+ SchemaFailureConverter,
14
+ SchemaFailureHandler,
15
+ SchemaType,
16
+ } from './endpointDefinitions'
17
+ import {
18
+ ENDPOINT_INFINITEQUERY,
19
+ ENDPOINT_MUTATION,
20
+ ENDPOINT_QUERY,
21
+ isInfiniteQueryDefinition,
22
+ } from './endpointDefinitions'
23
+
24
+ export interface CreateApiOptions<
25
+ BaseQuery extends BaseQueryFn,
26
+ Definitions extends EndpointDefinitions,
27
+ ReducerPath extends string = 'api',
28
+ TagTypes extends string = never,
29
+ > {
30
+ /**
31
+ * The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements.
32
+ *
33
+ * @example
34
+ *
35
+ * ```ts
36
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
37
+ *
38
+ * const api = createApi({
39
+ * // highlight-start
40
+ * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
41
+ * // highlight-end
42
+ * endpoints: (build) => ({
43
+ * // ...endpoints
44
+ * }),
45
+ * })
46
+ * ```
47
+ */
48
+ baseQuery: BaseQuery
49
+ /**
50
+ * An array of string tag type names. Specifying tag types is optional, but you should define them so that they can be used for caching and invalidation. When defining a tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `providesTags` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidatesTags` when configuring [endpoints](#endpoints).
51
+ *
52
+ * @example
53
+ *
54
+ * ```ts
55
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
56
+ *
57
+ * const api = createApi({
58
+ * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
59
+ * // highlight-start
60
+ * tagTypes: ['Post', 'User'],
61
+ * // highlight-end
62
+ * endpoints: (build) => ({
63
+ * // ...endpoints
64
+ * }),
65
+ * })
66
+ * ```
67
+ */
68
+ tagTypes?: readonly TagTypes[]
69
+ /**
70
+ * The `reducerPath` is a _unique_ key that your service will be mounted to in your store. If you call `createApi` more than once in your application, you will need to provide a unique value each time. Defaults to `'api'`.
71
+ *
72
+ * @example
73
+ *
74
+ * ```ts
75
+ * // codeblock-meta title="apis.js"
76
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';
77
+ *
78
+ * const apiOne = createApi({
79
+ * // highlight-start
80
+ * reducerPath: 'apiOne',
81
+ * // highlight-end
82
+ * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
83
+ * endpoints: (builder) => ({
84
+ * // ...endpoints
85
+ * }),
86
+ * });
87
+ *
88
+ * const apiTwo = createApi({
89
+ * // highlight-start
90
+ * reducerPath: 'apiTwo',
91
+ * // highlight-end
92
+ * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
93
+ * endpoints: (builder) => ({
94
+ * // ...endpoints
95
+ * }),
96
+ * });
97
+ * ```
98
+ */
99
+ reducerPath?: ReducerPath
100
+ /**
101
+ * Accepts a custom function if you have a need to change the creation of cache keys for any reason.
102
+ */
103
+ serializeQueryArgs?: SerializeQueryArgs<unknown>
104
+ /**
105
+ * Endpoints are a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are three endpoint types: [`query`](../../rtk-query/usage/queries), [`infiniteQuery`](../../rtk-query/usage/infinite-queries) and [`mutation`](../../rtk-query/usage/mutations).
106
+ */
107
+ endpoints(
108
+ build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,
109
+ ): Definitions
110
+ /**
111
+ * Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * // codeblock-meta title="keepUnusedDataFor example"
116
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
117
+ * interface Post {
118
+ * id: number
119
+ * name: string
120
+ * }
121
+ * type PostsResponse = Post[]
122
+ *
123
+ * const api = createApi({
124
+ * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
125
+ * endpoints: (build) => ({
126
+ * getPosts: build.query<PostsResponse, void>({
127
+ * query: () => 'posts'
128
+ * })
129
+ * }),
130
+ * // highlight-start
131
+ * keepUnusedDataFor: 5
132
+ * // highlight-end
133
+ * })
134
+ * ```
135
+ */
136
+ keepUnusedDataFor?: number
137
+ /**
138
+ * Defaults to `false`. This setting allows you to control whether if a cached result is already available RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
139
+ * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
140
+ * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
141
+ * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
142
+ *
143
+ * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
144
+ */
145
+ refetchOnMountOrArgChange?: boolean | number
146
+ /**
147
+ * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.
148
+ *
149
+ * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
150
+ *
151
+ * Note: requires [`setupListeners`](./setupListeners) to have been called.
152
+ */
153
+ refetchOnFocus?: boolean
154
+ /**
155
+ * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
156
+ *
157
+ * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
158
+ *
159
+ * Note: requires [`setupListeners`](./setupListeners) to have been called.
160
+ */
161
+ refetchOnReconnect?: boolean
162
+ /**
163
+ * Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.
164
+ *
165
+ * - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.
166
+ * If the query provides tags that were invalidated while it ran, it won't be re-fetched.
167
+ * - `'delayed'`: Invalidation only happens after all queries and mutations are settled.
168
+ * This ensures that queries are always invalidated correctly and automatically "batches" invalidations of concurrent mutations.
169
+ * Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.
170
+ */
171
+ invalidationBehavior?: 'delayed' | 'immediately'
172
+ /**
173
+ * A function that is passed every dispatched action. If this returns something other than `undefined`,
174
+ * that return value will be used to rehydrate fulfilled & errored queries.
175
+ *
176
+ * @example
177
+ *
178
+ * ```ts
179
+ * // codeblock-meta title="next-redux-wrapper rehydration example"
180
+ * import type { Action, PayloadAction } from '@reduxjs/toolkit'
181
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
182
+ * import { HYDRATE } from 'next-redux-wrapper'
183
+ *
184
+ * type RootState = any; // normally inferred from state
185
+ *
186
+ * function isHydrateAction(action: Action): action is PayloadAction<RootState> {
187
+ * return action.type === HYDRATE
188
+ * }
189
+ *
190
+ * export const api = createApi({
191
+ * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
192
+ * // highlight-start
193
+ * extractRehydrationInfo(action, { reducerPath }): any {
194
+ * if (isHydrateAction(action)) {
195
+ * return action.payload[reducerPath]
196
+ * }
197
+ * },
198
+ * // highlight-end
199
+ * endpoints: (build) => ({
200
+ * // omitted
201
+ * }),
202
+ * })
203
+ * ```
204
+ */
205
+ extractRehydrationInfo?: (
206
+ action: UnknownAction,
207
+ {
208
+ reducerPath,
209
+ }: {
210
+ reducerPath: ReducerPath
211
+ },
212
+ ) =>
213
+ | undefined
214
+ | CombinedState<
215
+ NoInfer<Definitions>,
216
+ NoInfer<TagTypes>,
217
+ NoInfer<ReducerPath>
218
+ >
219
+
220
+ /**
221
+ * A function that is called when a schema validation fails.
222
+ *
223
+ * Gets called with a `NamedSchemaError` and an object containing the endpoint name, the type of the endpoint, the argument passed to the endpoint, and the query cache key (if applicable).
224
+ *
225
+ * `NamedSchemaError` has the following properties:
226
+ * - `issues`: an array of issues that caused the validation to fail
227
+ * - `value`: the value that was passed to the schema
228
+ * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)
229
+ *
230
+ * @example
231
+ * ```ts
232
+ * // codeblock-meta no-transpile
233
+ * import { createApi } from '@reduxjs/toolkit/query/react'
234
+ * import * as v from "valibot"
235
+ *
236
+ * const api = createApi({
237
+ * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
238
+ * endpoints: (build) => ({
239
+ * getPost: build.query<Post, { id: number }>({
240
+ * query: ({ id }) => `/post/${id}`,
241
+ * }),
242
+ * }),
243
+ * onSchemaFailure: (error, info) => {
244
+ * console.error(error, info)
245
+ * },
246
+ * })
247
+ * ```
248
+ */
249
+ onSchemaFailure?: SchemaFailureHandler
250
+
251
+ /**
252
+ * Convert a schema validation failure into an error shape matching base query errors.
253
+ *
254
+ * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.
255
+ *
256
+ * @example
257
+ * ```ts
258
+ * // codeblock-meta no-transpile
259
+ * import { createApi } from '@reduxjs/toolkit/query/react'
260
+ * import * as v from "valibot"
261
+ *
262
+ * const api = createApi({
263
+ * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
264
+ * endpoints: (build) => ({
265
+ * getPost: build.query<Post, { id: number }>({
266
+ * query: ({ id }) => `/post/${id}`,
267
+ * responseSchema: v.object({ id: v.number(), name: v.string() }),
268
+ * }),
269
+ * }),
270
+ * catchSchemaFailure: (error, info) => ({
271
+ * status: "CUSTOM_ERROR",
272
+ * error: error.schemaName + " failed validation",
273
+ * data: error.issues,
274
+ * }),
275
+ * })
276
+ * ```
277
+ */
278
+ catchSchemaFailure?: SchemaFailureConverter<BaseQuery>
279
+
280
+ /**
281
+ * Defaults to `false`.
282
+ *
283
+ * If set to `true`, will skip schema validation for all endpoints, unless overridden by the endpoint.
284
+ *
285
+ * Can be overridden for specific schemas by passing an array of schema types to skip.
286
+ *
287
+ * @example
288
+ * ```ts
289
+ * // codeblock-meta no-transpile
290
+ * import { createApi } from '@reduxjs/toolkit/query/react'
291
+ * import * as v from "valibot"
292
+ *
293
+ * const api = createApi({
294
+ * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
295
+ * skipSchemaValidation: process.env.NODE_ENV === "test" ? ["response"] : false, // skip schema validation for response in tests, since we'll be mocking the response
296
+ * endpoints: (build) => ({
297
+ * getPost: build.query<Post, { id: number }>({
298
+ * query: ({ id }) => `/post/${id}`,
299
+ * responseSchema: v.object({ id: v.number(), name: v.string() }),
300
+ * }),
301
+ * })
302
+ * })
303
+ * ```
304
+ */
305
+ skipSchemaValidation?: boolean | SchemaType[]
306
+ }
307
+
308
+ export type CreateApi<Modules extends ModuleName> = {
309
+ /**
310
+ * Creates a service to use in your application. Contains only the basic redux logic (the core module).
311
+ *
312
+ * @link https://redux-toolkit.js.org/rtk-query/api/createApi
313
+ */
314
+ <
315
+ BaseQuery extends BaseQueryFn,
316
+ Definitions extends EndpointDefinitions,
317
+ ReducerPath extends string = 'api',
318
+ TagTypes extends string = never,
319
+ >(
320
+ options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>,
321
+ ): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>
322
+ }
323
+
324
+ /**
325
+ * Builds a `createApi` method based on the provided `modules`.
326
+ *
327
+ * @link https://redux-toolkit.js.org/rtk-query/usage/customizing-create-api
328
+ *
329
+ * @example
330
+ * ```ts
331
+ * const MyContext = React.createContext<ReactReduxContextValue | null>(null);
332
+ * const customCreateApi = buildCreateApi(
333
+ * coreModule(),
334
+ * reactHooksModule({
335
+ * hooks: {
336
+ * useDispatch: createDispatchHook(MyContext),
337
+ * useSelector: createSelectorHook(MyContext),
338
+ * useStore: createStoreHook(MyContext)
339
+ * }
340
+ * })
341
+ * );
342
+ * ```
343
+ *
344
+ * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints
345
+ * @returns A `createApi` method using the provided `modules`.
346
+ */
347
+ export function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(
348
+ ...modules: Modules
349
+ ): CreateApi<Modules[number]['name']> {
350
+ return function baseCreateApi(options) {
351
+ const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) =>
352
+ options.extractRehydrationInfo?.(action, {
353
+ reducerPath: (options.reducerPath ?? 'api') as any,
354
+ }),
355
+ )
356
+
357
+ const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {
358
+ reducerPath: 'api',
359
+ keepUnusedDataFor: 60,
360
+ refetchOnMountOrArgChange: false,
361
+ refetchOnFocus: false,
362
+ refetchOnReconnect: false,
363
+ invalidationBehavior: 'delayed',
364
+ ...options,
365
+ extractRehydrationInfo,
366
+ serializeQueryArgs(queryArgsApi) {
367
+ let finalSerializeQueryArgs = defaultSerializeQueryArgs
368
+ if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {
369
+ const endpointSQA =
370
+ queryArgsApi.endpointDefinition.serializeQueryArgs!
371
+ finalSerializeQueryArgs = (queryArgsApi) => {
372
+ const initialResult = endpointSQA(queryArgsApi)
373
+ if (typeof initialResult === 'string') {
374
+ // If the user function returned a string, use it as-is
375
+ return initialResult
376
+ } else {
377
+ // Assume they returned an object (such as a subset of the original
378
+ // query args) or a primitive, and serialize it ourselves
379
+ return defaultSerializeQueryArgs({
380
+ ...queryArgsApi,
381
+ queryArgs: initialResult,
382
+ })
383
+ }
384
+ }
385
+ } else if (options.serializeQueryArgs) {
386
+ finalSerializeQueryArgs = options.serializeQueryArgs
387
+ }
388
+
389
+ return finalSerializeQueryArgs(queryArgsApi)
390
+ },
391
+ tagTypes: [...(options.tagTypes || [])],
392
+ }
393
+
394
+ const context: ApiContext<EndpointDefinitions> = {
395
+ endpointDefinitions: {},
396
+ batch(fn) {
397
+ // placeholder "batch" method to be overridden by plugins, for example with React.unstable_batchedUpdate
398
+ fn()
399
+ },
400
+ apiUid: nanoid(),
401
+ extractRehydrationInfo,
402
+ hasRehydrationInfo: weakMapMemoize(
403
+ (action) => extractRehydrationInfo(action) != null,
404
+ ),
405
+ }
406
+
407
+ const api = {
408
+ injectEndpoints,
409
+ enhanceEndpoints({ addTagTypes, endpoints }) {
410
+ if (addTagTypes) {
411
+ for (const eT of addTagTypes) {
412
+ if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {
413
+ ;(optionsWithDefaults.tagTypes as any[]).push(eT)
414
+ }
415
+ }
416
+ }
417
+ if (endpoints) {
418
+ for (const [endpointName, partialDefinition] of Object.entries(
419
+ endpoints,
420
+ )) {
421
+ if (typeof partialDefinition === 'function') {
422
+ partialDefinition(getEndpointDefinition(context, endpointName))
423
+ } else {
424
+ Object.assign(
425
+ getEndpointDefinition(context, endpointName) || {},
426
+ partialDefinition,
427
+ )
428
+ }
429
+ }
430
+ }
431
+ return api
432
+ },
433
+ } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>
434
+
435
+ const initializedModules = modules.map((m) =>
436
+ m.init(api as any, optionsWithDefaults as any, context),
437
+ )
438
+
439
+ function injectEndpoints(
440
+ inject: Parameters<typeof api.injectEndpoints>[0],
441
+ ) {
442
+ const evaluatedEndpoints = inject.endpoints({
443
+ query: (x) => ({ ...x, type: ENDPOINT_QUERY }) as any,
444
+ mutation: (x) => ({ ...x, type: ENDPOINT_MUTATION }) as any,
445
+ infiniteQuery: (x) => ({ ...x, type: ENDPOINT_INFINITEQUERY }) as any,
446
+ })
447
+
448
+ for (const [endpointName, definition] of Object.entries(
449
+ evaluatedEndpoints,
450
+ )) {
451
+ if (
452
+ inject.overrideExisting !== true &&
453
+ endpointName in context.endpointDefinitions
454
+ ) {
455
+ if (inject.overrideExisting === 'throw') {
456
+ throw new Error(
457
+ `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``,
458
+ )
459
+ } else if (
460
+ typeof process !== 'undefined' &&
461
+ process.env.NODE_ENV === 'development'
462
+ ) {
463
+ console.error(
464
+ `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``,
465
+ )
466
+ }
467
+
468
+ continue
469
+ }
470
+
471
+ if (
472
+ typeof process !== 'undefined' &&
473
+ process.env.NODE_ENV === 'development'
474
+ ) {
475
+ if (isInfiniteQueryDefinition(definition)) {
476
+ const { infiniteQueryOptions } = definition
477
+ const { maxPages, getPreviousPageParam } = infiniteQueryOptions
478
+
479
+ if (typeof maxPages === 'number') {
480
+ if (maxPages < 1) {
481
+ throw new Error(
482
+ `maxPages for endpoint '${endpointName}' must be a number greater than 0`,
483
+ )
484
+ }
485
+
486
+ if (typeof getPreviousPageParam !== 'function') {
487
+ throw new Error(
488
+ `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`,
489
+ )
490
+ }
491
+ }
492
+ }
493
+ }
494
+
495
+ context.endpointDefinitions[endpointName] = definition
496
+ for (const m of initializedModules) {
497
+ m.injectEndpoint(endpointName, definition)
498
+ }
499
+ }
500
+
501
+ return api as any
502
+ }
503
+
504
+ return api.injectEndpoints({ endpoints: options.endpoints as any })
505
+ }
506
+ }
@@ -0,0 +1,52 @@
1
+ import type { QueryCacheKey } from './core/apiState'
2
+ import type { EndpointDefinition } from './endpointDefinitions'
3
+ import { isPlainObject } from './core/rtkImports'
4
+
5
+ const cache: WeakMap<any, string> | undefined = WeakMap
6
+ ? new WeakMap()
7
+ : undefined
8
+
9
+ export const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({
10
+ endpointName,
11
+ queryArgs,
12
+ }) => {
13
+ let serialized = ''
14
+
15
+ const cached = cache?.get(queryArgs)
16
+
17
+ if (typeof cached === 'string') {
18
+ serialized = cached
19
+ } else {
20
+ const stringified = JSON.stringify(queryArgs, (key, value) => {
21
+ // Handle bigints
22
+ value = typeof value === 'bigint' ? { $bigint: value.toString() } : value
23
+ // Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })
24
+ value = isPlainObject(value)
25
+ ? Object.keys(value)
26
+ .sort()
27
+ .reduce<any>((acc, key) => {
28
+ acc[key] = (value as any)[key]
29
+ return acc
30
+ }, {})
31
+ : value
32
+ return value
33
+ })
34
+ if (isPlainObject(queryArgs)) {
35
+ cache?.set(queryArgs, stringified)
36
+ }
37
+ serialized = stringified
38
+ }
39
+ return `${endpointName}(${serialized})`
40
+ }
41
+
42
+ export type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {
43
+ queryArgs: QueryArgs
44
+ endpointDefinition: EndpointDefinition<any, any, any, any>
45
+ endpointName: string
46
+ }) => ReturnType
47
+
48
+ export type InternalSerializeQueryArgs = (_: {
49
+ queryArgs: any
50
+ endpointDefinition: EndpointDefinition<any, any, any, any>
51
+ endpointName: string
52
+ }) => QueryCacheKey