feat: support async recipes
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Drafts won't be revoked until the returned promise is fulfilled or rejected.
authored by aleclarson · committed by aleclarson · parent 271cd1b · Browse files · 5 files·+182 added−92 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+182 added−92 removed
- tests:+31 added−1 removed
- other:+151 added−91 removed
Provenance
- Commit
5fee518- Tree
0f33dec- Author
aleclarson <alec.stanford.larson@gmail.com>- Committer
aleclarson <alec.stanford.larson@gmail.com>- Parent
271cd1b
5 files changed+182 added−92 removed
modified:__tests__/base.js+31 added-1 removed
813 unmodified lines814 })815 expect(next.obj).toBe(next.arr[0])816 })817 818- it("can return an object with two references to any pristine draft", () => {818+ it("can return an object with two references to an unmodified draft", () => {819 const base = {a: {}}820 const next = produce(base, d => {821 return [d.a, d.a]822 })9 unmodified lines832 }).toThrow("Immer forbids circular references")833 })834 })835 836+ describe("async recipe function", () => {837+ it("can modify the draft", async () => {838+ const base = {a: 0, b: 0}839+ const res = await produce(base, async d => {840+ d.a = 1841+ await Promise.resolve()842+ d.b = 1843+ })844+ expect(res).not.toBe(base)845+ expect(res).toEqual({a: 1, b: 1})846+ })847+848+ it("works with rejected promises", async () => {849+ let draft850+ const base = {a: 0, b: 0}851+ const err = new Error("passed")852+ try {853+ await produce(base, async d => {854+ draft = d855+ draft.b = 1856+ await Promise.reject(err)857+ })858+ throw "failed"859+ } catch (e) {860+ expect(e).toBe(err)861+ expect(() => draft.a).toThrowError(/revoked/)862+ }863+ })864+ })865+866 it("throws when the draft is modified and another object is returned", () => {867 const base = {x: 3}868 expect(() => {869 produce(base, draft => {312 unmodified linesmodified:src/es5.js+17 added-18 removed
1 "use strict"2-// @ts-check3-2 import {3 each,4 has,5 is,2 unmodified lines8 isEnumerable,9 shallowCopy,10 DRAFT_STATE11 } from "./common"12+import {ImmerScope} from "./scope"13 14 const descriptors = {}15 17-// For nested produce calls:18-export const scopes = []19-export const currentScope = () => scopes[scopes.length - 1]20-21-export 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)16+export function willFinalize(scope, result, isReplaced) {17+ scope.drafts.forEach(draft => {18+ draft[DRAFT_STATE].finalizing = true19+ })20+ if (!isReplaced) {21+ if (scope.patches) {22+ markChangesRecursively(scope.drafts[0])23+ }24 // This is faster when we don't care about which attributes changed.27- markChangesSweep(scope)25+ markChangesSweep(scope.drafts)26 }27 }28 29 export function createDraft(base, parent) {3 unmodified lines33 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))34 })35 36 // See "proxy.js" for property documentation.37+ const scope = parent ? parent.scope : ImmerScope.current38 const state = {40- scope: parent ? parent.scope : currentScope(),39+ scope,40 modified: false,41 finalizing: false, // es5 only42 finalized: false,43 assigned: {},5 unmodified lines49 revoked: false // es5 only50 }51 52 createHiddenProperty(draft, DRAFT_STATE, state)54- state.scope.push(state)53+ scope.drafts.push(draft)54 return draft55 }56 57 function revoke() {75 unmodified lines133 )134 }135 136 // This looks expensive, but only proxies are visited, and only objects without known changes are scanned.138-function markChangesSweep(scope) {137+function markChangesSweep(drafts) {138 // The natural order of drafts in the `scope` array is based on when they139 // were accessed. By processing drafts in reverse natural order, we have a140 // better chance of processing leaf nodes first. When a leaf node is known to141 // have changed, we can avoid any traversal of its ancestor nodes.143- for (let i = scope.length - 1; i >= 0; i--) {144- const state = scope[i]145- if (state.modified === false) {142+ for (let i = drafts.length - 1; i >= 0; i--) {143+ const state = drafts[i][DRAFT_STATE]144+ if (!state.modified) {145 if (Array.isArray(state.base)) {146 if (hasArrayChanges(state)) markChanged(state)147 } else if (hasObjectChanges(state)) markChanged(state)148 }85 unmodified linesmodified:src/immer.js+92 added-65 removed
11 unmodified lines12 shallowCopy,13 DRAFT_STATE,14 NOTHING15 } from "./common"16+import {ImmerScope} from "./scope"17 18 function verifyMinified() {}19 20 const configDefaults = {30 unmodified lines51 if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function")52 }53 54 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([])55+56+ // Only plain objects, arrays, and "immerable classes" are drafted.57+ if (isDraftable(base)) {58+ const scope = ImmerScope.enter()59 const baseDraft = this.createDraft(base)60 try {61 result = recipe.call(baseDraft, baseDraft)65- this.willFinalize(result, baseDraft, !!patchListener)66-67- // Never generate patches when no listener exists.68- var patches = patchListener && [],69- inversePatches = patchListener && []70-71- // 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-ignore85-86- // Finalize the replacement in case it contains (or is) a subset of the draft.87- if (isDraftable(result)) result = this.finalize(result)88-89- if (patchListener) {90- patches.push({91- op: "replace",92- path: [],93- value: result94- })95- inversePatches.push({96- op: "replace",97- path: [],98- value: base99- })62+ } catch (error) {63+ scope.revoke()64+ throw error65+ }66+ scope.leave()67+ if (result instanceof Promise) {68+ return result.then(69+ result => {70+ scope.usePatches(patchListener)71+ return this.processResult(result, scope)72+ },73+ error => {74+ scope.revoke()75+ throw error76 }101- }102- } finally {103- this.currentScope().forEach(state => state.revoke())104- this.scopes.pop()77+ )78 }106- patchListener && patchListener(patches, inversePatches)79+ scope.usePatches(patchListener)80+ return this.processResult(result, scope)81+ } else {82+ result = recipe(base)83+ if (result === undefined) return base84+ return result !== NOTHING ? result : undefined85 }108- // Normalize the result.109- return result === NOTHING ? undefined : result86 }87 setAutoFreeze(value) {88 this.autoFreeze = value89 }8 unmodified lines98 }99 // Otherwise, produce a copy of the base state.100 return this.produce(base, draft => applyPatches(draft, patches))101 }102+ /** @internal */103+ processResult(result, scope) {104+ const baseDraft = scope.drafts[0]105+ const isReplaced = result !== undefined && result !== baseDraft106+ this.willFinalize(scope, result, isReplaced)107+ if (isReplaced) {108+ if (baseDraft[DRAFT_STATE].modified) {109+ scope.revoke()110+ throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore111+ }112+ if (isDraftable(result)) {113+ // Finalize the result in case it contains (or is) a subset of the draft.114+ result = this.finalize(result, null, scope)115+ }116+ if (scope.patches) {117+ scope.patches.push({118+ op: "replace",119+ path: [],120+ value: result121+ })122+ scope.inversePatches.push({123+ op: "replace",124+ path: [],125+ value: baseDraft[DRAFT_STATE].base126+ })127+ }128+ } else {129+ // Finalize the base draft.130+ result = this.finalize(baseDraft, [], scope)131+ }132+ scope.revoke()133+ if (scope.patches) {134+ scope.patchListener(scope.patches, scope.inversePatches)135+ }136+ return result !== NOTHING ? result : undefined137+ }138 /**139 * @internal140 * Finalize a draft, returning either the unmodified base state or a modified141 * copy of the base state.142 */131- finalize(draft, path, patches, inversePatches) {143+ finalize(draft, path, scope) {144 const state = draft[DRAFT_STATE]145 if (!state) {146 if (Object.isFrozen(draft)) return draft135- return this.finalizeTree(draft)147+ return this.finalizeTree(draft, null, scope)148 }137- // Never finalize drafts owned by an outer scope.138- if (state.scope !== this.currentScope()) {149+ // Never finalize drafts owned by another scope.150+ if (state.scope !== scope) {151 return draft152 }141- if (!state.modified) return state.base153+ if (!state.modified) {154+ return state.base155+ }156 if (!state.finalized) {157 state.finalized = true144- this.finalizeTree(state.draft, path, patches, inversePatches)158+ this.finalizeTree(state.draft, path, scope)159+160 if (this.onDelete) {161 // The `assigned` object is unreliable with ES5 drafts.162 if (this.useProxies) {163 const {assigned} = state6 unmodified lines170 if (!has(copy, prop)) this.onDelete(state, prop)171 })172 }173 }159- if (this.onCopy) this.onCopy(state)174+ if (this.onCopy) {175+ this.onCopy(state)176+ }177 178 // Nested producers must never auto-freeze their result,179 // because it may contain drafts from parent producers.163- if (this.autoFreeze && this.scopes.length === 1) {180+ if (this.autoFreeze && !scope.parent) {181 Object.freeze(state.copy)182 }183 167- if (patches) generatePatches(state, path, patches, inversePatches)184+ if (path && scope.patches) {185+ generatePatches(186+ state,187+ path,188+ scope.patches,189+ scope.inversePatches190+ )191+ }192 }193 return state.copy194 }195 /**196 * @internal197 * Finalize all drafts in the given state tree.198 */175- finalizeTree(root, path, patches, inversePatches) {199+ finalizeTree(root, path, scope) {200 const state = root[DRAFT_STATE]201 if (state) {202 if (!this.useProxies) {203 state.finalizing = true12 unmodified lines216 // The only possible draft (in the scope of a `finalizeTree` call) is the `root` object.217 const inDraft = !!state && parent === root218 219 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)220+ const needPatches =221+ inDraft && path && scope.patches && !state.assigned[prop]222 223+ value = this.finalize(224+ value,225+ needPatches ? path.concat(prop) : null,226+ scope227+ )228+229 // Preserve non-enumerable properties.230 if (Array.isArray(parent) || isEnumerable(parent, prop)) {231 parent[prop] = value232 } else {24 unmodified linesmodified:src/proxy.js+4 added-8 removed
12323452 unmodified lines8910111213151617181415161718192025212223242519 unmodified lines45464748534950515253112 unmodified linesExpand all"use strict"// @ts-check
import { assign, each, has,2 unmodified lines isDraft, shallowCopy, DRAFT_STATE} from "./common"import {ImmerScope} from "./scope"
// For nested produce calls:export const scopes = []export const currentScope = () => scopes[scopes.length - 1]
// Do nothing before being finalized.export function willFinalize() {}
export function createDraft(base, parent) { const scope = parent ? parent.scope : ImmerScope.current const state = { // Track which produce call this is associated with. scope: parent ? parent.scope : currentScope(), scope, // True for both shallow and deep changes. modified: false, // Used during finalization. finalized: false,19 unmodified lines
state.draft = proxy state.revoke = revoke
state.scope.push(state) scope.drafts.push(proxy) return proxy}
const objectTraps = {112 unmodified linesExpand alladded:src/scope.js+38 added
1234567891011121314151617181920212223242526272829303132333435363738import {DRAFT_STATE} from "./common"
/** Each scope represents a `produce` call. */export class ImmerScope { constructor(parent) { this.drafts = [] this.parent = parent
// To avoid prototype lookups: this.patches = null } usePatches(patchListener) { if (patchListener) { this.patches = [] this.inversePatches = [] this.patchListener = patchListener } } revoke() { this.leave() this.drafts.forEach(revoke) this.drafts = null // Make draft-related methods throw. } leave() { if (this === ImmerScope.current) { ImmerScope.current = this.parent } }}
ImmerScope.current = nullImmerScope.enter = function() { return (this.current = new ImmerScope(this.current))}
function revoke(draft) { draft[DRAFT_STATE].revoke()}