Skip to content

Commit 9aae695

Browse files
authored
Byte-shave various chunks of code (#5129)
* Byte-shave setupListeners * Remove dead method * Deduplicate TS enums with string constants * Deduplicate RTKQ imports * Deduplicate promise unsubscribes and endpoint names * Deduplicate endpoint type enum * Deduplicate cache lifecycle action fields * Deduplicate endpoint definition lookups * Fix missed Immer imports * Try size-checking browser.mjs files instead
1 parent 952e7ed commit 9aae695

22 files changed

+233
-145
lines changed

packages/toolkit/.size-limit.cjs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
const webpack = require('webpack')
22
let { join } = require('path')
33

4-
const esmSuffixes = ['modern.mjs' /*, 'browser.mjs', 'legacy-esm.js'*/]
5-
const cjsSuffixes = [/*'development.cjs',*/ 'production.min.cjs']
4+
const esmSuffixes = ['modern.mjs', 'browser.mjs' /*, 'legacy-esm.js'*/]
5+
const cjsSuffixes = [
6+
/*'development.cjs',*/
7+
/*'production.min.cjs'*/
8+
]
69

710
function withRtkPath(suffix, cjs = false) {
811
/**

packages/toolkit/src/query/apiTypes.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { UnknownAction } from '@reduxjs/toolkit'
22
import type { BaseQueryFn } from './baseQueryTypes'
3-
import type { CombinedState, CoreModule } from './core'
3+
import type { CombinedState, CoreModule, QueryKeys } from './core'
44
import type { ApiModules } from './core/module'
55
import type { CreateApiOptions } from './createApi'
66
import type {
@@ -56,6 +56,14 @@ export interface ApiContext<Definitions extends EndpointDefinitions> {
5656
hasRehydrationInfo: (action: UnknownAction) => boolean
5757
}
5858

59+
export const getEndpointDefinition = <
60+
Definitions extends EndpointDefinitions,
61+
EndpointName extends keyof Definitions,
62+
>(
63+
context: ApiContext<Definitions>,
64+
endpointName: EndpointName,
65+
) => context.endpointDefinitions[endpointName]
66+
5967
export type Api<
6068
BaseQuery extends BaseQueryFn,
6169
Definitions extends EndpointDefinitions,

packages/toolkit/src/query/core/apiState.ts

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,13 @@ export type InfiniteData<DataType, PageParam> = {
6565
pageParams: Array<PageParam>
6666
}
6767

68+
// NOTE: DO NOT import and use this for runtime comparisons internally,
69+
// except in the RTKQ React package. Use the string versions just below this.
70+
// ESBuild auto-inlines TS enums, which bloats our bundle with many repeated
71+
// constants like "initialized":
72+
// https://github.com/evanw/esbuild/releases/tag/v0.14.7
73+
// We still have to use this in the React package since we don't publicly export
74+
// the string constants below.
6875
/**
6976
* Strings describing the query state at any given time.
7077
*/
@@ -75,6 +82,12 @@ export enum QueryStatus {
7582
rejected = 'rejected',
7683
}
7784

85+
// Use these string constants for runtime comparisons internally
86+
export const STATUS_UNINITIALIZED = QueryStatus.uninitialized
87+
export const STATUS_PENDING = QueryStatus.pending
88+
export const STATUS_FULFILLED = QueryStatus.fulfilled
89+
export const STATUS_REJECTED = QueryStatus.rejected
90+
7891
export type RequestStatusFlags =
7992
| {
8093
status: QueryStatus.uninitialized
@@ -108,10 +121,10 @@ export type RequestStatusFlags =
108121
export function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {
109122
return {
110123
status,
111-
isUninitialized: status === QueryStatus.uninitialized,
112-
isLoading: status === QueryStatus.pending,
113-
isSuccess: status === QueryStatus.fulfilled,
114-
isError: status === QueryStatus.rejected,
124+
isUninitialized: status === STATUS_UNINITIALIZED,
125+
isLoading: status === STATUS_PENDING,
126+
isSuccess: status === STATUS_FULFILLED,
127+
isError: status === STATUS_REJECTED,
115128
} as any
116129
}
117130

packages/toolkit/src/query/core/buildInitiate.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@ import type {
77
} from '@reduxjs/toolkit'
88
import type { Dispatch } from 'redux'
99
import { asSafePromise } from '../../tsHelpers'
10-
import type { Api, ApiContext } from '../apiTypes'
10+
import { getEndpointDefinition, type Api, type ApiContext } from '../apiTypes'
1111
import type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes'
1212
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
1313
import {
14+
ENDPOINT_QUERY,
1415
isQueryDefinition,
1516
type EndpointDefinition,
1617
type EndpointDefinitions,
@@ -303,7 +304,7 @@ export function buildInitiate({
303304

304305
function getRunningQueryThunk(endpointName: string, queryArgs: any) {
305306
return (dispatch: Dispatch) => {
306-
const endpointDefinition = context.endpointDefinitions[endpointName]
307+
const endpointDefinition = getEndpointDefinition(context, endpointName)
307308
const queryCacheKey = serializeQueryArgs({
308309
queryArgs,
309310
endpointDefinition,
@@ -393,7 +394,7 @@ You must add the middleware for RTK-Query to function correctly!`,
393394

394395
const commonThunkArgs = {
395396
...rest,
396-
type: 'query' as const,
397+
type: ENDPOINT_QUERY as 'query',
397398
subscribe,
398399
forceRefetch: forceRefetch,
399400
subscriptionOptions,

packages/toolkit/src/query/core/buildMiddleware/cacheCollection.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { getEndpointDefinition } from '@internal/query/apiTypes'
12
import type { QueryDefinition } from '../../endpointDefinitions'
23
import type { ConfigState, QueryCacheKey, QuerySubState } from '../apiState'
34
import { isAnyOf } from '../rtkImports'
@@ -155,9 +156,10 @@ export const buildCacheCollectionHandler: InternalHandlerBuilder = ({
155156
api: SubMiddlewareApi,
156157
config: ConfigState<string>,
157158
) {
158-
const endpointDefinition = context.endpointDefinitions[
159-
endpointName
160-
] as QueryDefinition<any, any, any, any>
159+
const endpointDefinition = getEndpointDefinition(
160+
context,
161+
endpointName,
162+
) as QueryDefinition<any, any, any, any>
161163
const keepUnusedDataFor =
162164
endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor
163165

packages/toolkit/src/query/core/buildMiddleware/cacheLifecycle.ts

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import type {
2323
PromiseWithKnownReason,
2424
SubMiddlewareApi,
2525
} from './types'
26+
import { getEndpointDefinition } from '@internal/query/apiTypes'
2627

2728
export type ReferenceCacheLifecycle = never
2829

@@ -205,6 +206,9 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
205206
}
206207
const lifecycleMap: Record<string, CacheLifecycle> = {}
207208

209+
const { removeQueryResult, removeMutationResult, cacheEntriesUpserted } =
210+
api.internalActions
211+
208212
function resolveLifecycleEntry(
209213
cacheKey: string,
210214
data: unknown,
@@ -229,6 +233,16 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
229233
}
230234
}
231235

236+
function getActionMetaFields(
237+
action:
238+
| ReturnType<typeof queryThunk.pending>
239+
| ReturnType<typeof mutationThunk.pending>,
240+
) {
241+
const { arg, requestId } = action.meta
242+
const { endpointName, originalArgs } = arg
243+
return [endpointName, originalArgs, requestId] as const
244+
}
245+
232246
const handler: ApiMiddlewareInternalHandler = (
233247
action,
234248
mwApi,
@@ -250,13 +264,10 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
250264
}
251265

252266
if (queryThunk.pending.match(action)) {
253-
checkForNewCacheKey(
254-
action.meta.arg.endpointName,
255-
cacheKey,
256-
action.meta.requestId,
257-
action.meta.arg.originalArgs,
258-
)
259-
} else if (api.internalActions.cacheEntriesUpserted.match(action)) {
267+
const [endpointName, originalArgs, requestId] =
268+
getActionMetaFields(action)
269+
checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs)
270+
} else if (cacheEntriesUpserted.match(action)) {
260271
for (const { queryDescription, value } of action.payload) {
261272
const { endpointName, originalArgs, queryCacheKey } = queryDescription
262273
checkForNewCacheKey(
@@ -271,19 +282,15 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
271282
} else if (mutationThunk.pending.match(action)) {
272283
const state = mwApi.getState()[reducerPath].mutations[cacheKey]
273284
if (state) {
274-
handleNewKey(
275-
action.meta.arg.endpointName,
276-
action.meta.arg.originalArgs,
277-
cacheKey,
278-
mwApi,
279-
action.meta.requestId,
280-
)
285+
const [endpointName, originalArgs, requestId] =
286+
getActionMetaFields(action)
287+
handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId)
281288
}
282289
} else if (isFulfilledThunk(action)) {
283290
resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta)
284291
} else if (
285-
api.internalActions.removeQueryResult.match(action) ||
286-
api.internalActions.removeMutationResult.match(action)
292+
removeQueryResult.match(action) ||
293+
removeMutationResult.match(action)
287294
) {
288295
removeLifecycleEntry(cacheKey)
289296
} else if (api.util.resetApiState.match(action)) {
@@ -298,9 +305,8 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
298305
if (isMutationThunk(action)) {
299306
return action.meta.arg.fixedCacheKey ?? action.meta.requestId
300307
}
301-
if (api.internalActions.removeQueryResult.match(action))
302-
return action.payload.queryCacheKey
303-
if (api.internalActions.removeMutationResult.match(action))
308+
if (removeQueryResult.match(action)) return action.payload.queryCacheKey
309+
if (removeMutationResult.match(action))
304310
return getMutationCacheKey(action.payload)
305311
return ''
306312
}
@@ -312,7 +318,7 @@ export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
312318
mwApi: SubMiddlewareApi,
313319
requestId: string,
314320
) {
315-
const endpointDefinition = context.endpointDefinitions[endpointName]
321+
const endpointDefinition = getEndpointDefinition(context, endpointName)
316322
const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded
317323
if (!onCacheEntryAdded) return
318324

packages/toolkit/src/query/core/buildMiddleware/invalidationByTags.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import type {
1111
} from '../../endpointDefinitions'
1212
import { calculateProvidedBy } from '../../endpointDefinitions'
1313
import type { CombinedState, QueryCacheKey } from '../apiState'
14-
import { QueryStatus } from '../apiState'
14+
import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
1515
import { calculateProvidedByThunk } from '../buildThunks'
1616
import type {
1717
SubMiddlewareApi,
@@ -127,7 +127,7 @@ export const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({
127127
queryCacheKey: queryCacheKey as QueryCacheKey,
128128
}),
129129
)
130-
} else if (querySubState.status !== QueryStatus.uninitialized) {
130+
} else if (querySubState.status !== STATUS_UNINITIALIZED) {
131131
mwApi.dispatch(refetchQuery(querySubState))
132132
}
133133
}

packages/toolkit/src/query/core/buildMiddleware/polling.ts

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import type {
44
Subscribers,
55
SubscribersInternal,
66
} from '../apiState'
7-
import { QueryStatus } from '../apiState'
7+
import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
88
import type {
99
QueryStateMeta,
1010
SubMiddlewareApi,
@@ -75,20 +75,6 @@ export const buildPollingHandler: InternalHandlerBuilder = ({
7575
}
7676
}
7777

78-
function getCacheEntrySubscriptions(
79-
queryCacheKey: QueryCacheKey,
80-
api: SubMiddlewareApi,
81-
) {
82-
const state = api.getState()[reducerPath]
83-
const querySubState = state.queries[queryCacheKey]
84-
const subscriptions = currentSubscriptions.get(queryCacheKey)
85-
86-
if (!querySubState || querySubState.status === QueryStatus.uninitialized)
87-
return
88-
89-
return subscriptions
90-
}
91-
9278
function startNextPoll(
9379
{ queryCacheKey }: QuerySubstateIdentifier,
9480
api: SubMiddlewareApi,
@@ -97,8 +83,7 @@ export const buildPollingHandler: InternalHandlerBuilder = ({
9783
const querySubState = state.queries[queryCacheKey]
9884
const subscriptions = currentSubscriptions.get(queryCacheKey)
9985

100-
if (!querySubState || querySubState.status === QueryStatus.uninitialized)
101-
return
86+
if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return
10287

10388
const { lowestPollingInterval, skipPollingIfUnfocused } =
10489
findLowestPollingInterval(subscriptions)
@@ -133,7 +118,7 @@ export const buildPollingHandler: InternalHandlerBuilder = ({
133118
const querySubState = state.queries[queryCacheKey]
134119
const subscriptions = currentSubscriptions.get(queryCacheKey)
135120

136-
if (!querySubState || querySubState.status === QueryStatus.uninitialized) {
121+
if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {
137122
return
138123
}
139124

packages/toolkit/src/query/core/buildMiddleware/queryLifecycle.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1+
import { getEndpointDefinition } from '@internal/query/apiTypes'
12
import type {
23
BaseQueryError,
34
BaseQueryFn,
45
BaseQueryMeta,
56
} from '../../baseQueryTypes'
6-
import { DefinitionType, isAnyQueryDefinition } from '../../endpointDefinitions'
7+
import { isAnyQueryDefinition } from '../../endpointDefinitions'
78
import type { Recipe } from '../buildThunks'
89
import { isFulfilled, isPending, isRejected } from '../rtkImports'
910
import type {
@@ -442,7 +443,7 @@ export const buildQueryLifecycleHandler: InternalHandlerBuilder = ({
442443
requestId,
443444
arg: { endpointName, originalArgs },
444445
} = action.meta
445-
const endpointDefinition = context.endpointDefinitions[endpointName]
446+
const endpointDefinition = getEndpointDefinition(context, endpointName)
446447
const onQueryStarted = endpointDefinition?.onQueryStarted
447448
if (onQueryStarted) {
448449
const lifecycle = {} as CacheLifecycle

packages/toolkit/src/query/core/buildMiddleware/windowEventHandling.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
import { QueryStatus } from '../apiState'
1+
import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
22
import type { QueryCacheKey } from '../apiState'
33
import { onFocus, onOnline } from '../setupListeners'
44
import type {
55
ApiMiddlewareInternalHandler,
66
InternalHandlerBuilder,
77
SubMiddlewareApi,
88
} from './types'
9-
import { countObjectKeys } from '../../utils/countObjectKeys'
109

1110
export const buildWindowEventHandler: InternalHandlerBuilder = ({
1211
reducerPath,
@@ -53,7 +52,7 @@ export const buildWindowEventHandler: InternalHandlerBuilder = ({
5352
queryCacheKey: queryCacheKey as QueryCacheKey,
5453
}),
5554
)
56-
} else if (querySubState.status !== QueryStatus.uninitialized) {
55+
} else if (querySubState.status !== STATUS_UNINITIALIZED) {
5756
api.dispatch(refetchQuery(querySubState))
5857
}
5958
}

0 commit comments

Comments
 (0)