immer.js
This file
Path
src/immer.js
327 lines · 8.8 KiB · JavaScript
Last changed by
fix: Don't use proxies if Proxy.revocable is not defined. Fixes #435Michel Weststratebefore adoptionc84aa53
History of this fileTake it
The walk stopped after 200 commits: lines older than 7d2f308 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
line 4why, one step back4import {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 5–13why, one step back5 assign,6 each,7 has,8 is,9 isDraft,10 isDraftable,11 isEnumerable,12 shallowCopy,13 DRAFT_STATE,BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581
lines 14–15why, one step back14 NOTHING,15 deepFreezeMerge 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"Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 18why, one step back18feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 19why, one step back19function verifyMinified() {}Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 20why, one step back20feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 21why, one step back21const configDefaults = {fix: Don't use proxies if Proxy.revocable is not defined. Fixes #435Michel Weststratebefore adoptionc84aa53
lines 22–25why, one step back22 useProxies:23 typeof Proxy !== "undefined" &&24 typeof Proxy.revocable !== "undefined" &&25 typeof Reflect !== "undefined",style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 26–32why, one step back26 autoFreeze:27 typeof process !== "undefined"28 ? process.env.NODE_ENV !== "production"29 : verifyMinified.name === "verifyMinified",30 onAssign: null,31 onDelete: null,32 onCopy: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 33why, one step back33}Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 34why, one step back34feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 35why, one step back35export class Immer {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 36–45why, one step back36 constructor(config) {37 assign(this, configDefaults, config)38 this.setUseProxies(this.useProxies)39 this.produce = this.produce.bind(this)40 }41 produce(base, recipe, patchListener) {42 // curried invocation43 if (typeof base === "function" && typeof recipe !== "function") {44 const defaultBase = recipe45 recipe = baseMerge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 46why, one step back46style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 47–51why, one step back47 const self = this48 return function curriedProduce(base = defaultBase, ...args) {49 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore50 }51 }Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 52why, one step back52style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 53–61why, one step back53 // prettier-ignore54 {55 if (typeof recipe !== "function") {56 throw new Error("The first or second argument to `produce` must be a function")57 }58 if (patchListener !== undefined && typeof patchListener !== "function") {59 throw new Error("The third argument to `produce` must be a function or undefined")60 }61 }Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 62why, one step back62style: use tabsuse-tabsbefore adoptiona9c0fd0
line 63why, one step back63 let resultnit: dedupe some codealeclarsonbefore adoptionc9e1d98
line 64why, one step back64style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 65–93why, one step back65 // Only plain objects, arrays, and "immerable classes" are drafted.66 if (isDraftable(base)) {67 const scope = ImmerScope.enter()68 const proxy = this.createProxy(base)69 let hasError = true70 try {71 result = recipe(proxy)72 hasError = false73 } finally {74 // finally instead of catch + rethrow better preserves original stack75 if (hasError) scope.revoke()76 else scope.leave()77 }78 if (result instanceof Promise) {79 return result.then(80 result => {81 scope.usePatches(patchListener)82 return this.processResult(result, scope)83 },84 error => {85 scope.revoke()86 throw error87 }88 )89 }90 scope.usePatches(patchListener)91 return this.processResult(result, scope)92 } else {93 result = recipe(base)BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581
lines 94–97why, one step back94 if (result === NOTHING) return undefined95 if (result === undefined) result = base96 this.maybeFreeze(result, true)97 return resultstyle: use tabsuse-tabsbefore adoptiona9c0fd0
lines 98–99why, one step back98 }99 }Merge pull request #402 from immerjs/produce-with-patchesMichel Weststratebefore adoptiona16deda
lines 100–115why, one step back100 produceWithPatches(arg1, arg2, arg3) {101 if (typeof arg1 === "function") {102 const self = this103 return (state, ...args) =>104 this.produceWithPatches(state, draft => arg1(draft, ...args))105 }106 // non-curried form107 if (arg3)108 throw new Error("A patch listener cannot be passed to produceWithPatches")109 let patches, inversePatches110 const nextState = this.produce(arg1, arg2, (p, ip) => {111 patches = p112 inversePatches = ip113 })114 return [nextState, patches, inversePatches]115 }style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 116–145why, one step back116 createDraft(base) {117 if (!isDraftable(base)) {118 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore119 }120 const scope = ImmerScope.enter()121 const proxy = this.createProxy(base)122 proxy[DRAFT_STATE].isManual = true123 scope.leave()124 return proxy125 }126 finishDraft(draft, patchListener) {127 const state = draft && draft[DRAFT_STATE]128 if (!state || !state.isManual) {129 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore130 }131 if (state.finalized) {132 throw new Error("The given draft is already finalized") // prettier-ignore133 }134 const {scope} = state135 scope.usePatches(patchListener)136 return this.processResult(undefined, scope)137 }138 setAutoFreeze(value) {139 this.autoFreeze = value140 }141 setUseProxies(value) {142 this.useProxies = value143 assign(this, value ? modernProxy : legacyProxy)144 }145 applyPatches(base, patches) {fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e
lines 146–156why, one step back146 // If a patch replaces the entire state, take that replacement as base147 // before applying patches148 let i149 for (i = patches.length - 1; i >= 0; i--) {150 const patch = patches[i]151 if (patch.path.length === 0 && patch.op === "replace") {152 base = patch.value153 break154 }155 }156style: use tabsuse-tabsbefore adoptiona9c0fd0
line 157why, one step back157 if (isDraft(base)) {fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e
line 158why, one step back158 // N.B: never hits if some patch a replacement, patches are never draftsstyle: use tabsuse-tabsbefore adoptiona9c0fd0
lines 159–161why, one step back159 return applyPatches(base, patches)160 }161 // Otherwise, produce a copy of the base state.fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e
lines 162–164why, one step back162 return this.produce(base, draft =>163 applyPatches(draft, patches.slice(i + 1))164 )style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 165–178why, one step back165 }166 /** @internal */167 processResult(result, scope) {168 const baseDraft = scope.drafts[0]169 const isReplaced = result !== undefined && result !== baseDraft170 this.willFinalize(scope, result, isReplaced)171 if (isReplaced) {172 if (baseDraft[DRAFT_STATE].modified) {173 scope.revoke()174 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore175 }176 if (isDraftable(result)) {177 // Finalize the result in case it contains (or is) a subset of the draft.178 result = this.finalize(result, null, scope)BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581
line 179why, one step back179 this.maybeFreeze(result)style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 180–218why, one step back180 }181 if (scope.patches) {182 scope.patches.push({183 op: "replace",184 path: [],185 value: result186 })187 scope.inversePatches.push({188 op: "replace",189 path: [],190 value: baseDraft[DRAFT_STATE].base191 })192 }193 } else {194 // Finalize the base draft.195 result = this.finalize(baseDraft, [], scope)196 }197 scope.revoke()198 if (scope.patches) {199 scope.patchListener(scope.patches, scope.inversePatches)200 }201 return result !== NOTHING ? result : undefined202 }203 /**204 * @internal205 * Finalize a draft, returning either the unmodified base state or a modified206 * copy of the base state.207 */208 finalize(draft, path, scope) {209 const state = draft[DRAFT_STATE]210 if (!state) {211 if (Object.isFrozen(draft)) return draft212 return this.finalizeTree(draft, null, scope)213 }214 // Never finalize drafts owned by another scope.215 if (state.scope !== scope) {216 return draft217 }218 if (!state.modified) {BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581
line 219why, one step back219 this.maybeFreeze(state.base, true)style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 220–224why, one step back220 return state.base221 }222 if (!state.finalized) {223 state.finalized = true224 this.finalizeTree(state.draft, path, scope)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 225why, one step back225style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 226–242why, one step back226 if (this.onDelete) {227 // The `assigned` object is unreliable with ES5 drafts.228 if (this.useProxies) {229 const {assigned} = state230 for (const prop in assigned) {231 if (!assigned[prop]) this.onDelete(state, prop)232 }233 } else {234 const {base, copy} = state235 each(base, prop => {236 if (!has(copy, prop)) this.onDelete(state, prop)237 })238 }239 }240 if (this.onCopy) {241 this.onCopy(state)242 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 243why, one step back243style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 244–248why, one step back244 // At this point, all descendants of `state.copy` have been finalized,245 // so we can be sure that `scope.canAutoFreeze` is accurate.246 if (this.autoFreeze && scope.canAutoFreeze) {247 Object.freeze(state.copy)248 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 249why, one step back249style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 250–268why, one step back250 if (path && scope.patches) {251 generatePatches(state, path, scope.patches, scope.inversePatches)252 }253 }254 return state.copy255 }256 /**257 * @internal258 * Finalize all drafts in the given state tree.259 */260 finalizeTree(root, rootPath, scope) {261 const state = root[DRAFT_STATE]262 if (state) {263 if (!this.useProxies) {264 // Create the final copy, with added keys and without deleted keys.265 state.copy = shallowCopy(state.draft, true)266 }267 root = state.copy268 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 269why, one step back269style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 270–274why, one step back270 const needPatches = !!rootPath && !!scope.patches271 const finalizeProperty = (prop, value, parent) => {272 if (value === parent) {273 throw Error("Immer forbids circular references")274 }fix: throw on circular referencesaleclarsonbefore adoption9c6603e
line 275why, one step back275style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 276–277why, one step back276 // In the `finalizeTree` method, only the `root` object may be a draft.277 const isDraftProp = !!state && parent === rootfeat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 278why, one step back278style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 279–283why, one step back279 if (isDraft(value)) {280 const path =281 isDraftProp && needPatches && !state.assigned[prop]282 ? rootPath.concat(prop)283 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 284why, one step back284style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 285–286why, one step back285 // Drafts owned by `scope` are finalized here.286 value = this.finalize(value, path, scope)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 287why, one step back287style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 288–291why, one step back288 // Drafts from another scope must prevent auto-freezing.289 if (isDraft(value)) {290 scope.canAutoFreeze = false291 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 292why, one step back292style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 293–298why, one step back293 // Preserve non-enumerable properties.294 if (Array.isArray(parent) || isEnumerable(parent, prop)) {295 parent[prop] = value296 } else {297 Object.defineProperty(parent, prop, {value})298 }feat: limited class supportaleclarsonbefore adoption9877d64
line 299why, one step back299style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 300–309why, one step back300 // Unchanged drafts are never passed to the `onAssign` hook.301 if (isDraftProp && value === state.base[prop]) return302 }303 // Unchanged draft properties are ignored.304 else if (isDraftProp && is(value, state.base[prop])) {305 return306 }307 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.308 else if (isDraftable(value) && !Object.isFrozen(value)) {309 each(value, finalizeProperty)BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581
line 310why, one step back310 this.maybeFreeze(value)style: use tabsuse-tabsbefore adoptiona9c0fd0
line 311why, one step back311 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 312why, one step back312style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 313–316why, one step back313 if (isDraftProp && this.onAssign) {314 this.onAssign(state, prop, value)315 }316 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 317why, one step back317style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 318–319why, one step back318 each(root, finalizeProperty)319 return rootBREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581
lines 320–325why, one step back320 }321 maybeFreeze(value, deep = false) {322 if (this.autoFreeze && !isDraft(value)) {323 if (deep) deepFreeze(value)324 else Object.freeze(value)325 }style: use tabsuse-tabsbefore adoptiona9c0fd0
line 326why, one step back326 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 327why, one step back327}