immer.js
This file
Path
src/immer.js
288 lines · 9.7 KiB · JavaScript
Last changed by
nit: improved error messagesAlec Larsonbefore adoptiona951f40
History of this fileTake it
The walk stopped after 200 commits: lines older than d87d637 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: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 12–13why, one step back12 shallowCopy,13 DRAFT_STATE,nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 14why, one step back14 NOTHINGMerge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 15why, one step back15} from "./common"Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 16why, one step back16import {ImmerScope} from "./scope"Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
line 17why, one step back17feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 18why, one step back18function verifyMinified() {}Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
line 19why, one step back19feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 20–24why, one step back20const configDefaults = {21 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",22 autoFreeze:23 typeof process !== "undefined"24 ? process.env.NODE_ENV !== "production"feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
lines 25–28why, one step back25 : verifyMinified.name === "verifyMinified",26 onAssign: null,27 onDelete: null,28 onCopy: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 29why, one step back29}Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
line 30why, one step back30feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 31–41why, one step back31export class Immer {32 constructor(config) {33 assign(this, configDefaults, config)34 this.setUseProxies(this.useProxies)35 this.produce = this.produce.bind(this)36 }37 produce(base, recipe, patchListener) {38 // curried invocation39 if (typeof base === "function" && typeof recipe !== "function") {40 const defaultBase = recipe41 recipe = baseMerge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
line 42why, one step back42feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 43–45why, one step back43 // prettier-ignore44 return (base = defaultBase, ...args) =>45 this.produce(base, draft => recipe.call(draft, draft, ...args))Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
lines 46–47why, one step back46 }47feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 48–49why, one step back48 // prettier-ignore49 {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 50–55why, one step back50 if (typeof recipe !== "function") {51 throw new Error("The first or second argument to `produce` must be a function")52 }53 if (patchListener !== undefined && typeof patchListener !== "function") {54 throw new Error("The third argument to `produce` must be a function or undefined")55 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 56why, one step back56 }Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
line 57why, one step back57feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 58why, one step back58 let resultnit: dedupe some codealeclarsonbefore adoptionc9e1d98
line 59why, one step back59Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 60–67why, one step back60 // Only plain objects, arrays, and "immerable classes" are drafted.61 if (isDraftable(base)) {62 const scope = ImmerScope.enter()63 const proxy = this.createProxy(base)64 let hasError = true65 try {66 result = recipe.call(proxy, proxy)67 hasError = falsefeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 68why, one step back68 } finally {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 69–71why, one step back69 // finally instead of catch + rethrow better preserves original stack70 if (hasError) scope.revoke()71 else scope.leave()feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 72why, one step back72 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 73–90why, one step back73 if (result instanceof Promise) {74 return result.then(75 result => {76 scope.usePatches(patchListener)77 return this.processResult(result, scope)78 },79 error => {80 scope.revoke()81 throw error82 }83 )84 }85 scope.usePatches(patchListener)86 return this.processResult(result, scope)87 } else {88 result = recipe(base)89 if (result === undefined) return base90 return result !== NOTHING ? result : undefinedfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 91–92why, one step back91 }92 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 93why, one step back93 createDraft(base) {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 94–96why, one step back94 if (!isDraftable(base)) {95 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore96 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 97–98why, one step back97 const scope = ImmerScope.enter()98 const proxy = this.createProxy(base)nit: improved error messagesAlec Larsonbefore adoptiona951f40
line 99why, one step back99 proxy[DRAFT_STATE].isManual = trueMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 100–103why, one step back100 scope.leave()101 return proxy102 }103 finishDraft(draft, patchListener) {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 104–110why, one step back104 const state = draft && draft[DRAFT_STATE]105 if (!state || !state.isManual) {106 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore107 }108 if (state.finalized) {109 throw new Error("The given draft is already finalized") // prettier-ignore110 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 111–114why, one step back111 const {scope} = state112 scope.usePatches(patchListener)113 return this.processResult(undefined, scope)114 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 115–120why, one step back115 setAutoFreeze(value) {116 this.autoFreeze = value117 }118 setUseProxies(value) {119 this.useProxies = value120 assign(this, value ? modernProxy : legacyProxy)fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77
lines 121–128why, one step back121 }122 applyPatches(base, patches) {123 // Mutate the base state when a draft is passed.124 if (isDraft(base)) {125 return applyPatches(base, patches)126 }127 // Otherwise, produce a copy of the base state.128 return this.produce(base, draft => applyPatches(draft, patches))feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 129why, one step back129 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 130–165why, one step back130 /** @internal */131 processResult(result, scope) {132 const baseDraft = scope.drafts[0]133 const isReplaced = result !== undefined && result !== baseDraft134 this.willFinalize(scope, result, isReplaced)135 if (isReplaced) {136 if (baseDraft[DRAFT_STATE].modified) {137 scope.revoke()138 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore139 }140 if (isDraftable(result)) {141 // Finalize the result in case it contains (or is) a subset of the draft.142 result = this.finalize(result, null, scope)143 }144 if (scope.patches) {145 scope.patches.push({146 op: "replace",147 path: [],148 value: result149 })150 scope.inversePatches.push({151 op: "replace",152 path: [],153 value: baseDraft[DRAFT_STATE].base154 })155 }156 } else {157 // Finalize the base draft.158 result = this.finalize(baseDraft, [], scope)159 }160 scope.revoke()161 if (scope.patches) {162 scope.patchListener(scope.patches, scope.inversePatches)163 }164 return result !== NOTHING ? result : undefined165 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 166–170why, one step back166 /**167 * @internal168 * Finalize a draft, returning either the unmodified base state or a modified169 * copy of the base state.170 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 171why, one step back171 finalize(draft, path, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 172–174why, one step back172 const state = draft[DRAFT_STATE]173 if (!state) {174 if (Object.isFrozen(draft)) return draftMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 175why, one step back175 return this.finalizeTree(draft, null, scope)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 176why, one step back176 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 177–178why, one step back177 // Never finalize drafts owned by another scope.178 if (state.scope !== scope) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 179–180why, one step back179 return draft180 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 181–183why, one step back181 if (!state.modified) {182 return state.base183 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 184–185why, one step back184 if (!state.finalized) {185 state.finalized = trueMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 186–187why, one step back186 this.finalizeTree(state.draft, path, scope)187feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 188why, one step back188 if (this.onDelete) {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 189–196why, one step back189 // The `assigned` object is unreliable with ES5 drafts.190 if (this.useProxies) {191 const {assigned} = state192 for (const prop in assigned) {193 if (!assigned[prop]) this.onDelete(state, prop)194 }195 } else {196 const {base, copy} = statenit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 197why, one step back197 each(base, prop => {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 198–200why, one step back198 if (!has(copy, prop)) this.onDelete(state, prop)199 })200 }feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 201why, one step back201 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 202–204why, one step back202 if (this.onCopy) {203 this.onCopy(state)204 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 205why, one step back205Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 206–208why, one step back206 // At this point, all descendants of `state.copy` have been finalized,207 // so we can be sure that `scope.canAutoFreeze` is accurate.208 if (this.autoFreeze && scope.canAutoFreeze) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 209–211why, one step back209 Object.freeze(state.copy)210 }211Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 212–219why, one step back212 if (path && scope.patches) {213 generatePatches(214 state,215 path,216 scope.patches,217 scope.inversePatches218 )219 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 220–226why, one step back220 }221 return state.copy222 }223 /**224 * @internal225 * Finalize all drafts in the given state tree.226 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 227why, one step back227 finalizeTree(root, rootPath, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 228–229why, one step back228 const state = root[DRAFT_STATE]229 if (state) {feat: limited class supportaleclarsonbefore adoption9877d64
lines 230–235why, one step back230 if (!this.useProxies) {231 state.finalizing = true232 state.copy = shallowCopy(state.draft, true)233 state.finalizing = false234 }235 root = state.copyfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 236why, one step back236 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 237why, one step back237Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 238why, one step back238 const needPatches = !!rootPath && !!scope.patchesfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 239why, one step back239 const finalizeProperty = (prop, value, parent) => {fix: throw on circular referencesaleclarsonbefore adoption9c6603e
lines 240–243why, one step back240 if (value === parent) {241 throw Error("Immer forbids circular references")242 }243Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 244–245why, one step back244 // In the `finalizeTree` method, only the `root` object may be a draft.245 const isDraftProp = !!state && parent === rootfeat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 246why, one step back246refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 247why, one step back247 if (isDraft(value)) {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 248–251why, one step back248 const path =249 isDraftProp && needPatches && !state.assigned[prop]250 ? rootPath.concat(prop)251 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 252why, one step back252Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 253–260why, one step back253 // Drafts owned by `scope` are finalized here.254 value = this.finalize(value, path, scope)255256 // Drafts from another scope must prevent auto-freezing.257 if (isDraft(value)) {258 scope.canAutoFreeze = false259 }260feat: limited class supportaleclarsonbefore adoption9877d64
lines 261–268why, one step back261 // Preserve non-enumerable properties.262 if (Array.isArray(parent) || isEnumerable(parent, prop)) {263 parent[prop] = value264 } else {265 Object.defineProperty(parent, prop, {value})266 }267268 // Unchanged drafts are never passed to the `onAssign` hook.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 269why, one step back269 if (isDraftProp && value === state.base[prop]) returnrefactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 270why, one step back270 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 271why, one step back271 // Unchanged draft properties are ignored.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 272why, one step back272 else if (isDraftProp && is(value, state.base[prop])) {feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 273why, one step back273 returnfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 274why, one step back274 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 275–276why, one step back275 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.276 else if (isDraftable(value) && !Object.isFrozen(value)) {nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 277why, one step back277 each(value, finalizeProperty)refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 278–279why, one step back278 }279Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 280–281why, one step back280 if (isDraftProp && this.onAssign) {281 this.onAssign(state, prop, value)feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 282why, one step back282 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 283why, one step back283 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 284why, one step back284nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 285why, one step back285 each(root, finalizeProperty)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 286–288why, one step back286 return root287 }288}