Skip to content
Myr

refactor(middleware): split into multiple files (#664)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Daishi Kato · committed by GitHub · parent c319075 · Browse files · 6 files+649 added−626 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+649 added−626 removed

  • other:+649 added−626 removed

6 files+649 added−626 removed

added:src/middleware/combine.ts+25 added
added:src/middleware/devtools.ts+167 added
1import { GetState, PartialState, SetState, State, StoreApi } from '../vanilla'23const DEVTOOLS = Symbol()45type DevtoolsType = {6 prefix: string7 subscribe: (dispatch: any) => () => void8 unsubscribe: () => void9 send: (action: string, state: any) => void10 init: (state: any) => void11 error: (payload: any) => void12}1314export type NamedSet<T extends State> = {15 <16 K1 extends keyof T,17 K2 extends keyof T = K1,18 K3 extends keyof T = K2,19 K4 extends keyof T = K320 >(21 partial: PartialState<T, K1, K2, K3, K4>,22 replace?: boolean,23 name?: string24 ): void25}2627export type StoreApiWithDevtools<T extends State> = StoreApi<T> & {28 setState: NamedSet<T>29 devtools?: DevtoolsType30}3132export const devtools =33 <34 S extends State,35 CustomSetState extends SetState<S>,36 CustomGetState extends GetState<S>,37 CustomStoreApi extends StoreApi<S>38 >(39 fn: (set: NamedSet<S>, get: CustomGetState, api: CustomStoreApi) => S,40 options?:41 | string42 | {43 name?: string44 serialize?: {45 options:46 | boolean47 | {48 date?: boolean49 regex?: boolean50 undefined?: boolean51 nan?: boolean52 infinity?: boolean53 error?: boolean54 symbol?: boolean55 map?: boolean56 set?: boolean57 }58 }59 }60 ) =>61 (62 set: CustomSetState,63 get: CustomGetState,64 api: CustomStoreApi & StoreApiWithDevtools<S> & { dispatch?: unknown }65 ): S => {66 let extension67 try {68 extension =69 (window as any).__REDUX_DEVTOOLS_EXTENSION__ ||70 (window as any).top.__REDUX_DEVTOOLS_EXTENSION__71 } catch {}7273 if (!extension) {74 if (75 process.env.NODE_ENV === 'development' &&76 typeof window !== 'undefined'77 ) {78 console.warn('Please install/enable Redux devtools extension')79 }80 delete api.devtools81 return fn(set, get, api)82 }83 const namedSet: NamedSet<S> = (state, replace, name) => {84 set(state, replace)85 if (!api.dispatch && api.devtools) {86 api.devtools.send(api.devtools.prefix + (name || 'action'), get())87 }88 }89 api.setState = namedSet90 const initialState = fn(namedSet, get, api)91 if (!api.devtools) {92 const savedSetState = api.setState93 api.setState = <94 K1 extends keyof S = keyof S,95 K2 extends keyof S = K1,96 K3 extends keyof S = K2,97 K4 extends keyof S = K398 >(99 state: PartialState<S, K1, K2, K3, K4>,100 replace?: boolean101 ) => {102 const newState = api.getState()103 if (state !== newState) {104 savedSetState(state, replace)105 if (state !== (newState as any)[DEVTOOLS] && api.devtools) {106 api.devtools.send(api.devtools.prefix + 'setState', api.getState())107 }108 }109 }110 options = typeof options === 'string' ? { name: options } : options111 const connection = (api.devtools = extension.connect({ ...options }))112 connection.prefix = options?.name ? `${options.name} > ` : ''113 connection.subscribe((message: any) => {114 if (message.type === 'ACTION' && message.payload) {115 try {116 api.setState(JSON.parse(message.payload))117 } catch (e) {118 console.error(119 'please dispatch a serializable value that JSON.parse() support\n',120 e121 )122 }123 } else if (message.type === 'DISPATCH' && message.state) {124 const jumpState =125 message.payload.type === 'JUMP_TO_ACTION' ||126 message.payload.type === 'JUMP_TO_STATE'127 const newState = api.getState()128 ;(newState as any)[DEVTOOLS] = JSON.parse(message.state)129130 if (!api.dispatch && !jumpState) {131 api.setState(newState)132 } else if (jumpState) {133 api.setState((newState as any)[DEVTOOLS])134 } else {135 savedSetState(newState)136 }137 } else if (138 message.type === 'DISPATCH' &&139 message.payload?.type === 'COMMIT'140 ) {141 connection.init(api.getState())142 } else if (143 message.type === 'DISPATCH' &&144 message.payload?.type === 'IMPORT_STATE'145 ) {146 const actions = message.payload.nextLiftedState?.actionsById147 const computedStates =148 message.payload.nextLiftedState?.computedStates || []149150 computedStates.forEach(151 ({ state }: { state: PartialState<S> }, index: number) => {152 const action = actions[index] || 'No action found'153154 if (index === 0) {155 connection.init(state)156 } else {157 savedSetState(state)158 connection.send(action, api.getState())159 }160 }161 )162 }163 })164 connection.init(initialState)165 }166 return initialState167 }
added:src/middleware/persist.ts+345 added
1import { GetState, SetState, State, StoreApi } from '../vanilla'23type DeepPartial<T extends Object> = {4 [P in keyof T]?: DeepPartial<T[P]>5}67export type StateStorage = {8 getItem: (name: string) => string | null | Promise<string | null>9 setItem: (name: string, value: string) => void | Promise<void>10 // Note: This will be required in v411 removeItem?: (name: string) => void | Promise<void>12}1314type StorageValue<S> = { state: DeepPartial<S>; version?: number }1516export type PersistOptions<17 S,18 PersistedState extends Partial<S> = Partial<S>19> = {20 /** Name of the storage (must be unique) */21 name: string22 /**23 * A function returning a storage.24 * The storage must fit `window.localStorage`'s api (or an async version of it).25 * For example the storage could be `AsyncStorage` from React Native.26 *27 * @default () => localStorage28 */29 getStorage?: () => StateStorage30 /**31 * Use a custom serializer.32 * The returned string will be stored in the storage.33 *34 * @default JSON.stringify35 */36 serialize?: (state: StorageValue<S>) => string | Promise<string>37 /**38 * Use a custom deserializer.39 * Must return an object matching StorageValue<State>40 *41 * @param str The storage's current value.42 * @default JSON.parse43 */44 deserialize?: (45 str: string46 ) => StorageValue<PersistedState> | Promise<StorageValue<PersistedState>>47 /**48 * Prevent some items from being stored.49 *50 * @deprecated This options is deprecated and will be removed in the next version. Please use the `partialize` option instead.51 */52 blacklist?: (keyof S)[]53 /**54 * Only store the listed properties.55 *56 * @deprecated This options is deprecated and will be removed in the next version. Please use the `partialize` option instead.57 */58 whitelist?: (keyof S)[]59 /**60 * Filter the persisted value.61 *62 * @params state The state's value63 */64 partialize?: (state: S) => DeepPartial<S>65 /**66 * A function returning another (optional) function.67 * The main function will be called before the state rehydration.68 * The returned function will be called after the state rehydration or when an error occurred.69 */70 onRehydrateStorage?: (state: S) => ((state?: S, error?: Error) => void) | void71 /**72 * If the stored state's version mismatch the one specified here, the storage will not be used.73 * This is useful when adding a breaking change to your store.74 */75 version?: number76 /**77 * A function to perform persisted state migration.78 * This function will be called when persisted state versions mismatch with the one specified here.79 */80 migrate?: (persistedState: any, version: number) => S | Promise<S>81 /**82 * A function to perform custom hydration merges when combining the stored state with the current one.83 * By default, this function does a shallow merge.84 */85 merge?: (persistedState: any, currentState: S) => S86}8788type PersistListener<S> = (state: S) => void8990export type StoreApiWithPersist<S extends State> = StoreApi<S> & {91 persist: {92 setOptions: (options: Partial<PersistOptions<S>>) => void93 clearStorage: () => void94 rehydrate: () => Promise<void>95 hasHydrated: () => boolean96 onHydrate: (fn: PersistListener<S>) => () => void97 onFinishHydration: (fn: PersistListener<S>) => () => void98 }99}100101type Thenable<Value> = {102 then<V>(103 onFulfilled: (value: Value) => V | Promise<V> | Thenable<V>104 ): Thenable<V>105 catch<V>(106 onRejected: (reason: Error) => V | Promise<V> | Thenable<V>107 ): Thenable<V>108}109110const toThenable =111 <Result, Input>(112 fn: (input: Input) => Result | Promise<Result> | Thenable<Result>113 ) =>114 (input: Input): Thenable<Result> => {115 try {116 const result = fn(input)117 if (result instanceof Promise) {118 return result as Thenable<Result>119 }120 return {121 then(onFulfilled) {122 return toThenable(onFulfilled)(result as Result)123 },124 catch(_onRejected) {125 return this as Thenable<any>126 },127 }128 } catch (e: any) {129 return {130 then(_onFulfilled) {131 return this as Thenable<any>132 },133 catch(onRejected) {134 return toThenable(onRejected)(e)135 },136 }137 }138 }139140export const persist =141 <142 S extends State,143 CustomSetState extends SetState<S>,144 CustomGetState extends GetState<S>,145 CustomStoreApi extends StoreApi<S>146 >(147 config: (148 set: CustomSetState,149 get: CustomGetState,150 api: CustomStoreApi151 ) => S,152 baseOptions: PersistOptions<S>153 ) =>154 (155 set: CustomSetState,156 get: CustomGetState,157 api: CustomStoreApi & StoreApiWithPersist<S>158 ): S => {159 let options = {160 getStorage: () => localStorage,161 serialize: JSON.stringify as (state: StorageValue<S>) => string,162 deserialize: JSON.parse as (str: string) => StorageValue<Partial<S>>,163 partialize: (state: S) => state,164 version: 0,165 merge: (persistedState: any, currentState: S) => ({166 ...currentState,167 ...persistedState,168 }),169 ...baseOptions,170 }171172 if (options.blacklist || options.whitelist) {173 console.warn(174 `The ${175 options.blacklist ? 'blacklist' : 'whitelist'176 } option is deprecated and will be removed in the next version. Please use the 'partialize' option instead.`177 )178 }179180 let hasHydrated = false181 const hydrationListeners = new Set<PersistListener<S>>()182 const finishHydrationListeners = new Set<PersistListener<S>>()183 let storage: StateStorage | undefined184185 try {186 storage = options.getStorage()187 } catch (e) {188 // prevent error if the storage is not defined (e.g. when server side rendering a page)189 }190191 if (!storage) {192 return config(193 ((...args) => {194 console.warn(195 `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`196 )197 set(...args)198 }) as CustomSetState,199 get,200 api201 )202 } else if (!storage.removeItem) {203 console.warn(204 `[zustand persist middleware] The given storage for item '${options.name}' does not contain a 'removeItem' method, which will be required in v4.`205 )206 }207208 const thenableSerialize = toThenable(options.serialize)209210 const setItem = (): Thenable<void> => {211 const state = options.partialize({ ...get() })212213 if (options.whitelist) {214 ;(Object.keys(state) as (keyof S)[]).forEach((key) => {215 !options.whitelist?.includes(key) && delete state[key]216 })217 }218 if (options.blacklist) {219 options.blacklist.forEach((key) => delete state[key])220 }221222 let errorInSync: Error | undefined223 const thenable = thenableSerialize({ state, version: options.version })224 .then((serializedValue) =>225 (storage as StateStorage).setItem(options.name, serializedValue)226 )227 .catch((e) => {228 errorInSync = e229 })230 if (errorInSync) {231 throw errorInSync232 }233 return thenable234 }235236 const savedSetState = api.setState237238 api.setState = (state, replace) => {239 savedSetState(state, replace)240 void setItem()241 }242243 const configResult = config(244 ((...args) => {245 set(...args)246 void setItem()247 }) as CustomSetState,248 get,249 api250 )251252 // a workaround to solve the issue of not storing rehydrated state in sync storage253 // the set(state) value would be later overridden with initial state by create()254 // to avoid this, we merge the state from localStorage into the initial state.255 let stateFromStorage: S | undefined256257 // rehydrate initial state with existing stored state258 const hydrate = () => {259 if (!storage) return260261 hasHydrated = false262 hydrationListeners.forEach((cb) => cb(get()))263264 const postRehydrationCallback =265 options.onRehydrateStorage?.(get()) || undefined266267 // bind is used to avoid `TypeError: Illegal invocation` error268 return toThenable(storage.getItem.bind(storage))(options.name)269 .then((storageValue) => {270 if (storageValue) {271 return options.deserialize(storageValue)272 }273 })274 .then((deserializedStorageValue) => {275 if (deserializedStorageValue) {276 if (277 typeof deserializedStorageValue.version === 'number' &&278 deserializedStorageValue.version !== options.version279 ) {280 if (options.migrate) {281 return options.migrate(282 deserializedStorageValue.state,283 deserializedStorageValue.version284 )285 }286 console.error(287 `State loaded from storage couldn't be migrated since no migrate function was provided`288 )289 } else {290 return deserializedStorageValue.state291 }292 }293 })294 .then((migratedState) => {295 stateFromStorage = options.merge(migratedState as S, configResult)296297 set(stateFromStorage as S, true)298 return setItem()299 })300 .then(() => {301 postRehydrationCallback?.(stateFromStorage, undefined)302 hasHydrated = true303 finishHydrationListeners.forEach((cb) => cb(stateFromStorage as S))304 })305 .catch((e: Error) => {306 postRehydrationCallback?.(undefined, e)307 })308 }309310 api.persist = {311 setOptions: (newOptions) => {312 options = {313 ...options,314 ...newOptions,315 }316317 if (newOptions.getStorage) {318 storage = newOptions.getStorage()319 }320 },321 clearStorage: () => {322 storage?.removeItem?.(options.name)323 },324 rehydrate: () => hydrate() as Promise<void>,325 hasHydrated: () => hasHydrated,326 onHydrate: (cb) => {327 hydrationListeners.add(cb)328329 return () => {330 hydrationListeners.delete(cb)331 }332 },333 onFinishHydration: (cb) => {334 finishHydrationListeners.add(cb)335336 return () => {337 finishHydrationListeners.delete(cb)338 }339 },340 }341342 hydrate()343344 return stateFromStorage || configResult345 }
added:src/middleware/redux.ts+37 added
added:src/middleware/subscribeWithSelector.ts+70 added
modified:src/middleware.ts+5 added-626 removed
1import {2 EqualityChecker,3 GetState,4 PartialState,5 SetState,6 State,7 StateListener,8 StateSelector,9 StateSliceListener,10 StoreApi,11 Subscribe,12} from './vanilla'1314const DEVTOOLS = Symbol()1516type DevtoolsType = {17 prefix: string18 subscribe: (dispatch: any) => () => void19 unsubscribe: () => void20 send: (action: string, state: any) => void21 init: (state: any) => void22 error: (payload: any) => void23}2425export type StoreApiWithRedux<26 T extends State,27 A extends { type: unknown }28> = StoreApi<T & { dispatch: (a: A) => A }> & {29 dispatch: (a: A) => A30}3132export const redux =33 <S extends State, A extends { type: unknown }>(34 reducer: (state: S, action: A) => S,35 initial: S36 ) =>37 (38 set: SetState<S & { dispatch: (a: A) => A }>,39 get: GetState<S & { dispatch: (a: A) => A }>,40 api: StoreApiWithRedux<S, A> & { devtools?: DevtoolsType }41 ): S & { dispatch: (a: A) => A } => {42 api.dispatch = (action: A) => {43 set((state: S) => reducer(state, action))44 if (api.devtools) {45 api.devtools.send(api.devtools.prefix + action.type, get())46 }47 return action48 }49 return { dispatch: api.dispatch, ...initial }50 }5152export type NamedSet<T extends State> = {53 <54 K1 extends keyof T,55 K2 extends keyof T = K1,56 K3 extends keyof T = K2,57 K4 extends keyof T = K358 >(59 partial: PartialState<T, K1, K2, K3, K4>,60 replace?: boolean,61 name?: string62 ): void63}6465export type StoreApiWithDevtools<T extends State> = StoreApi<T> & {66 setState: NamedSet<T>67 devtools?: DevtoolsType68}6970export const devtools =71 <72 S extends State,73 CustomSetState extends SetState<S>,74 CustomGetState extends GetState<S>,75 CustomStoreApi extends StoreApi<S>76 >(77 fn: (set: NamedSet<S>, get: CustomGetState, api: CustomStoreApi) => S,78 options?:79 | string80 | {81 name?: string82 serialize?: {83 options:84 | boolean85 | {86 date?: boolean87 regex?: boolean88 undefined?: boolean89 nan?: boolean90 infinity?: boolean91 error?: boolean92 symbol?: boolean93 map?: boolean94 set?: boolean95 }96 }97 }98 ) =>99 (100 set: CustomSetState,101 get: CustomGetState,102 api: CustomStoreApi & StoreApiWithDevtools<S> & { dispatch?: unknown }103 ): S => {104 let extension105 try {106 extension =107 (window as any).__REDUX_DEVTOOLS_EXTENSION__ ||108 (window as any).top.__REDUX_DEVTOOLS_EXTENSION__109 } catch {}110111 if (!extension) {112 if (113 process.env.NODE_ENV === 'development' &&114 typeof window !== 'undefined'115 ) {116 console.warn('Please install/enable Redux devtools extension')117 }118 delete api.devtools119 return fn(set, get, api)120 }121 const namedSet: NamedSet<S> = (state, replace, name) => {122 set(state, replace)123 if (!api.dispatch && api.devtools) {124 api.devtools.send(api.devtools.prefix + (name || 'action'), get())125 }126 }127 api.setState = namedSet128 const initialState = fn(namedSet, get, api)129 if (!api.devtools) {130 const savedSetState = api.setState131 api.setState = <132 K1 extends keyof S = keyof S,133 K2 extends keyof S = K1,134 K3 extends keyof S = K2,135 K4 extends keyof S = K3136 >(137 state: PartialState<S, K1, K2, K3, K4>,138 replace?: boolean139 ) => {140 const newState = api.getState()141 if (state !== newState) {142 savedSetState(state, replace)143 if (state !== (newState as any)[DEVTOOLS] && api.devtools) {144 api.devtools.send(api.devtools.prefix + 'setState', api.getState())145 }146 }147 }148 options = typeof options === 'string' ? { name: options } : options149 const connection = (api.devtools = extension.connect({ ...options }))150 connection.prefix = options?.name ? `${options.name} > ` : ''151 connection.subscribe((message: any) => {152 if (message.type === 'ACTION' && message.payload) {153 try {154 api.setState(JSON.parse(message.payload))155 } catch (e) {156 console.error(157 'please dispatch a serializable value that JSON.parse() support\n',158 e159 )160 }161 } else if (message.type === 'DISPATCH' && message.state) {162 const jumpState =163 message.payload.type === 'JUMP_TO_ACTION' ||164 message.payload.type === 'JUMP_TO_STATE'165 const newState = api.getState()166 ;(newState as any)[DEVTOOLS] = JSON.parse(message.state)167168 if (!api.dispatch && !jumpState) {169 api.setState(newState)170 } else if (jumpState) {171 api.setState((newState as any)[DEVTOOLS])172 } else {173 savedSetState(newState)174 }175 } else if (176 message.type === 'DISPATCH' &&177 message.payload?.type === 'COMMIT'178 ) {179 connection.init(api.getState())180 } else if (181 message.type === 'DISPATCH' &&182 message.payload?.type === 'IMPORT_STATE'183 ) {184 const actions = message.payload.nextLiftedState?.actionsById185 const computedStates =186 message.payload.nextLiftedState?.computedStates || []187188 computedStates.forEach(189 ({ state }: { state: PartialState<S> }, index: number) => {190 const action = actions[index] || 'No action found'191192 if (index === 0) {193 connection.init(state)194 } else {195 savedSetState(state)196 connection.send(action, api.getState())197 }198 }199 )200 }201 })202 connection.init(initialState)203 }204 return initialState205 }206207export type StoreApiWithSubscribeWithSelector<T extends State> = Omit<208 StoreApi<T>,209 'subscribe' // FIXME remove omit in v4210> & {211 subscribe: {212 (listener: StateListener<T>): () => void213 <StateSlice>(214 selector: StateSelector<T, StateSlice>,215 listener: StateSliceListener<StateSlice>,216 options?: {217 equalityFn?: EqualityChecker<StateSlice>218 fireImmediately?: boolean219 }220 ): () => void221 }222}223224export const subscribeWithSelector =225 <226 S extends State,227 CustomSetState extends SetState<S>,228 CustomGetState extends GetState<S>,229 CustomStoreApi extends StoreApi<S>230 >(231 fn: (set: CustomSetState, get: CustomGetState, api: CustomStoreApi) => S232 ) =>233 (234 set: CustomSetState,235 get: CustomGetState,236 api: Omit<CustomStoreApi, 'subscribe'> & // FIXME remove omit in v4237 StoreApiWithSubscribeWithSelector<S>238 ): S => {239 const origSubscribe = api.subscribe as Subscribe<S>240 api.subscribe = ((selector: any, optListener: any, options: any) => {241 let listener: StateListener<S> = selector // if no selector242 if (optListener) {243 const equalityFn = options?.equalityFn || Object.is244 let currentSlice = selector(api.getState())245 listener = (state) => {246 const nextSlice = selector(state)247 if (!equalityFn(currentSlice, nextSlice)) {248 const previousSlice = currentSlice249 optListener((currentSlice = nextSlice), previousSlice)250 }251 }252 if (options?.fireImmediately) {253 optListener(currentSlice, currentSlice)254 }255 }256 return origSubscribe(listener)257 }) as any258 const initialState = fn(259 set,260 get,261 api as CustomStoreApi // FIXME can remove in v4?262 )263 return initialState264 }265266type Combine<T, U> = Omit<T, keyof U> & U267268export const combine =269 <PrimaryState extends State, SecondaryState extends State>(270 initialState: PrimaryState,271 create: (272 // Note: NamedSet added for convenience273 set: SetState<PrimaryState> & NamedSet<PrimaryState>,274 get: GetState<PrimaryState>,275 api: StoreApi<PrimaryState>276 ) => SecondaryState277 ) =>278 (279 set: SetState<Combine<PrimaryState, SecondaryState>>,280 get: GetState<Combine<PrimaryState, SecondaryState>>,281 api: StoreApi<Combine<PrimaryState, SecondaryState>>282 ) =>283 Object.assign(284 {},285 initialState,286 create(set as any, get as any, api as any)287 ) as Combine<PrimaryState, SecondaryState>288289type DeepPartial<T extends Object> = {290 [P in keyof T]?: DeepPartial<T[P]>291}292export type StateStorage = {293 getItem: (name: string) => string | null | Promise<string | null>294 setItem: (name: string, value: string) => void | Promise<void>295 // Note: This will be required in v4296 removeItem?: (name: string) => void | Promise<void>297}298type StorageValue<S> = { state: DeepPartial<S>; version?: number }299export type PersistOptions<300 S,301 PersistedState extends Partial<S> = Partial<S>302> = {303 /** Name of the storage (must be unique) */304 name: string305 /**306 * A function returning a storage.307 * The storage must fit `window.localStorage`'s api (or an async version of it).308 * For example the storage could be `AsyncStorage` from React Native.309 *310 * @default () => localStorage311 */312 getStorage?: () => StateStorage313 /**314 * Use a custom serializer.315 * The returned string will be stored in the storage.316 *317 * @default JSON.stringify318 */319 serialize?: (state: StorageValue<S>) => string | Promise<string>320 /**321 * Use a custom deserializer.322 * Must return an object matching StorageValue<State>323 *324 * @param str The storage's current value.325 * @default JSON.parse326 */327 deserialize?: (328 str: string329 ) => StorageValue<PersistedState> | Promise<StorageValue<PersistedState>>330 /**331 * Prevent some items from being stored.332 *333 * @deprecated This options is deprecated and will be removed in the next version. Please use the `partialize` option instead.334 */335 blacklist?: (keyof S)[]336 /**337 * Only store the listed properties.338 *339 * @deprecated This options is deprecated and will be removed in the next version. Please use the `partialize` option instead.340 */341 whitelist?: (keyof S)[]342 /**343 * Filter the persisted value.344 *345 * @params state The state's value346 */347 partialize?: (state: S) => DeepPartial<S>348 /**349 * A function returning another (optional) function.350 * The main function will be called before the state rehydration.351 * The returned function will be called after the state rehydration or when an error occurred.352 */353 onRehydrateStorage?: (state: S) => ((state?: S, error?: Error) => void) | void354 /**355 * If the stored state's version mismatch the one specified here, the storage will not be used.356 * This is useful when adding a breaking change to your store.357 */358 version?: number359 /**360 * A function to perform persisted state migration.361 * This function will be called when persisted state versions mismatch with the one specified here.362 */363 migrate?: (persistedState: any, version: number) => S | Promise<S>364 /**365 * A function to perform custom hydration merges when combining the stored state with the current one.366 * By default, this function does a shallow merge.367 */368 merge?: (persistedState: any, currentState: S) => S369}370type PersistListener<S> = (state: S) => void371export type StoreApiWithPersist<S extends State> = StoreApi<S> & {372 persist: {373 setOptions: (options: Partial<PersistOptions<S>>) => void374 clearStorage: () => void375 rehydrate: () => Promise<void>376 hasHydrated: () => boolean377 onHydrate: (fn: PersistListener<S>) => () => void378 onFinishHydration: (fn: PersistListener<S>) => () => void379 }380}381382type Thenable<Value> = {383 then<V>(384 onFulfilled: (value: Value) => V | Promise<V> | Thenable<V>385 ): Thenable<V>386 catch<V>(387 onRejected: (reason: Error) => V | Promise<V> | Thenable<V>388 ): Thenable<V>389}390391const toThenable =392 <Result, Input>(393 fn: (input: Input) => Result | Promise<Result> | Thenable<Result>394 ) =>395 (input: Input): Thenable<Result> => {396 try {397 const result = fn(input)398 if (result instanceof Promise) {399 return result as Thenable<Result>400 }401 return {402 then(onFulfilled) {403 return toThenable(onFulfilled)(result as Result)404 },405 catch(_onRejected) {406 return this as Thenable<any>407 },408 }409 } catch (e: any) {410 return {411 then(_onFulfilled) {412 return this as Thenable<any>413 },414 catch(onRejected) {415 return toThenable(onRejected)(e)416 },417 }418 }419 }420421export const persist =422 <423 S extends State,424 CustomSetState extends SetState<S>,425 CustomGetState extends GetState<S>,426 CustomStoreApi extends StoreApi<S>427 >(428 config: (429 set: CustomSetState,430 get: CustomGetState,431 api: CustomStoreApi432 ) => S,433 baseOptions: PersistOptions<S>434 ) =>435 (436 set: CustomSetState,437 get: CustomGetState,438 api: CustomStoreApi & StoreApiWithPersist<S>439 ): S => {440 let options = {441 getStorage: () => localStorage,442 serialize: JSON.stringify as (state: StorageValue<S>) => string,443 deserialize: JSON.parse as (str: string) => StorageValue<Partial<S>>,444 partialize: (state: S) => state,445 version: 0,446 merge: (persistedState: any, currentState: S) => ({447 ...currentState,448 ...persistedState,449 }),450 ...baseOptions,451 }452453 if (options.blacklist || options.whitelist) {454 console.warn(455 `The ${456 options.blacklist ? 'blacklist' : 'whitelist'457 } option is deprecated and will be removed in the next version. Please use the 'partialize' option instead.`458 )459 }460461 let hasHydrated = false462 const hydrationListeners = new Set<PersistListener<S>>()463 const finishHydrationListeners = new Set<PersistListener<S>>()464 let storage: StateStorage | undefined465466 try {467 storage = options.getStorage()468 } catch (e) {469 // prevent error if the storage is not defined (e.g. when server side rendering a page)470 }471472 if (!storage) {473 return config(474 ((...args) => {475 console.warn(476 `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`477 )478 set(...args)479 }) as CustomSetState,480 get,481 api482 )483 } else if (!storage.removeItem) {484 console.warn(485 `[zustand persist middleware] The given storage for item '${options.name}' does not contain a 'removeItem' method, which will be required in v4.`486 )487 }488489 const thenableSerialize = toThenable(options.serialize)490491 const setItem = (): Thenable<void> => {492 const state = options.partialize({ ...get() })493494 if (options.whitelist) {495 ;(Object.keys(state) as (keyof S)[]).forEach((key) => {496 !options.whitelist?.includes(key) && delete state[key]497 })498 }499 if (options.blacklist) {500 options.blacklist.forEach((key) => delete state[key])501 }502503 let errorInSync: Error | undefined504 const thenable = thenableSerialize({ state, version: options.version })505 .then((serializedValue) =>506 (storage as StateStorage).setItem(options.name, serializedValue)507 )508 .catch((e) => {509 errorInSync = e510 })511 if (errorInSync) {512 throw errorInSync513 }514 return thenable515 }516517 const savedSetState = api.setState518519 api.setState = (state, replace) => {520 savedSetState(state, replace)521 void setItem()522 }523524 const configResult = config(525 ((...args) => {526 set(...args)527 void setItem()528 }) as CustomSetState,529 get,530 api531 )532533 // a workaround to solve the issue of not storing rehydrated state in sync storage534 // the set(state) value would be later overridden with initial state by create()535 // to avoid this, we merge the state from localStorage into the initial state.536 let stateFromStorage: S | undefined537538 // rehydrate initial state with existing stored state539 const hydrate = () => {540 if (!storage) return541542 hasHydrated = false543 hydrationListeners.forEach((cb) => cb(get()))544545 const postRehydrationCallback =546 options.onRehydrateStorage?.(get()) || undefined547548 // bind is used to avoid `TypeError: Illegal invocation` error549 return toThenable(storage.getItem.bind(storage))(options.name)550 .then((storageValue) => {551 if (storageValue) {552 return options.deserialize(storageValue)553 }554 })555 .then((deserializedStorageValue) => {556 if (deserializedStorageValue) {557 if (558 typeof deserializedStorageValue.version === 'number' &&559 deserializedStorageValue.version !== options.version560 ) {561 if (options.migrate) {562 return options.migrate(563 deserializedStorageValue.state,564 deserializedStorageValue.version565 )566 }567 console.error(568 `State loaded from storage couldn't be migrated since no migrate function was provided`569 )570 } else {571 return deserializedStorageValue.state572 }573 }574 })575 .then((migratedState) => {576 stateFromStorage = options.merge(migratedState as S, configResult)577578 set(stateFromStorage as S, true)579 return setItem()580 })581 .then(() => {582 postRehydrationCallback?.(stateFromStorage, undefined)583 hasHydrated = true584 finishHydrationListeners.forEach((cb) => cb(stateFromStorage as S))585 })586 .catch((e: Error) => {587 postRehydrationCallback?.(undefined, e)588 })589 }590591 api.persist = {592 setOptions: (newOptions) => {593 options = {594 ...options,595 ...newOptions,596 }597598 if (newOptions.getStorage) {599 storage = newOptions.getStorage()600 }601 },602 clearStorage: () => {603 storage?.removeItem?.(options.name)604 },605 rehydrate: () => hydrate() as Promise<void>,606 hasHydrated: () => hasHydrated,607 onHydrate: (cb) => {608 hydrationListeners.add(cb)609610 return () => {611 hydrationListeners.delete(cb)612 }613 },614 onFinishHydration: (cb) => {615 finishHydrationListeners.add(cb)616617 return () => {618 finishHydrationListeners.delete(cb)619 }620 },621 }622623 hydrate()624625 return stateFromStorage || configResult626 }1export * from './middleware/redux'2export * from './middleware/devtools'3export * from './middleware/subscribeWithSelector'4export * from './middleware/combine'5export * from './middleware/persist'