immer.ts
This file
Path
src/immer.ts
279 lines · 7.8 KiB · TypeScript
Last changed by
Processed bunch of todosMichel Weststratebefore adoption00425e1
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–12why, one step back5import {6 each,7 isDraft,8 isSet,9 isMap,10 isDraftable,11 DRAFT_STATE,12 NOTHING,clean up create proxyMichel Weststratebefore adoptionc182c1e
line 13why, one step back13 isPlainObject,TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 14–15why, one step back14 DRAFTABLE,15 dieMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 16–17why, one step back16} from "./common"17import {ImmerScope} from "./scope"Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 18–24why, one step back18import {19 ImmerState,20 IProduce,21 IProduceWithPatches,22 Objectish,23 PatchListener,24 Draft,clean up create proxyMichel Weststratebefore adoptionc182c1e
lines 25–26why, one step back25 Patch,26 DraftedStop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
line 27why, one step back27} from "./types"clean up create proxyMichel Weststratebefore adoptionc182c1e
line 28why, one step back28import {proxyMap} from "./map"TS type improvementsMichel Weststratebefore adoptiondd1808e
line 29why, one step back29import {proxySet} from "./set"Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 30why, one step back30import {processResult, maybeFreeze} from "./finalize"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 31–45why, one step back3132function verifyMinified() {}3334const configDefaults = {35 useProxies:36 typeof Proxy !== "undefined" &&37 typeof Proxy.revocable !== "undefined" &&38 typeof Reflect !== "undefined",39 autoFreeze:40 typeof process !== "undefined"41 ? process.env.NODE_ENV !== "production"42 : verifyMinified.name === "verifyMinified",43 onAssign: null,44 onDelete: null,45 onCopy: nullTS type improvementsMichel Weststratebefore adoptiondd1808e
line 46why, one step back46} as constMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 47–55why, one step back4748interface ProducersFns {49 produce: IProduce50 produceWithPatches: IProduceWithPatches51}5253export class Immer implements ProducersFns {54 useProxies: boolean = false55 autoFreeze: boolean = falseStop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
line 56why, one step back56 onAssign?: (state: ImmerState, prop: string | number, value: unknown) => voidMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 57–70why, one step back57 onDelete?: (state: ImmerState, prop: string | number) => void58 onCopy?: (state: ImmerState) => void5960 constructor(config?: {61 useProxies?: boolean62 autoFreeze?: boolean63 onAssign?: (64 state: ImmerState,65 prop: string | number,66 value: unknown67 ) => void68 onDelete?: (state: ImmerState, prop: string | number) => void69 onCopy?: (state: ImmerState) => void70 }) {Dropped Object.assignMichel Weststratebefore adoption79a1d2c
line 71why, one step back71 each(configDefaults, (key, value) => {TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 72–73why, one step back72 // @ts-ignore73 this[key] = config?.[key] ?? valueDropped Object.assignMichel Weststratebefore adoption79a1d2c
line 74why, one step back74 })Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 75–98why, one step back75 this.setUseProxies(this.useProxies)76 this.produce = this.produce.bind(this)77 this.produceWithPatches = this.produceWithPatches.bind(this)78 }7980 /**81 * The `produce` function takes a value and a "recipe function" (whose82 * return value often depends on the base state). The recipe function is83 * free to mutate its first argument however it wants. All mutations are84 * only ever applied to a __copy__ of the base state.85 *86 * Pass only a function to create a "curried producer" which relieves you87 * from passing the recipe function every time.88 *89 * Only plain objects and arrays are made mutable. All other objects are90 * considered uncopyable.91 *92 * Note: This function is __bound__ to its `Immer` instance.93 *94 * @param {any} base - the initial state95 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified96 * @param {Function} patchListener - optional function that will be called with all the patches produced here97 * @returns {any} a new state, or the initial state if nothing was modified98 */TS type improvementsMichel Weststratebefore adoptiondd1808e
line 99why, one step back99 produce(base: any, recipe?: any, patchListener?: any) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 100–105why, one step back100 // curried invocation101 if (typeof base === "function" && typeof recipe !== "function") {102 const defaultBase = recipe103 recipe = base104105 const self = thisTS type improvementsMichel Weststratebefore adoptiondd1808e
lines 106–111why, one step back106 return function curriedProduce(107 this: any,108 base = defaultBase,109 ...args: any[]110 ) {111 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignoreMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 112–128why, one step back112 }113 }114115 // prettier-ignore116 {117 if (typeof recipe !== "function") {118 throw new Error("The first or second argument to `produce` must be a function")119 }120 if (patchListener !== undefined && typeof patchListener !== "function") {121 throw new Error("The third argument to `produce` must be a function or undefined")122 }123 }124125 let result126127 // Only plain objects, arrays, and "immerable classes" are drafted.128 if (isDraftable(base)) {map unification WIPMichel Weststratebefore adoption9bcefb6
lines 129–130why, one step back129 const scope = ImmerScope.enter(this)130 const proxy = this.createProxy(base, undefined)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 131–143why, one step back131 let hasError = true132 try {133 result = recipe(proxy)134 hasError = false135 } finally {136 // finally instead of catch + rethrow better preserves original stack137 if (hasError) scope.revoke()138 else scope.leave()139 }140 if (typeof Promise !== "undefined" && result instanceof Promise) {141 return result.then(142 result => {143 scope.usePatches(patchListener)Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 144why, one step back144 return processResult(this, result, scope)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 145–152why, one step back145 },146 error => {147 scope.revoke()148 throw error149 }150 )151 }152 scope.usePatches(patchListener)Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 153why, one step back153 return processResult(this, result, scope)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 154–157why, one step back154 } else {155 result = recipe(base)156 if (result === NOTHING) return undefined157 if (result === undefined) result = baseFurther cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 158why, one step back158 maybeFreeze(this, result, true)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 159–162why, one step back159 return result160 }161 }162TS type improvementsMichel Weststratebefore adoptiondd1808e
line 163why, one step back163 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 164–165why, one step back164 if (typeof arg1 === "function") {165 const self = thisTS type improvementsMichel Weststratebefore adoptiondd1808e
lines 166–167why, one step back166 return (state: any, ...args: any[]) =>167 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 168–171why, one step back168 }169 // non-curried form170 if (arg3)171 throw new Error("A patch listener cannot be passed to produceWithPatches")TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 172–173why, one step back172 let patches: Patch[], inversePatches: Patch[]173 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 174–176why, one step back174 patches = p175 inversePatches = ip176 })TS type improvementsMichel Weststratebefore adoptiondd1808e
line 177why, one step back177 return [nextState, patches!, inversePatches!]Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 178–179why, one step back178 }179TS type improvementsMichel Weststratebefore adoptiondd1808e
line 180why, one step back180 createDraft<T extends Objectish>(base: T): Drafted<T> {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 181–183why, one step back181 if (!isDraftable(base)) {182 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore183 }map unification WIPMichel Weststratebefore adoption9bcefb6
lines 184–185why, one step back184 const scope = ImmerScope.enter(this)185 const proxy = this.createProxy(base, undefined)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 186–187why, one step back186 proxy[DRAFT_STATE].isManual = true187 scope.leave()Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 188why, one step back188 return proxyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 189–190why, one step back189 }190Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 191–194why, one step back191 finishDraft<D extends Draft<any>>(192 draft: D,193 patchListener: PatchListener194 ): D extends Draft<infer T> ? T : never {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 195–203why, one step back195 const state = draft && draft[DRAFT_STATE]196 if (!state || !state.isManual) {197 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore198 }199 if (state.finalized) {200 throw new Error("The given draft is already finalized") // prettier-ignore201 }202 const {scope} = state203 scope.usePatches(patchListener)Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 204why, one step back204 return processResult(this, undefined, scope)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 205–228why, one step back205 }206207 /**208 * Pass true to automatically freeze all copies created by Immer.209 *210 * By default, auto-freezing is disabled in production.211 */212 setAutoFreeze(value: boolean) {213 this.autoFreeze = value214 }215216 /**217 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is218 * always faster than using ES5 proxies.219 *220 * By default, feature detection is used, so calling this is rarely necessary.221 */222 setUseProxies(value: boolean) {223 this.useProxies = value224 }225226 applyPatches(base: Objectish, patches: Patch[]) {227 // If a patch replaces the entire state, take that replacement as base228 // before applying patchesTS type improvementsMichel Weststratebefore adoptiondd1808e
line 229why, one step back229 let i: numberMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 230–242why, one step back230 for (i = patches.length - 1; i >= 0; i--) {231 const patch = patches[i]232 if (patch.path.length === 0 && patch.op === "replace") {233 base = patch.value234 break235 }236 }237238 if (isDraft(base)) {239 // N.B: never hits if some patch a replacement, patches are never drafts240 return applyPatches(base, patches)241 }242 // Otherwise, produce a copy of the base state.TS type improvementsMichel Weststratebefore adoptiondd1808e
line 243why, one step back243 return this.produce(base, (draft: Drafted) =>Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 244–247why, one step back244 applyPatches(draft, patches.slice(i + 1))245 )246 }247TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 248–251why, one step back248 createProxy<T extends Objectish>(249 value: T,250 parent?: ImmerState251 ): Drafted<T, ImmerState> {clean up create proxyMichel Weststratebefore adoptionc182c1e
line 252why, one step back252 let draft: DraftedTS type improvementsMichel Weststratebefore adoptiondd1808e
lines 253–257why, one step back253 // TODO: use switch + type discovery>254 if (isMap(value)) draft = proxyMap(value, parent)255 else if (isSet(value)) draft = proxySet(value, parent)256 else {257 // createProxy should be guarded by isDraftable, so we know we can safely draftclean up create proxyMichel Weststratebefore adoptionc182c1e
lines 258–260why, one step back258 draft = this.useProxies259 ? createProxy(value, parent)260 : createES5Proxy(value, parent)TS type improvementsMichel Weststratebefore adoptiondd1808e
line 261why, one step back261 }clean up create proxyMichel Weststratebefore adoptionc182c1e
lines 262–265why, one step back262263 const scope = parent ? parent.scope : ImmerScope.current!264 scope.drafts.push(draft)265 return draftStop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 266–271why, one step back266 }267268 willFinalize(scope: ImmerScope, thing: any, isReplaced: boolean) {269 if (!this.useProxies) willFinalizeES5(scope, thing, isReplaced)270 }271TS type improvementsMichel Weststratebefore adoptiondd1808e
line 272why, one step back272 markChanged(state: ImmerState) {Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 273–277why, one step back273 if (this.useProxies) {274 markChanged(state)275 } else {276 markChangedES5(state)277 }Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 278–279why, one step back278 }279}