Skip to content
Myr

devtools.ts

This file

Path

src/middleware/devtools.ts

437 lines · 13.2 KiB · TypeScript

Last changed by

chore(deps): update dev dependencies (#3560)Daishi Katobefore adoption1f531ba

History of this file

Take it

The walk stopped after 200 commits: lines older than f85898f point at it.

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

line 1why, one step back
1import type {} from '@redux-devtools/extension'

feat(devtool): inferred action type (#2987)Ali Mert Çakarbefore adoption670b60e

line 2why, one step back
2

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 3–11why, one step back
3import type {
4 StateCreator,5 StoreApi,6 StoreMutatorIdentifier,7} from '../vanilla.ts'89type Config = Parameters<10 (Window extends { __REDUX_DEVTOOLS_EXTENSION__?: infer T }11 ? T

fix(devtools): correct redux devtools config type extension (#3414)Grigoriy Reshetniakbefore adoption89ebcd7

line 12why, one step back
12 : { connect: (param: any) => unknown })['connect']

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 13–28why, one step back
13>[0]
1415declare module '../vanilla' {16 // eslint-disable-next-line @typescript-eslint/no-unused-vars17 interface StoreMutators<S, A> {18 'zustand/devtools': WithDevtools<S>19 }20}2122// FIXME https://github.com/reduxjs/redux-devtools/issues/109723type Message = {24 type: string25 payload?: any26 state?: any27}28

chore: improve typing in devtools middleware (#3362)Grigoriy Reshetniakbefore adoption6e026d7

lines 29–37why, one step back
29type WithDispatch = {
30 dispatch: (...args: unknown[]) => void31 dispatchFromDevtools: unknown32}3334const shouldDispatchFromDevtools = (api: unknown): api is WithDispatch =>35 !!(api as WithDispatch).dispatchFromDevtools &&36 typeof (api as WithDispatch).dispatch === 'function'37

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 38–77why, one step back
38type Cast<T, U> = T extends U ? T : U
39type Write<T, U> = Omit<T, keyof U> & U40type TakeTwo<T> = T extends { length: 0 }41 ? [undefined, undefined]42 : T extends { length: 1 }43 ? [...args0: Cast<T, unknown[]>, arg1: undefined]44 : T extends { length: 0 | 1 }45 ? [...args0: Cast<T, unknown[]>, arg1: undefined]46 : T extends { length: 2 }47 ? T48 : T extends { length: 1 | 2 }49 ? T50 : T extends { length: 0 | 1 | 2 }51 ? T52 : T extends [infer A0, infer A1, ...unknown[]]53 ? [A0, A1]54 : T extends [infer A0, (infer A1)?, ...unknown[]]55 ? [A0, A1?]56 : T extends [(infer A0)?, (infer A1)?, ...unknown[]]57 ? [A0?, A1?]58 : never5960type WithDevtools<S> = Write<S, StoreDevtools<S>>6162type Action =63 | string64 | {65 type: string66 [x: string | number | symbol]: unknown67 }68type StoreDevtools<S> = S extends {69 setState: {70 // capture both overloads of setState71 (...args: infer Sa1): infer Sr172 (...args: infer Sa2): infer Sr273 }74}75 ? {76 setState(...args: [...args: TakeTwo<Sa1>, action?: Action]): Sr177 setState(...args: [...args: TakeTwo<Sa2>, action?: Action]): Sr2

feat: add devtools.cleanup() method (#3111)Hong-Kuan Wubefore adoptionb4177b3

lines 78–80why, one step back
78 devtools: {
79 cleanup: () => void80 }

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 81–98why, one step back
81 }
82 : never8384export interface DevtoolsOptions extends Config {85 name?: string86 enabled?: boolean87 anonymousActionType?: string88 store?: string89}9091type Devtools = <92 T,93 Mps extends [StoreMutatorIdentifier, unknown][] = [],94 Mcs extends [StoreMutatorIdentifier, unknown][] = [],95 U = T,96>(97 initializer: StateCreator<T, [...Mps, ['zustand/devtools', never]], Mcs, U>,98 devtoolsOptions?: DevtoolsOptions,

fix(devtools): improve type inference for Devtools initializer (#3511)Danilo Brittobefore adoptionad77bd3

line 99why, one step back
99) => StateCreator<T, Mps, [['zustand/devtools', never], ...Mcs], U>

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 100–117why, one step back
100
101type DevtoolsImpl = <T>(102 storeInitializer: StateCreator<T, [], []>,103 devtoolsOptions?: DevtoolsOptions,104) => StateCreator<T, [], []>105106export type NamedSet<T> = WithDevtools<StoreApi<T>>['setState']107108type Connection = ReturnType<109 NonNullable<Window['__REDUX_DEVTOOLS_EXTENSION__']>['connect']110>111type ConnectionName = string | undefined112type StoreName = string113type StoreInformation = StoreApi<unknown>114type ConnectionInformation = {115 connection: Connection116 stores: Record<StoreName, StoreInformation>117}

feat(devtool): inferred action type (#2987)Ali Mert Çakarbefore adoption670b60e

line 118why, one step back
118

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 119–155why, one step back
119const trackedConnections: Map<ConnectionName, ConnectionInformation> = new Map()
120121const getTrackedConnectionState = (122 name: string | undefined,123): Record<string, any> => {124 const api = trackedConnections.get(name)125 if (!api) return {}126 return Object.fromEntries(127 Object.entries(api.stores).map(([key, api]) => [key, api.getState()]),128 )129}130131const extractConnectionInformation = (132 store: string | undefined,133 extensionConnector: NonNullable<134 (typeof window)['__REDUX_DEVTOOLS_EXTENSION__']135 >,136 options: Omit<DevtoolsOptions, 'enabled' | 'anonymousActionType' | 'store'>,137) => {138 if (store === undefined) {139 return {140 type: 'untracked' as const,141 connection: extensionConnector.connect(options),142 }143 }144 const existingConnection = trackedConnections.get(options.name)145 if (existingConnection) {146 return { type: 'tracked' as const, store, ...existingConnection }147 }148 const newConnection: ConnectionInformation = {149 connection: extensionConnector.connect(options),150 stores: {},151 }152 trackedConnections.set(options.name, newConnection)153 return { type: 'tracked' as const, store, ...newConnection }154}155

feat: add devtools.cleanup() method (#3111)Hong-Kuan Wubefore adoptionb4177b3

lines 156–168why, one step back
156const removeStoreFromTrackedConnections = (
157 name: string | undefined,158 store: string | undefined,159) => {160 if (store === undefined) return161 const connectionInfo = trackedConnections.get(name)162 if (!connectionInfo) return163 delete connectionInfo.stores[store]164 if (Object.keys(connectionInfo.stores).length === 0) {165 trackedConnections.delete(name)166 }167}168

fix(devtools): correct V8 stack regex when source path contains spaces (#3531)Copilotbefore adoptionf44cecc

lines 169–170why, one step back
169// V8 (Chrome/Edge/Node): "at [async|new] <name> (<source>)"
170const v8StackLineRe = /^at (?:new |async )?(.+?) \(/

fix(devtools): support Firefox/Safari stack format in findCallerName (#3469)Siniša Bolšecbefore adoption4e9bcf0

lines 171–174why, one step back
171// SpiderMonkey (Firefox) / JavaScriptCore (Safari): "<name>@<source>"
172const geckoStackLineRe = /^([^@]+)@/173174function findCallerName(stack: string | undefined) {

feat(devtool): inferred action type (#2987)Ali Mert Çakarbefore adoption670b60e

lines 175–181why, one step back
175 if (!stack) return undefined
176 const traceLines = stack.split('\n')177 const apiSetStateLineIndex = traceLines.findIndex((traceLine) =>178 traceLine.includes('api.setState'),179 )180 if (apiSetStateLineIndex < 0) return undefined181 const callerLine = traceLines[apiSetStateLineIndex + 1]?.trim() || ''

fix(devtools): support Firefox/Safari stack format in findCallerName (#3469)Siniša Bolšecbefore adoption4e9bcf0

lines 182–185why, one step back
182 return (
183 v8StackLineRe.exec(callerLine)?.[1] ||184 geckoStackLineRe.exec(callerLine)?.[1]185 )

feat(devtool): inferred action type (#2987)Ali Mert Çakarbefore adoption670b60e

lines 186–187why, one step back
186}
187

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 188–198why, one step back
188const devtoolsImpl: DevtoolsImpl =
189 (fn, devtoolsOptions = {}) =>190 (set, get, api) => {191 const { enabled, anonymousActionType, store, ...options } = devtoolsOptions192193 type S = ReturnType<typeof fn> & {194 [store: string]: ReturnType<typeof fn>195 }196 type PartialState = Partial<S> | ((s: S) => Partial<S>)197198 let extensionConnector:

chore(deps): update dev dependencies (#3560)Daishi Katobefore adoption1f531ba

line 199why, one step back
199 (typeof window)['__REDUX_DEVTOOLS_EXTENSION__'] | false

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 200–215why, one step back
200 try {
201 extensionConnector =202 (enabled ?? import.meta.env?.MODE !== 'production') &&203 window.__REDUX_DEVTOOLS_EXTENSION__204 } catch {205 // ignored206 }207208 if (!extensionConnector) {209 return fn(set, get, api)210 }211212 const { connection, ...connectionInformation } =213 extractConnectionInformation(store, extensionConnector, options)214215 let isRecording = true

chore: improve typing in devtools middleware (#3362)Grigoriy Reshetniakbefore adoption6e026d7

line 216why, one step back
216 api.setState = ((state, replace, nameOrAction: Action) => {

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 217–220why, one step back
217 const r = set(state, replace as any)
218 if (!isRecording) return r219 const action: { type: string } =220 nameOrAction === undefined

perf(devtools): avoid inferring action type when explicit action name is provided (#3147)Vladimir Chirikovbefore adoptionca08a5e

lines 221–226why, one step back
221 ? {
222 type:223 anonymousActionType ||224 findCallerName(new Error().stack) ||225 'anonymous',226 }

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 227–245why, one step back
227 : typeof nameOrAction === 'string'
228 ? { type: nameOrAction }229 : nameOrAction230 if (store === undefined) {231 connection?.send(action, get())232 return r233 }234 connection?.send(235 {236 ...action,237 type: `${store}/${action.type}`,238 },239 {240 ...getTrackedConnectionState(options.name),241 [store]: api.getState(),242 },243 )244 return r245 }) as NamedSet<S>

feat: add devtools.cleanup() method (#3111)Hong-Kuan Wubefore adoptionb4177b3

lines 246–256why, one step back
246 ;(api as StoreApi<S> & StoreDevtools<S>).devtools = {
247 cleanup: () => {248 if (249 connection &&250 typeof (connection as any).unsubscribe === 'function'251 ) {252 ;(connection as any).unsubscribe()253 }254 removeStoreFromTrackedConnections(options.name, store)255 },256 }

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 257–281why, one step back
257
258 const setStateFromDevtools: StoreApi<S>['setState'] = (...a) => {259 const originalIsRecording = isRecording260 isRecording = false261 set(...(a as Parameters<typeof set>))262 isRecording = originalIsRecording263 }264265 const initialState = fn(api.setState, get, api)266 if (connectionInformation.type === 'untracked') {267 connection?.init(initialState)268 } else {269 connectionInformation.stores[connectionInformation.store] = api270 connection?.init(271 Object.fromEntries(272 Object.entries(connectionInformation.stores).map(([key, store]) => [273 key,274 key === connectionInformation.store275 ? initialState276 : store.getState(),277 ]),278 ),279 )280 }281

chore: improve typing in devtools middleware (#3362)Grigoriy Reshetniakbefore adoption6e026d7

line 282why, one step back
282 if (shouldDispatchFromDevtools(api)) {

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

line 283why, one step back
283 let didWarnAboutReservedActionType = false

chore: improve typing in devtools middleware (#3362)Grigoriy Reshetniakbefore adoption6e026d7

lines 284–285why, one step back
284 const originalDispatch = api.dispatch
285 api.dispatch = (...args: any[]) => {

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 286–296why, one step back
286 if (
287 import.meta.env?.MODE !== 'production' &&288 args[0].type === '__setState' &&289 !didWarnAboutReservedActionType290 ) {291 console.warn(292 '[zustand devtools middleware] "__setState" action type is reserved ' +293 'to set state from the devtools. Avoid using it.',294 )295 didWarnAboutReservedActionType = true296 }

chore: improve typing in devtools middleware (#3362)Grigoriy Reshetniakbefore adoption6e026d7

line 297why, one step back
297 originalDispatch(...args)

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 298–307why, one step back
298 }
299 }300301 ;(302 connection as unknown as {303 // FIXME https://github.com/reduxjs/redux-devtools/issues/1097304 subscribe: (305 listener: (message: Message) => void,306 ) => (() => void) | undefined307 }

chore: improve typing in devtools middleware (#3362)Grigoriy Reshetniakbefore adoption6e026d7

line 308why, one step back
308 ).subscribe((message) => {

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 309–349why, one step back
309 switch (message.type) {
310 case 'ACTION':311 if (typeof message.payload !== 'string') {312 console.error(313 '[zustand devtools middleware] Unsupported action format',314 )315 return316 }317 return parseJsonThen<{ type: unknown; state?: PartialState }>(318 message.payload,319 (action) => {320 if (action.type === '__setState') {321 if (store === undefined) {322 setStateFromDevtools(action.state as PartialState)323 return324 }325 if (Object.keys(action.state as S).length !== 1) {326 console.error(327 `328 [zustand devtools middleware] Unsupported __setState action format.329 When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),330 and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }331 `,332 )333 }334 const stateFromDevtools = (action.state as S)[store]335 if (336 stateFromDevtools === undefined ||337 stateFromDevtools === null338 ) {339 return340 }341 if (342 JSON.stringify(api.getState()) !==343 JSON.stringify(stateFromDevtools)344 ) {345 setStateFromDevtools(stateFromDevtools)346 }347 return348 }349

chore: improve typing in devtools middleware (#3362)Grigoriy Reshetniakbefore adoption6e026d7

lines 350–352why, one step back
350 if (shouldDispatchFromDevtools(api)) {
351 api.dispatch(action)352 }

chore(eslint.config.mjs): update 'eslint-plugin-react-hooks', 'eslint-plugin-react-compiler' config (#3043)Wonsuk Choibefore adoptionf85898f

lines 353–437why, one step back
353 },
354 )355356 case 'DISPATCH':357 switch (message.payload.type) {358 case 'RESET':359 setStateFromDevtools(initialState as S)360 if (store === undefined) {361 return connection?.init(api.getState())362 }363 return connection?.init(getTrackedConnectionState(options.name))364365 case 'COMMIT':366 if (store === undefined) {367 connection?.init(api.getState())368 return369 }370 return connection?.init(getTrackedConnectionState(options.name))371372 case 'ROLLBACK':373 return parseJsonThen<S>(message.state, (state) => {374 if (store === undefined) {375 setStateFromDevtools(state)376 connection?.init(api.getState())377 return378 }379 setStateFromDevtools(state[store] as S)380 connection?.init(getTrackedConnectionState(options.name))381 })382383 case 'JUMP_TO_STATE':384 case 'JUMP_TO_ACTION':385 return parseJsonThen<S>(message.state, (state) => {386 if (store === undefined) {387 setStateFromDevtools(state)388 return389 }390 if (391 JSON.stringify(api.getState()) !==392 JSON.stringify(state[store])393 ) {394 setStateFromDevtools(state[store] as S)395 }396 })397398 case 'IMPORT_STATE': {399 const { nextLiftedState } = message.payload400 const lastComputedState =401 nextLiftedState.computedStates.slice(-1)[0]?.state402 if (!lastComputedState) return403 if (store === undefined) {404 setStateFromDevtools(lastComputedState)405 } else {406 setStateFromDevtools(lastComputedState[store])407 }408 connection?.send(409 null as any, // FIXME no-any410 nextLiftedState,411 )412 return413 }414415 case 'PAUSE_RECORDING':416 return (isRecording = !isRecording)417 }418 return419 }420 })421422 return initialState423 }424export const devtools = devtoolsImpl as unknown as Devtools425426const parseJsonThen = <T>(stringified: string, fn: (parsed: T) => void) => {427 let parsed: T | undefined428 try {429 parsed = JSON.parse(stringified)430 } catch (e) {431 console.error(432 '[zustand devtools middleware] Could not parse the received json',433 e,434 )435 }436 if (parsed !== undefined) fn(parsed as T)437}