immer.js
This file
Path
src/immer.js
281 lines · 9.8 KiB · JavaScript
Last changed by
Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
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–52why, one step back48 // prettier-ignore49 {50 if (typeof recipe !== "function") throw new Error("if first argument is not a function, the second argument to produce should be a function")51 if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function")52 }Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
line 53why, one step back53feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 54why, one step back54 let resultnit: dedupe some codealeclarsonbefore adoptionc9e1d98
line 55why, one step back55Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 56–63why, one step back56 // 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 = falsefeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 64why, one step back64 } finally {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 65–67why, one step back65 // finally instead of catch + rethrow better preserves original stack66 if (hasError) scope.revoke()67 else scope.leave()feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 68why, one step back68 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 69–86why, one step back69 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 : undefinedfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 87–88why, one step back87 }88 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 89–107why, one step back89 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 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 108–113why, one step back108 setAutoFreeze(value) {109 this.autoFreeze = value110 }111 setUseProxies(value) {112 this.useProxies = value113 assign(this, value ? modernProxy : legacyProxy)fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77
lines 114–121why, one step back114 }115 applyPatches(base, patches) {116 // Mutate the base state when a draft is passed.117 if (isDraft(base)) {118 return applyPatches(base, patches)119 }120 // Otherwise, produce a copy of the base state.121 return this.produce(base, draft => applyPatches(draft, patches))feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 122why, one step back122 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 123–158why, one step back123 /** @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 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 159–163why, one step back159 /**160 * @internal161 * Finalize a draft, returning either the unmodified base state or a modified162 * copy of the base state.163 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 164why, one step back164 finalize(draft, path, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 165–167why, one step back165 const state = draft[DRAFT_STATE]166 if (!state) {167 if (Object.isFrozen(draft)) return draftMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 168why, one step back168 return this.finalizeTree(draft, null, scope)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 169why, one step back169 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 170–171why, one step back170 // Never finalize drafts owned by another scope.171 if (state.scope !== scope) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 172–173why, one step back172 return draft173 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 174–176why, one step back174 if (!state.modified) {175 return state.base176 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 177–178why, one step back177 if (!state.finalized) {178 state.finalized = trueMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 179–180why, one step back179 this.finalizeTree(state.draft, path, scope)180feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 181why, one step back181 if (this.onDelete) {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 182–189why, one step back182 // The `assigned` object is unreliable with ES5 drafts.183 if (this.useProxies) {184 const {assigned} = state185 for (const prop in assigned) {186 if (!assigned[prop]) this.onDelete(state, prop)187 }188 } else {189 const {base, copy} = statenit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 190why, one step back190 each(base, prop => {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 191–193why, one step back191 if (!has(copy, prop)) this.onDelete(state, prop)192 })193 }feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 194why, one step back194 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 195–197why, one step back195 if (this.onCopy) {196 this.onCopy(state)197 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 198why, one step back198Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 199–201why, one step back199 // 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) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 202–204why, one step back202 Object.freeze(state.copy)203 }204Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 205–212why, one step back205 if (path && scope.patches) {206 generatePatches(207 state,208 path,209 scope.patches,210 scope.inversePatches211 )212 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 213–219why, one step back213 }214 return state.copy215 }216 /**217 * @internal218 * Finalize all drafts in the given state tree.219 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 220why, one step back220 finalizeTree(root, rootPath, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 221–222why, one step back221 const state = root[DRAFT_STATE]222 if (state) {feat: limited class supportaleclarsonbefore adoption9877d64
lines 223–228why, one step back223 if (!this.useProxies) {224 state.finalizing = true225 state.copy = shallowCopy(state.draft, true)226 state.finalizing = false227 }228 root = state.copyfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 229why, one step back229 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 230why, one step back230Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 231why, one step back231 const needPatches = !!rootPath && !!scope.patchesfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 232why, one step back232 const finalizeProperty = (prop, value, parent) => {fix: throw on circular referencesaleclarsonbefore adoption9c6603e
lines 233–236why, one step back233 if (value === parent) {234 throw Error("Immer forbids circular references")235 }236Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 237–238why, one step back237 // In the `finalizeTree` method, only the `root` object may be a draft.238 const isDraftProp = !!state && parent === rootfeat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 239why, one step back239refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 240why, one step back240 if (isDraft(value)) {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 241–244why, one step back241 const path =242 isDraftProp && needPatches && !state.assigned[prop]243 ? rootPath.concat(prop)244 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 245why, one step back245Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 246–253why, one step back246 // 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 }253feat: limited class supportaleclarsonbefore adoption9877d64
lines 254–261why, one step back254 // 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.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 262why, one step back262 if (isDraftProp && value === state.base[prop]) returnrefactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 263why, one step back263 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 264why, one step back264 // Unchanged draft properties are ignored.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 265why, one step back265 else if (isDraftProp && is(value, state.base[prop])) {feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 266why, one step back266 returnfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 267why, one step back267 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 268–269why, one step back268 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.269 else if (isDraftable(value) && !Object.isFrozen(value)) {nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 270why, one step back270 each(value, finalizeProperty)refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 271–272why, one step back271 }272Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 273–274why, one step back273 if (isDraftProp && this.onAssign) {274 this.onAssign(state, prop, value)feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 275why, one step back275 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 276why, one step back276 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 277why, one step back277nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 278why, one step back278 each(root, finalizeProperty)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 279–281why, one step back279 return root280 }281}