immer.ts
This file
Path
src/immer.ts
273 lines · 7.6 KiB · TypeScript
Last changed by
Several refactoringsMichel Weststratebefore adoptionc7f8f5b
History of this fileTake it
Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 1–2why, one step back1import {createES5Proxy, willFinalizeES5, markChangedES5} from "./es5"2import {createProxy, markChanged} from "./proxy"basic map tests succeedingMichel Weststratebefore adoption735c402
line 3why, one step back3TS type improvementsMichel Weststratebefore adoptiondd1808e
line 4why, one step back4import {applyPatches} from "./patches"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 5–11why, one step back5import {6 each,7 isDraft,8 isSet,9 isMap,10 isDraftable,11 DRAFT_STATE,Several refactoringsMichel Weststratebefore adoptionc7f8f5b
line 12why, one step back12 NOTHINGMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 13–14why, one step back13} from "./common"14import {ImmerScope} from "./scope"Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 15–21why, one step back15import {16 ImmerState,17 IProduce,18 IProduceWithPatches,19 Objectish,20 PatchListener,21 Draft,clean up create proxyMichel Weststratebefore adoptionc182c1e
lines 22–23why, one step back22 Patch,23 DraftedStop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
line 24why, one step back24} from "./types"clean up create proxyMichel Weststratebefore adoptionc182c1e
line 25why, one step back25import {proxyMap} from "./map"TS type improvementsMichel Weststratebefore adoptiondd1808e
line 26why, one step back26import {proxySet} from "./set"Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 27why, one step back27import {processResult, maybeFreeze} from "./finalize"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 28–42why, one step back2829function verifyMinified() {}3031const configDefaults = {32 useProxies:33 typeof Proxy !== "undefined" &&34 typeof Proxy.revocable !== "undefined" &&35 typeof Reflect !== "undefined",36 autoFreeze:37 typeof process !== "undefined"38 ? process.env.NODE_ENV !== "production"39 : verifyMinified.name === "verifyMinified",40 onAssign: null,41 onDelete: null,42 onCopy: nullTS type improvementsMichel Weststratebefore adoptiondd1808e
line 43why, one step back43} as constMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 44–52why, one step back4445interface ProducersFns {46 produce: IProduce47 produceWithPatches: IProduceWithPatches48}4950export class Immer implements ProducersFns {51 useProxies: boolean = false52 autoFreeze: boolean = falseStop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
line 53why, one step back53 onAssign?: (state: ImmerState, prop: string | number, value: unknown) => voidMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 54–67why, one step back54 onDelete?: (state: ImmerState, prop: string | number) => void55 onCopy?: (state: ImmerState) => void5657 constructor(config?: {58 useProxies?: boolean59 autoFreeze?: boolean60 onAssign?: (61 state: ImmerState,62 prop: string | number,63 value: unknown64 ) => void65 onDelete?: (state: ImmerState, prop: string | number) => void66 onCopy?: (state: ImmerState) => void67 }) {Dropped Object.assignMichel Weststratebefore adoption79a1d2c
line 68why, one step back68 each(configDefaults, (key, value) => {TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 69–70why, one step back69 // @ts-ignore70 this[key] = config?.[key] ?? valueDropped Object.assignMichel Weststratebefore adoption79a1d2c
line 71why, one step back71 })Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 72–95why, one step back72 this.setUseProxies(this.useProxies)73 this.produce = this.produce.bind(this)74 this.produceWithPatches = this.produceWithPatches.bind(this)75 }7677 /**78 * The `produce` function takes a value and a "recipe function" (whose79 * return value often depends on the base state). The recipe function is80 * free to mutate its first argument however it wants. All mutations are81 * only ever applied to a __copy__ of the base state.82 *83 * Pass only a function to create a "curried producer" which relieves you84 * from passing the recipe function every time.85 *86 * Only plain objects and arrays are made mutable. All other objects are87 * considered uncopyable.88 *89 * Note: This function is __bound__ to its `Immer` instance.90 *91 * @param {any} base - the initial state92 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified93 * @param {Function} patchListener - optional function that will be called with all the patches produced here94 * @returns {any} a new state, or the initial state if nothing was modified95 */TS type improvementsMichel Weststratebefore adoptiondd1808e
line 96why, one step back96 produce(base: any, recipe?: any, patchListener?: any) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 97–102why, one step back97 // curried invocation98 if (typeof base === "function" && typeof recipe !== "function") {99 const defaultBase = recipe100 recipe = base101102 const self = thisTS type improvementsMichel Weststratebefore adoptiondd1808e
lines 103–108why, one step back103 return function curriedProduce(104 this: any,105 base = defaultBase,106 ...args: any[]107 ) {108 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignoreMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 109–125why, one step back109 }110 }111112 // prettier-ignore113 {114 if (typeof recipe !== "function") {115 throw new Error("The first or second argument to `produce` must be a function")116 }117 if (patchListener !== undefined && typeof patchListener !== "function") {118 throw new Error("The third argument to `produce` must be a function or undefined")119 }120 }121122 let result123124 // Only plain objects, arrays, and "immerable classes" are drafted.125 if (isDraftable(base)) {map unification WIPMichel Weststratebefore adoption9bcefb6
lines 126–127why, one step back126 const scope = ImmerScope.enter(this)127 const proxy = this.createProxy(base, undefined)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 128–140why, one step back128 let hasError = true129 try {130 result = recipe(proxy)131 hasError = false132 } finally {133 // finally instead of catch + rethrow better preserves original stack134 if (hasError) scope.revoke()135 else scope.leave()136 }137 if (typeof Promise !== "undefined" && result instanceof Promise) {138 return result.then(139 result => {140 scope.usePatches(patchListener)Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 141why, one step back141 return processResult(this, result, scope)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 142–149why, one step back142 },143 error => {144 scope.revoke()145 throw error146 }147 )148 }149 scope.usePatches(patchListener)Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 150why, one step back150 return processResult(this, result, scope)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 151–154why, one step back151 } else {152 result = recipe(base)153 if (result === NOTHING) return undefined154 if (result === undefined) result = baseFurther cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 155why, one step back155 maybeFreeze(this, result, true)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 156–159why, one step back156 return result157 }158 }159TS type improvementsMichel Weststratebefore adoptiondd1808e
line 160why, one step back160 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 161why, one step back161 if (typeof arg1 === "function") {TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 162–163why, one step back162 return (state: any, ...args: any[]) =>163 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 164–167why, one step back164 }165 // non-curried form166 if (arg3)167 throw new Error("A patch listener cannot be passed to produceWithPatches")TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 168–169why, one step back168 let patches: Patch[], inversePatches: Patch[]169 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 170–172why, one step back170 patches = p171 inversePatches = ip172 })TS type improvementsMichel Weststratebefore adoptiondd1808e
line 173why, one step back173 return [nextState, patches!, inversePatches!]Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 174–175why, one step back174 }175TS type improvementsMichel Weststratebefore adoptiondd1808e
line 176why, one step back176 createDraft<T extends Objectish>(base: T): Drafted<T> {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 177–179why, one step back177 if (!isDraftable(base)) {178 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore179 }map unification WIPMichel Weststratebefore adoption9bcefb6
lines 180–181why, one step back180 const scope = ImmerScope.enter(this)181 const proxy = this.createProxy(base, undefined)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 182–183why, one step back182 proxy[DRAFT_STATE].isManual = true183 scope.leave()Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 184why, one step back184 return proxyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 185–186why, one step back185 }186Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 187–190why, one step back187 finishDraft<D extends Draft<any>>(188 draft: D,189 patchListener: PatchListener190 ): D extends Draft<infer T> ? T : never {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 191–199why, one step back191 const state = draft && draft[DRAFT_STATE]192 if (!state || !state.isManual) {193 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore194 }195 if (state.finalized) {196 throw new Error("The given draft is already finalized") // prettier-ignore197 }198 const {scope} = state199 scope.usePatches(patchListener)Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 200why, one step back200 return processResult(this, undefined, scope)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 201–224why, one step back201 }202203 /**204 * Pass true to automatically freeze all copies created by Immer.205 *206 * By default, auto-freezing is disabled in production.207 */208 setAutoFreeze(value: boolean) {209 this.autoFreeze = value210 }211212 /**213 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is214 * always faster than using ES5 proxies.215 *216 * By default, feature detection is used, so calling this is rarely necessary.217 */218 setUseProxies(value: boolean) {219 this.useProxies = value220 }221222 applyPatches(base: Objectish, patches: Patch[]) {223 // If a patch replaces the entire state, take that replacement as base224 // before applying patchesTS type improvementsMichel Weststratebefore adoptiondd1808e
line 225why, one step back225 let i: numberMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 226–238why, one step back226 for (i = patches.length - 1; i >= 0; i--) {227 const patch = patches[i]228 if (patch.path.length === 0 && patch.op === "replace") {229 base = patch.value230 break231 }232 }233234 if (isDraft(base)) {235 // N.B: never hits if some patch a replacement, patches are never drafts236 return applyPatches(base, patches)237 }238 // Otherwise, produce a copy of the base state.TS type improvementsMichel Weststratebefore adoptiondd1808e
line 239why, one step back239 return this.produce(base, (draft: Drafted) =>Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 240–243why, one step back240 applyPatches(draft, patches.slice(i + 1))241 )242 }243TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 244–247why, one step back244 createProxy<T extends Objectish>(245 value: T,246 parent?: ImmerState247 ): Drafted<T, ImmerState> {Several refactoringsMichel Weststratebefore adoptionc7f8f5b
lines 248–255why, one step back248 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft249 const draft: Drafted = isMap(value)250 ? proxyMap(value, parent)251 : isSet(value)252 ? proxySet(value, parent)253 : this.useProxies254 ? createProxy(value, parent)255 : createES5Proxy(value, parent)clean up create proxyMichel Weststratebefore adoptionc182c1e
lines 256–259why, one step back256257 const scope = parent ? parent.scope : ImmerScope.current!258 scope.drafts.push(draft)259 return draftStop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 260–265why, one step back260 }261262 willFinalize(scope: ImmerScope, thing: any, isReplaced: boolean) {263 if (!this.useProxies) willFinalizeES5(scope, thing, isReplaced)264 }265TS type improvementsMichel Weststratebefore adoptiondd1808e
line 266why, one step back266 markChanged(state: ImmerState) {Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 267–271why, one step back267 if (this.useProxies) {268 markChanged(state)269 } else {270 markChangedES5(state)271 }Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 272–273why, one step back272 }273}