Skip to content
Myr

immer.js

This file

Path

src/immer.js

349 lines · 9.4 KiB · JavaScript

Last changed by

fix ie11Andrey Boldyrevbefore adoptionffd8769

History of this file

Take it

The walk stopped after 200 commits: lines older than 53e9ce8 point at it.

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 1–2why, one step back
1import * as legacyProxy from "./es5"
2import * as modernProxy from "./proxy"

fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77

line 3why, one step back
3import {applyPatches, generatePatches} from "./patches"

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 4why, one step back
4import {

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 5–9why, one step back
5 assign,
6 each,7 has,8 is,9 isDraft,

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

lines 10–12why, one step back
10 isSet,
11 get,12 isMap,

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 13–17why, one step back
13 isDraftable,
14 isEnumerable,15 shallowCopy,16 DRAFT_STATE,17 NOTHING,

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

line 18why, one step back
18 deepFreeze

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 19why, one step back
19} from "./common"

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 20why, one step back
20import {ImmerScope} from "./scope"

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 21why, one step back
21

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 22why, one step back
22function verifyMinified() {}

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 23why, one step back
23

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 24why, one step back
24const configDefaults = {

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

lines 25–28why, one step back
25 useProxies:
26 typeof Proxy !== "undefined" &&27 typeof Proxy.revocable !== "undefined" &&28 typeof Reflect !== "undefined",

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 29–35why, one step back
29 autoFreeze:
30 typeof process !== "undefined"31 ? process.env.NODE_ENV !== "production"32 : verifyMinified.name === "verifyMinified",33 onAssign: null,34 onDelete: null,35 onCopy: null

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 36why, one step back
36}

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 37why, one step back
37

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 38why, one step back
38export class Immer {

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 39–48why, one step back
39 constructor(config) {
40 assign(this, configDefaults, config)41 this.setUseProxies(this.useProxies)42 this.produce = this.produce.bind(this)43 }44 produce(base, recipe, patchListener) {45 // curried invocation46 if (typeof base === "function" && typeof recipe !== "function") {47 const defaultBase = recipe48 recipe = base

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 49why, one step back
49

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 50–54why, one step back
50 const self = this
51 return function curriedProduce(base = defaultBase, ...args) {52 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore53 }54 }

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 55why, one step back
55

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 56–57why, one step back
56 // prettier-ignore
57 {

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

lines 58–64why, one step back
58 if (typeof recipe !== "function") {
59 throw new Error("The first or second argument to `produce` must be a function")60 }61 if (patchListener !== undefined && typeof patchListener !== "function") {62 throw new Error("The third argument to `produce` must be a function or undefined")63 }64 }

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 65why, one step back
65

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

line 66why, one step back
66 let result

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 67why, one step back
67

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 68–80why, one step back
68 // Only plain objects, arrays, and "immerable classes" are drafted.
69 if (isDraftable(base)) {70 const scope = ImmerScope.enter()71 const proxy = this.createProxy(base)72 let hasError = true73 try {74 result = recipe(proxy)75 hasError = false76 } finally {77 // finally instead of catch + rethrow better preserves original stack78 if (hasError) scope.revoke()79 else scope.leave()80 }

fix ie11Andrey Boldyrevbefore adoptionffd8769

line 81why, one step back
81 if (typeof Promise !== "undefined" && result instanceof Promise) {

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 82–96why, one step back
82 return result.then(
83 result => {84 scope.usePatches(patchListener)85 return this.processResult(result, scope)86 },87 error => {88 scope.revoke()89 throw error90 }91 )92 }93 scope.usePatches(patchListener)94 return this.processResult(result, scope)95 } else {96 result = recipe(base)

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

lines 97–100why, one step back
97 if (result === NOTHING) return undefined
98 if (result === undefined) result = base99 this.maybeFreeze(result, true)100 return result

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 101–102why, one step back
101 }
102 }

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

lines 103–118why, one step back
103 produceWithPatches(arg1, arg2, arg3) {
104 if (typeof arg1 === "function") {105 const self = this106 return (state, ...args) =>107 this.produceWithPatches(state, draft => arg1(draft, ...args))108 }109 // non-curried form110 if (arg3)111 throw new Error("A patch listener cannot be passed to produceWithPatches")112 let patches, inversePatches113 const nextState = this.produce(arg1, arg2, (p, ip) => {114 patches = p115 inversePatches = ip116 })117 return [nextState, patches, inversePatches]118 }

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 119–148why, one step back
119 createDraft(base) {
120 if (!isDraftable(base)) {121 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore122 }123 const scope = ImmerScope.enter()124 const proxy = this.createProxy(base)125 proxy[DRAFT_STATE].isManual = true126 scope.leave()127 return proxy128 }129 finishDraft(draft, patchListener) {130 const state = draft && draft[DRAFT_STATE]131 if (!state || !state.isManual) {132 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore133 }134 if (state.finalized) {135 throw new Error("The given draft is already finalized") // prettier-ignore136 }137 const {scope} = state138 scope.usePatches(patchListener)139 return this.processResult(undefined, scope)140 }141 setAutoFreeze(value) {142 this.autoFreeze = value143 }144 setUseProxies(value) {145 this.useProxies = value146 assign(this, value ? modernProxy : legacyProxy)147 }148 applyPatches(base, patches) {

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

lines 149–159why, one step back
149 // If a patch replaces the entire state, take that replacement as base
150 // before applying patches151 let i152 for (i = patches.length - 1; i >= 0; i--) {153 const patch = patches[i]154 if (patch.path.length === 0 && patch.op === "replace") {155 base = patch.value156 break157 }158 }159

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

line 160why, one step back
160 if (isDraft(base)) {

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

line 161why, one step back
161 // N.B: never hits if some patch a replacement, patches are never drafts

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 162–164why, one step back
162 return applyPatches(base, patches)
163 }164 // Otherwise, produce a copy of the base state.

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

lines 165–167why, one step back
165 return this.produce(base, draft =>
166 applyPatches(draft, patches.slice(i + 1))167 )

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 168–181why, one step back
168 }
169 /** @internal */170 processResult(result, scope) {171 const baseDraft = scope.drafts[0]172 const isReplaced = result !== undefined && result !== baseDraft173 this.willFinalize(scope, result, isReplaced)174 if (isReplaced) {175 if (baseDraft[DRAFT_STATE].modified) {176 scope.revoke()177 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore178 }179 if (isDraftable(result)) {180 // Finalize the result in case it contains (or is) a subset of the draft.181 result = this.finalize(result, null, scope)

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

line 182why, one step back
182 this.maybeFreeze(result)

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 183–221why, one step back
183 }
184 if (scope.patches) {185 scope.patches.push({186 op: "replace",187 path: [],188 value: result189 })190 scope.inversePatches.push({191 op: "replace",192 path: [],193 value: baseDraft[DRAFT_STATE].base194 })195 }196 } else {197 // Finalize the base draft.198 result = this.finalize(baseDraft, [], scope)199 }200 scope.revoke()201 if (scope.patches) {202 scope.patchListener(scope.patches, scope.inversePatches)203 }204 return result !== NOTHING ? result : undefined205 }206 /**207 * @internal208 * Finalize a draft, returning either the unmodified base state or a modified209 * copy of the base state.210 */211 finalize(draft, path, scope) {212 const state = draft[DRAFT_STATE]213 if (!state) {214 if (Object.isFrozen(draft)) return draft215 return this.finalizeTree(draft, null, scope)216 }217 // Never finalize drafts owned by another scope.218 if (state.scope !== scope) {219 return draft220 }221 if (!state.modified) {

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

line 222why, one step back
222 this.maybeFreeze(state.base, true)

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 223–227why, one step back
223 return state.base
224 }225 if (!state.finalized) {226 state.finalized = true227 this.finalizeTree(state.draft, path, scope)

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 228why, one step back
228

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 229–247why, one step back
229 // We cannot really delete anything inside of a Set. We can only replace the whole Set.
230 if (this.onDelete && !isSet(state.base)) {231 // The `assigned` object is unreliable with ES5 drafts.232 if (this.useProxies) {233 const {assigned} = state234 each(assigned, (prop, exists) => {235 if (!exists) this.onDelete(state, prop)236 })237 } else {238 // TODO: Figure it out for Maps and Sets if we need to support ES5239 const {base, copy} = state240 each(base, prop => {241 if (!has(copy, prop)) this.onDelete(state, prop)242 })243 }244 }245 if (this.onCopy) {246 this.onCopy(state)247 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 248why, one step back
248

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 249–253why, one step back
249 // At this point, all descendants of `state.copy` have been finalized,
250 // so we can be sure that `scope.canAutoFreeze` is accurate.251 if (this.autoFreeze && scope.canAutoFreeze) {252 Object.freeze(state.copy)253 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 254why, one step back
254

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 255–273why, one step back
255 if (path && scope.patches) {
256 generatePatches(state, path, scope.patches, scope.inversePatches)257 }258 }259 return state.copy260 }261 /**262 * @internal263 * Finalize all drafts in the given state tree.264 */265 finalizeTree(root, rootPath, scope) {266 const state = root[DRAFT_STATE]267 if (state) {268 if (!this.useProxies) {269 // Create the final copy, with added keys and without deleted keys.270 state.copy = shallowCopy(state.draft, true)271 }272 root = state.copy273 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 274why, one step back
274

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 275–279why, one step back
275 const needPatches = !!rootPath && !!scope.patches
276 const finalizeProperty = (prop, value, parent) => {277 if (value === parent) {278 throw Error("Immer forbids circular references")279 }

fix: throw on circular referencesaleclarsonbefore adoption9c6603e

line 280why, one step back
280

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 281–283why, one step back
281 // In the `finalizeTree` method, only the `root` object may be a draft.
282 const isDraftProp = !!state && parent === root283 const isSetMember = isSet(parent)

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 284why, one step back
284

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 285–292why, one step back
285 if (isDraft(value)) {
286 const path =287 isDraftProp &&288 needPatches &&289 !isSetMember && // Set objects are atomic since they have no keys.290 !has(state.assigned, prop) // Skip deep patches for assigned keys.291 ? rootPath.concat(prop)292 : null

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 293why, one step back
293

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 294–296why, one step back
294 // Drafts owned by `scope` are finalized here.
295 value = this.finalize(value, path, scope)296 replace(parent, prop, value)

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 297why, one step back
297

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 298–301why, one step back
298 // Drafts from another scope must prevent auto-freezing.
299 if (isDraft(value)) {300 scope.canAutoFreeze = false301 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 302why, one step back
302

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 303–312why, one step back
303 // Unchanged drafts are never passed to the `onAssign` hook.
304 if (isDraftProp && value === get(state.base, prop)) return305 }306 // Unchanged draft properties are ignored.307 else if (isDraftProp && is(value, get(state.base, prop))) {308 return309 }310 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.311 else if (isDraftable(value) && !Object.isFrozen(value)) {312 each(value, finalizeProperty)

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

line 313why, one step back
313 this.maybeFreeze(value)

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

line 314why, one step back
314 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 315why, one step back
315

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 316–319why, one step back
316 if (isDraftProp && this.onAssign && !isSetMember) {
317 this.onAssign(state, prop, value)318 }319 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 320why, one step back
320

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 321–322why, one step back
321 each(root, finalizeProperty)
322 return root

Merge branch 'master' into v4Michel Weststratebefore adoption741e941

lines 323–328why, one step back
323 }
324 maybeFreeze(value, deep = false) {325 if (this.autoFreeze && !isDraft(value)) {326 if (deep) deepFreeze(value)327 else Object.freeze(value)328 }

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

line 329why, one step back
329 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 330why, one step back
330}

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 331why, one step back
331

nit: minor refactoringAlec Larsonbefore adoptiona2c4754

line 332why, one step back
332function replace(parent, prop, value) {

run prettier with master config before mergingMichel Weststratebefore adoptionae80361

lines 333–348why, one step back
333 if (isMap(parent)) {
334 parent.set(prop, value)335 } else if (isSet(parent)) {336 // In this case, the `prop` is actually a draft.337 parent.delete(prop)338 parent.add(value)339 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {340 // Preserve non-enumerable properties.341 parent[prop] = value342 } else {343 Object.defineProperty(parent, prop, {344 value,345 writable: true,346 configurable: true347 })348 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 349why, one step back
349}