Skip to content
Myr

immer.js

This file

Path

src/immer.js

310 lines · 10.4 KiB · JavaScript

Last changed by

feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5

History of this file

Take it

The walk stopped after 200 commits: lines older than 5360e6c 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: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 12why, one step back
12 isMap,

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 15–16why, one step back
15 NOTHING,
16 isSet

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

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

Merge pull request #249 from aleclarson/patch1Michel Weststratebefore adoption5360e6c

line 19why, one step back
19

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

Merge pull request #249 from aleclarson/patch1Michel Weststratebefore adoption5360e6c

line 21why, one step back
21

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 22–26why, one step back
22const configDefaults = {
23 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",24 autoFreeze:25 typeof process !== "undefined"26 ? process.env.NODE_ENV !== "production"

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

lines 27–30why, one step back
27 : verifyMinified.name === "verifyMinified",
28 onAssign: null,29 onDelete: null,30 onCopy: null

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 31why, one step back
31}

Merge pull request #249 from aleclarson/patch1Michel Weststratebefore adoption5360e6c

line 32why, one step back
32

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 33–43why, one step back
33export class Immer {
34 constructor(config) {35 assign(this, configDefaults, config)36 this.setUseProxies(this.useProxies)37 this.produce = this.produce.bind(this)38 }39 produce(base, recipe, patchListener) {40 // curried invocation41 if (typeof base === "function" && typeof recipe !== "function") {42 const defaultBase = recipe43 recipe = base

Merge pull request #249 from aleclarson/patch1Michel Weststratebefore adoption5360e6c

line 44why, one step back
44

refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04

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

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

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

refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04

line 47why, one step back
47 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 48why, one step back
48 }

Merge pull request #249 from aleclarson/patch1Michel Weststratebefore adoption5360e6c

lines 49–50why, one step back
49 }
50

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 51–52why, one step back
51 // prettier-ignore
52 {

nit: improved error messagesAlec Larsonbefore adoptiona951f40

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 59why, one step back
59 }

Merge pull request #249 from aleclarson/patch1Michel Weststratebefore adoption5360e6c

line 60why, one step back
60

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 61why, one step back
61 let result

nit: dedupe some codealeclarsonbefore adoptionc9e1d98

line 62why, one step back
62

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

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

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 70why, one step back
70 hasError = false

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 71why, one step back
71 } finally {

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 75why, one step back
75 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 94–95why, one step back
94 }
95 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

nit: improved error messagesAlec Larsonbefore adoptiona951f40

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

nit: improved error messagesAlec Larsonbefore adoptiona951f40

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 103–106why, one step back
103 scope.leave()
104 return proxy105 }106 finishDraft(draft, patchListener) {

nit: improved error messagesAlec Larsonbefore adoptiona951f40

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 118–123why, one step back
118 setAutoFreeze(value) {
119 this.autoFreeze = value120 }121 setUseProxies(value) {122 this.useProxies = value123 assign(this, value ? modernProxy : legacyProxy)

fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 132why, one step back
132 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 169–173why, one step back
169 /**
170 * @internal171 * Finalize a draft, returning either the unmodified base state or a modified172 * copy of the base state.173 */

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 179why, one step back
179 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 182–183why, one step back
182 return draft
183 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 184–186why, one step back
184 if (!state.modified) {
185 return state.base186 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

line 191why, one step back
191 // TODO: It won't fire for Sets because they don't use `assigned`. Is it an issue?

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

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

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

lines 193–199why, one step back
193 // The `assigned` object is unreliable with ES5 drafts.
194 if (this.useProxies) {195 const {assigned} = state196 for (const prop in assigned) {197 if (!assigned[prop]) this.onDelete(state, prop)198 }199 } else {

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

line 200why, one step back
200 // TODO: Figure it out for Maps and Sets if we need to support ES5

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

line 201why, one step back
201 const {base, copy} = state

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

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

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

lines 203–205why, one step back
203 if (!has(copy, prop)) this.onDelete(state, prop)
204 })205 }

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 206why, one step back
206 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 207–209why, one step back
207 if (this.onCopy) {
208 this.onCopy(state)209 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 210why, one step back
210

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 214–216why, one step back
214 Object.freeze(state.copy)
215 }216

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 217–224why, one step back
217 if (path && scope.patches) {
218 generatePatches(219 state,220 path,221 scope.patches,222 scope.inversePatches223 )224 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 225–231why, one step back
225 }
226 return state.copy227 }228 /**229 * @internal230 * Finalize all drafts in the given state tree.231 */

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

feat: limited class supportaleclarsonbefore adoption9877d64

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

chore: comments and formattingAlec Larsonbefore adoptionff96173

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

feat: limited class supportaleclarsonbefore adoption9877d64

lines 237–239why, one step back
237 state.copy = shallowCopy(state.draft, true)
238 }239 root = state.copy

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 240why, one step back
240 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 241why, one step back
241

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

fix: throw on circular referencesaleclarsonbefore adoption9c6603e

lines 244–247why, one step back
244 if (value === parent) {
245 throw Error("Immer forbids circular references")246 }247

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 250why, one step back
250

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 252why, one step back
252 const path =

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 253–255why, one step back
253 isDraftProp &&
254 needPatches &&255 !isSet(parent) &&

feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5

line 256why, one step back
256 !has(state.assigned, prop)

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 257–258why, one step back
257 ? rootPath.concat(prop)
258 : null

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 259why, one step back
259

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 260–267why, one step back
260 // Drafts owned by `scope` are finalized here.
261 value = this.finalize(value, path, scope)262263 // Drafts from another scope must prevent auto-freezing.264 if (isDraft(value)) {265 scope.canAutoFreeze = false266 }267

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 268why, one step back
268 setProperty(parent, prop, value)

feat: limited class supportaleclarsonbefore adoption9877d64

lines 269–270why, one step back
269
270 // Unchanged drafts are never passed to the `onAssign` hook.

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

line 271why, one step back
271 // TODO: Add tests and support for Maps and Sets

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 272why, one step back
272 if (isDraftProp && value === state.base[prop]) return

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 273why, one step back
273 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 276why, one step back
276 return

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 277why, one step back
277 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

lines 278–279why, one step back
278 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.
279 else if (isDraftable(value) && !Object.isFrozen(value)) {

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

line 280why, one step back
280 each(value, finalizeProperty)

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

lines 281–282why, one step back
281 }
282

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 285why, one step back
285 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 286why, one step back
286 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 287why, one step back
287

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

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 289why, one step back
289 return root

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 290why, one step back
290 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 291why, one step back
291}

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 292why, one step back
292

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 293–297why, one step back
293function setProperty(parent, prop, value) {
294 // Preserve non-enumerable properties.295 if (Array.isArray(parent) || isEnumerable(parent, prop)) {296 parent[prop] = value297 return

feat: `Map` supportkeenondrumsbefore adoption8276a6c

line 298why, one step back
298 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 299–300why, one step back
299 if (isMap(parent)) {
300 parent.set(prop, value)

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 301–306why, one step back
301 return
302 }303 if (isSet(parent)) {304 // Here prop is a proxied value305 parent.delete(prop)306 parent.add(value)

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 307–309why, one step back
307 return
308 }309 Object.defineProperty(parent, prop, {value})

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 310why, one step back
310}