Skip to content
Myr

Merge branch 'async-recipes'

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

authored by Michel Weststrate · committed by Michel Weststrate · parents eabe9db, b79bb97 · Browse files · 12 files+706 added−188 removed
This commit

State

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

Diff stats

12 files+706 added−188 removed

  • tests:+339 added−6 removed
  • other:+367 added−182 removed

12 files+706 added−188 removed

added:__tests__/__snapshots__/manual.js.snap+101 added
1// Jest Snapshot v1, https://goo.gl/fbAQLP23exports[`manual - es5 cannot modify after finish 1`] = `"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {\\"a\\":2}"`;45exports[`manual - es5 should check arguments 1`] = `"First argument to createDraft should be a plain object, an array, or an immerable object."`;67exports[`manual - es5 should check arguments 2`] = `"First argument to createDraft should be a plain object, an array, or an immerable object."`;89exports[`manual - es5 should check arguments 3`] = `"First argument to finishDraft should be an object from createDraft."`;1011exports[`manual - es5 should not finish drafts from produce 1`] = `"The draft provided was not created using \`createDraft\`"`;1213exports[`manual - es5 should not finish twice 1`] = `"The draft provided was has already been finished"`;1415exports[`manual - es5 should support patches drafts 1`] = `16Array [17 Array [18 Array [19 Object {20 "op": "replace",21 "path": Array [22 "a",23 ],24 "value": 2,25 },26 Object {27 "op": "add",28 "path": Array [29 "b",30 ],31 "value": 3,32 },33 ],34 Array [35 Object {36 "op": "replace",37 "path": Array [38 "a",39 ],40 "value": 1,41 },42 Object {43 "op": "remove",44 "path": Array [45 "b",46 ],47 },48 ],49 ],50]51`;5253exports[`manual - proxy cannot modify after finish 1`] = `"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? {\\"a\\":2}"`;5455exports[`manual - proxy should check arguments 1`] = `"First argument to createDraft should be a plain object, an array, or an immerable object."`;5657exports[`manual - proxy should check arguments 2`] = `"First argument to createDraft should be a plain object, an array, or an immerable object."`;5859exports[`manual - proxy should check arguments 3`] = `"First argument to finishDraft should be an object from createDraft."`;6061exports[`manual - proxy should not finish drafts from produce 1`] = `"The draft provided was not created using \`createDraft\`"`;6263exports[`manual - proxy should not finish twice 1`] = `"The draft provided was has already been finished"`;6465exports[`manual - proxy should support patches drafts 1`] = `66Array [67 Array [68 Array [69 Object {70 "op": "replace",71 "path": Array [72 "a",73 ],74 "value": 2,75 },76 Object {77 "op": "add",78 "path": Array [79 "b",80 ],81 "value": 3,82 },83 ],84 Array [85 Object {86 "op": "replace",87 "path": Array [88 "a",89 ],90 "value": 1,91 },92 Object {93 "op": "remove",94 "path": Array [95 "b",96 ],97 },98 ],99 ],100]101`;
modified:__tests__/base.js+60 added-1 removed
824 unmodified lines
825 })826 expect(next.obj).toBe(next.arr[0])827 })828829 it("can return an object with two references to any pristine draft", () => {829 it("can return an object with two references to an unmodified draft", () => {830 const base = {a: {}}831 const next = produce(base, d => {832 return [d.a, d.a]833 })
9 unmodified lines
843 }).toThrow("Immer forbids circular references")844 })845 })846847 // TODO: rewrite tests with async/await once node 6 support is dropped848 describe("async recipe function", () => {849 it("can modify the draft", () => {850 const base = {a: 0, b: 0}851 return produce(base, d => {852 d.a = 1853 return Promise.resolve().then(() => {854 d.b = 1855 })856 }).then(res => {857 expect(res).not.toBe(base)858 expect(res).toEqual({a: 1, b: 1})859 })860 })861862 it("works with rejected promises", () => {863 let draft864 const base = {a: 0, b: 0}865 const err = new Error("passed")866 return produce(base, d => {867 draft = d868 draft.b = 1869 return Promise.reject(err)870 }).then(871 () => {872 throw "failed"873 },874 e => {875 expect(e).toBe(err)876 expect(() => draft.a).toThrowError(/revoked/)877 }878 )879 })880881 it("supports recursive produce calls after await", () => {882 const base = {obj: {k: 1}}883 return produce(base, d => {884 const obj = d.obj885 delete d.obj886 return Promise.resolve().then(() => {887 d.a = produce({}, d => {888 d.b = obj // Assign a draft owned by the parent scope.889 })890891 // Auto-freezing is prevented when an unowned draft exists.892 expect(Object.isFrozen(d.a)).toBeFalsy()893894 // Ensure `obj` is not revoked.895 obj.c = 1896 })897 }).then(res => {898 expect(res).not.toBe(base)899 expect(res).toEqual({900 a: {b: {k: 1, c: 1}}901 })902 })903 })904 })905906 it("throws when the draft is modified and another object is returned", () => {907 const base = {x: 3}908 expect(() => {909 produce(base, draft => {
312 unmodified lines
added:__tests__/manual.js+136 added
1"use strict"2import {3 setUseProxies,4 createDraft,5 finishDraft,6 produce,7 isDraft8} from "../src/index"910runTests("proxy", true)11runTests("es5", false)1213function runTests(name, useProxies) {14 describe("manual - " + name, () => {15 setUseProxies(useProxies)1617 it("should check arguments", () => {18 expect(() => createDraft(3)).toThrowErrorMatchingSnapshot()19 const buf = new Buffer([])20 expect(() => createDraft(buf)).toThrowErrorMatchingSnapshot()21 expect(() => finishDraft({})).toThrowErrorMatchingSnapshot()22 })2324 it("should support manual drafts", () => {25 const state = [{}, {}, {}]2627 const draft = createDraft(state)28 draft.forEach((item, index) => {29 item.index = index30 })3132 const result = finishDraft(draft)3334 expect(result).not.toBe(state)35 expect(result).toEqual([{index: 0}, {index: 1}, {index: 2}])36 expect(state).toEqual([{}, {}, {}])37 })3839 it("cannot modify after finish", () => {40 const state = {a: 1}4142 const draft = createDraft(state)43 draft.a = 244 expect(finishDraft(draft)).toEqual({a: 2})45 expect(() => {46 draft.a = 347 }).toThrowErrorMatchingSnapshot()48 })4950 it("should support patches drafts", () => {51 const state = {a: 1}5253 const draft = createDraft(state)54 draft.a = 255 draft.b = 35657 const listener = jest.fn()58 const result = finishDraft(draft, listener)5960 expect(result).not.toBe(state)61 expect(result).toEqual({a: 2, b: 3})62 expect(listener.mock.calls).toMatchSnapshot()63 })6465 it("should handle multiple create draft calls", () => {66 const state = {a: 1}6768 const draft = createDraft(state)69 draft.a = 27071 const draft2 = createDraft(state)72 draft2.b = 37374 const result = finishDraft(draft)7576 expect(result).not.toBe(state)77 expect(result).toEqual({a: 2})7879 draft2.a = 480 const result2 = finishDraft(draft2)81 expect(result2).not.toBe(result)82 expect(result2).toEqual({a: 4, b: 3})83 })8485 it("combines with produce - 1", () => {86 const state = {a: 1}8788 const draft = createDraft(state)89 draft.a = 290 const res1 = produce(draft, d => {91 d.b = 392 })93 draft.b = 494 const res2 = finishDraft(draft)95 expect(res1).toEqual({a: 2, b: 3})96 expect(res2).toEqual({a: 2, b: 4})97 })9899 it("combines with produce - 2", () => {100 const state = {a: 1}101102 const res1 = produce(state, draft => {103 draft.b = 3104 const draft2 = createDraft(draft)105 draft.c = 4106 draft2.d = 5107 const res2 = finishDraft(draft2)108 expect(res2).toEqual({109 a: 1,110 b: 3,111 d: 5112 })113 draft.d = 2114 })115 expect(res1).toEqual({116 a: 1,117 b: 3,118 c: 4,119 d: 2120 })121 })122123 it("should not finish drafts from produce", () => {124 produce({x: 1}, draft => {125 expect(() => finishDraft(draft)).toThrowErrorMatchingSnapshot()126 })127 })128129 it("should not finish twice", () => {130 const draft = createDraft({a: 1})131 draft.a++132 finishDraft(draft)133 expect(() => finishDraft(draft)).toThrowErrorMatchingSnapshot()134 })135 })136}
modified:__tests__/produce.ts+42 added-5 removed
194 unmodified lines
195 })196 exactType(result, {} as any[])197})198199it("can produce nothing", () => {200 let result = produce({}, _ => nothing)199it("can produce an undefined value", () => {200 let base = {} as {readonly a: number}201202 // Return only nothing.203 let result = produce(base, _ => nothing)204 exactType(result, undefined)205206 // Return maybe nothing.207 let result2 = produce(base, draft => {208 if (draft.a > 0) return nothing209 })210 exactType(result2, {} as typeof base | undefined)211})212213it("can return the draft itself", () => {214 let base = {} as {readonly a: number}215 let result = produce(base, draft => draft)216217 // Currently, the `readonly` modifier is lost.218 exactType(result, {} as {a: number} | undefined)219})220221it("can return a promise", () => {222 let base = {} as {readonly a: number}223224 // Return a promise only.225 exactType(226 produce(base, draft => {227 return Promise.resolve(draft.a > 0 ? null : undefined)228 }),229 {} as Promise<{readonly a: number} | null>230 )231232 // Return a promise or undefined.233 exactType(234 produce(base, draft => {235 if (draft.a > 0) return Promise.resolve()236 }),237 {} as (Promise<{readonly a: number}> | {readonly a: number})238 )239})240241it("works with `void` hack", () => {205 let obj = {} as {readonly a: number}206 let res = produce(obj, s => void s.a++)207 exactType(res, obj)242 let base = {} as {readonly a: number}243 let copy = produce(base, s => void s.a++)244 exactType(copy, base)245})246247it("works with generic parameters", () => {248 let insert = <T>(array: ReadonlyArray<T>, index: number, elem: T) => {
11 unmodified lines
modified:src/es5.js+21 added-20 removed
1"use strict"2// @ts-check32import {3 each,4 has,5 is,
2 unmodified lines
8 isEnumerable,9 shallowCopy,10 DRAFT_STATE11} from "./common"12import {ImmerScope} from "./scope"1314// property descriptors are recycled to make sure we don't create a get and set closure per property,15// but share them all instead16const descriptors = {}1717// For nested produce calls:18export const scopes = []19export const currentScope = () => scopes[scopes.length - 1]2021export function willFinalize(result, baseDraft, needPatches) {22 const scope = currentScope()23 scope.forEach(state => (state.finalizing = true))24 if (result === undefined || result === baseDraft) {25 if (needPatches) markChangesRecursively(baseDraft)18export function willFinalize(scope, result, isReplaced) {19 scope.drafts.forEach(draft => {20 draft[DRAFT_STATE].finalizing = true21 })22 if (!isReplaced) {23 if (scope.patches) {24 markChangesRecursively(scope.drafts[0])25 }26 // This is faster when we don't care about which attributes changed.27 markChangesSweep(scope)27 markChangesSweep(scope.drafts)28 }29 // When a child draft is returned, look for changes.30 else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {31 markChangesSweep(scope.drafts)32 }33}3435export function createDraft(base, parent) {35export function createProxy(base, parent) {36 const isArray = Array.isArray(base)37 const draft = clonePotentialDraft(base)38 each(draft, prop => {39 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))40 })4142 // See "proxy.js" for property documentation.43 const scope = parent ? parent.scope : ImmerScope.current44 const state = {44 scope: parent ? parent.scope : currentScope(),45 scope,46 modified: false,47 finalizing: false, // es5 only48 finalized: false,49 assigned: {},
5 unmodified lines
55 revoked: false // es5 only56 }5758 createHiddenProperty(draft, DRAFT_STATE, state)58 state.scope.push(state)59 scope.drafts.push(draft)60 return draft61}6263function revoke() {
9 unmodified lines
73 const value = source(state)[prop]74 // Drafts are only created for proxyable values that exist in the base state.75 if (!state.finalizing && value === state.base[prop] && isDraftable(value)) {76 prepareCopy(state)76 return (state.copy[prop] = createDraft(value, state))77 return (state.copy[prop] = createProxy(value, state))78 }79 return value80}81
57 unmodified lines
139 )140}141142// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.142function markChangesSweep(scope) {143function markChangesSweep(drafts) {144 // The natural order of drafts in the `scope` array is based on when they145 // were accessed. By processing drafts in reverse natural order, we have a146 // better chance of processing leaf nodes first. When a leaf node is known to147 // have changed, we can avoid any traversal of its ancestor nodes.147 for (let i = scope.length - 1; i >= 0; i--) {148 const state = scope[i]149 if (state.modified === false) {148 for (let i = drafts.length - 1; i >= 0; i--) {149 const state = drafts[i][DRAFT_STATE]150 if (!state.modified) {151 if (Array.isArray(state.base)) {152 if (hasArrayChanges(state)) markChanged(state)153 } else if (hasObjectChanges(state)) markChanged(state)154 }
85 unmodified lines
modified:src/immer.d.ts+22 added-8 removed
41 unmodified lines
42}4344export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void4546type IsVoidLike<T> = T extends void | undefined ? 1 : 04746/** Converts `nothing` into `undefined` */49type FromNothing<T> = Nothing extends T ? Exclude<T, Nothing> | undefined : T47type FromNothing<T> = T extends Nothing ? undefined : T4849/** The inferred return type of `produce` */52export type Produced<T, Return> = IsVoidLike<Return> extends 053 ? FromNothing<Return>54 : IsVoidLike<Return> extends 155 ? T56 : T | FromNothing<Exclude<Return, void>>50export type Produced<Base, Return> = Return extends void51 ? Base52 : Return extends Promise<infer Result>53 ? Promise<Result extends void ? Base : FromNothing<Result>>54 : FromNothing<Return>5556type ImmutableTuple<T extends ReadonlyArray<any>> = {57 readonly [P in keyof T]: Immutable<T[P]>58}
92 unmodified lines
151 * This function is a producer, which means copy-on-write is in effect.152 */153export function applyPatches<S>(base: S, patches: Patch[]): S154155/**156 * Create an Immer draft from the given base state, which may be a draft itself.157 * The draft can be modified until you finalize it with the `finishDraft` function.158 */159export function createDraft<T>(base: T): Draft<T>160161/**162 * Finalize an Immer draft from a `createDraft` call, returning the base state163 * (if no changes were made) or a modified copy. The draft must *not* be164 * mutated afterwards.165 *166 * Pass a function as the 2nd argument to generate Immer patches based on the167 * changes that were made.168 */169export function finishDraft<T>(draft: T, listener?: PatchListener): Immutable<T>170171/** Get the underlying object that is represented by the given draft */172export function original<T>(value: T): T | void173174/** Returns true if the given value is an Immer draft */
66 unmodified lines
modified:src/immer.js+128 added-76 removed
11 unmodified lines
12 shallowCopy,13 DRAFT_STATE,14 NOTHING15} from "./common"16import {ImmerScope} from "./scope"1718function verifyMinified() {}1920const configDefaults = {
30 unmodified lines
51 if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function")52 }5354 let result54 // Only create proxies for plain objects/arrays.55 if (!isDraftable(base)) {56 result = recipe(base)57 if (result === undefined) return base58 }59 // The given value must be proxied.60 else {61 this.scopes.push([])62 const baseDraft = this.createDraft(base)63 try {64 result = recipe.call(baseDraft, baseDraft)65 this.willFinalize(result, baseDraft, !!patchListener)5567 // Never generate patches when no listener exists.68 var patches = patchListener && [],69 inversePatches = patchListener && []7071 // Finalize the modified draft...72 if (result === undefined || result === baseDraft) {73 result = this.finalize(74 baseDraft,75 [],76 patches,77 inversePatches78 )79 }80 // ...or use a replacement value.81 else {82 // Users must never modify the draft _and_ return something else.83 if (baseDraft[DRAFT_STATE].modified)84 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore8586 // Finalize the replacement in case it contains (or is) a subset of the draft.87 if (isDraftable(result)) result = this.finalize(result)8889 if (patchListener) {90 patches.push({91 op: "replace",92 path: [],93 value: result94 })95 inversePatches.push({96 op: "replace",97 path: [],98 value: base99 })100 }101 }56 // Only plain objects, arrays, and "immerable classes" are drafted.57 if (isDraftable(base)) {58 const scope = ImmerScope.enter()59 const proxy = this.createProxy(base)60 let hasError = true61 try {62 result = recipe.call(proxy, proxy)63 hasError = false64 } finally {103 this.currentScope().forEach(state => state.revoke())104 this.scopes.pop()65 // finally instead of catch + rethrow better preserves original stack66 if (hasError) scope.revoke()67 else scope.leave()68 }106 patchListener && patchListener(patches, inversePatches)69 if (result instanceof Promise) {70 return result.then(71 result => {72 scope.usePatches(patchListener)73 return this.processResult(result, scope)74 },75 error => {76 scope.revoke()77 throw error78 }79 )80 }81 scope.usePatches(patchListener)82 return this.processResult(result, scope)83 } else {84 result = recipe(base)85 if (result === undefined) return base86 return result !== NOTHING ? result : undefined87 }108 // Normalize the result.109 return result === NOTHING ? undefined : result88 }89 createDraft(base) {90 if (!isDraftable(base)) throw new Error("First argument to createDraft should be a plain object, an array, or an immerable object.") // prettier-ignore91 const scope = ImmerScope.enter()92 const proxy = this.createProxy(base)93 scope.leave()94 proxy[DRAFT_STATE].customDraft = true95 return proxy96 }97 finishDraft(draft, patchListener) {98 if (!isDraft(draft)) throw new Error("First argument to finishDraft should be an object from createDraft.") // prettier-ignore99 const state = draft[DRAFT_STATE]100 if (!state.customDraft) throw new Error("The draft provided was not created using `createDraft`") // prettier-ignore101 if (state.finalized) throw new Error("The draft provided was has already been finished") // prettier-ignore102 // TODO: check if created with createDraft103 // TODO: check if not finsihed twice104 const {scope} = state105 scope.usePatches(patchListener)106 return this.processResult(undefined, scope)107 }108 setAutoFreeze(value) {109 this.autoFreeze = value110 }111 setUseProxies(value) {
7 unmodified lines
119 }120 // Otherwise, produce a copy of the base state.121 return this.produce(base, draft => applyPatches(draft, patches))122 }123 /** @internal */124 processResult(result, scope) {125 const baseDraft = scope.drafts[0]126 const isReplaced = result !== undefined && result !== baseDraft127 this.willFinalize(scope, result, isReplaced)128 if (isReplaced) {129 if (baseDraft[DRAFT_STATE].modified) {130 scope.revoke()131 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore132 }133 if (isDraftable(result)) {134 // Finalize the result in case it contains (or is) a subset of the draft.135 result = this.finalize(result, null, scope)136 }137 if (scope.patches) {138 scope.patches.push({139 op: "replace",140 path: [],141 value: result142 })143 scope.inversePatches.push({144 op: "replace",145 path: [],146 value: baseDraft[DRAFT_STATE].base147 })148 }149 } else {150 // Finalize the base draft.151 result = this.finalize(baseDraft, [], scope)152 }153 scope.revoke()154 if (scope.patches) {155 scope.patchListener(scope.patches, scope.inversePatches)156 }157 return result !== NOTHING ? result : undefined158 }159 /**160 * @internal161 * Finalize a draft, returning either the unmodified base state or a modified162 * copy of the base state.163 */131 finalize(draft, path, patches, inversePatches) {164 finalize(draft, path, scope) {165 const state = draft[DRAFT_STATE]166 if (!state) {167 if (Object.isFrozen(draft)) return draft135 return this.finalizeTree(draft)168 return this.finalizeTree(draft, null, scope)169 }137 // Never finalize drafts owned by an outer scope.138 if (state.scope !== this.currentScope()) {170 // Never finalize drafts owned by another scope.171 if (state.scope !== scope) {172 return draft173 }141 if (!state.modified) return state.base174 if (!state.modified) {175 return state.base176 }177 if (!state.finalized) {178 state.finalized = true144 this.finalizeTree(state.draft, path, patches, inversePatches)179 this.finalizeTree(state.draft, path, scope)180181 if (this.onDelete) {182 // The `assigned` object is unreliable with ES5 drafts.183 if (this.useProxies) {184 const {assigned} = state
6 unmodified lines
191 if (!has(copy, prop)) this.onDelete(state, prop)192 })193 }194 }159 if (this.onCopy) this.onCopy(state)195 if (this.onCopy) {196 this.onCopy(state)197 }198161 // Nested producers must never auto-freeze their result,162 // because it may contain drafts from parent producers.163 if (this.autoFreeze && this.scopes.length === 1) {199 // At this point, all descendants of `state.copy` have been finalized,200 // so we can be sure that `scope.canAutoFreeze` is accurate.201 if (this.autoFreeze && scope.canAutoFreeze) {202 Object.freeze(state.copy)203 }204167 if (patches) generatePatches(state, path, patches, inversePatches)205 if (path && scope.patches) {206 generatePatches(207 state,208 path,209 scope.patches,210 scope.inversePatches211 )212 }213 }214 return state.copy215 }216 /**217 * @internal218 * Finalize all drafts in the given state tree.219 */175 finalizeTree(root, path, patches, inversePatches) {220 finalizeTree(root, rootPath, scope) {221 const state = root[DRAFT_STATE]222 if (state) {223 if (!this.useProxies) {224 state.finalizing = true
2 unmodified lines
227 }228 root = state.copy229 }230186 const {onAssign} = this231 const needPatches = !!rootPath && !!scope.patches232 const finalizeProperty = (prop, value, parent) => {233 if (value === parent) {234 throw Error("Immer forbids circular references")235 }236192 // The only possible draft (in the scope of a `finalizeTree` call) is the `root` object.193 const inDraft = !!state && parent === root237 // In the `finalizeTree` method, only the `root` object may be a draft.238 const isDraftProp = !!state && parent === root239240 if (isDraft(value)) {196 value =197 // Patches are never generated for assigned properties.198 patches && inDraft && !state.assigned[prop]199 ? this.finalize(value, path.concat(prop), patches, inversePatches) // prettier-ignore200 : this.finalize(value)241 const path =242 isDraftProp && needPatches && !state.assigned[prop]243 ? rootPath.concat(prop)244 : null245246 // Drafts owned by `scope` are finalized here.247 value = this.finalize(value, path, scope)248249 // Drafts from another scope must prevent auto-freezing.250 if (isDraft(value)) {251 scope.canAutoFreeze = false252 }253254 // Preserve non-enumerable properties.255 if (Array.isArray(parent) || isEnumerable(parent, prop)) {256 parent[prop] = value257 } else {258 Object.defineProperty(parent, prop, {value})259 }260261 // Unchanged drafts are never passed to the `onAssign` hook.210 if (inDraft && value === state.base[prop]) return262 if (isDraftProp && value === state.base[prop]) return263 }264 // Unchanged draft properties are ignored.213 else if (inDraft && is(value, state.base[prop])) {265 else if (isDraftProp && is(value, state.base[prop])) {266 return267 }268 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.269 else if (isDraftable(value) && !Object.isFrozen(value)) {270 each(value, finalizeProperty)271 }272221 if (inDraft && onAssign) {222 onAssign(state, prop, value)273 if (isDraftProp && this.onAssign) {274 this.onAssign(state, prop, value)275 }276 }277278 each(root, finalizeProperty)
3 unmodified lines
modified:src/immer.js.flow+13 added
88 unmodified lines
8990declare export function original<S>(value: S): ?S9192declare export function isDraft(value: any): boolean9394/**95 * Creates a mutable draft from an (immutable) object / array. 96 * The draft can be modified until `finishDraft` is called97 */98declare export function createDraft<T>(base: T): T99100/**101 * Given a draft that was created using `createDraft`, 102 * finalizes the draft into a new immutable object.103 * Optionally a patch-listener can be provided to gather the patches that are needed to construct the object.104 */105declare export function finishDraft<T>(base: T, listener?: PatchListener): T
modified:src/index.js+16 added
modified:src/proxy.js+10 added-11 removed
1"use strict"2// @ts-check32import {3 assign,4 each,5 has,
2 unmodified lines
8 isDraft,9 shallowCopy,10 DRAFT_STATE11} from "./common"12import {ImmerScope} from "./scope"1315// For nested produce calls:16export const scopes = []17export const currentScope = () => scopes[scopes.length - 1]1814// Do nothing before being finalized.15export function willFinalize() {}1622export function createDraft(base, parent) {17export function createProxy(base, parent) {18 const scope = parent ? parent.scope : ImmerScope.current19 const state = {20 // Track which produce call this is associated with.25 scope: parent ? parent.scope : currentScope(),21 scope,22 // True for both shallow and deep changes.23 modified: false,24 // Used during finalization.25 finalized: false,
13 unmodified lines
39 revoke: null40 }4142 const {revoke, proxy} = Array.isArray(base)43 ? // [state] is used for arrays, to make sure the proxy is array-ish and not violate invariants,44 // although state itself is an object47 ? Proxy.revocable([state], arrayTraps)45 Proxy.revocable([state], arrayTraps)46 : Proxy.revocable(state, objectTraps)4748 state.draft = proxy49 state.revoke = revoke5053 state.scope.push(state)51 scope.drafts.push(proxy)52 return proxy53}5455const objectTraps = {
37 unmodified lines
93 }94 return objectTraps.set.call(this, state[0], prop, value)95}9697// returns the object we should be reading the current value from, which is base, until some change has been made98function source(state) {99 return state.copy || state.base100}101
16 unmodified lines
118 // Store drafts on the copy (when one exists).119 drafts = state.copy120 }121123 return (drafts[prop] = createDraft(value, state))122 return (drafts[prop] = createProxy(value, state))123}124125function set(state, prop, value) {126 if (!state.modified) {
42 unmodified lines
added:src/scope.js+42 added
1import {DRAFT_STATE} from "./common"23/** Each scope represents a `produce` call. */4export class ImmerScope {5 constructor(parent) {6 this.drafts = []7 this.parent = parent89 // Whenever the modified draft contains a draft from another scope, we10 // need to prevent auto-freezing so the unowned draft can be finalized.11 this.canAutoFreeze = true1213 // To avoid prototype lookups:14 this.patches = null15 }16 usePatches(patchListener) {17 if (patchListener) {18 this.patches = []19 this.inversePatches = []20 this.patchListener = patchListener21 }22 }23 revoke() {24 this.leave()25 this.drafts.forEach(revoke)26 this.drafts = null // Make draft-related methods throw.27 }28 leave() {29 if (this === ImmerScope.current) {30 ImmerScope.current = this.parent31 }32 }33}3435ImmerScope.current = null36ImmerScope.enter = function() {37 return (this.current = new ImmerScope(this.current))38}3940function revoke(draft) {41 draft[DRAFT_STATE].revoke()42}
modified:readme.md+115 added-67 removed
333 unmodified lines
334For a more in-depth study, see [Distributing patches and rebasing actions using Immer](https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-2-2f50d8363988)335336Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.337338## Auto freezing338## Async producers339340Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. It is by default enabled. By default, it is turned on during local development and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.340It is allowed to return Promise objects from recipes. Or, in other words, to use `async / await`. This can be pretty useful for long running processes, that only produce the new object once the promise chain resolves. Note that `produce` itself (even in the curried form) will return a promise if the producer is async. Example:341342```javascript343import produce from "immer"344345const user = {346 name: "michel",347 todos: []348}349350const loadedUser = await produce(user, async function(draft) {351 user.todos = await (await window.fetch("http://host/" + draft.name)).json()352})353```354355_Warning: please note that the draft shouldn't be 'leaked' from the async process and stored else where. The draft will still be revoked as soon as the async process completes._356357## `createDraft` and `finishDraft`358359`createDraft` and `finishDraft` are two low-level functions that are mostly useful for libraries that build abstractions on top of immer. It avoids the need to always create a function in order to work with drafts. Instead, one can create a draft, modify it, and at some time in the future finish the draft, in which case the next immutable state will be produced. We could for example rewrite our above example as:360361```javascript362import {createDraft, finishDraft} from "immer"363364const user = {365 name: "michel",366 todos: []367}368369const draft = createDraft(user)370draft.todos = await (await window.fetch("http://host/" + draft.name)).json()371const loadedUser = finishDraft(draft)372```373374Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.375376_Warning: in general, we recommend to use `produce` instead of the `createDraft` / `finishDraft` combo, `produce` is less error prone in usage, and more clearly separates the concepts of mutability and immutability in your code base._377378## Returning data from producers379380It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway. However, it is allowed to just `return draft`.381
75 unmodified lines
457```458459N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.460461## Inline shortcuts using `void`462463Draft mutations in Immer usually warrant a code block, since a return denotes an overwrite. Sometimes that can stretch code a little more than you might be comfortable with.464465In such cases, you can use javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) operator, which evaluates expressions and returns `undefined`.466467```javascript468// Single mutation469produce(draft => void (draft.user.age += 1))470471// Multiple mutations472produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))473```474475Code style is highly personal, but for code bases that are to be understood by many, we recommend to stick to the classic `draft => { draft.user.age += 1}` to avoid cognitive overhead.476477## Extracting the original object from a proxied instance478479Immer exposes a named export `original` that will get the original object from the proxied instance inside `produce` (or return `undefined` for unproxied values). A good example of when this can be useful is when searching for nodes in a tree-like state using strict equality.480
17 unmodified lines
498})499isDraft(nextState) // => false500```501450## Using `this`502## Auto freezing503452The recipe will be always invoked with the `draft` as `this` context.504Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. It is by default enabled. By default, it is turned on during local development and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.505454This means that the following constructions are also valid:455456```javascript457const base = {counter: 0}458459const next = produce(base, function() {460 this.counter++461})462console.log(next.counter) // 1463464// OR465const increment = produce(function() {466 this.counter++467})468console.log(increment(base).counter) // 1469```470471## Inline shortcuts using `void`472473Draft mutations in Immer usually warrant a code block, since a return denotes an overwrite. Sometimes that can stretch code a little more than you might be comfortable with.474475In such cases, you can use javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) operator, which evaluates expressions and returns `undefined`.476477```javascript478// Single mutation479produce(draft => void (draft.user.age += 1))480481// Multiple mutations482produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))483```484485Code style is highly personal, but for code bases that are to be understood by many, we recommend to stick to the classic `draft => { draft.user.age += 1}` to avoid cognitive overhead.486487## TypeScript or Flow488489The Immer package ships with type definitions inside the package, which should be picked up by TypeScript and Flow out of the box and without further configuration.490491The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:492493```ts494import produce from "immer"495496interface State {497 readonly x: number498}499500// `x` cannot be modified here501const state: State = {502 x: 0503}504505const newState = produce<State>(state, draft => {506 // `x` can be modified here507 draft.x++508})509510// `newState.x` cannot be modified here511```512513This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!514515**Note:** Immer v1.9+ supports Typescript v3.1+ only.516506## Immer on older JavaScript environments?507508By default `produce` tries to use proxies for optimal performance. However, on older JavaScript engines `Proxy` is not available. For example, when running Microsoft Internet Explorer or React Native on Android. In such cases, Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.509
54 unmodified lines
564 draft.map = newMap565})566```567568## TypeScript or Flow569570The Immer package ships with type definitions inside the package, which should be picked up by TypeScript and Flow out of the box and without further configuration.571572The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:573574```ts575import produce from "immer"576577interface State {578 readonly x: number579}580581// `x` cannot be modified here582const state: State = {583 x: 0584}585586const newState = produce<State>(state, draft => {587 // `x` can be modified here588 draft.x++589})590591// `newState.x` cannot be modified here592```593594This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!595596**Note:** Immer v1.9+ supports Typescript v3.1+ only.597598## Using `this`599600_Deprecated, this will probably be removed in a next major version, see [#308](https://github.com/mweststrate/immer/issues/308)_601602The recipe will be always invoked with the `draft` as `this` context.603604This means that the following constructions are also valid:605606```javascript607const base = {counter: 0}608609const next = produce(base, function() {610 this.counter++611})612console.log(next.counter) // 1613614// OR615const increment = produce(function() {616 this.counter++617})618console.log(increment(base).counter) // 1619```620621# Pitfalls6226231. Don't redefine draft like, `draft = myCoolNewState`. Instead, either modify the `draft` or return a new state. See [Returning data from producers](#returning-data-from-producers).6241. Immer assumes your state to be a unidirectional tree. That is, no object should appear twice in the tree, and there should be no circular references.
85 unmodified lines
710- Immer is roughly as fast as ImmutableJS. However, the _immutableJS + toJS_ makes clear the cost that often needs to be paid later; converting the immutableJS objects back to plain objects, to be able to pass them to components, over the network etc... (And there is also the upfront cost of converting data received from e.g. the server to immutable JS)711- Generating patches doesn't significantly slow immer down712- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.713714## Migration715716**Immer 1.\* -> 2.0**717718Make sure you don't return any promises as state, because `produce` will actually invoke the promise and wait until it settles.719720## FAQ721722_(for those who skimmed the above instead of actually reading)_723
35 unmodified lines