immer.js
This file
Path
src/immer.js
297 lines · 10.0 KiB · JavaScript
Last changed by
feat: `Map` supportkeenondrumsbefore adoption8276a6c
History of this fileTake it
The walk stopped after 200 commits: lines older than 0d262e1 point at it.
feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 1–2why, one step back1import * as legacyProxy from "./es5"2import * as modernProxy from "./proxy"fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77
line 3why, one step back3import {applyPatches, generatePatches} from "./patches"feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 4–6why, one step back4import {5 assign,6 each,fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
line 7why, one step back7 has,feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 8–10why, one step back8 is,9 isDraft,10 isDraftable,nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 11why, one step back11 isEnumerable,feat: `Map` supportkeenondrumsbefore adoption8276a6c
line 12why, one step back12 isMap,feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 13–14why, one step back13 shallowCopy,14 DRAFT_STATE,nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 15why, one step back15 NOTHINGMerge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 16why, one step back16} from "./common"Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 17why, one step back17import {ImmerScope} from "./scope"Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1
line 18why, one step back18feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 19why, one step back19function verifyMinified() {}Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1
line 20why, one step back20feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 21–25why, one step back21const configDefaults = {22 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",23 autoFreeze:24 typeof process !== "undefined"25 ? process.env.NODE_ENV !== "production"feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
lines 26–29why, one step back26 : verifyMinified.name === "verifyMinified",27 onAssign: null,28 onDelete: null,29 onCopy: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 30why, one step back30}Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1
line 31why, one step back31feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 32–42why, one step back32export class Immer {33 constructor(config) {34 assign(this, configDefaults, config)35 this.setUseProxies(this.useProxies)36 this.produce = this.produce.bind(this)37 }38 produce(base, recipe, patchListener) {39 // curried invocation40 if (typeof base === "function" && typeof recipe !== "function") {41 const defaultBase = recipe42 recipe = baseFixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1
line 43why, one step back43refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04
line 44why, one step back44 const self = thisfeat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298
line 45why, one step back45 return function curriedProduce(base = defaultBase, ...args) {refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04
line 46why, one step back46 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignorefeat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298
line 47why, one step back47 }Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1
lines 48–49why, one step back48 }49feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 50–51why, one step back50 // prettier-ignore51 {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 52–57why, one step back52 if (typeof recipe !== "function") {53 throw new Error("The first or second argument to `produce` must be a function")54 }55 if (patchListener !== undefined && typeof patchListener !== "function") {56 throw new Error("The third argument to `produce` must be a function or undefined")57 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 58why, one step back58 }Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1
line 59why, one step back59feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 60why, one step back60 let resultnit: dedupe some codealeclarsonbefore adoptionc9e1d98
line 61why, one step back61Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 62–67why, one step back62 // Only plain objects, arrays, and "immerable classes" are drafted.63 if (isDraftable(base)) {64 const scope = ImmerScope.enter()65 const proxy = this.createProxy(base)66 let hasError = true67 try {feat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298
line 68why, one step back68 result = recipe(proxy)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 69why, one step back69 hasError = falsefeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 70why, one step back70 } finally {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 71–73why, one step back71 // finally instead of catch + rethrow better preserves original stack72 if (hasError) scope.revoke()73 else scope.leave()feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 74why, one step back74 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 75–92why, one step back75 if (result instanceof Promise) {76 return result.then(77 result => {78 scope.usePatches(patchListener)79 return this.processResult(result, scope)80 },81 error => {82 scope.revoke()83 throw error84 }85 )86 }87 scope.usePatches(patchListener)88 return this.processResult(result, scope)89 } else {90 result = recipe(base)91 if (result === undefined) return base92 return result !== NOTHING ? result : undefinedfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 93–94why, one step back93 }94 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 95why, one step back95 createDraft(base) {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 96–98why, one step back96 if (!isDraftable(base)) {97 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore98 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 99–100why, one step back99 const scope = ImmerScope.enter()100 const proxy = this.createProxy(base)nit: improved error messagesAlec Larsonbefore adoptiona951f40
line 101why, one step back101 proxy[DRAFT_STATE].isManual = trueMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 102–105why, one step back102 scope.leave()103 return proxy104 }105 finishDraft(draft, patchListener) {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 106–112why, one step back106 const state = draft && draft[DRAFT_STATE]107 if (!state || !state.isManual) {108 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore109 }110 if (state.finalized) {111 throw new Error("The given draft is already finalized") // prettier-ignore112 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 113–116why, one step back113 const {scope} = state114 scope.usePatches(patchListener)115 return this.processResult(undefined, scope)116 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 117–122why, one step back117 setAutoFreeze(value) {118 this.autoFreeze = value119 }120 setUseProxies(value) {121 this.useProxies = value122 assign(this, value ? modernProxy : legacyProxy)fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77
lines 123–130why, one step back123 }124 applyPatches(base, patches) {125 // Mutate the base state when a draft is passed.126 if (isDraft(base)) {127 return applyPatches(base, patches)128 }129 // Otherwise, produce a copy of the base state.130 return this.produce(base, draft => applyPatches(draft, patches))feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 131why, one step back131 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 132–167why, one step back132 /** @internal */133 processResult(result, scope) {134 const baseDraft = scope.drafts[0]135 const isReplaced = result !== undefined && result !== baseDraft136 this.willFinalize(scope, result, isReplaced)137 if (isReplaced) {138 if (baseDraft[DRAFT_STATE].modified) {139 scope.revoke()140 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore141 }142 if (isDraftable(result)) {143 // Finalize the result in case it contains (or is) a subset of the draft.144 result = this.finalize(result, null, scope)145 }146 if (scope.patches) {147 scope.patches.push({148 op: "replace",149 path: [],150 value: result151 })152 scope.inversePatches.push({153 op: "replace",154 path: [],155 value: baseDraft[DRAFT_STATE].base156 })157 }158 } else {159 // Finalize the base draft.160 result = this.finalize(baseDraft, [], scope)161 }162 scope.revoke()163 if (scope.patches) {164 scope.patchListener(scope.patches, scope.inversePatches)165 }166 return result !== NOTHING ? result : undefined167 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 168–172why, one step back168 /**169 * @internal170 * Finalize a draft, returning either the unmodified base state or a modified171 * copy of the base state.172 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 173why, one step back173 finalize(draft, path, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 174–176why, one step back174 const state = draft[DRAFT_STATE]175 if (!state) {176 if (Object.isFrozen(draft)) return draftMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 177why, one step back177 return this.finalizeTree(draft, null, scope)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 178why, one step back178 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 179–180why, one step back179 // Never finalize drafts owned by another scope.180 if (state.scope !== scope) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 181–182why, one step back181 return draft182 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 183–185why, one step back183 if (!state.modified) {184 return state.base185 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 186–187why, one step back186 if (!state.finalized) {187 state.finalized = trueMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 188–189why, one step back188 this.finalizeTree(state.draft, path, scope)189feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 190why, one step back190 if (this.onDelete) {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 191–198why, one step back191 // The `assigned` object is unreliable with ES5 drafts.192 if (this.useProxies) {193 const {assigned} = state194 for (const prop in assigned) {195 if (!assigned[prop]) this.onDelete(state, prop)196 }197 } else {198 const {base, copy} = statenit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 199why, one step back199 each(base, prop => {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 200–202why, one step back200 if (!has(copy, prop)) this.onDelete(state, prop)201 })202 }feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 203why, one step back203 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 204–206why, one step back204 if (this.onCopy) {205 this.onCopy(state)206 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 207why, one step back207Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 208–210why, one step back208 // At this point, all descendants of `state.copy` have been finalized,209 // so we can be sure that `scope.canAutoFreeze` is accurate.210 if (this.autoFreeze && scope.canAutoFreeze) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 211–213why, one step back211 Object.freeze(state.copy)212 }213Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 214–221why, one step back214 if (path && scope.patches) {215 generatePatches(216 state,217 path,218 scope.patches,219 scope.inversePatches220 )221 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 222–228why, one step back222 }223 return state.copy224 }225 /**226 * @internal227 * Finalize all drafts in the given state tree.228 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 229why, one step back229 finalizeTree(root, rootPath, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 230–231why, one step back230 const state = root[DRAFT_STATE]231 if (state) {feat: limited class supportaleclarsonbefore adoption9877d64
line 232why, one step back232 if (!this.useProxies) {chore: comments and formattingAlec Larsonbefore adoptionff96173
line 233why, one step back233 // Create the final copy, with added keys and without deleted keys.feat: limited class supportaleclarsonbefore adoption9877d64
lines 234–236why, one step back234 state.copy = shallowCopy(state.draft, true)235 }236 root = state.copyfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 237why, one step back237 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 238why, one step back238Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 239why, one step back239 const needPatches = !!rootPath && !!scope.patchesfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 240why, one step back240 const finalizeProperty = (prop, value, parent) => {fix: throw on circular referencesaleclarsonbefore adoption9c6603e
lines 241–244why, one step back241 if (value === parent) {242 throw Error("Immer forbids circular references")243 }244Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 245–246why, one step back245 // In the `finalizeTree` method, only the `root` object may be a draft.246 const isDraftProp = !!state && parent === rootfeat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 247why, one step back247refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 248why, one step back248 if (isDraft(value)) {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 249–252why, one step back249 const path =250 isDraftProp && needPatches && !state.assigned[prop]251 ? rootPath.concat(prop)252 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 253why, one step back253Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 254–261why, one step back254 // Drafts owned by `scope` are finalized here.255 value = this.finalize(value, path, scope)256257 // Drafts from another scope must prevent auto-freezing.258 if (isDraft(value)) {259 scope.canAutoFreeze = false260 }261feat: `Map` supportkeenondrumsbefore adoption8276a6c
line 262why, one step back262 this.assignPropertyInParent(parent, prop, value)feat: limited class supportaleclarsonbefore adoption9877d64
lines 263–264why, one step back263264 // Unchanged drafts are never passed to the `onAssign` hook.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 265why, one step back265 if (isDraftProp && value === state.base[prop]) returnrefactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 266why, one step back266 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 267why, one step back267 // Unchanged draft properties are ignored.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 268why, one step back268 else if (isDraftProp && is(value, state.base[prop])) {feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 269why, one step back269 returnfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 270why, one step back270 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 271–272why, one step back271 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.272 else if (isDraftable(value) && !Object.isFrozen(value)) {nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 273why, one step back273 each(value, finalizeProperty)refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 274–275why, one step back274 }275Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 276–277why, one step back276 if (isDraftProp && this.onAssign) {277 this.onAssign(state, prop, value)feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 278why, one step back278 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 279why, one step back279 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 280why, one step back280nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 281why, one step back281 each(root, finalizeProperty)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 282why, one step back282 return rootfeat: `Map` supportkeenondrumsbefore adoption8276a6c
lines 283–295why, one step back283 }284285 assignPropertyInParent(parent, prop, value) {286 if (isMap(parent)) {287 parent.set(prop, value)288 return289 }290 // Preserve non-enumerable properties.291 if (Array.isArray(parent) || isEnumerable(parent, prop)) {292 parent[prop] = value293 return294 }295 Object.defineProperty(parent, prop, {value})feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 296–297why, one step back296 }297}