Skip to content
Myr

immer.js

This file

Path

src/immer.js

288 lines · 9.8 KiB · JavaScript

Last changed by

refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04

History of this file

Take it

The walk stopped after 200 commits: lines older than 0d262e1 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

lines 4–6why, one step back
4import {
5 assign,6 each,

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

line 7why, one step back
7 has,

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 8–10why, one step back
8 is,
9 isDraft,10 isDraftable,

nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419

line 11why, one step back
11 isEnumerable,

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 12–13why, one step back
12 shallowCopy,
13 DRAFT_STATE,

nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419

line 14why, one step back
14 NOTHING

Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1

line 17why, one step back
17

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1

line 19why, one step back
19

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 20–24why, one step back
20const 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 back
25 : verifyMinified.name === "verifyMinified",
26 onAssign: null,27 onDelete: null,28 onCopy: null

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 29why, one step back
29}

Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1

line 30why, one step back
30

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 31–41why, one step back
31export 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 = base

Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1

line 42why, one step back
42

refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04

line 43why, one step back
43 const self = this

feat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298

line 44why, one step back
44 return function curriedProduce(base = defaultBase, ...args) {

refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04

line 45why, one step back
45 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore

feat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298

line 46why, one step back
46 }

Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1

lines 47–48why, one step back
47 }
48

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 49–50why, one step back
49 // prettier-ignore
50 {

nit: improved error messagesAlec Larsonbefore adoptiona951f40

lines 51–56why, one step back
51 if (typeof recipe !== "function") {
52 throw new Error("The first or second argument to `produce` must be a function")53 }54 if (patchListener !== undefined && typeof patchListener !== "function") {55 throw new Error("The third argument to `produce` must be a function or undefined")56 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 57why, one step back
57 }

Fixed issue in the flow type for `nothing`Michel Weststratebefore adoption0d262e1

line 58why, one step back
58

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 59why, one step back
59 let result

nit: dedupe some codealeclarsonbefore adoptionc9e1d98

line 60why, one step back
60

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 61–66why, one step back
61 // Only plain objects, arrays, and "immerable classes" are drafted.
62 if (isDraftable(base)) {63 const scope = ImmerScope.enter()64 const proxy = this.createProxy(base)65 let hasError = true66 try {

feat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298

line 67why, one step back
67 result = recipe(proxy)

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 68why, one step back
68 hasError = false

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 69why, one step back
69 } finally {

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 70–72why, one step back
70 // finally instead of catch + rethrow better preserves original stack
71 if (hasError) scope.revoke()72 else scope.leave()

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 73why, one step back
73 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 74–91why, one step back
74 if (result instanceof Promise) {
75 return result.then(76 result => {77 scope.usePatches(patchListener)78 return this.processResult(result, scope)79 },80 error => {81 scope.revoke()82 throw error83 }84 )85 }86 scope.usePatches(patchListener)87 return this.processResult(result, scope)88 } else {89 result = recipe(base)90 if (result === undefined) return base91 return result !== NOTHING ? result : undefined

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 92–93why, one step back
92 }
93 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 94why, one step back
94 createDraft(base) {

nit: improved error messagesAlec Larsonbefore adoptiona951f40

lines 95–97why, one step back
95 if (!isDraftable(base)) {
96 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore97 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 98–99why, one step back
98 const scope = ImmerScope.enter()
99 const proxy = this.createProxy(base)

nit: improved error messagesAlec Larsonbefore adoptiona951f40

line 100why, one step back
100 proxy[DRAFT_STATE].isManual = true

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 101–104why, one step back
101 scope.leave()
102 return proxy103 }104 finishDraft(draft, patchListener) {

nit: improved error messagesAlec Larsonbefore adoptiona951f40

lines 105–111why, one step back
105 const state = draft && draft[DRAFT_STATE]
106 if (!state || !state.isManual) {107 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore108 }109 if (state.finalized) {110 throw new Error("The given draft is already finalized") // prettier-ignore111 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 112–115why, one step back
112 const {scope} = state
113 scope.usePatches(patchListener)114 return this.processResult(undefined, scope)115 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 116–121why, one step back
116 setAutoFreeze(value) {
117 this.autoFreeze = value118 }119 setUseProxies(value) {120 this.useProxies = value121 assign(this, value ? modernProxy : legacyProxy)

fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77

lines 122–129why, one step back
122 }
123 applyPatches(base, patches) {124 // Mutate the base state when a draft is passed.125 if (isDraft(base)) {126 return applyPatches(base, patches)127 }128 // Otherwise, produce a copy of the base state.129 return this.produce(base, draft => applyPatches(draft, patches))

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 130why, one step back
130 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 131–166why, one step back
131 /** @internal */
132 processResult(result, scope) {133 const baseDraft = scope.drafts[0]134 const isReplaced = result !== undefined && result !== baseDraft135 this.willFinalize(scope, result, isReplaced)136 if (isReplaced) {137 if (baseDraft[DRAFT_STATE].modified) {138 scope.revoke()139 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore140 }141 if (isDraftable(result)) {142 // Finalize the result in case it contains (or is) a subset of the draft.143 result = this.finalize(result, null, scope)144 }145 if (scope.patches) {146 scope.patches.push({147 op: "replace",148 path: [],149 value: result150 })151 scope.inversePatches.push({152 op: "replace",153 path: [],154 value: baseDraft[DRAFT_STATE].base155 })156 }157 } else {158 // Finalize the base draft.159 result = this.finalize(baseDraft, [], scope)160 }161 scope.revoke()162 if (scope.patches) {163 scope.patchListener(scope.patches, scope.inversePatches)164 }165 return result !== NOTHING ? result : undefined166 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 167–171why, one step back
167 /**
168 * @internal169 * Finalize a draft, returning either the unmodified base state or a modified170 * copy of the base state.171 */

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 172why, one step back
172 finalize(draft, path, scope) {

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 173–175why, one step back
173 const state = draft[DRAFT_STATE]
174 if (!state) {175 if (Object.isFrozen(draft)) return draft

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 176why, one step back
176 return this.finalizeTree(draft, null, scope)

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 177why, one step back
177 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 178–179why, one step back
178 // Never finalize drafts owned by another scope.
179 if (state.scope !== scope) {

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 180–181why, one step back
180 return draft
181 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 182–184why, one step back
182 if (!state.modified) {
183 return state.base184 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 185–186why, one step back
185 if (!state.finalized) {
186 state.finalized = true

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 187–188why, one step back
187 this.finalizeTree(state.draft, path, scope)
188

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 189why, one step back
189 if (this.onDelete) {

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

lines 190–197why, one step back
190 // The `assigned` object is unreliable with ES5 drafts.
191 if (this.useProxies) {192 const {assigned} = state193 for (const prop in assigned) {194 if (!assigned[prop]) this.onDelete(state, prop)195 }196 } else {197 const {base, copy} = state

nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419

line 198why, one step back
198 each(base, prop => {

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

lines 199–201why, one step back
199 if (!has(copy, prop)) this.onDelete(state, prop)
200 })201 }

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 202why, one step back
202 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 203–205why, one step back
203 if (this.onCopy) {
204 this.onCopy(state)205 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 206why, one step back
206

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 207–209why, one step back
207 // At this point, all descendants of `state.copy` have been finalized,
208 // so we can be sure that `scope.canAutoFreeze` is accurate.209 if (this.autoFreeze && scope.canAutoFreeze) {

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 210–212why, one step back
210 Object.freeze(state.copy)
211 }212

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 213–220why, one step back
213 if (path && scope.patches) {
214 generatePatches(215 state,216 path,217 scope.patches,218 scope.inversePatches219 )220 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 221–227why, one step back
221 }
222 return state.copy223 }224 /**225 * @internal226 * Finalize all drafts in the given state tree.227 */

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 228why, one step back
228 finalizeTree(root, rootPath, scope) {

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 229–230why, one step back
229 const state = root[DRAFT_STATE]
230 if (state) {

feat: limited class supportaleclarsonbefore adoption9877d64

line 231why, one step back
231 if (!this.useProxies) {

chore: comments and formattingAlec Larsonbefore adoptionff96173

line 232why, one step back
232 // Create the final copy, with added keys and without deleted keys.

feat: limited class supportaleclarsonbefore adoption9877d64

lines 233–235why, one step back
233 state.copy = shallowCopy(state.draft, true)
234 }235 root = state.copy

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 236why, one step back
236 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 237why, one step back
237

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 238why, one step back
238 const needPatches = !!rootPath && !!scope.patches

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 239why, one step back
239 const finalizeProperty = (prop, value, parent) => {

fix: throw on circular referencesaleclarsonbefore adoption9c6603e

lines 240–243why, one step back
240 if (value === parent) {
241 throw Error("Immer forbids circular references")242 }243

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 244–245why, one step back
244 // In the `finalizeTree` method, only the `root` object may be a draft.
245 const isDraftProp = !!state && parent === root

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 246why, one step back
246

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 247why, one step back
247 if (isDraft(value)) {

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 248–251why, one step back
248 const path =
249 isDraftProp && needPatches && !state.assigned[prop]250 ? rootPath.concat(prop)251 : null

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 252why, one step back
252

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 253–260why, one step back
253 // 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 }260

feat: limited class supportaleclarsonbefore adoption9877d64

lines 261–268why, one step back
261 // 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 back
269 if (isDraftProp && value === state.base[prop]) return

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 270why, one step back
270 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 271why, one step back
271 // Unchanged draft properties are ignored.

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 272why, one step back
272 else if (isDraftProp && is(value, state.base[prop])) {

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 273why, one step back
273 return

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 274why, one step back
274 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

lines 275–276why, one step back
275 // 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 back
277 each(value, finalizeProperty)

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

lines 278–279why, one step back
278 }
279

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 280–281why, one step back
280 if (isDraftProp && this.onAssign) {
281 this.onAssign(state, prop, value)

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 282why, one step back
282 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 283why, one step back
283 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 284why, one step back
284

nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419

line 285why, one step back
285 each(root, finalizeProperty)

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 286–288why, one step back
286 return root
287 }288}