Skip to content
Myr

immerClass.ts

This file

Path

src/immerClass.ts

275 lines · 7.5 KiB · TypeScript

Last changed by

Killed `die`, -14 bytesMichel Weststratebefore adoptiond77a5c1

History of this file

Take it

More WIPMichel Weststratebefore adoptionee1c977

lines 1–28why, one step back
1import {
2 createES5Proxy,3 willFinalizeES5,4 markChangedES5,5 IProduceWithPatches,6 IProduce,7 ImmerState,8 each,9 Drafted,10 isDraftable,11 ImmerScope,12 processResult,13 NOTHING,14 maybeFreeze,15 Patch,16 Objectish,17 DRAFT_STATE,18 Draft,19 PatchListener,20 isDraft,21 applyPatches,22 isMap,23 proxyMap,24 isSet,25 proxySet,26 markChangedProxy,27 createProxyProxy28} from "./internal"

use invariant -321 bytesMichel Weststratebefore adoptionac57da5

line 29why, one step back
29import invariant from "tiny-invariant"

More WIPMichel Weststratebefore adoptionee1c977

line 30why, one step back
30

New build set. Current statsMichel Weststratebefore adoption9aec0fe

line 31why, one step back
31declare const __DEV__: boolean

More WIPMichel Weststratebefore adoptionee1c977

lines 32–39why, one step back
32/* istanbul ignore next */
33function verifyMinified() {}3435const configDefaults = {36 useProxies:37 typeof Proxy !== "undefined" &&38 typeof Proxy.revocable !== "undefined" &&39 typeof Reflect !== "undefined",

New build set. Current statsMichel Weststratebefore adoption9aec0fe

lines 40–42why, one step back
40 autoFreeze: __DEV__
41 ? false /* istanbul ignore next */42 : verifyMinified.name === "verifyMinified",

More WIPMichel Weststratebefore adoptionee1c977

lines 43–114why, one step back
43 onAssign: null,
44 onDelete: null,45 onCopy: null46} as const4748interface ProducersFns {49 produce: IProduce50 produceWithPatches: IProduceWithPatches51}5253export class Immer implements ProducersFns {54 useProxies: boolean = false55 autoFreeze: boolean = false56 onAssign?: (state: ImmerState, prop: string | number, value: unknown) => void57 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 }) {71 each(configDefaults, (key, value) => {72 // @ts-ignore73 this[key] = config?.[key] ?? value74 })75 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 */99 produce(base: any, recipe?: any, patchListener?: any) {100 // curried invocation101 if (typeof base === "function" && typeof recipe !== "function") {102 const defaultBase = recipe103 recipe = base104105 const self = this106 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-ignore112 }113 }114

use invariant -321 bytesMichel Weststratebefore adoptionac57da5

lines 115–122why, one step back
115 invariant(
116 typeof recipe === "function",117 "The first or second argument to `produce` must be a function"118 )119 invariant(120 patchListener === undefined || typeof patchListener === "function",121 "The third argument to `produce` must be a function or undefined"122 )

More WIPMichel Weststratebefore adoptionee1c977

lines 123–127why, one step back
123
124 let result125126 // Only plain objects, arrays, and "immerable classes" are drafted.127 if (isDraftable(base)) {

Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd

line 128why, one step back
128 const scope = ImmerScope.enter_(this)

More WIPMichel Weststratebefore adoptionee1c977

lines 129–135why, one step back
129 const proxy = createProxy(this, base, undefined)
130 let hasError = true131 try {132 result = recipe(proxy)133 hasError = false134 } finally {135 // finally instead of catch + rethrow better preserves original stack

Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd

lines 136–137why, one step back
136 if (hasError) scope.revoke_()
137 else scope.leave_()

More WIPMichel Weststratebefore adoptionee1c977

lines 138–141why, one step back
138 }
139 if (typeof Promise !== "undefined" && result instanceof Promise) {140 return result.then(141 result => {

Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd

line 142why, one step back
142 scope.usePatches_(patchListener)

More WIPMichel Weststratebefore adoptionee1c977

lines 143–145why, one step back
143 return processResult(this, result, scope)
144 },145 error => {

Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd

line 146why, one step back
146 scope.revoke_()

More WIPMichel Weststratebefore adoptionee1c977

lines 147–150why, one step back
147 throw error
148 }149 )150 }

Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd

line 151why, one step back
151 scope.usePatches_(patchListener)

More WIPMichel Weststratebefore adoptionee1c977

lines 152–168why, one step back
152 return processResult(this, result, scope)
153 } else {154 result = recipe(base)155 if (result === NOTHING) return undefined156 if (result === undefined) result = base157 maybeFreeze(this, result, true)158 return result159 }160 }161162 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {163 if (typeof arg1 === "function") {164 return (state: any, ...args: any[]) =>165 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))166 }167 // non-curried form168 /* istanbul ignore next */

Killed `die`, -14 bytesMichel Weststratebefore adoptiond77a5c1

line 169why, one step back
169 invariant(!arg3)

More WIPMichel Weststratebefore adoptionee1c977

lines 170–178why, one step back
170 let patches: Patch[], inversePatches: Patch[]
171 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {172 patches = p173 inversePatches = ip174 })175 return [nextState, patches!, inversePatches!]176 }177178 createDraft<T extends Objectish>(base: T): Draft<T> {

use invariant -321 bytesMichel Weststratebefore adoptionac57da5

line 179why, one step back
179 invariant(isDraftable(base), "First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore

Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd

line 180why, one step back
180 const scope = ImmerScope.enter_(this)

More WIPMichel Weststratebefore adoptionee1c977

line 181why, one step back
181 const proxy = createProxy(this, base, undefined)

Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd

lines 182–183why, one step back
182 proxy[DRAFT_STATE].isManual_ = true
183 scope.leave_()

More WIPMichel Weststratebefore adoptionee1c977

lines 184–191why, one step back
184 return proxy as any
185 }186187 finishDraft<D extends Draft<any>>(188 draft: D,189 patchListener?: PatchListener190 ): D extends Draft<infer T> ? T : never {191 const state: ImmerState = draft && draft[DRAFT_STATE]

Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd

lines 192–195why, one step back
192 invariant(state && state.isManual_, "First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore
193 invariant(!state.finalized_, "The given draft is already finalized") // prettier-ignore194 const {scope_: scope} = state195 scope.usePatches_(patchListener)

More WIPMichel Weststratebefore adoptionee1c977

lines 196–254why, one step back
196 return processResult(this, undefined, scope)
197 }198199 /**200 * Pass true to automatically freeze all copies created by Immer.201 *202 * By default, auto-freezing is disabled in production.203 */204 setAutoFreeze(value: boolean) {205 this.autoFreeze = value206 }207208 /**209 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is210 * always faster than using ES5 proxies.211 *212 * By default, feature detection is used, so calling this is rarely necessary.213 */214 setUseProxies(value: boolean) {215 this.useProxies = value216 }217218 applyPatches(base: Objectish, patches: Patch[]) {219 // If a patch replaces the entire state, take that replacement as base220 // before applying patches221 let i: number222 for (i = patches.length - 1; i >= 0; i--) {223 const patch = patches[i]224 if (patch.path.length === 0 && patch.op === "replace") {225 base = patch.value226 break227 }228 }229230 if (isDraft(base)) {231 // N.B: never hits if some patch a replacement, patches are never drafts232 return applyPatches(base, patches)233 }234 // Otherwise, produce a copy of the base state.235 return this.produce(base, (draft: Drafted) =>236 applyPatches(draft, patches.slice(i + 1))237 )238 }239}240241export function createProxy<T extends Objectish>(242 immer: Immer,243 value: T,244 parent?: ImmerState245): Drafted<T, ImmerState> {246 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft247 const draft: Drafted = isMap(value)248 ? proxyMap(value, parent)249 : isSet(value)250 ? proxySet(value, parent)251 : immer.useProxies252 ? createProxyProxy(value, parent)253 : createES5Proxy(value, parent)254

Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd

lines 255–256why, one step back
255 const scope = parent ? parent.scope_ : ImmerScope.current_!
256 scope.drafts_.push(draft)

More WIPMichel Weststratebefore adoptionee1c977

lines 257–275why, one step back
257 return draft
258}259260export function willFinalize(261 immer: Immer,262 scope: ImmerScope,263 thing: any,264 isReplaced: boolean265) {266 if (!immer.useProxies) willFinalizeES5(scope, thing, isReplaced)267}268269export function markChanged(immer: Immer, state: ImmerState) {270 if (immer.useProxies) {271 markChangedProxy(state)272 } else {273 markChangedES5(state)274 }275}