Skip to content
Myr

feat: add `Immer` class

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

Every instance of the `Immer` class provides a bound `produce` function. As explained in #254, this class makes room for advanced configuration (if we need it) and allows for interop between Immer-using libraries that have different needs. I took the time to refactor while I was implementing this, so the diff may look more overwhelming than it is. :) Summary: 1. Renamed `immer.js` to `index.js` so the `Immer` class can have `immer.js` 2. Use the word "draft" in place of "proxy" in most places, because "draft" is a higher level of abstraction. It also makes sense to use the same semantics both internally and externally. 3. Moved `finalize` logic to the `Immer` class 4. Inlined the `freeze` function as only one callsite existed 5. Inlined the `createState` functions in both `proxy.js` and `es5.js` 6. Extract repeated code from `produceEs5` and `produceProxy` (which have since been removed) into the `Immer` class 7. The `es5.js` and `proxy.js` modules now have different exports: - `scopes`: an array of nested `produce` calls, where each value is an array of unrevoked proxies - `currentScope()`: shortcut for getting the last value of the `scopes` array - `createDraft()`: a renamed `createProxy` with the arguments swapped - `willFinalize()`: called right after the recipe function returns (only used by ES5 proxies) 8. Changed some "draft state" properties: - removed `hasCopy` in ES5 state (checking for truthiness of `copy` does the job) - renamed `proxy` to `draft` in ES5 state - renamed `finished` to `revoked` in ES5 state - renamed `proxies` to `drafts` in Proxy state - added `revoke` method (called by the `Immer` class) - added `draft` property to Proxy state - use null literals instead of undefined 9. Delay creation of `patches` and `inversePatches` arrays until the recipe function returns. This avoids array allocations when a rollback is performed by throwing. 10. Simplified `generatePatches` by removing the last two arguments, since they can be obtained from the `state` argument.

authored by aleclarson · committed by aleclarson · parent 66e51e1 · Browse files · 13 files+607 added−661 removed
This commit

State

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

Diff stats

13 files+607 added−661 removed

  • tests:+6 added−6 removed
  • other:+601 added−655 removed

13 files+607 added−661 removed

modified:__tests__/curry.js+5 added-5 removed
modified:__tests__/patch.js+1 added-1 removed
67 unmodified lines
68 // Splice is unsupported69 expect(() => {70 const patch = {op: "remove", path: [0]}71 applyPatches([1, 2], [patch])72 }).toThrowError(/^Remove can only remove the last key of an array/)72 }).toThrowError(/^Only the last index of an array can be removed/)73 })74})7576describe("simple assignment - 1", () => {
260 unmodified lines
modified:src/common.js+9 added-113 removed
modified:src/es5.js+76 added-106 removed
1"use strict"2// @ts-check34import {5 each,6 has,7 is,6 isProxyable,7 PROXY_STATE,8 isDraft,9 isDraftable,10 shallowCopy,9 RETURNED_AND_MODIFIED_ERROR,10 has,11 each,12 finalize11 DRAFT_STATE12} from "./common"1314const descriptors = {}16let states = null1518function createState(parent, proxy, base) {19 return {16// For nested produce calls:17export const scopes = []18export const currentScope = () => scopes[scopes.length - 1]1920export function willFinalize(result, baseDraft, needPatches) {21 const scope = currentScope()22 scope.forEach(state => (state.finalizing = true))23 if (result === undefined || result === baseDraft) {24 if (needPatches) markChangesRecursively(baseDraft)25 // This is faster when we don't care about which attributes changed.26 markChangesSweep(scope)27 }28}2930export function createDraft(base, parent) {31 if (isDraft(base)) throw new Error("This should never happen. Please report: https://github.com/mweststrate/immer/issues/new") // prettier-ignore3233 const draft = shallowCopy(base)34 each(base, prop => {35 Object.defineProperty(draft, "" + prop, createPropertyProxy("" + prop))36 })3738 const state = {39 modified: false,40 finalizing: false,41 finalized: false,42 assigned: {}, // true: value was assigned to these props, false: was removed22 hasCopy: false,43 parent,44 base,25 proxy,26 copy: undefined,27 finished: false,28 finalizing: false,29 finalized: false45 draft,46 copy: null,47 revoke,48 revoked: false49 }5051 createHiddenProperty(draft, DRAFT_STATE, state)52 currentScope().push(state)53 return draft54}5556function revoke() {57 this.revoked = true58}5960function source(state) {34 return state.hasCopy ? state.copy : state.base61 return state.copy || state.base62}6364function get(state, prop) {38 assertUnfinished(state)65 assertUnrevoked(state)66 const value = source(state)[prop]40 if (!state.finalizing && value === state.base[prop] && isProxyable(value)) {41 // only create a proxy if the value is proxyable, and the value was in the base state42 // if it wasn't in the base state, the object is already modified and we will process it in finalize67 // Drafts are only created for proxyable values that exist in the base state.68 if (!state.finalizing && value === state.base[prop] && isDraftable(value)) {69 prepareCopy(state)44 return (state.copy[prop] = createProxy(state, value))70 return (state.copy[prop] = createDraft(value, state))71 }72 return value73}7475function set(state, prop, value) {50 assertUnfinished(state)76 assertUnrevoked(state)77 state.assigned[prop] = true // optimization; skip this if there is no listener78 if (!state.modified) {79 if (is(source(state)[prop], value)) return80 markChanged(state)
9 unmodified lines
90 }91}9293function prepareCopy(state) {68 if (state.hasCopy) return69 state.hasCopy = true70 state.copy = shallowCopy(state.base)94 if (!state.copy) state.copy = shallowCopy(state.base)95}9673// creates a proxy for plain objects / arrays74function createProxy(parent, base) {75 const proxy = shallowCopy(base)76 each(base, i => {77 Object.defineProperty(proxy, "" + i, createPropertyProxy("" + i))78 })79 const state = createState(parent, proxy, base)80 createHiddenProperty(proxy, PROXY_STATE, state)81 states.push(state)82 return proxy83}8497function createPropertyProxy(prop) {98 return (99 descriptors[prop] ||100 (descriptors[prop] = {101 configurable: true,102 enumerable: true,103 get() {92 return get(this[PROXY_STATE], prop)104 return get(this[DRAFT_STATE], prop)105 },106 set(value) {95 set(this[PROXY_STATE], prop, value)107 set(this[DRAFT_STATE], prop, value)108 }109 })110 )111}112101function assertUnfinished(state) {102 if (state.finished === true)113function assertUnrevoked(state) {114 if (state.revoked === true)115 throw new Error(116 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +117 JSON.stringify(state.copy || state.base)118 )119}120109// this sounds very expensive, but actually it is not that expensive in practice110// as it will only visit proxies, and only do key-based change detection for objects for111// which it is not already know that they are changed (that is, only object for which no known key was changed)112function markChangesSweep() {113 // intentionally we process the proxies in reverse order;114 // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore115 // reverse order of proxy creation approximates this116 for (let i = states.length - 1; i >= 0; i--) {117 const state = states[i]121// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.122function markChangesSweep(scope) {123 // The natural order of drafts in the `scope` array is based on when they124 // were accessed. By processing drafts in reverse natural order, we have a125 // better chance of processing leaf nodes first. When a leaf node is known to126 // have changed, we can avoid any traversal of its ancestor nodes.127 for (let i = scope.length - 1; i >= 0; i--) {128 const state = scope[i]129 if (state.modified === false) {130 if (Array.isArray(state.base)) {131 if (hasArrayChanges(state)) markChanged(state)132 } else if (hasObjectChanges(state)) markChanged(state)
2 unmodified lines
135}136137function markChangesRecursively(object) {138 if (!object || typeof object !== "object") return128 const state = object[PROXY_STATE]139 const state = object[DRAFT_STATE]140 if (!state) return130 const {proxy, base, assigned} = state141 const {base, draft, assigned} = state142 if (!Array.isArray(object)) {143 // Look for added keys.133 Object.keys(proxy).forEach(key => {144 Object.keys(draft).forEach(key => {145 // The `undefined` check is a fast path for pre-existing keys.146 if (base[key] === undefined && !has(base, key)) {147 assigned[key] = true148 markChanged(state)149 } else if (!assigned[key]) {150 // Only untouched properties trigger recursion.140 markChangesRecursively(proxy[key])151 markChangesRecursively(draft[key])152 }153 })154 // Look for removed keys.155 Object.keys(base).forEach(key => {156 // The `undefined` check is a fast path for pre-existing keys.146 if (proxy[key] === undefined && !has(proxy, key)) {157 if (draft[key] === undefined && !has(draft, key)) {158 assigned[key] = false159 markChanged(state)160 }161 })162 } else if (hasArrayChanges(state)) {163 markChanged(state)164 assigned.length = true154 if (proxy.length < base.length) {155 for (let i = proxy.length; i < base.length; i++) assigned[i] = false165 if (draft.length < base.length) {166 for (let i = draft.length; i < base.length; i++) assigned[i] = false167 } else {157 for (let i = base.length; i < proxy.length; i++) assigned[i] = true168 for (let i = base.length; i < draft.length; i++) assigned[i] = true169 }159 for (let i = 0; i < proxy.length; i++) {170 for (let i = 0; i < draft.length; i++) {171 // Only untouched indices trigger recursion.161 if (assigned[i] === undefined) markChangesRecursively(proxy[i])172 if (assigned[i] === undefined) markChangesRecursively(draft[i])173 }174 }175}176177function hasObjectChanges(state) {167 const {base, proxy} = state178 const {base, draft} = state179180 // Search for added keys. Start at the back, because non-numeric keys181 // are ordered by time of definition on the object.171 const keys = Object.keys(proxy)182 const keys = Object.keys(draft)183 for (let i = keys.length - 1; i >= 0; i--) {184 // The `undefined` check is a fast path for pre-existing keys.185 if (base[keys[i]] === undefined && !has(base, keys[i])) {186 return true
5 unmodified lines
192 return keys.length !== Object.keys(base).length193}194195function hasArrayChanges(state) {185 const {proxy} = state186 if (proxy.length !== state.base.length) return true196 const {draft} = state197 if (draft.length !== state.base.length) return true198 // See #116199 // If we first shorten the length, our array interceptors will be removed.200 // If after that new items are added, result in the same original length,201 // those last items will have no intercepting property.202 // So if there is no own descriptor on the last position, we know that items were removed and added203 // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check204 // the last one194 const descriptor = Object.getOwnPropertyDescriptor(proxy, proxy.length - 1)205 const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)206 // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)207 if (descriptor && !descriptor.get) return true208 // For all other cases, we don't have to compare, as they would have been picked up by the index setters209 return false210}211201export function produceEs5(baseState, producer, patchListener) {202 const prevStates = states203 states = []204 const patches = patchListener && []205 const inversePatches = patchListener && []206 try {207 // create proxy for root208 const rootProxy = createProxy(undefined, baseState)209 // execute the thunk210 const returnValue = producer.call(rootProxy, rootProxy)211 // and finalize the modified proxy212 each(states, (_, state) => {213 state.finalizing = true214 })215 let result216 // check whether the draft was modified and/or a value was returned217 if (returnValue !== undefined && returnValue !== rootProxy) {218 // something was returned, and it wasn't the proxy itself219 if (rootProxy[PROXY_STATE].modified)220 throw new Error(RETURNED_AND_MODIFIED_ERROR)221 result = finalize(returnValue)222 if (patches) {223 patches.push({op: "replace", path: [], value: result})224 inversePatches.push({op: "replace", path: [], value: baseState})225 }226 } else {227 if (patchListener) markChangesRecursively(rootProxy)228 markChangesSweep() // this one is more efficient if we don't need to know which attributes have changed229 result = finalize(rootProxy, [], patches, inversePatches)230 }231 // make sure all proxies become unusable232 each(states, (_, state) => {233 state.finished = true234 })235 patchListener && patchListener(patches, inversePatches)236 return result237 } finally {238 states = prevStates239 }240}241212function createHiddenProperty(target, prop, value) {213 Object.defineProperty(target, prop, {214 value: value,215 enumerable: false,
3 unmodified lines
deleted:src/immer.d.ts-115 removed
1/** Object types that should never be mapped */2type AtomicObject =3 | Function4 | Map<any, any>5 | WeakMap<any, any>6 | Set<any>7 | WeakSet<any>8 | Promise<any>9 | Date10 | RegExp11 | Boolean12 | Number13 | String1415/** Use type inference to know when an array is finite */16type IsFinite<T extends any[]> = T extends never[]17 ? true18 : T extends ReadonlyArray<infer U>19 ? (U[] extends T ? false : true)20 : true2122export type DraftObject<T> = T extends object23 ? T extends AtomicObject24 ? T25 : {-readonly [P in keyof T]: Draft<T[P]>}26 : T2728export type DraftArray<T> = Array<29 T extends ReadonlyArray<any>30 ? {[P in keyof T]: Draft<T>}[keyof T]31 : DraftObject<T>32>3334export type DraftTuple<T extends any[]> = {35 [P in keyof T]: T[P] extends T[number] ? Draft<T[P]> : never36}3738export type Draft<T> = T extends any[]39 ? IsFinite<T> extends true40 ? DraftTuple<T>41 : DraftArray<T[number]>42 : T extends ReadonlyArray<any>43 ? DraftArray<T[number]>44 : T extends object45 ? DraftObject<T>46 : T4748export interface Patch {49 op: "replace" | "remove" | "add"50 path: (string | number)[]51 value?: any52}5354export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void5556export interface IProduce {57 /**58 * Immer takes a state, and runs a function against it.59 * That function can freely mutate the state, as it will create copies-on-write.60 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.61 *62 * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe63 * any time it is called with the current state.64 *65 * @param currentState - the state to start with66 * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified67 * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined68 * @returns The next state: a new state, or the current state if nothing was modified69 */70 <S = any, R = never>(71 currentState: S,72 recipe: (this: Draft<S>, draftState: Draft<S>) => void | R,73 listener?: PatchListener74 ): R7576 /** Curried producer with an initial state */77 <S = any, R = never>(78 recipe: (this: Draft<S>, draftState: Draft<S>) => void | R,79 initialState: S80 ): (currentState: S | undefined) => R8182 /** Curried producer with no initial state */83 <S = any, R = never, Args extends any[] = any[]>(84 recipe: (85 this: Draft<S>,86 draftState: Draft<S>,87 ...extraArgs: Args88 ) => void | R89 ): (currentState: S, ...extraArgs: Args) => R90}9192export const produce: IProduce93export default produce9495export const nothing: undefined9697/**98 * Automatically freezes any state trees generated by immer.99 * This protects against accidental modifications of the state tree outside of an immer function.100 * This comes with a performance impact, so it is recommended to disable this option in production.101 * It is by default enabled.102 */103export function setAutoFreeze(autoFreeze: boolean): void104105/**106 * Manually override whether proxies should be used.107 * By default done by using feature detection108 */109export function setUseProxies(useProxies: boolean): void110111export function applyPatches<S>(state: S, patches: Patch[]): S112113export function original<T>(value: T): T | void114115export function isDraft(value: any): boolean
modified:src/immer.js+156 added-65 removed
1export {2 setAutoFreeze,3 setUseProxies,4 original,5 isProxy as isDraft1import * as legacyProxy from "./es5"2import * as modernProxy from "./proxy"3import {generatePatches} from "./patches"4import {5 assign,6 each,7 has,8 is,9 isDraft,10 isDraftable,11 shallowCopy,12 DRAFT_STATE,13 NOTHING14} from "./common"158import {applyPatches as applyPatchesImpl} from "./patches"9import {isProxy, isProxyable, getUseProxies, NOTHING} from "./common"10import {produceProxy} from "./proxy"11import {produceEs5} from "./es5"16function verifyMinified() {}1713/**14 * produce takes a state, and runs a function against it.15 * That function can freely mutate the state, as it will create copies-on-write.16 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned17 *18 * @export19 * @param {any} baseState - the state to start with20 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified21 * @param {Function} patchListener - optional function that will be called with all the patches produced here22 * @returns {any} a new state, or the base state if nothing was modified23 */24export function produce(baseState, producer, patchListener) {25 // prettier-ignore26 if (arguments.length < 1 || arguments.length > 3) throw new Error("produce expects 1 to 3 arguments, got " + arguments.length)18const configDefaults = {19 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",20 autoFreeze:21 typeof process !== "undefined"22 ? process.env.NODE_ENV !== "production"23 : verifyMinified.name === "verifyMinified"24}2528 // curried invocation29 if (typeof baseState === "function" && typeof producer !== "function") {30 const initialState = producer31 const recipe = baseState26export class Immer {27 constructor(config) {28 assign(this, configDefaults, config)29 this.setUseProxies(this.useProxies)30 this.produce = this.produce.bind(this)31 }32 produce(base, recipe, patchListener) {33 // curried invocation34 if (typeof base === "function" && typeof recipe !== "function") {35 const defaultBase = recipe36 recipe = base3733 return function(currentState = initialState, ...args) {34 return produce(currentState, draft =>35 recipe.call(draft, draft, ...args)36 )38 // prettier-ignore39 return (base = defaultBase, ...args) =>40 this.produce(base, draft => recipe.call(draft, draft, ...args))41 }38 }4240 // prettier-ignore41 {42 if (typeof producer !== "function") throw new Error("if first argument is not a function, the second argument to produce should be a function")43 if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function")44 }43 // prettier-ignore44 {45 if (typeof recipe !== "function") throw new Error("if first argument is not a function, the second argument to produce should be a function")46 if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function")47 }4846 // avoid proxying anything except plain objects and arrays47 if (!isProxyable(baseState)) {48 const returnValue = producer(baseState)49 return returnValue === undefined50 ? baseState51 : normalizeResult(returnValue)52 }49 let result50 // Only create proxies for plain objects/arrays.51 if (!isDraftable(base)) {52 result = recipe(base)53 if (result === undefined) return base54 }55 // See #100, don't nest producers56 else if (isDraft(base)) {57 result = recipe.call(base, base)58 if (result === undefined) return base59 }60 // The given value must be proxied.61 else {62 this.scopes.push([])63 const baseDraft = this.createDraft(base)64 try {65 result = recipe.call(baseDraft, baseDraft)66 this.willFinalize(result, baseDraft, !!patchListener)6754 // See #100, don't nest producers55 if (isProxy(baseState)) {56 const returnValue = producer.call(baseState, baseState)57 return returnValue === undefined58 ? baseState59 : normalizeResult(returnValue)60 }68 // Never generate patches when no listener exists.69 var patches = patchListener && [],70 inversePatches = patchListener && []7162 return normalizeResult(63 getUseProxies()64 ? produceProxy(baseState, producer, patchListener)65 : produceEs5(baseState, producer, patchListener)66 )67}72 // Finalize the modified draft...73 if (result === undefined || result === baseDraft) {74 result = this.finalize(75 baseDraft,76 [],77 patches,78 inversePatches79 )80 }81 // ...or use a replacement value.82 else {83 // Users must never modify the draft _and_ return something else.84 if (baseDraft[DRAFT_STATE].modified)85 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore8669function normalizeResult(result) {70 return result === NOTHING ? undefined : result71}87 // Finalize the replacement in case it contains (or is) a subset of the draft.88 if (isDraftable(result)) result = this.finalize(result)8973export default produce7475export const applyPatches = produce(applyPatchesImpl)7677export const nothing = NOTHING90 if (patchListener) {91 patches.push({92 op: "replace",93 path: [],94 value: result95 })96 inversePatches.push({97 op: "replace",98 path: [],99 value: base100 })101 }102 }103 } finally {104 this.currentScope().forEach(state => state.revoke())105 this.scopes.pop()106 }107 patchListener && patchListener(patches, inversePatches)108 }109 // Normalize the result.110 return result === NOTHING ? undefined : result111 }112 setAutoFreeze(value) {113 this.autoFreeze = value114 }115 setUseProxies(value) {116 this.useProxies = value117 assign(this, value ? modernProxy : legacyProxy)118 }119 /**120 * @internal121 * Finalize a draft, returning either the unmodified base state or a modified122 * copy of the base state.123 */124 finalize(draft, path, patches, inversePatches) {125 const state = draft[DRAFT_STATE]126 if (!state) {127 if (Object.isFrozen(draft)) return draft128 return this.finalizeTree(draft)129 }130 if (!state.modified) return state.base131 if (!state.finalized) {132 state.finalized = true133 this.finalizeTree(state.draft, path, patches, inversePatches)134 if (this.autoFreeze) Object.freeze(state.copy)135 if (patches) generatePatches(state, path, patches, inversePatches)136 }137 return state.copy138 }139 /**140 * @internal141 * Finalize all drafts in the given state tree.142 */143 finalizeTree(root, path, patches, inversePatches) {144 const state = root[DRAFT_STATE]145 if (state) {146 root = this.useProxies147 ? state.copy148 : (state.copy = shallowCopy(state.draft))149 }150 const finalizeProperty = (prop, value, parent) => {151 // Skip unchanged properties in draft objects.152 if (state && parent === root && is(value, state.base[prop])) return153 if (!isDraftable(value)) return154 if (!isDraft(value)) {155 // Frozen values are already finalized.156 return Object.isFrozen(value) || each(value, finalizeProperty)157 }158 // prettier-ignore159 parent[prop] =160 // Patches are never generated for assigned properties.161 patches && parent === root && !(state && has(state.assigned, prop))162 ? this.finalize(value, path.concat(prop), patches, inversePatches)163 : this.finalize(value)164 }165 each(root, finalizeProperty)166 return root167 }168}
deleted:src/immer.js.flow-92 removed
1// @flow23export interface Patch {4 op: "replace" | "remove" | "add",5 path: (string|number)[],6 value?: any7}89export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void1011interface IProduce {12 /**13 * Immer takes a state, and runs a function against it.14 * That function can freely mutate the state, as it will create copies-on-write.15 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.16 *17 * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe18 * any time it is called with the current state.19 *20 * @param currentState - the state to start with21 * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified22 * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined23 * @returns The next state: a new state, or the current state if nothing was modified24 */25 <S>(26 currentState: S,27 recipe: (draftState: S) => S | void,28 patchListener?: PatchListener29 ): S;30 // curried invocations with inital state31 <S, A, B, C>(32 recipe: (draftState: S, a: A, b: B, c: C) => S | void,33 initialState: S34 ): (currentState: S | void, a: A, b: B, c: C) => S;35 <S, A, B>(36 recipe: (draftState: S, a: A, b: B) => S | void,37 initialState: S38 ): (currentState: S | void, a: A, b: B) => S;39 <S, A>(40 recipe: (draftState: S, a: A) => S | void,41 initialState: S42 ): (currentState: S | void, a: A) => S;43 <S>(44 recipe: (draftState: S) => S | void,45 initialState: S46 ): (currentState: S | void) => S;47 <S>(48 recipe: (draftState: S, ...extraArgs: any[]) => S | void,49 initialState: S50 ): (currentState: S | void, ...extraArgs: any[]) => S;51 // curried invocations without inital state52 <S, A, B, C>(53 recipe: (draftState: S, a: A, b: B, c: C) => S | void54 ): (currentState: S, a: A, b: B, c: C) => S;55 <S, A, B>(56 recipe: (draftState: S, a: A, b: B) => S | void57 ): (currentState: S, a: A, b: B) => S;58 <S, A>(59 recipe: (draftState: S, a: A) => S | void60 ): (currentState: S, a: A) => S;61 <S>(62 recipe: (draftState: S) => S | void63 ): (currentState: S) => S;64 <S>(65 recipe: (draftState: S, ...extraArgs: any[]) => S | void66 ): (currentState: S, ...extraArgs: any[]) => S;67}6869declare export var produce: IProduce70declare export default IProduce7172declare export var nothing: typeof undefined7374/**75 * Automatically freezes any state trees generated by immer.76 * This protects against accidental modifications of the state tree outside of an immer function.77 * This comes with a performance impact, so it is recommended to disable this option in production.78 * By default it is turned on during local development, and turned off in production.79 */80declare export function setAutoFreeze(autoFreeze: boolean): void8182/**83 * Manually override whether proxies should be used.84 * By default done by using feature detection85 */86declare export function setUseProxies(useProxies: boolean): void8788declare export function applyPatches<S>(state: S, patches: Patch[]): S8990declare export function original<S>(value: S): ?S9192declare export function isDraft(value: any): boolean
added:src/index.d.ts+115 added
1/** Object types that should never be mapped */2type AtomicObject =3 | Function4 | Map<any, any>5 | WeakMap<any, any>6 | Set<any>7 | WeakSet<any>8 | Promise<any>9 | Date10 | RegExp11 | Boolean12 | Number13 | String1415/** Use type inference to know when an array is finite */16type IsFinite<T extends any[]> = T extends never[]17 ? true18 : T extends ReadonlyArray<infer U>19 ? (U[] extends T ? false : true)20 : true2122export type DraftObject<T> = T extends object23 ? T extends AtomicObject24 ? T25 : {-readonly [P in keyof T]: Draft<T[P]>}26 : T2728export type DraftArray<T> = Array<29 T extends ReadonlyArray<any>30 ? {[P in keyof T]: Draft<T>}[keyof T]31 : DraftObject<T>32>3334export type DraftTuple<T extends any[]> = {35 [P in keyof T]: T[P] extends T[number] ? Draft<T[P]> : never36}3738export type Draft<T> = T extends any[]39 ? IsFinite<T> extends true40 ? DraftTuple<T>41 : DraftArray<T[number]>42 : T extends ReadonlyArray<any>43 ? DraftArray<T[number]>44 : T extends object45 ? DraftObject<T>46 : T4748export interface Patch {49 op: "replace" | "remove" | "add"50 path: (string | number)[]51 value?: any52}5354export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void5556export interface IProduce {57 /**58 * Immer takes a state, and runs a function against it.59 * That function can freely mutate the state, as it will create copies-on-write.60 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.61 *62 * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe63 * any time it is called with the current state.64 *65 * @param currentState - the state to start with66 * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified67 * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined68 * @returns The next state: a new state, or the current state if nothing was modified69 */70 <S = any, R = never>(71 currentState: S,72 recipe: (this: Draft<S>, draftState: Draft<S>) => void | R,73 listener?: PatchListener74 ): R7576 /** Curried producer with an initial state */77 <S = any, R = never>(78 recipe: (this: Draft<S>, draftState: Draft<S>) => void | R,79 initialState: S80 ): (currentState: S | undefined) => R8182 /** Curried producer with no initial state */83 <S = any, R = never, Args extends any[] = any[]>(84 recipe: (85 this: Draft<S>,86 draftState: Draft<S>,87 ...extraArgs: Args88 ) => void | R89 ): (currentState: S, ...extraArgs: Args) => R90}9192export const produce: IProduce93export default produce9495export const nothing: undefined9697/**98 * Automatically freezes any state trees generated by immer.99 * This protects against accidental modifications of the state tree outside of an immer function.100 * This comes with a performance impact, so it is recommended to disable this option in production.101 * It is by default enabled.102 */103export function setAutoFreeze(autoFreeze: boolean): void104105/**106 * Manually override whether proxies should be used.107 * By default done by using feature detection108 */109export function setUseProxies(useProxies: boolean): void110111export function applyPatches<S>(state: S, patches: Patch[]): S112113export function original<T>(value: T): T | void114115export function isDraft(value: any): boolean
added:src/index.js+52 added
1import {applyPatches as applyPatchesImpl} from "./patches"2import {Immer} from "./immer"34const immer = new Immer()56/**7 * The `produce` function takes a value and a "recipe function" (whose8 * return value often depends on the base state). The recipe function is9 * free to mutate its first argument however it wants. All mutations are10 * only ever applied to a __copy__ of the base state.11 *12 * Pass only a function to create a "curried producer" which relieves you13 * from passing the recipe function every time.14 *15 * Only plain objects and arrays are made mutable. All other objects are16 * considered uncopyable.17 *18 * Note: This function is __bound__ to its `Immer` instance.19 *20 * @param {any} base - the initial state21 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified22 * @param {Function} patchListener - optional function that will be called with all the patches produced here23 * @returns {any} a new state, or the initial state if nothing was modified24 */25export const produce = immer.produce26export default produce2728/**29 * Pass true to automatically freeze all copies created by Immer.30 *31 * By default, auto-freezing is disabled in production.32 */33export const setAutoFreeze = value => immer.setAutoFreeze(value)3435/**36 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is37 * always faster than using ES5 proxies.38 *39 * By default, feature detection is used, so calling this is rarely necessary.40 */41export const setUseProxies = value => immer.setUseProxies(value)4243/**44 * Apply an array of Immer patches to the first argument.45 *46 * This function is a producer, which means copy-on-write is in effect.47 */48export const applyPatches = produce(applyPatchesImpl)4950export {original, isDraft, NOTHING as nothing} from "./common"5152export {Immer}
added:src/index.js.flow+92 added
1// @flow23export interface Patch {4 op: "replace" | "remove" | "add",5 path: (string|number)[],6 value?: any7}89export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void1011interface IProduce {12 /**13 * Immer takes a state, and runs a function against it.14 * That function can freely mutate the state, as it will create copies-on-write.15 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.16 *17 * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe18 * any time it is called with the current state.19 *20 * @param currentState - the state to start with21 * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified22 * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined23 * @returns The next state: a new state, or the current state if nothing was modified24 */25 <S>(26 currentState: S,27 recipe: (draftState: S) => S | void,28 patchListener?: PatchListener29 ): S;30 // curried invocations with inital state31 <S, A, B, C>(32 recipe: (draftState: S, a: A, b: B, c: C) => S | void,33 initialState: S34 ): (currentState: S | void, a: A, b: B, c: C) => S;35 <S, A, B>(36 recipe: (draftState: S, a: A, b: B) => S | void,37 initialState: S38 ): (currentState: S | void, a: A, b: B) => S;39 <S, A>(40 recipe: (draftState: S, a: A) => S | void,41 initialState: S42 ): (currentState: S | void, a: A) => S;43 <S>(44 recipe: (draftState: S) => S | void,45 initialState: S46 ): (currentState: S | void) => S;47 <S>(48 recipe: (draftState: S, ...extraArgs: any[]) => S | void,49 initialState: S50 ): (currentState: S | void, ...extraArgs: any[]) => S;51 // curried invocations without inital state52 <S, A, B, C>(53 recipe: (draftState: S, a: A, b: B, c: C) => S | void54 ): (currentState: S, a: A, b: B, c: C) => S;55 <S, A, B>(56 recipe: (draftState: S, a: A, b: B) => S | void57 ): (currentState: S, a: A, b: B) => S;58 <S, A>(59 recipe: (draftState: S, a: A) => S | void60 ): (currentState: S, a: A) => S;61 <S>(62 recipe: (draftState: S) => S | void63 ): (currentState: S) => S;64 <S>(65 recipe: (draftState: S, ...extraArgs: any[]) => S | void66 ): (currentState: S, ...extraArgs: any[]) => S;67}6869declare export var produce: IProduce70declare export default IProduce7172declare export var nothing: typeof undefined7374/**75 * Automatically freezes any state trees generated by immer.76 * This protects against accidental modifications of the state tree outside of an immer function.77 * This comes with a performance impact, so it is recommended to disable this option in production.78 * By default it is turned on during local development, and turned off in production.79 */80declare export function setAutoFreeze(autoFreeze: boolean): void8182/**83 * Manually override whether proxies should be used.84 * By default done by using feature detection85 */86declare export function setUseProxies(useProxies: boolean): void8788declare export function applyPatches<S>(state: S, patches: Patch[]): S8990declare export function original<S>(value: S): ?S9192declare export function isDraft(value: any): boolean
modified:src/patches.js+53 added-86 removed
1import {each} from "./common"23export function generatePatches(4 state,5 basepath,6 patches,7 inversePatches,8 baseValue,9 resultValue10) {11 if (patches)12 if (Array.isArray(baseValue))13 generateArrayPatches(14 state,15 basepath,16 patches,17 inversePatches,18 baseValue,19 resultValue20 )21 else22 generateObjectPatches(23 state,24 basepath,25 patches,26 inversePatches,27 baseValue,28 resultValue29 )3export function generatePatches(state, basePath, patches, inversePatches) {4 Array.isArray(state.base)5 ? generateArrayPatches(state, basePath, patches, inversePatches)6 : generateObjectPatches(state, basePath, patches, inversePatches)7}832export function generateArrayPatches(33 state,34 basepath,35 patches,36 inversePatches,37 baseValue,38 resultValue39) {40 const shared = Math.min(baseValue.length, resultValue.length)41 for (let i = 0; i < shared; i++) {42 if (state.assigned[i] && baseValue[i] !== resultValue[i]) {43 const path = basepath.concat(i)44 patches.push({op: "replace", path, value: resultValue[i]})45 inversePatches.push({op: "replace", path, value: baseValue[i]})9export function generateArrayPatches(state, basePath, patches, inversePatches) {10 const {base, copy, assigned} = state11 const minLength = Math.min(base.length, copy.length)1213 // Look for replaced indices.14 for (let i = 0; i < minLength; i++) {15 if (assigned[i] && base[i] !== copy[i]) {16 const path = basePath.concat(i)17 patches.push({op: "replace", path, value: copy[i]})18 inversePatches.push({op: "replace", path, value: base[i]})19 }20 }48 if (shared < resultValue.length) {49 // stuff was added50 for (let i = shared; i < resultValue.length; i++) {51 const path = basepath.concat(i)52 patches.push({op: "add", path, value: resultValue[i]})2122 // Did the array expand?23 if (minLength < copy.length) {24 for (let i = minLength; i < copy.length; i++) {25 patches.push({26 op: "add",27 path: basePath.concat(i),28 value: copy[i]29 })30 }31 inversePatches.push({32 op: "replace",56 path: basepath.concat("length"),57 value: baseValue.length33 path: basePath.concat("length"),34 value: base.length35 })59 } else if (shared < baseValue.length) {60 // stuff was removed36 }3738 // ...or did it shrink?39 else if (minLength < base.length) {40 patches.push({41 op: "replace",63 path: basepath.concat("length"),64 value: resultValue.length42 path: basePath.concat("length"),43 value: copy.length44 })66 for (let i = shared; i < baseValue.length; i++) {67 const path = basepath.concat(i)68 inversePatches.push({op: "add", path, value: baseValue[i]})45 for (let i = minLength; i < base.length; i++) {46 inversePatches.push({47 op: "add",48 path: basePath.concat(i),49 value: base[i]50 })51 }52 }53}5473function generateObjectPatches(74 state,75 basepath,76 patches,77 inversePatches,78 baseValue,79 resultValue80) {55function generateObjectPatches(state, basePath, patches, inversePatches) {56 const {base, copy} = state57 each(state.assigned, (key, assignedValue) => {82 const origValue = baseValue[key]83 const value = resultValue[key]84 const op = !assignedValue85 ? "remove"86 : key in baseValue87 ? "replace"88 : "add"89 if (origValue === baseValue && op === "replace") return90 const path = basepath.concat(key)58 const origValue = base[key]59 const value = copy[key]60 const op = !assignedValue ? "remove" : key in base ? "replace" : "add"61 if (origValue === base && op === "replace") return62 const path = basePath.concat(key)63 patches.push(op === "remove" ? {op, path} : {op, path, value})64 inversePatches.push(65 op === "add"66 ? {op: "remove", path}67 : op === "remove"96 ? {op: "add", path, value: origValue}97 : {op: "replace", path, value: origValue}68 ? {op: "add", path, value: origValue}69 : {op: "replace", path, value: origValue}70 )71 })72}73
7 unmodified lines
81 let base = draft82 for (let i = 0; i < path.length - 1; i++) {83 base = base[path[i]]84 if (!base || typeof base !== "object")113 throw new Error(114 "Cannot apply patch, path doesn't resolve: " +115 path.join("/")116 )85 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore86 }87 const key = path[path.length - 1]88 switch (patch.op) {89 case "replace":
2 unmodified lines
92 base[key] = patch.value93 break94 case "remove":95 if (Array.isArray(base)) {127 if (key === base.length - 1) base.length -= 1128 else129 throw new Error(130 `Remove can only remove the last key of an array, index: ${key}, length: ${131 base.length132 }`133 )134 } else delete base[key]96 if (key !== base.length - 1)97 throw new Error(`Only the last index of an array can be removed, index: ${key}, length: ${base.length}`) // prettier-ignore98 base.length -= 199 } else {100 delete base[key]101 }102 break103 default:104 throw new Error("Unsupported patch operation: " + patch.op)105 }
4 unmodified lines
modified:src/proxy.js+47 added-77 removed
4 unmodified lines
5 assign,6 each,7 has,8 is,9 isProxyable,10 isProxy,11 finalize,9 isDraftable,10 isDraft,11 shallowCopy,13 PROXY_STATE,14 RETURNED_AND_MODIFIED_ERROR12 DRAFT_STATE13} from "./common"1417let proxies = null15// For nested produce calls:16export const scopes = []17export const currentScope = () => scopes[scopes.length - 1]1819// Do nothing before being finalized.20export function willFinalize() {}2122export function createDraft(base, parent) {23 if (isDraft(base)) throw new Error("This should never happen. Please report: https://github.com/mweststrate/immer/issues/new") // prettier-ignore2425 const state = {26 modified: false, // this tree is modified (either this object or one of it's children)27 assigned: {}, // true: value was assigned to these props, false: was removed28 parent,29 base,30 draft: null, // the root proxy31 drafts: {}, // proxied properties32 copy: null,33 revoke: null,34 finalized: false35 }3637 const {revoke, proxy} = Array.isArray(base)38 ? Proxy.revocable([state], arrayTraps)39 : Proxy.revocable(state, objectTraps)4041 state.draft = proxy42 state.revoke = revoke4344 currentScope().push(state)45 return proxy46}4748const objectTraps = {49 get,50 has(target, prop) {51 return prop in source(target)
32 unmodified lines
84 )85 return objectTraps.set.call(this, state[0], prop, value)86}8759function createState(parent, base) {60 return {61 modified: false, // this tree is modified (either this object or one of it's children)62 assigned: {}, // true: value was assigned to these props, false: was removed63 finalized: false,64 parent,65 base,66 copy: undefined,67 proxies: {}68 }69}7088function source(state) {89 return state.modified === true ? state.copy : state.base90}9192function get(state, prop) {76 if (prop === PROXY_STATE) return state93 if (prop === DRAFT_STATE) return state94 if (state.modified) {95 const value = state.copy[prop]79 if (value === state.base[prop] && isProxyable(value))96 if (value === state.base[prop] && isDraftable(value))97 // only create proxy if it is not yet a proxy, and not a new object98 // (new objects don't need proxying, they will be processed in finalize anyway)82 return (state.copy[prop] = createProxy(state, value))99 return (state.copy[prop] = createDraft(value, state))100 return value101 } else {85 if (has(state.proxies, prop)) return state.proxies[prop]102 if (has(state.drafts, prop)) return state.drafts[prop]103 const value = state.base[prop]87 if (!isProxy(value) && isProxyable(value))88 return (state.proxies[prop] = createProxy(state, value))104 if (!isDraft(value) && isDraftable(value))105 return (state.drafts[prop] = createDraft(value, state))106 return value107 }108}109110function set(state, prop, value) {111 if (!state.modified) {112 // Optimize based on value's truthiness. Truthy values are guaranteed to113 // never be undefined, so we can avoid the `in` operator. Lastly, truthy97 // values may be proxies, but falsy values are never proxies.114 // values may be drafts, but falsy values are never drafts.115 const isUnchanged = value99 ? is(state.base[prop], value) || value === state.proxies[prop]116 ? is(state.base[prop], value) || value === state.drafts[prop]117 : is(state.base[prop], value) && prop in state.base118 if (isUnchanged) return true119 markChanged(state)120 }
14 unmodified lines
135136function getOwnPropertyDescriptor(state, prop) {137 const owner = state.modified138 ? state.copy122 : has(state.proxies, prop)123 ? state.proxies139 : has(state.drafts, prop)140 ? state.drafts141 : state.base142 const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)143 if (descriptor && !(Array.isArray(owner) && prop === "length"))144 descriptor.configurable = true
9 unmodified lines
154function markChanged(state) {155 if (!state.modified) {156 state.modified = true157 state.copy = shallowCopy(state.base)141 // copy the proxies over the base-copy142 assign(state.copy, state.proxies) // yup that works for arrays as well158 // copy the drafts over the base-copy159 assign(state.copy, state.drafts) // yup that works for arrays as well160 if (state.parent) markChanged(state.parent)161 }162}146147// creates a proxy for plain objects / arrays148function createProxy(parentState, base) {149 if (isProxy(base)) throw new Error("Immer bug. Plz report.")150 const state = createState(parentState, base)151 const proxy = Array.isArray(base)152 ? Proxy.revocable([state], arrayTraps)153 : Proxy.revocable(state, objectTraps)154 proxies.push(proxy)155 return proxy.proxy156}157158export function produceProxy(baseState, producer, patchListener) {159 const previousProxies = proxies160 proxies = []161 const patches = patchListener && []162 const inversePatches = patchListener && []163 try {164 // create proxy for root165 const rootProxy = createProxy(undefined, baseState)166 // execute the producer function167 const returnValue = producer.call(rootProxy, rootProxy)168 // and finalize the modified proxy169 let result170 // check whether the draft was modified and/or a value was returned171 if (returnValue !== undefined && returnValue !== rootProxy) {172 // something was returned, and it wasn't the proxy itself173 if (rootProxy[PROXY_STATE].modified)174 throw new Error(RETURNED_AND_MODIFIED_ERROR)175176 // we need to finalize the return value in case it's a subset of the draft177 result = finalize(returnValue)178 if (patches) {179 patches.push({op: "replace", path: [], value: result})180 inversePatches.push({op: "replace", path: [], value: baseState})181 }182 } else {183 result = finalize(rootProxy, [], patches, inversePatches)184 }185 // revoke all proxies186 each(proxies, (_, p) => p.revoke())187 patchListener && patchListener(patches, inversePatches)188 return result189 } finally {190 proxies = previousProxies191 }192}
modified:rollup.config.js+1 added-1 removed
5 unmodified lines
6import babel from "rollup-plugin-babel"78function getConfig(dest, format, ugly) {9 const conf = {10 input: "src/immer.js",10 input: "src/index.js",11 output: {12 exports: "named",13 file: dest,14 format,
55 unmodified lines