immer.ts
This file
Path
src/immer.ts
446 lines · 12.4 KiB · TypeScript
Last changed by
Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
History of this fileTake it
1import {createES5Proxy, willFinalizeES5, markChangedES5} from "./es5"2import {createProxy, markChanged} from "./proxy"34import {applyPatches, generatePatches} from "./patches"5import {6 assign,7 each,8 has,9 is,10 isDraft,11 isSet,12 get,13 isMap,14 isDraftable,15 isEnumerable,16 shallowCopy,17 DRAFT_STATE,18 NOTHING,19 freeze,20 latest21} from "./common"22import {ImmerScope} from "./scope"23import {24 ImmerState,25 IProduce,26 IProduceWithPatches,27 Objectish,28 PatchListener,29 Draft,30 Patch31} from "./types"3233function verifyMinified() {}3435const configDefaults = {36 useProxies:37 typeof Proxy !== "undefined" &&38 typeof Proxy.revocable !== "undefined" &&39 typeof Reflect !== "undefined",40 autoFreeze:41 typeof process !== "undefined"42 ? process.env.NODE_ENV !== "production"43 : verifyMinified.name === "verifyMinified",44 onAssign: null,45 onDelete: null,46 onCopy: null47}4849interface ProducersFns {50 produce: IProduce51 produceWithPatches: IProduceWithPatches52}5354export class Immer implements ProducersFns {55 useProxies: boolean = false56 autoFreeze: boolean = false57 onAssign?: (state: ImmerState, prop: string | number, value: unknown) => void58 onDelete?: (state: ImmerState, prop: string | number) => void59 onCopy?: (state: ImmerState) => void6061 constructor(config?: {62 useProxies?: boolean63 autoFreeze?: boolean64 onAssign?: (65 state: ImmerState,66 prop: string | number,67 value: unknown68 ) => void69 onDelete?: (state: ImmerState, prop: string | number) => void70 onCopy?: (state: ImmerState) => void71 }) {72 assign(this, configDefaults, config)73 this.setUseProxies(this.useProxies)74 this.produce = this.produce.bind(this)75 this.produceWithPatches = this.produceWithPatches.bind(this)76 }7778 /**79 * The `produce` function takes a value and a "recipe function" (whose80 * return value often depends on the base state). The recipe function is81 * free to mutate its first argument however it wants. All mutations are82 * only ever applied to a __copy__ of the base state.83 *84 * Pass only a function to create a "curried producer" which relieves you85 * from passing the recipe function every time.86 *87 * Only plain objects and arrays are made mutable. All other objects are88 * considered uncopyable.89 *90 * Note: This function is __bound__ to its `Immer` instance.91 *92 * @param {any} base - the initial state93 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified94 * @param {Function} patchListener - optional function that will be called with all the patches produced here95 * @returns {any} a new state, or the initial state if nothing was modified96 */97 produce(base, recipe?, patchListener?) {98 // curried invocation99 if (typeof base === "function" && typeof recipe !== "function") {100 const defaultBase = recipe101 recipe = base102103 const self = this104 return function curriedProduce(this: any, base = defaultBase, ...args) {105 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore106 }107 }108109 // prettier-ignore110 {111 if (typeof recipe !== "function") {112 throw new Error("The first or second argument to `produce` must be a function")113 }114 if (patchListener !== undefined && typeof patchListener !== "function") {115 throw new Error("The third argument to `produce` must be a function or undefined")116 }117 }118119 let result120121 // Only plain objects, arrays, and "immerable classes" are drafted.122 if (isDraftable(base)) {123 const scope = ImmerScope.enter(this)124 const proxy = this.createProxy(base, undefined)125 let hasError = true126 try {127 result = recipe(proxy)128 hasError = false129 } finally {130 // finally instead of catch + rethrow better preserves original stack131 if (hasError) scope.revoke()132 else scope.leave()133 }134 if (typeof Promise !== "undefined" && result instanceof Promise) {135 return result.then(136 result => {137 scope.usePatches(patchListener)138 return this.processResult(result, scope)139 },140 error => {141 scope.revoke()142 throw error143 }144 )145 }146 scope.usePatches(patchListener)147 return this.processResult(result, scope)148 } else {149 result = recipe(base)150 if (result === NOTHING) return undefined151 if (result === undefined) result = base152 this.maybeFreeze(result, true)153 return result154 }155 }156157 produceWithPatches(arg1, arg2?, arg3?): any {158 if (typeof arg1 === "function") {159 const self = this160 return (state, ...args) =>161 this.produceWithPatches(state, draft => arg1(draft, ...args))162 }163 // non-curried form164 if (arg3)165 throw new Error("A patch listener cannot be passed to produceWithPatches")166 let patches, inversePatches167 const nextState = this.produce(arg1, arg2, (p, ip) => {168 patches = p169 inversePatches = ip170 })171 return [nextState, patches, inversePatches]172 }173174 createDraft<T extends Objectish>(base: T): Draft<T> {175 if (!isDraftable(base)) {176 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore177 }178 const scope = ImmerScope.enter(this)179 const proxy = this.createProxy(base, undefined)180 proxy[DRAFT_STATE].isManual = true181 scope.leave()182 return proxy as any183 }184185 finishDraft<D extends Draft<any>>(186 draft: D,187 patchListener: PatchListener188 ): D extends Draft<infer T> ? T : never {189 const state = draft && draft[DRAFT_STATE]190 if (!state || !state.isManual) {191 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore192 }193 if (state.finalized) {194 throw new Error("The given draft is already finalized") // prettier-ignore195 }196 const {scope} = state197 scope.usePatches(patchListener)198 return this.processResult(undefined, scope)199 }200201 /**202 * Pass true to automatically freeze all copies created by Immer.203 *204 * By default, auto-freezing is disabled in production.205 */206 setAutoFreeze(value: boolean) {207 this.autoFreeze = value208 }209210 /**211 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is212 * always faster than using ES5 proxies.213 *214 * By default, feature detection is used, so calling this is rarely necessary.215 */216 setUseProxies(value: boolean) {217 this.useProxies = value218 }219220 applyPatches(base: Objectish, patches: Patch[]) {221 // If a patch replaces the entire state, take that replacement as base222 // before applying patches223 let i224 for (i = patches.length - 1; i >= 0; i--) {225 const patch = patches[i]226 if (patch.path.length === 0 && patch.op === "replace") {227 base = patch.value228 break229 }230 }231232 if (isDraft(base)) {233 // N.B: never hits if some patch a replacement, patches are never drafts234 return applyPatches(base, patches)235 }236 // Otherwise, produce a copy of the base state.237 return this.produce(base, draft =>238 applyPatches(draft, patches.slice(i + 1))239 )240 }241242 /** @internal */243 processResult(result: any, scope: ImmerScope) {244 const baseDraft = scope.drafts![0]245 const isReplaced = result !== undefined && result !== baseDraft246 this.willFinalize(scope, result, isReplaced)247 if (isReplaced) {248 if (baseDraft[DRAFT_STATE].modified) {249 scope.revoke()250 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore251 }252 if (isDraftable(result)) {253 // Finalize the result in case it contains (or is) a subset of the draft.254 result = this.finalize(result, null, scope)255 this.maybeFreeze(result)256 }257 if (scope.patches) {258 scope.patches.push({259 op: "replace",260 path: [],261 value: result262 })263 scope.inversePatches!.push({264 op: "replace",265 path: [],266 value: baseDraft[DRAFT_STATE].base267 })268 }269 } else {270 // Finalize the base draft.271 result = this.finalize(baseDraft, [], scope)272 }273 scope.revoke()274 if (scope.patches) {275 scope.patchListener!(scope.patches, scope.inversePatches!)276 }277 return result !== NOTHING ? result : undefined278 }279280 createProxy<T>(value: any, parent: any) {281 if (this.useProxies) return createProxy(value, parent)282 else return createES5Proxy(value, parent)283 }284285 willFinalize(scope: ImmerScope, thing: any, isReplaced: boolean) {286 if (!this.useProxies) willFinalizeES5(scope, thing, isReplaced)287 }288289 markChanged(state: any) {290 if (this.useProxies) {291 markChanged(state)292 } else {293 markChangedES5(state)294 }295 }296297 /**298 * @internal299 * Finalize a draft, returning either the unmodified base state or a modified300 * copy of the base state.301 */302 finalize(draft: any, path: string[] | null, scope: ImmerScope) {303 const state = draft[DRAFT_STATE]304 if (!state) {305 if (Object.isFrozen(draft)) return draft306 return this.finalizeTree(draft, null, scope)307 }308 // Never finalize drafts owned by another scope.309 if (state.scope !== scope) {310 return draft311 }312 if (!state.modified) {313 this.maybeFreeze(state.base, true)314 return state.base315 }316 if (!state.finalized) {317 state.finalized = true318 this.finalizeTree(state.draft, path, scope)319320 // We cannot really delete anything inside of a Set. We can only replace the whole Set.321 if (this.onDelete && !isSet(state.base)) {322 // The `assigned` object is unreliable with ES5 drafts.323 if (this.useProxies) {324 const {assigned} = state325 each(assigned, (prop, exists) => {326 if (!exists) this.onDelete?.(state, prop as any)327 })328 } else {329 // TODO: Figure it out for Maps and Sets if we need to support ES5330 const {base, copy} = state331 each(base, prop => {332 if (!has(copy, prop)) this.onDelete?.(state, prop as any)333 })334 }335 }336 if (this.onCopy) {337 this.onCopy(state)338 }339340 // At this point, all descendants of `state.copy` have been finalized,341 // so we can be sure that `scope.canAutoFreeze` is accurate.342 if (this.autoFreeze && scope.canAutoFreeze) {343 freeze(state.copy, false)344 }345346 if (path && scope.patches) {347 generatePatches(state, path, scope.patches, scope.inversePatches!)348 }349 }350 return state.copy351 }352353 /**354 * @internal355 * Finalize all drafts in the given state tree.356 */357 finalizeTree(root: any, rootPath: string[] | null, scope: ImmerScope) {358 const state = root[DRAFT_STATE]359 if (state) {360 // TODO: remove crap361 // if (state.modified && !state.copy) {362 // state.copy = shallowCopy(state.base, false)363 // }364 // else365 if (!this.useProxies && !isMap(root) && !isSet(root)) {366 // Create the final copy, with added keys and without deleted keys.367 state.copy = shallowCopy(state.draft, true) // TODO: optimization, can we get rid of this and just use state.copy?368 }369370 root = state.copy371 }372373 const needPatches = !!rootPath && !!scope.patches374 const finalizeProperty = (prop, value, parent) => {375 if (value === parent) {376 throw Error("Immer forbids circular references")377 }378379 // In the `finalizeTree` method, only the `root` object may be a draft.380 const isDraftProp = !!state && parent === root381 const isSetMember = isSet(parent)382383 if (isDraft(value)) {384 const path =385 isDraftProp &&386 needPatches &&387 !isSetMember && // Set objects are atomic since they have no keys.388 !has(state.assigned, prop) // Skip deep patches for assigned keys.389 ? rootPath!.concat(prop)390 : null391392 // Drafts owned by `scope` are finalized here.393 value = this.finalize(value, path, scope)394 replace(parent, prop, value)395396 // Drafts from another scope must prevent auto-freezing.397 if (isDraft(value)) {398 scope.canAutoFreeze = false399 }400401 // Unchanged drafts are never passed to the `onAssign` hook.402 if (isDraftProp && !isSet && value === get(state.base, prop)) return403 }404 // Unchanged draft properties are ignored.405 else if (isDraftProp && is(value, get(state.base, prop))) {406 return407 }408 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.409 else if (isDraftable(value) && !Object.isFrozen(value)) {410 each(value, finalizeProperty)411 this.maybeFreeze(value)412 }413414 if (isDraftProp && this.onAssign && !isSetMember) {415 this.onAssign(state, prop, value)416 }417 }418419 each(root, finalizeProperty)420 return root421 }422 maybeFreeze(value, deep = false) {423 if (this.autoFreeze && !isDraft(value)) {424 freeze(value, deep)425 }426 }427}428429function replace(parent, prop, value) {430 if (isMap(parent)) {431 parent.set(prop, value)432 } else if (isSet(parent)) {433 // In this case, the `prop` is actually a draft.434 parent.delete(prop)435 parent.add(value)436 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {437 // Preserve non-enumerable properties.438 parent[prop] = value439 } else {440 Object.defineProperty(parent, prop, {441 value,442 writable: true,443 configurable: true444 })445 }446}