immer.js
This file
Path
src/immer.js
324 lines · 8.7 KiB · JavaScript
Last changed by
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
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 = {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 22–29why, one step back22 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",23 autoFreeze:24 typeof process !== "undefined"25 ? process.env.NODE_ENV !== "production"26 : verifyMinified.name === "verifyMinified",27 onAssign: null,28 onDelete: null,29 onCopy: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 30why, one step back30}Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 31why, one step back31feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 32why, one step back32export class Immer {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 33–42why, one step back33 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 = baseMerge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 43why, one step back43style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 44–48why, one step back44 const self = this45 return function curriedProduce(base = defaultBase, ...args) {46 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore47 }48 }Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 49why, one step back49style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 50–58why, one step back50 // prettier-ignore51 {52 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 }58 }Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 59why, one step back59style: use tabsuse-tabsbefore adoptiona9c0fd0
line 60why, one step back60 let resultnit: dedupe some codealeclarsonbefore adoptionc9e1d98
line 61why, one step back61style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 62–90why, 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 {68 result = recipe(proxy)69 hasError = false70 } finally {71 // finally instead of catch + rethrow better preserves original stack72 if (hasError) scope.revoke()73 else scope.leave()74 }75 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)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 91–94why, one step back91 if (result === NOTHING) return undefined92 if (result === undefined) result = base93 this.maybeFreeze(result, true)94 return resultstyle: use tabsuse-tabsbefore adoptiona9c0fd0
lines 95–96why, one step back95 }96 }Merge pull request #402 from immerjs/produce-with-patchesMichel Weststratebefore adoptiona16deda
lines 97–112why, one step back97 produceWithPatches(arg1, arg2, arg3) {98 if (typeof arg1 === "function") {99 const self = this100 return (state, ...args) =>101 this.produceWithPatches(state, draft => arg1(draft, ...args))102 }103 // non-curried form104 if (arg3)105 throw new Error("A patch listener cannot be passed to produceWithPatches")106 let patches, inversePatches107 const nextState = this.produce(arg1, arg2, (p, ip) => {108 patches = p109 inversePatches = ip110 })111 return [nextState, patches, inversePatches]112 }style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 113–142why, one step back113 createDraft(base) {114 if (!isDraftable(base)) {115 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore116 }117 const scope = ImmerScope.enter()118 const proxy = this.createProxy(base)119 proxy[DRAFT_STATE].isManual = true120 scope.leave()121 return proxy122 }123 finishDraft(draft, patchListener) {124 const state = draft && draft[DRAFT_STATE]125 if (!state || !state.isManual) {126 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore127 }128 if (state.finalized) {129 throw new Error("The given draft is already finalized") // prettier-ignore130 }131 const {scope} = state132 scope.usePatches(patchListener)133 return this.processResult(undefined, scope)134 }135 setAutoFreeze(value) {136 this.autoFreeze = value137 }138 setUseProxies(value) {139 this.useProxies = value140 assign(this, value ? modernProxy : legacyProxy)141 }142 applyPatches(base, patches) {fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e
lines 143–153why, one step back143 // If a patch replaces the entire state, take that replacement as base144 // before applying patches145 let i146 for (i = patches.length - 1; i >= 0; i--) {147 const patch = patches[i]148 if (patch.path.length === 0 && patch.op === "replace") {149 base = patch.value150 break151 }152 }153style: use tabsuse-tabsbefore adoptiona9c0fd0
line 154why, one step back154 if (isDraft(base)) {fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e
line 155why, one step back155 // N.B: never hits if some patch a replacement, patches are never draftsstyle: use tabsuse-tabsbefore adoptiona9c0fd0
lines 156–158why, one step back156 return applyPatches(base, patches)157 }158 // 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 159–161why, one step back159 return this.produce(base, draft =>160 applyPatches(draft, patches.slice(i + 1))161 )style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 162–175why, one step back162 }163 /** @internal */164 processResult(result, scope) {165 const baseDraft = scope.drafts[0]166 const isReplaced = result !== undefined && result !== baseDraft167 this.willFinalize(scope, result, isReplaced)168 if (isReplaced) {169 if (baseDraft[DRAFT_STATE].modified) {170 scope.revoke()171 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore172 }173 if (isDraftable(result)) {174 // Finalize the result in case it contains (or is) a subset of the draft.175 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 176why, one step back176 this.maybeFreeze(result)style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 177–215why, one step back177 }178 if (scope.patches) {179 scope.patches.push({180 op: "replace",181 path: [],182 value: result183 })184 scope.inversePatches.push({185 op: "replace",186 path: [],187 value: baseDraft[DRAFT_STATE].base188 })189 }190 } else {191 // Finalize the base draft.192 result = this.finalize(baseDraft, [], scope)193 }194 scope.revoke()195 if (scope.patches) {196 scope.patchListener(scope.patches, scope.inversePatches)197 }198 return result !== NOTHING ? result : undefined199 }200 /**201 * @internal202 * Finalize a draft, returning either the unmodified base state or a modified203 * copy of the base state.204 */205 finalize(draft, path, scope) {206 const state = draft[DRAFT_STATE]207 if (!state) {208 if (Object.isFrozen(draft)) return draft209 return this.finalizeTree(draft, null, scope)210 }211 // Never finalize drafts owned by another scope.212 if (state.scope !== scope) {213 return draft214 }215 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 216why, one step back216 this.maybeFreeze(state.base, true)style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 217–221why, one step back217 return state.base218 }219 if (!state.finalized) {220 state.finalized = true221 this.finalizeTree(state.draft, path, scope)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 222why, one step back222style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 223–239why, one step back223 if (this.onDelete) {224 // The `assigned` object is unreliable with ES5 drafts.225 if (this.useProxies) {226 const {assigned} = state227 for (const prop in assigned) {228 if (!assigned[prop]) this.onDelete(state, prop)229 }230 } else {231 const {base, copy} = state232 each(base, prop => {233 if (!has(copy, prop)) this.onDelete(state, prop)234 })235 }236 }237 if (this.onCopy) {238 this.onCopy(state)239 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 240why, one step back240style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 241–245why, one step back241 // At this point, all descendants of `state.copy` have been finalized,242 // so we can be sure that `scope.canAutoFreeze` is accurate.243 if (this.autoFreeze && scope.canAutoFreeze) {244 Object.freeze(state.copy)245 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 246why, one step back246style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 247–265why, one step back247 if (path && scope.patches) {248 generatePatches(state, path, scope.patches, scope.inversePatches)249 }250 }251 return state.copy252 }253 /**254 * @internal255 * Finalize all drafts in the given state tree.256 */257 finalizeTree(root, rootPath, scope) {258 const state = root[DRAFT_STATE]259 if (state) {260 if (!this.useProxies) {261 // Create the final copy, with added keys and without deleted keys.262 state.copy = shallowCopy(state.draft, true)263 }264 root = state.copy265 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 266why, one step back266style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 267–271why, one step back267 const needPatches = !!rootPath && !!scope.patches268 const finalizeProperty = (prop, value, parent) => {269 if (value === parent) {270 throw Error("Immer forbids circular references")271 }fix: throw on circular referencesaleclarsonbefore adoption9c6603e
line 272why, one step back272style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 273–274why, one step back273 // In the `finalizeTree` method, only the `root` object may be a draft.274 const isDraftProp = !!state && parent === rootfeat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 275why, one step back275style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 276–280why, one step back276 if (isDraft(value)) {277 const path =278 isDraftProp && needPatches && !state.assigned[prop]279 ? rootPath.concat(prop)280 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 281why, one step back281style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 282–283why, one step back282 // Drafts owned by `scope` are finalized here.283 value = this.finalize(value, path, scope)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 284why, one step back284style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 285–288why, one step back285 // Drafts from another scope must prevent auto-freezing.286 if (isDraft(value)) {287 scope.canAutoFreeze = false288 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 289why, one step back289style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 290–295why, one step back290 // Preserve non-enumerable properties.291 if (Array.isArray(parent) || isEnumerable(parent, prop)) {292 parent[prop] = value293 } else {294 Object.defineProperty(parent, prop, {value})295 }feat: limited class supportaleclarsonbefore adoption9877d64
line 296why, one step back296style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 297–306why, one step back297 // Unchanged drafts are never passed to the `onAssign` hook.298 if (isDraftProp && value === state.base[prop]) return299 }300 // Unchanged draft properties are ignored.301 else if (isDraftProp && is(value, state.base[prop])) {302 return303 }304 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.305 else if (isDraftable(value) && !Object.isFrozen(value)) {306 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 307why, one step back307 this.maybeFreeze(value)style: use tabsuse-tabsbefore adoptiona9c0fd0
line 308why, one step back308 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 309why, one step back309style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 310–313why, one step back310 if (isDraftProp && this.onAssign) {311 this.onAssign(state, prop, value)312 }313 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 314why, one step back314style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 315–316why, one step back315 each(root, finalizeProperty)316 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 317–322why, one step back317 }318 maybeFreeze(value, deep = false) {319 if (this.autoFreeze && !isDraft(value)) {320 if (deep) deepFreeze(value)321 else Object.freeze(value)322 }style: use tabsuse-tabsbefore adoptiona9c0fd0
line 323why, one step back323 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 324why, one step back324}