feat: rewrote Map and Set implementation, code base cleanup
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fixes #472, #466, #449, #492. Also drops bundle size with ~10%.
authored by Michel Weststrate · committed by Michel Weststrate · parents 98794b8, f4a4701 · Browse files · 20 files·+1624 added−1088 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
20 files+1624 added−1088 removed
- tests:+510 added−55 removed
- other:+1114 added−1033 removed
Provenance
- Commit
1913fe8- Tree
9daf857- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent 1
98794b8- Parent 2
f4a4701
20 files changed+1624 added−1088 removed
modified:__tests__/base.js+177 added-21 removed
186 unmodified lines187 expect(nextState).toBe(baseState)188 })189 190 it("supports iteration", () => {191- const base = [{id: 1, a: 1}, {id: 2, a: 1}]191+ const base = [192+ {id: 1, a: 1},193+ {id: 2, a: 1}194+ ]195 const findById = (collection, id) => {196 for (const item of collection) {197 if (item.id === id) return item198 }189 unmodified lines388 expect(result.get("second").a).toEqual(2)389 })390 391 it("supports 'keys", () => {389- const base = new Map([["first", Symbol()], ["second", Symbol()]])392+ const base = new Map([393+ ["first", Symbol()],394+ ["second", Symbol()]395+ ])396 const result = produce(base, draft => {397 expect([...draft.keys()]).toEqual(["first", "second"])398 draft.set("third", Symbol())399 expect([...draft.keys()]).toEqual(["first", "second", "third"])95 unmodified lines495 496 it("can use 'delete' to remove items", () => {497 const nextState = produce(baseState, s => {498 expect(s.aMap.has("jedi")).toBe(true)493- s.aMap.delete("jedi")499+ expect(s.aMap.delete("jedi")).toBe(true)500 expect(s.aMap.has("jedi")).toBe(false)501 })502 expect(nextState.aMap).not.toBe(baseState.aMap)503 expect(nextState.aMap.size).toBe(baseState.aMap.size - 1)36 unmodified lines540 )541 expect(base.get("first").get("second").prop).toBe("test")542 expect(result.get("first").get("second").prop).toBe("test1")543 })544+545+ it("treats void deletes as no-op", () => {546+ const base = new Map([["x", 1]])547+ const next = produce(base, d => {548+ expect(d.delete("y")).toBe(false)549+ })550+ expect(next).toBe(base)551+ })552+553+ it("revokes map proxies", () => {554+ let m555+ produce(baseState, s => {556+ m = s.aMap557+ })558+ expect(() => m.get("x")).toThrow(559+ "Cannot use a proxy that has been revoked"560+ )561+ expect(() => m.set("x", 3)).toThrow(562+ "Cannot use a proxy that has been revoked"563+ )564+ })565+566+ it("does not draft map keys", () => {567+ // anything else would be terribly confusing568+ const key = {a: 1}569+ const map = new Map([[key, 2]])570+ const next = produce(map, d => {571+ const dKey = Array.from(d.keys())[0]572+ expect(isDraft(dKey)).toBe(false)573+ expect(dKey).toBe(key)574+ dKey.a += 1575+ d.set(dKey, d.get(dKey) + 1)576+ d.set(key, d.get(key) + 1)577+ expect(d.get(key)).toBe(4)578+ expect(key.a).toBe(2)579+ })580+ const entries = Array.from(next.entries())581+ expect(entries).toEqual([[key, 4]])582+ expect(entries[0][0]).toBe(key)583+ expect(entries[0][0].a).toBe(2)584+ })585 })586 587 describe("set drafts", () => {588 it("supports iteration", () => {542- const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])589+ const base = new Set([590+ {id: 1, a: 1},591+ {id: 2, a: 1}592+ ])593 const findById = (set, id) => {594 for (const item of set) {595 if (item.id === id) return item596 }5 unmodified lines602 obj1.a = 2603 obj2.a = 2604 })605 expect(result).not.toBe(base)556- expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))557- expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))606+ expect(base).toEqual(607+ new Set([608+ {id: 1, a: 1},609+ {id: 2, a: 1}610+ ])611+ )612+ expect(result).toEqual(613+ new Set([614+ {id: 1, a: 2},615+ {id: 2, a: 2}616+ ])617+ )618 })619 620 it("supports 'entries'", () => {561- const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])621+ const base = new Set([622+ {id: 1, a: 1},623+ {id: 2, a: 1}624+ ])625 const findById = (set, id) => {626 for (const [item1, item2] of set.entries()) {627 expect(item1).toBe(item2)628 if (item1.id === id) return item16 unmodified lines635 obj1.a = 2636 obj2.a = 2637 })638 expect(result).not.toBe(base)576- expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))577- expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))639+ expect(base).toEqual(640+ new Set([641+ {id: 1, a: 1},642+ {id: 2, a: 1}643+ ])644+ )645+ expect(result).toEqual(646+ new Set([647+ {id: 1, a: 2},648+ {id: 2, a: 2}649+ ])650+ )651 })652 653 it("supports 'values'", () => {581- const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])654+ const base = new Set([655+ {id: 1, a: 1},656+ {id: 2, a: 1}657+ ])658 const findById = (set, id) => {659 for (const item of set.values()) {660 if (item.id === id) return item661 }5 unmodified lines667 obj1.a = 2668 obj2.a = 2669 })670 expect(result).not.toBe(base)595- expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))596- expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))671+ expect(base).toEqual(672+ new Set([673+ {id: 1, a: 1},674+ {id: 2, a: 1}675+ ])676+ )677+ expect(result).toEqual(678+ new Set([679+ {id: 1, a: 2},680+ {id: 2, a: 2}681+ ])682+ )683 })684 685 it("supports 'keys'", () => {600- const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])686+ const base = new Set([687+ {id: 1, a: 1},688+ {id: 2, a: 1}689+ ])690 const findById = (set, id) => {691 for (const item of set.keys()) {692 if (item.id === id) return item693 }5 unmodified lines699 obj1.a = 2700 obj2.a = 2701 })702 expect(result).not.toBe(base)614- expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))615- expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))703+ expect(base).toEqual(704+ new Set([705+ {id: 1, a: 1},706+ {id: 2, a: 1}707+ ])708+ )709+ expect(result).toEqual(710+ new Set([711+ {id: 1, a: 2},712+ {id: 2, a: 2}713+ ])714+ )715 })716 717 it("supports forEach with mutation after reads", () => {619- const base = new Set([{id: 1, a: 1}, {id: 2, a: 2}])718+ const base = new Set([719+ {id: 1, a: 1},720+ {id: 2, a: 2}721+ ])722 const result = produce(base, draft => {723 let sum1 = 0724 draft.forEach(({a}) => {725 sum1 += a6 unmodified lines732 })733 expect(sum2).toBe(23)734 })735 expect(result).not.toBe(base)634- expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 2}]))635- expect(result).toEqual(new Set([{id: 1, a: 11}, {id: 2, a: 12}]))736+ expect(base).toEqual(737+ new Set([738+ {id: 1, a: 1},739+ {id: 2, a: 2}740+ ])741+ )742+ expect(result).toEqual(743+ new Set([744+ {id: 1, a: 11},745+ {id: 2, a: 12}746+ ])747+ )748 })749 750 it("state stays the same if the same item is added", () => {751 const nextState = produce(baseState, s => {28 unmodified lines780 781 it("can use 'delete' to remove items", () => {782 const nextState = produce(baseState, s => {783 expect(s.aSet.has("Luke")).toBe(true)672- s.aSet.delete("Luke")784+ expect(s.aSet.delete("Luke")).toBe(true)785+ expect(s.aSet.delete("Luke")).toBe(false)786 expect(s.aSet.has("Luke")).toBe(false)787 })788 expect(nextState.aSet).not.toBe(baseState.aSet)676- expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)789 expect(baseState.aSet.has("Luke")).toBe(true)790 expect(nextState.aSet.has("Luke")).toBe(false)791+ expect(nextState.aSet.size).toBe(baseState.aSet.size - 1)792 })793 794 it("can use 'clear' to remove items", () => {795 const nextState = produce(baseState, s => {26 unmodified lines822 expect(result).not.toBe(base)823 expect(base).toEqual(new Set([new Set(["Serenity"])]))824 expect(result).toEqual(new Set([new Set(["Serenity", "Firefly"])]))825 })826+827+ it("supports has / delete on elements from the original", () => {828+ const obj = {}829+ const set = new Set([obj])830+ const next = produce(set, d => {831+ expect(d.has(obj)).toBe(true)832+ d.add(3)833+ expect(d.has(obj)).toBe(true)834+ d.delete(obj)835+ expect(d.has(obj)).toBe(false)836+ })837+ expect(next).toEqual(new Set([3]))838+ })839+840+ it("revokes sets", () => {841+ let m842+ produce(baseState, s => {843+ m = s.aSet844+ })845+ expect(() => m.has("x")).toThrow(846+ "Cannot use a proxy that has been revoked"847+ )848+ expect(() => m.add("x")).toThrow(849+ "Cannot use a proxy that has been revoked"850+ )851+ })852 })853 854 it("supports `immerable` symbol on constructor", () => {855 class One {}518 unmodified lines1374 expect(base[0].a).toEqual(1)1375 expect(result[0].a).toEqual(2)1376 })1377 1378+ it("does not draft external data", () => {1379+ const externalData = {x: 3}1380+ const base = {}1381+ const next = produce(base, draft => {1382+ // potentially, we *could* draft external data automatically, but only if those statements are not switched...1383+ draft.y = externalData1384+ draft.y.x += 11385+ externalData.x += 11386+ })1387+ expect(next).toEqual({y: {x: 5}})1388+ expect(externalData.x).toBe(5)1389+ expect(next.y).toBe(externalData)1390+ })1391+1392 autoFreeze &&1393 test("issue #469, state not frozen", () => {1394 const project = produce(1395 {354 unmodified lines1750 const b = {b: 2}1751 const c = {c: 3}1752 const set1 = new Set([a, b])1753 const set2 = new Set([c])1601- const map = new Map([["set1", set1], ["set2", set2]])1754+ const map = new Map([1755+ ["set1", set1],1756+ ["set2", set2]1757+ ])1758 const base = {map}1759 1760 function first(set) {1761 return Array.from(set.values())[0]166 unmodified linesmodified:__tests__/empty.ts+134 added-6 removed
11234567789108910111213141516171819122021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import {produce, produceWithPatches} from "../src"import {produce, produceWithPatches, setUseProxies} from "../src"import {DRAFT_STATE} from "../src/common"
test("empty stub test", () => { expect(true).toBe(true)})
test("delete 7", () => { debugger const [_, p] = produceWithPatches(new Set(["y", 1]), d => { d.delete("y")describe("map set - es5", () => { test("can assign set value", () => { setUseProxies(false)
const baseState = new Map([["x", 1]]) const nextState = produce(baseState, s => { s.set("x", 2) }) expect(baseState.get("x")).toEqual(1) expect(nextState).not.toBe(baseState) expect(nextState.get("x")).toEqual(2) }) expect(p.length).toBe(1)
test("can assign by key", () => { setUseProxies(false)
const baseState = new Map([["x", {a: 1}]]) const nextState = produce(baseState, s => { s.get("x")!.a++ }) expect(nextState.get("x")!.a).toEqual(2) expect(baseState.get("x")!.a).toEqual(1) expect(nextState).not.toBe(baseState) })})
describe("map set - proxy", () => { test("can assign set value", () => { setUseProxies(true)
const baseState = new Map([["x", 1]]) const nextState = produce(baseState, s => { s.set("x", 2) }) expect(baseState.get("x")).toEqual(1) expect(nextState).not.toBe(baseState) expect(nextState.get("x")).toEqual(2) })
test("can assign by key", () => { setUseProxies(true)
const baseState = new Map([["x", {a: 1}]]) const nextState = produce(baseState, s => { s.get("x")!.a++ }) expect(nextState.get("x")!.a).toEqual(2) expect(baseState.get("x")!.a).toEqual(1) expect(nextState).not.toBe(baseState) })
test("deep change bubbles up", () => { setUseProxies(true)
const baseState = createBaseState() const nextState = produce(baseState, s => { s.anObject.nested.yummie = false }) expect(nextState).not.toBe(baseState) expect(nextState.anObject).not.toBe(baseState.anObject) expect(baseState.anObject.nested.yummie).toBe(true) expect(nextState.anObject.nested.yummie).toBe(false) expect(nextState.anArray).toBe(baseState.anArray) })
it("can assign by key", () => { setUseProxies(true) const baseState = createBaseState()
const nextState = produce(baseState, s => { // Map.prototype.set should return the Map itself const res = s.aMap.set("force", true) expect(res).toBe((s.aMap as any)[DRAFT_STATE].draft) }) expect(nextState).not.toBe(baseState) expect(nextState.aMap).not.toBe(baseState.aMap) expect(nextState.aMap.get("force")).toEqual(true) })
it("can use 'delete' to remove items", () => { const baseState = createBaseState()
const nextState = produce(baseState, s => { expect(s.aMap.has("jedi")).toBe(true) expect(s.aMap.delete("jedi")).toBe(true) expect(s.aMap.has("jedi")).toBe(false) }) expect(nextState.aMap).not.toBe(baseState.aMap) expect(nextState.aMap.size).toBe(baseState.aMap.size - 1) expect(baseState.aMap.has("jedi")).toBe(true) expect(nextState.aMap.has("jedi")).toBe(false) })
it("support 'has'", () => { const baseState = createBaseState()
const nextState = produce(baseState, s => { expect(s.aMap.has("newKey")).toBe(false) s.aMap.set("newKey", true) expect(s.aMap.has("newKey")).toBe(true) }) expect(nextState).not.toBe(baseState) expect(nextState.aMap).not.toBe(baseState.aMap) expect(baseState.aMap.has("newKey")).toBe(false) expect(nextState.aMap.has("newKey")).toBe(true) })})
function createBaseState() { const data = { anInstance: new (class {})(), anArray: [3, 2, {c: 3}, 1], aMap: new Map([ ["jedi", {name: "Luke", skill: 10}], ["jediTotal", 42], ["force", "these aren't the droids you're looking for"] ] as any), aSet: new Set([ "Luke", 42, { jedi: "Yoda" } ]), aProp: "hi", anObject: { nested: { yummie: true }, coffee: false } } return data}added:__tests__/map-set.js+197 added
1+"use strict"2+import {Immer, nothing, original, isDraft, immerable} from "../src/index"3+import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/common"4+5+jest.setTimeout(1000)6+7+runBaseTest("proxy (no freeze)", true, false)8+// runBaseTest("proxy (autofreeze)", true, true)9+// runBaseTest("proxy (autofreeze)(patch listener)", true, true, true)10+// runBaseTest("es5 (no freeze)", false, false)11+// runBaseTest("es5 (autofreeze)", false, true)12+// runBaseTest("es5 (autofreeze)(patch listener)", false, true, true)13+14+function runBaseTest(name, useProxies, autoFreeze, useListener) {15+ const listener = useListener ? function() {} : undefined16+ const {produce, produceWithPatches} = createPatchedImmer({17+ useProxies,18+ autoFreeze19+ })20+21+ // When `useListener` is true, append a function to the arguments of every22+ // uncurried `produce` call in every test. This makes tests easier to read.23+ function createPatchedImmer(options) {24+ const immer = new Immer(options)25+26+ const {produce} = immer27+ immer.produce = function(...args) {28+ return typeof args[1] === "function" && args.length < 329+ ? produce(...args, listener)30+ : produce(...args)31+ }32+33+ return immer34+ }35+36+ describe("map issues " + name, () => {37+ test("#472 ", () => {38+ const project = produce(new Map(), draft => {39+ draft.set("bar1", {blocked: false})40+ draft.set("bar2", {blocked: false})41+ })42+43+ // Read before write -- no error44+ produce(project, draft => {45+ const bar1 = draft.get("bar1")46+ const bar2 = draft.get("bar2")47+ bar1.blocked = true48+ bar2.blocked = true49+ })50+51+ // Read/write interleaved -- error52+ produce(project, draft => {53+ const bar1 = draft.get("bar1")54+ bar1.blocked = true55+ const bar2 = draft.get("bar2")56+ bar2.blocked = true // TypeError: "blocked" is read-only57+ })58+ })59+60+ test("#466 - setNoPatches", () => {61+ const obj = {62+ set: new Set()63+ }64+65+ const result = produceWithPatches(obj, draft => {66+ draft.set.add("abc")67+ })68+ expect(result).toEqual([69+ {set: new Set(["abc"])},70+ [{op: "add", path: ["set", 0], value: "abc"}],71+ [{op: "remove", path: ["set", 0], value: "abc"}]72+ ])73+ })74+75+ test("#466 - mapChangeBug ", () => {76+ const obj = {77+ map: new Map([78+ ["a", new Map([["b", true], ["c", true], ["d", true]])],79+ ["b", new Map([["a", true]])],80+ ["c", new Map([["a", true]])],81+ ["d", new Map([["a", true]])]82+ ])83+ }84+ const result = produceWithPatches(obj, draft => {85+ const aMap = draft.map.get("a")86+ aMap.forEach((_, other) => {87+ const otherMap = draft.map.get(other)88+ otherMap.delete("a")89+ })90+ })91+ expect(result).toEqual([92+ {93+ map: new Map([94+ ["a", new Map([["b", true], ["c", true], ["d", true]])],95+ ["b", new Map()],96+ ["c", new Map()],97+ ["d", new Map()]98+ ])99+ },100+ [101+ {102+ op: "remove",103+ path: ["map", "b", "a"]104+ },105+ {106+ op: "remove",107+ path: ["map", "c", "a"]108+ },109+ {110+ op: "remove",111+ path: ["map", "d", "a"]112+ }113+ ],114+ [115+ {116+ op: "add",117+ path: ["map", "b", "a"],118+ value: true119+ },120+ {121+ op: "add",122+ path: ["map", "c", "a"],123+ value: true124+ },125+ {126+ op: "add",127+ path: ["map", "d", "a"],128+ value: true129+ }130+ ]131+ ])132+ })133+134+ test("#466 - mapChangeBug2 ", () => {135+ const obj = {136+ map: new Map([137+ ["a", new Map([["b", true], ["c", true], ["d", true]])],138+ ["b", new Map([["a", true]])],139+ ["c", new Map([["a", true]])],140+ ["d", new Map([["a", true]])]141+ ])142+ }143+ const obj1 = produce(obj, draft => {})144+ const [result, p, ip] = produceWithPatches(obj1, draft => {145+ const aMap = draft.map.get("a")146+ aMap.forEach((_, other) => {147+ const otherMap = draft.map.get(other)148+ otherMap.delete("a")149+ })150+ })151+ expect(result).toEqual(152+ {153+ map: new Map([154+ ["a", new Map([["b", true], ["c", true], ["d", true]])],155+ ["b", new Map([])],156+ ["c", new Map([])],157+ ["d", new Map([])]158+ ])159+ }160+ )161+ expect(p).toEqual(162+ [163+ {164+ op: "remove",165+ path: ["map", "b", "a"]166+ },167+ {168+ op: "remove",169+ path: ["map", "c", "a"]170+ },171+ {172+ op: "remove",173+ path: ["map", "d", "a"]174+ }175+ ])176+ expect(ip).toEqual(177+ [178+ {179+ op: "add",180+ path: ["map", "b", "a"],181+ value: true182+ },183+ {184+ op: "add",185+ path: ["map", "c", "a"],186+ value: true187+ },188+ {189+ op: "add",190+ path: ["map", "d", "a"],191+ value: true192+ }193+ ]194+ )195+ })196+ })197+}modified:__tests__/polyfills.js-27 removed
28 unmodified lines293031323334353637383940414243444546474849505152535455565758593334353612 unmodified lines28 unmodified lines expect(typeof value).toBe("string") })})
describe("Object.assign", () => { const {assign} = common
it("only copies enumerable keys", () => { const src = {a: 1} Object.defineProperty(src, "b", {value: 1}) const dest = {} assign(dest, src) expect(dest.a).toBe(1) expect(dest.b).toBeUndefined() })
it("only copies own properties", () => { const src = Object.create({a: 1}) src.b = 1 const dest = {} assign(dest, src) expect(dest.a).toBeUndefined() expect(dest.b).toBe(1) })
it("can handle null", () => { const res = assign({a: 1, b: 2}, null, {a: 2, c: 2}) expect(res).toEqual({a: 2, b: 2, c: 2}) })})
describe("Reflect.ownKeys", () => { const {ownKeys} = common
// Symbol keys are always last.12 unmodified linesmodified:__tests__/tsconfig.json+2 added-1 removed
123455678{ "include": ["*", "../dist"], "compilerOptions": { "lib": ["es2015"], "strict": true "strict": true, "noUnusedLocals": false }}modified:docs/complex-objects.md+2 added
70 unmodified lines71 72 When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.73 74 Maps and Sets that are produced by Immer will be made artificially immutable. This means that they will throw an exception when trying mutative methods like `set`, `clear` etc. outside a producer.75+76+_Note: The **keys** of a map are never drafted! This is done to avoid confusing semantics and keep keys always referentially equal_modified:docs/pitfalls.md+17 added
8 unmodified lines910111213141516171819202122232425262728298 unmodified lines1. Immer assumes your state to be a unidirectional tree. That is, no object should appear twice in the tree, and there should be no circular references.1. Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`. Also, realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.1. Always try to pull `produce` 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower than `produce(base, d => { for (let x of y) d.push(x)})`1. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistinguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.1. Note that data that comes from the closure, and not from the base state, will never be drafted, even when the data has become part of the new draft:
```javascriptfunction onReceiveTodo(todo) { const nextTodos = produce(todos, draft => { draft.todos[todo.id] = todo // Note, because 'todo' is coming from external, and not from the 'draft', // it isn't draft so the following modification affects the original todo! draft.todos[todo.id].done = true
// The reason for this, is that it means that the behavior of the 2 lines above // is equivalent to code, making this whole process more consistent todo.done = true draft.todos[todo.id] = todo })}```modified:src/common.ts+144 added-182 removed
1-import {Objectish, ObjectishNoSet, ImmerState} from "./types"1+import {2+ Objectish,3+ Drafted,4+ AnyObject,5+ AnyArray,6+ AnyMap,7+ AnySet,8+ ImmerState,9+ ProxyType,10+ Archtype11+} from "./types"12 13 /** Use a class type for `nothing` so its type is unique */14 export class Nothing {15 // This lets us do `Exclude<T, Nothing>`6- // TODO: do this better, use unique symbol instead7- private _: any16+ // @ts-ignore17+ private _!: unique symbol18 }19 20+const hasSymbol = typeof Symbol !== "undefined"21+export const hasMap = typeof Map !== "undefined"22+export const hasSet = typeof Set !== "undefined"23+24 /**25 * The sentinel value returned by producers to replace the draft with undefined.26 */13-export const NOTHING: Nothing =14- typeof Symbol !== "undefined"15- ? Symbol("immer-nothing")16- : ({["immer-nothing"]: true} as any)27+export const NOTHING: Nothing = hasSymbol28+ ? Symbol("immer-nothing")29+ : ({["immer-nothing"]: true} as any)30 31 /**32 * To let Immer treat your class instances as plain immutable objects33 * (albeit with a custom prototype), you must define either an instance property1 unmodified line35 *36 * Otherwise, your class instance will never be drafted, which means it won't be37 * safe to mutate in a produce callback.38 */26-export const DRAFTABLE: unique symbol =27- typeof Symbol !== "undefined" && Symbol.for28- ? Symbol.for("immer-draftable")29- : ("__$immer_draftable" as any)39+export const DRAFTABLE: unique symbol = hasSymbol40+ ? Symbol("immer-draftable")41+ : ("__$immer_draftable" as any)42 31-export const DRAFT_STATE: unique symbol =32- typeof Symbol !== "undefined" && Symbol.for33- ? Symbol.for("immer-state")34- : ("__$immer_state" as any)43+export const DRAFT_STATE: unique symbol = hasSymbol44+ ? Symbol("immer-state")45+ : ("__$immer_state" as any)46 47+export const iteratorSymbol: typeof Symbol.iterator = hasSymbol48+ ? Symbol.iterator49+ : ("@@iterator" as any)50+51 /** Returns true if the given value is an Immer draft */52 export function isDraft(value: any): boolean {53 return !!value && !!value[DRAFT_STATE]54 }2 unmodified lines57 export function isDraftable(value: any): boolean {58 if (!value) return false59 return (60 isPlainObject(value) ||61+ Array.isArray(value) ||62 !!value[DRAFTABLE] ||63 !!value.constructor[DRAFTABLE] ||64 isMap(value) ||65 isSet(value)66 )67 }68 53-export function isPlainObject(value): boolean {69+export function isPlainObject(value: any): boolean {70 if (!value || typeof value !== "object") return false55- if (Array.isArray(value)) return true71 const proto = Object.getPrototypeOf(value)72 return !proto || proto === Object.prototype73 }74 75 /** Get the underlying object that is represented by the given draft */61-export function original<T>(value: T): T | undefined {76+export function original<T>(value: Drafted<T>): T | undefined {77 if (value && value[DRAFT_STATE]) {63- return value[DRAFT_STATE].base78+ return value[DRAFT_STATE].base as any79 }80 // otherwise return undefined81 }82 68-// We use Maps as `drafts` for Sets, not Objects69-// See proxy.js70-export function assignSet(target: Map<any, any>, override) {71- override.forEach(value => {72- // When we add new drafts we have to remove their originals if present73- const prev = original(value)74- if (prev) target.delete(prev)75- // @ts-ignore TODO investigate76- target.add(value)77- })78- return target79-}80-81-// We use Maps as `drafts` for Maps, not Objects82-// See proxy.js83-export function assignMap(target: Map<any, any>, override: Map<any, any>) {84- override.forEach((value, key) => target.set(key, value))85- return target86-}87-88-export const assign =89- Object.assign ||90- ((target, ...overrides) => {91- overrides.forEach(override => {92- if (typeof override === "object" && override !== null)93- Object.keys(override).forEach(key => (target[key] = override[key]))94- })95- return target96- })97-98-export const ownKeys: (target) => PropertyKey[] =83+export const ownKeys: (target: AnyObject) => PropertyKey[] =84 typeof Reflect !== "undefined" && Reflect.ownKeys85 ? Reflect.ownKeys86 : typeof Object.getOwnPropertySymbols !== "undefined"87 ? obj =>103- Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(104- obj105- ) as any)106- : Object.getOwnPropertyNames88+ Object.getOwnPropertyNames(obj).concat(89+ Object.getOwnPropertySymbols(obj) as any90+ )91+ : /* istanbul ignore next */ Object.getOwnPropertyNames92 108-export function shallowCopy<T extends Objectish>(109- base: T,110- invokeGetters?: boolean111-): T112-export function shallowCopy(base, invokeGetters = false) {113- if (Array.isArray(base)) return base.slice()114- if (isMap(base)) return new Map(base)115- if (isSet(base)) return new Set(base)116- const clone = Object.create(Object.getPrototypeOf(base))117- ownKeys(base).forEach(key => {118- if (key === DRAFT_STATE) {119- return // Never copy over draft state.120- }121- const desc = Object.getOwnPropertyDescriptor(base, key)!122- let {value} = desc123- if (desc.get) {124- if (!invokeGetters) {125- throw new Error("Immer drafts cannot have computed properties")126- }127- value = desc.get.call(base)128- }129- if (desc.enumerable) {130- clone[key] = value131- } else {132- Object.defineProperty(clone, key, {133- value,134- writable: true,135- configurable: true136- })137- }138- })139- return clone140-}141-93 export function each<T extends Objectish>(94 obj: T,144- iter: (key: PropertyKey, value: any, source: T) => void145-)146-export function each(obj, iter) {147- if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {148- obj.forEach((entry, index) => iter(index, entry, obj))149- } else {95+ iter: (key: string | number, value: any, source: T) => void96+): void97+export function each(obj: any, iter: any) {98+ if (getArchtype(obj) === Archtype.Object) {99 ownKeys(obj).forEach(key => iter(key, obj[key], obj))100+ } else {101+ obj.forEach((entry: any, index: any) => iter(index, entry, obj))102 }103 }104 154-export function isEnumerable(base: {}, prop: PropertyKey): boolean {105+export function isEnumerable(base: AnyObject, prop: PropertyKey): boolean {106 const desc = Object.getOwnPropertyDescriptor(base, prop)107 return desc && desc.enumerable ? true : false108 }109 159-export function has(thing: ObjectishNoSet, prop: PropertyKey): boolean {160- return isMap(thing)110+export function getArchtype(thing: any): Archtype {111+ /* istanbul ignore next */112+ if (!thing) die()113+ if (thing[DRAFT_STATE]) {114+ switch ((thing as Drafted)[DRAFT_STATE].type) {115+ case ProxyType.ES5Object:116+ case ProxyType.ProxyObject:117+ return Archtype.Object118+ case ProxyType.ES5Array:119+ case ProxyType.ProxyArray:120+ return Archtype.Array121+ case ProxyType.Map:122+ return Archtype.Map123+ case ProxyType.Set:124+ return Archtype.Set125+ }126+ }127+ return Array.isArray(thing)128+ ? Archtype.Array129+ : isMap(thing)130+ ? Archtype.Map131+ : isSet(thing)132+ ? Archtype.Set133+ : Archtype.Object134+}135+136+export function has(thing: any, prop: PropertyKey): boolean {137+ return getArchtype(thing) === Archtype.Map138 ? thing.has(prop)139 : Object.prototype.hasOwnProperty.call(thing, prop)140 }141 165-export function get(thing: ObjectishNoSet, prop: PropertyKey) {166- return isMap(thing) ? thing.get(prop) : thing[prop]142+export function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {143+ // @ts-ignore144+ return getArchtype(thing) === Archtype.Map ? thing.get(prop) : thing[prop]145 }146 147+export function set(thing: any, propOrOldValue: PropertyKey, value: any) {148+ switch (getArchtype(thing)) {149+ case Archtype.Map:150+ thing.set(propOrOldValue, value)151+ break152+ case Archtype.Set:153+ thing.delete(propOrOldValue)154+ thing.add(value)155+ break156+ default:157+ thing[propOrOldValue] = value158+ }159+}160+169-export function is(x, y): boolean {161+export function is(x: any, y: any): boolean {162 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js163 if (x === y) {164 return x !== 0 || 1 / x === 1 / y165 } else {166 return x !== x && y !== y167 }168 }169 178-export const hasSymbol = typeof Symbol !== "undefined"179-180-export const hasMap = typeof Map !== "undefined"181-182-export function isMap(target): target is Map<any, any> {170+export function isMap(target: any): target is AnyMap {171 return hasMap && target instanceof Map172 }173 186-export const hasSet = typeof Set !== "undefined"187-188-export function isSet(target): target is Set<any> {174+export function isSet(target: any): target is AnySet {175 return hasSet && target instanceof Set176 }177 192-export function makeIterable(next: () => {done: boolean; value: any}) {193- let self194- return (self = {195- [Symbol.iterator]: () => self,196- next197- })178+export function latest(state: ImmerState): any {179+ return state.copy || state.base180 }181 200-/** Map.prototype.values _-or-_ Map.prototype.entries */201-export function iterateMapValues(state, prop, receiver) {202- const isEntries = prop !== "values"203- return () => {204- const iterator = latest(state)[Symbol.iterator]()205- return makeIterable(() => {206- const result = iterator.next()207- if (!result.done) {208- const [key] = result.value209- const value = receiver.get(key)210- result.value = isEntries ? [key, value] : value211- }212- return result213- })214- }215-}216-217-export function makeIterateSetValues(createProxy) {218- function iterateSetValues(state, prop?) {219- const isEntries = prop === "entries"220- return () => {221- const iterator = latest(state)[Symbol.iterator]()222- return makeIterable(() => {223- const result = iterator.next()224- if (!result.done) {225- const value = wrapSetValue(state, result.value)226- result.value = isEntries ? [value, value] : value227- }228- return result229- })182+export function shallowCopy<T extends AnyObject | AnyArray>(183+ base: T,184+ invokeGetters?: boolean185+): T186+export function shallowCopy(base: any, invokeGetters = false) {187+ if (Array.isArray(base)) return base.slice()188+ const clone = Object.create(Object.getPrototypeOf(base))189+ ownKeys(base).forEach(key => {190+ if (key === DRAFT_STATE) {191+ return // Never copy over draft state.192 }231- }232-233- function wrapSetValue(state, value) {234- const key = original(value) || value235- let draft = state.drafts.get(key)236- if (!draft) {237- if (state.finalized || !isDraftable(value) || state.finalizing) {238- return value193+ const desc = Object.getOwnPropertyDescriptor(base, key)!194+ let {value} = desc195+ if (desc.get) {196+ if (!invokeGetters) {197+ throw new Error("Immer drafts cannot have computed properties")198 }240- draft = createProxy(value, state)241- state.drafts.set(key, draft)242- if (state.modified) {243- state.copy.add(draft)244- }199+ value = desc.get.call(base)200 }246- return draft247- }248-249- return iterateSetValues201+ if (desc.enumerable) {202+ clone[key] = value203+ } else {204+ Object.defineProperty(clone, key, {205+ value,206+ writable: true,207+ configurable: true208+ })209+ }210+ })211+ return clone212 }213 252-function latest<T = any>(state: ImmerState<T>): T {253- return state.copy || state.base254-}255-256-export function clone<T extends Objectish>(obj: T): T257-export function clone(obj) {258- if (!isDraftable(obj)) return obj259- if (Array.isArray(obj)) return obj.map(clone)260- if (isMap(obj)) return new Map(obj)261- if (isSet(obj)) return new Set(obj)262- const cloned = Object.create(Object.getPrototypeOf(obj))263- for (const key in obj) cloned[key] = clone(obj[key])264- return cloned265-}266-267-export function freeze<T extends Objectish>(268- obj: T,269- deep: boolean = false270-): void {214+export function freeze(obj: any, deep: boolean): void {215 if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) return272- if (isSet(obj)) {216+ const type = getArchtype(obj)217+ if (type === Archtype.Set) {218 obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any274- } else if (isMap(obj)) {219+ } else if (type === Archtype.Map) {220 obj.set = obj.clear = obj.delete = dontMutateFrozenCollections as any221 }222 Object.freeze(obj)223 if (deep) each(obj, (_, value) => freeze(value, true))1 unmodified line225 226 function dontMutateFrozenCollections() {227 throw new Error("This object has been frozen and should not be mutated")228 }229+230+export function createHiddenProperty(231+ target: AnyObject,232+ prop: PropertyKey,233+ value: any234+) {235+ Object.defineProperty(target, prop, {236+ value: value,237+ enumerable: false,238+ writable: true239+ })240+}241+242+/* istanbul ignore next */243+export function die(): never {244+ throw new Error("Illegal state, please file a bug")245+}modified:src/es5.ts+94 added-283 removed
4 unmodified lines5 is,6 isDraft,7 isDraftable,8 isEnumerable,9- isMap,10- isSet,11- hasSymbol,9 shallowCopy,10 DRAFT_STATE,14- iterateMapValues,15- makeIterable,16- makeIterateSetValues11+ latest,12+ createHiddenProperty13 } from "./common"14+15 import {ImmerScope} from "./scope"19-import {ImmerState} from "./types"16+import {17+ ImmerState,18+ Drafted,19+ AnyObject,20+ Objectish,21+ ImmerBaseState,22+ AnyArray,23+ ProxyType24+} from "./types"25+import {MapState} from "./map"26+import {SetState} from "./set"27 21-interface ES5Draft {22- [DRAFT_STATE]: ES5State23-}24-25-// TODO: merge with ImmerState?26-interface ES5State<T = any> {27- scope: ImmerScope28- modified: boolean28+interface ES5BaseState extends ImmerBaseState {29 finalizing: boolean30- finalized: boolean31- assigned: Map<any, any> | {[key: string]: any}32- parent: ES5State30+ assigned: {[key: string]: any}31+ parent?: ImmerState33- base: T34- draft: T & ES5Draft35- drafts: Map<any, any> | null36- copy: T | null37- revoke()32 revoked: boolean33 }34 35+export interface ES5ObjectState extends ES5BaseState {36+ type: ProxyType.ES5Object37+ draft: Drafted<AnyObject, ES5ObjectState>38+ base: AnyObject39+ copy: AnyObject | null40+}41+42+export interface ES5ArrayState extends ES5BaseState {43+ type: ProxyType.ES5Array44+ draft: Drafted<AnyObject, ES5ArrayState>45+ base: AnyArray46+ copy: AnyArray | null47+}48+49+type ES5State = ES5ArrayState | ES5ObjectState50+41-export function willFinalize(51+export function willFinalizeES5(52 scope: ImmerScope,53 result: any,54 isReplaced: boolean55 ) {12 unmodified lines68 markChangesSweep(scope.drafts)69 }70 }71 62-export function createProxy<T>(base: T, parent: ES5State): ES5Draft {72+export function createES5Proxy<T>(73+ base: T,74+ parent?: ImmerState75+): Drafted<T, ES5ObjectState | ES5ArrayState> {76 const isArray = Array.isArray(base)77 const draft = clonePotentialDraft(base)78 66- if (isMap(base)) {67- proxyMap(draft)68- } else if (isSet(base)) {69- proxySet(draft)70- } else {71- each(draft, prop => {72- proxyProperty(draft, prop, isArray || isEnumerable(base, prop))73- })79+ each(draft, prop => {80+ proxyProperty(draft, prop, isArray || isEnumerable(base, prop))81+ })74- }82 76- // See "proxy.js" for property documentation.77- const scope = parent ? parent.scope : ImmerScope.current!78- const state: ES5State<T> = {79- scope,83+ const state: ES5ObjectState | ES5ArrayState = {84+ type: isArray ? ProxyType.ES5Array : (ProxyType.ES5Object as any),85+ scope: parent ? parent.scope : ImmerScope.current!,86 modified: false,81- finalizing: false, // es5 only87+ finalizing: false,88 finalized: false,83- assigned: isMap(base) ? new Map() : {},89+ assigned: {},90 parent,91 base,92 draft,87- drafts: isSet(base) ? new Map() : null,93 copy: null,89- revoke,90- revoked: false // es5 only94+ revoked: false,95+ isManual: false96 }97 98 createHiddenProperty(draft, DRAFT_STATE, state)94- scope.drafts!.push(draft)99 return draft100 }101 98-function revoke(this: ES5State) {99- this.revoked = true100-}101-102-function latest(state) {103- return state.copy || state.base104-}105-102 // Access a property without creating an Immer draft.107-function peek(draft, prop) {103+function peek(draft: Drafted, prop: PropertyKey) {104 const state = draft[DRAFT_STATE]105 if (state && !state.finalizing) {106 state.finalizing = true107 const value = draft[prop]2 unmodified lines110 }111 return draft[prop]112 }113 118-function get(state, prop) {114+function get(state: ES5State, prop: string | number) {115 assertUnrevoked(state)116 const value = peek(latest(state), prop)117 if (state.finalizing) return value118 // Create a draft if the value is unmodified.119 if (value === peek(state.base, prop) && isDraftable(value)) {120 prepareCopy(state)121+ // @ts-ignore125- return (state.copy[prop] = createProxy(value, state))122+ return (state.copy![prop] = state.scope.immer.createProxy(value, state))123 }124 return value125 }126 130-function set(state, prop, value) {127+function set(state: ES5State, prop: string | number, value: any) {128 assertUnrevoked(state)129 state.assigned[prop] = true130 if (!state.modified) {131 if (is(value, peek(latest(state), prop))) return135- markChanged(state)132+ markChangedES5(state)133 prepareCopy(state)134 }135+ // @ts-ignore138- state.copy[prop] = value136+ state.copy![prop] = value137 }138 141-function markChanged(state) {139+export function markChangedES5(state: ImmerState) {140 if (!state.modified) {141 state.modified = true144- if (state.parent) markChanged(state.parent)142+ if (state.parent) markChangedES5(state.parent)143 }144 }145 148-function prepareCopy(state) {146+function prepareCopy(state: ES5State) {147 if (!state.copy) state.copy = clonePotentialDraft(state.base)148 }149 152-function clonePotentialDraft(base) {153- const state = base && base[DRAFT_STATE]150+function clonePotentialDraft(base: Objectish) {151+ const state = base && (base as any)[DRAFT_STATE]152 if (state) {153 state.finalizing = true154 const draft = shallowCopy(state.draft, true)155 state.finalizing = false3 unmodified lines159 }160 161 // property descriptors are recycled to make sure we don't create a get and set closure per property,162 // but share them all instead165-const descriptors = {}163+const descriptors: {[prop: string]: PropertyDescriptor} = {}164 167-function proxyProperty(draft, prop, enumerable) {165+function proxyProperty(166+ draft: Drafted<any, ES5State>,167+ prop: string | number,168+ enumerable: boolean169+) {170 let desc = descriptors[prop]171 if (desc) {172 desc.enumerable = enumerable173 } else {174 descriptors[prop] = desc = {175 configurable: true,176 enumerable,175- get() {177+ get(this: any) {178 return get(this[DRAFT_STATE], prop)179 },178- set(value) {180+ set(this: any, value) {181 set(this[DRAFT_STATE], prop, value)182 }183 }184 }185 Object.defineProperty(draft, prop, desc)186 }187 186-function proxyMap(target) {187- Object.defineProperties(target, mapTraps)188-189- if (hasSymbol) {190- Object.defineProperty(191- target,192- Symbol.iterator,193- // @ts-ignore194- proxyMethod(iterateMapValues) //TODO: , Symbol.iterator)195- )196- }197-}198-199-const mapTraps = finalizeTraps({200- size: state => latest(state).size,201- has: state => key => latest(state).has(key),202- set: state => (key, value) => {203- if (latest(state).get(key) !== value) {204- prepareCopy(state)205- markChanged(state)206- state.assigned.set(key, true)207- state.copy.set(key, value)208- }209- return state.draft210- },211- delete: state => key => {212- prepareCopy(state)213- markChanged(state)214- state.assigned.set(key, false)215- state.copy.delete(key)216- return false217- },218- clear: state => () => {219- if (!state.copy) {220- prepareCopy(state)221- }222- markChanged(state)223- state.assigned = new Map()224- for (const key of latest(state).keys()) {225- state.assigned.set(key, false)226- }227- return state.copy.clear()228- },229- forEach: (state, key, reciever) => cb => {230- latest(state).forEach((value, key, map) => {231- cb(reciever.get(key), key, map)232- })233- },234- get: state => key => {235- const value = latest(state).get(key)236-237- if (state.finalizing || state.finalized || !isDraftable(value)) {238- return value239- }240-241- if (value !== state.base.get(key)) {242- return value243- }244- const draft = createProxy(value, state)245- prepareCopy(state)246- state.copy.set(key, draft)247- return draft248- },249- keys: state => () => latest(state).keys(),250- values: iterateMapValues,251- entries: iterateMapValues252-})253-254-function proxySet(target) {255- Object.defineProperties(target, setTraps)256-257- if (hasSymbol) {258- Object.defineProperty(259- target,260- Symbol.iterator,261- // @ts-ignore262- proxyMethod(iterateSetValues) //TODO: , Symbol.iterator)263- )264- }265-}266-267-const iterateSetValues = makeIterateSetValues(createProxy)268-269-const setTraps = finalizeTraps({270- size: state => {271- return latest(state).size272- },273- add: state => value => {274- if (!latest(state).has(value)) {275- markChanged(state)276- if (!state.copy) {277- prepareCopy(state)278- }279- state.copy.add(value)280- }281- return state.draft282- },283- delete: state => value => {284- markChanged(state)285- if (!state.copy) {286- prepareCopy(state)287- }288- return state.copy.delete(value)289- },290- has: state => key => {291- return latest(state).has(key)292- },293- clear: state => () => {294- markChanged(state)295- if (!state.copy) {296- prepareCopy(state)297- }298- return state.copy.clear()299- },300- keys: iterateSetValues,301- entries: iterateSetValues,302- values: iterateSetValues,303- forEach: state => (cb, thisArg) => {304- const iterator = iterateSetValues(state)()305- let result = iterator.next()306- while (!result.done) {307- cb.call(thisArg, result.value, result.value, state.draft)308- result = iterator.next()309- }310- }311-})312-313-function finalizeTraps(traps) {314- return Object.keys(traps).reduce(function(acc, key) {315- const builder = key === "size" ? proxyAttr : proxyMethod316- acc[key] = builder(traps[key], key)317- return acc318- }, {})319-}320-321-function proxyAttr(fn) {322- return {323- get() {324- const state = this[DRAFT_STATE]325- assertUnrevoked(state)326- return fn(state)327- }328- }329-}330-331-function proxyMethod(trap, key) {332- return {333- get() {334- return function(this: ES5Draft, ...args) {335- const state = this[DRAFT_STATE]336- assertUnrevoked(state)337- return trap(state, key, state.draft)(...args)338- }339- }340- }341-}342-343-function assertUnrevoked(state) {188+export function assertUnrevoked(state: ES5State | MapState | SetState) {189 if (state.revoked === true)190 throw new Error(191 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +192 JSON.stringify(latest(state))193 )194 }195 196 // This looks expensive, but only proxies are visited, and only objects without known changes are scanned.352-function markChangesSweep(drafts) {197+function markChangesSweep(drafts: Drafted<any, ImmerState>[]) {198 // The natural order of drafts in the `scope` array is based on when they199 // were accessed. By processing drafts in reverse natural order, we have a200 // better chance of processing leaf nodes first. When a leaf node is known to201 // have changed, we can avoid any traversal of its ancestor nodes.202 for (let i = drafts.length - 1; i >= 0; i--) {203 const state = drafts[i][DRAFT_STATE]204 if (!state.modified) {360- if (Array.isArray(state.base)) {361- if (hasArrayChanges(state)) markChanged(state)362- } else if (isMap(state.base)) {363- if (hasMapChanges(state)) markChanged(state)364- } else if (isSet(state.base)) {365- if (hasSetChanges(state)) markChanged(state)366- } else if (hasObjectChanges(state)) {367- markChanged(state)205+ switch (state.type) {206+ case ProxyType.ES5Array:207+ if (hasArrayChanges(state)) markChangedES5(state)208+ break209+ case ProxyType.ES5Object:210+ if (hasObjectChanges(state)) markChangedES5(state)211+ break212 }213 }214 }215 }216 373-function markChangesRecursively(object) {217+function markChangesRecursively(object: any) {218 if (!object || typeof object !== "object") return219 const state = object[DRAFT_STATE]220 if (!state) return377- const {base, draft, assigned} = state378- if (!Array.isArray(object)) {221+ const {base, draft, assigned, type} = state222+ if (type === ProxyType.ES5Object) {223 // Look for added keys.380- Object.keys(draft).forEach(key => {224+ // TODO: looks quite duplicate to hasObjectChanges,225+ // probably there is a faster way to detect changes, as sweep + recurse seems to do some226+ // unnecessary work.227+ // also: probably we can store the information we detect here, to speed up tree finalization!228+ each(draft, key => {229+ if ((key as any) === DRAFT_STATE) return230 // The `undefined` check is a fast path for pre-existing keys.231 if (base[key] === undefined && !has(base, key)) {232 assigned[key] = true384- markChanged(state)233+ markChangedES5(state)234 } else if (!assigned[key]) {235 // Only untouched properties trigger recursion.236 markChangesRecursively(draft[key])237 }238 })239 // Look for removed keys.391- Object.keys(base).forEach(key => {240+ each(base, key => {241 // The `undefined` check is a fast path for pre-existing keys.242 if (draft[key] === undefined && !has(draft, key)) {243 assigned[key] = false395- markChanged(state)244+ markChangedES5(state)245 }246 })398- } else if (hasArrayChanges(state)) {399- markChanged(state)247+ } else if (type === ProxyType.ES5Array && hasArrayChanges(state)) {248+ markChangedES5(state)249 assigned.length = true250 if (draft.length < base.length) {251 for (let i = draft.length; i < base.length; i++) assigned[i] = false252 } else {5 unmodified lines258 }259 }260 }261 413-function hasObjectChanges(state) {262+function hasObjectChanges(state: ES5ObjectState) {263 const {base, draft} = state264 265 // Search for added keys and changed keys. Start at the back, because266 // non-numeric keys are ordered by time of definition on the object.20 unmodified lines287 // Compare key count to determine if keys were deleted.288 return keys.length !== Object.keys(base).length289 }290 442-function hasArrayChanges(state) {291+function hasArrayChanges(state: ES5ArrayState) {292 const {draft} = state293 if (draft.length !== state.base.length) return true294 // See #116295 // If we first shorten the length, our array interceptors will be removed.7 unmodified lines303 if (descriptor && !descriptor.get) return true304 // For all other cases, we don't have to compare, as they would have been picked up by the index setters305 return false306 }458-459-function hasMapChanges(state) {460- const {base, draft} = state461-462- if (base.size !== draft.size) return true463-464- // IE11 supports only forEach iteration465- let hasChanges = false466- draft.forEach(function(value, key) {467- if (!hasChanges) {468- hasChanges = isDraftable(value) ? value.modified : value !== base.get(key)469- }470- })471- return hasChanges472-}473-474-function hasSetChanges(state) {475- const {base, draft} = state476-477- if (base.size !== draft.size) return true478-479- // IE11 supports only forEach iteration480- let hasChanges = false481- draft.forEach(function(value, key) {482- if (!hasChanges) {483- hasChanges = isDraftable(value) ? value.modified : !base.has(key)484- }485- })486- return hasChanges487-}488-489-function createHiddenProperty(target, prop, value) {490- Object.defineProperty(target, prop, {491- value: value,492- enumerable: false,493- writable: true494- })495-}added:src/finalize.ts+203 added
1+import {Immer} from "./immer"2+import {ImmerState, Drafted, ProxyType} from "./types"3+import {ImmerScope} from "./scope"4+import {5+ isSet,6+ has,7+ is,8+ get,9+ each,10+ DRAFT_STATE,11+ NOTHING,12+ freeze,13+ shallowCopy,14+ set15+} from "./common"16+import {isDraft, isDraftable} from "./index"17+import {SetState} from "./set"18+import {generatePatches, PatchPath} from "./patches"19+20+export function processResult(immer: Immer, result: any, scope: ImmerScope) {21+ const baseDraft = scope.drafts![0]22+ const isReplaced = result !== undefined && result !== baseDraft23+ immer.willFinalize(scope, result, isReplaced)24+ if (isReplaced) {25+ if (baseDraft[DRAFT_STATE].modified) {26+ scope.revoke()27+ throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore28+ }29+ if (isDraftable(result)) {30+ // Finalize the result in case it contains (or is) a subset of the draft.31+ result = finalize(immer, result, scope)32+ maybeFreeze(immer, result)33+ }34+ if (scope.patches) {35+ scope.patches.push({36+ op: "replace",37+ path: [],38+ value: result39+ })40+ scope.inversePatches!.push({41+ op: "replace",42+ path: [],43+ value: baseDraft[DRAFT_STATE].base44+ })45+ }46+ } else {47+ // Finalize the base draft.48+ result = finalize(immer, baseDraft, scope, [])49+ }50+ scope.revoke()51+ if (scope.patches) {52+ scope.patchListener!(scope.patches, scope.inversePatches!)53+ }54+ return result !== NOTHING ? result : undefined55+}56+57+function finalize(58+ immer: Immer,59+ draft: Drafted,60+ scope: ImmerScope,61+ path?: PatchPath62+) {63+ const state = draft[DRAFT_STATE]64+ if (!state) {65+ if (Object.isFrozen(draft)) return draft66+ return finalizeTree(immer, draft, scope)67+ }68+ // Never finalize drafts owned by another scope.69+ if (state.scope !== scope) {70+ return draft71+ }72+ if (!state.modified) {73+ maybeFreeze(immer, state.base, true)74+ return state.base75+ }76+ if (!state.finalized) {77+ state.finalized = true78+ finalizeTree(immer, state.draft, scope, path)79+80+ // We cannot really delete anything inside of a Set. We can only replace the whole Set.81+ if (immer.onDelete && state.type !== ProxyType.Set) {82+ // The `assigned` object is unreliable with ES5 drafts.83+ if (immer.useProxies) {84+ const {assigned} = state85+ each(assigned, (prop, exists) => {86+ if (!exists) immer.onDelete!(state, prop as any)87+ })88+ } else {89+ const {base, copy} = state90+ each(base, prop => {91+ if (!has(copy, prop)) immer.onDelete!(state, prop as any)92+ })93+ }94+ }95+ if (immer.onCopy) {96+ immer.onCopy(state)97+ }98+99+ // At this point, all descendants of `state.copy` have been finalized,100+ // so we can be sure that `scope.canAutoFreeze` is accurate.101+ if (immer.autoFreeze && scope.canAutoFreeze) {102+ freeze(state.copy, false)103+ }104+105+ if (path && scope.patches) {106+ generatePatches(state, path, scope.patches, scope.inversePatches!)107+ }108+ }109+ return state.copy110+}111+112+function finalizeTree(113+ immer: Immer,114+ root: Drafted,115+ scope: ImmerScope,116+ rootPath?: PatchPath117+) {118+ const state = root[DRAFT_STATE]119+ if (state) {120+ if (121+ state.type === ProxyType.ES5Object ||122+ state.type === ProxyType.ES5Array123+ ) {124+ // Create the final copy, with added keys and without deleted keys.125+ state.copy = shallowCopy(state.draft, true)126+ }127+ root = state.copy128+ }129+ each(root, (key, value) =>130+ finalizeProperty(immer, scope, root, state, root, key, value, rootPath)131+ )132+ return root133+}134+135+function finalizeProperty(136+ immer: Immer,137+ scope: ImmerScope,138+ root: Drafted,139+ rootState: ImmerState,140+ parentValue: Drafted,141+ prop: string | number,142+ childValue: any,143+ rootPath?: PatchPath144+) {145+ if (childValue === parentValue) {146+ throw Error("Immer forbids circular references")147+ }148+149+ // In the `finalizeTree` method, only the `root` object may be a draft.150+ const isDraftProp = !!rootState && parentValue === root151+ const isSetMember = isSet(parentValue)152+153+ if (isDraft(childValue)) {154+ const path =155+ rootPath &&156+ isDraftProp &&157+ !isSetMember && // Set objects are atomic since they have no keys.158+ !has((rootState as Exclude<ImmerState, SetState>).assigned!, prop) // Skip deep patches for assigned keys.159+ ? rootPath!.concat(prop)160+ : undefined161+162+ // Drafts owned by `scope` are finalized here.163+ childValue = finalize(immer, childValue, scope, path)164+ set(parentValue, prop, childValue)165+166+ // Drafts from another scope must prevent auto-freezing.167+ if (isDraft(childValue)) {168+ scope.canAutoFreeze = false169+ }170+ }171+ // Unchanged draft properties are ignored.172+ else if (isDraftProp && is(childValue, get(rootState.base, prop))) {173+ return174+ }175+ // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.176+ // TODO: the recursion over here looks weird, shouldn't non-draft stuff have it's own recursion?177+ // especially the passing on of root and rootState doesn't make sense...178+ else if (isDraftable(childValue) && !Object.isFrozen(childValue)) {179+ each(childValue, (key, grandChild) =>180+ finalizeProperty(181+ immer,182+ scope,183+ root,184+ rootState,185+ childValue,186+ key,187+ grandChild,188+ rootPath189+ )190+ )191+ maybeFreeze(immer, childValue)192+ }193+194+ if (isDraftProp && immer.onAssign && !isSetMember) {195+ immer.onAssign(rootState, prop, childValue)196+ }197+}198+199+export function maybeFreeze(immer: Immer, value: any, deep = false) {200+ if (immer.autoFreeze && !isDraft(value)) {201+ freeze(value, deep)202+ }203+}modified:src/immer.ts+82 added-223 removed
1-import * as legacyProxy from "./es5"2-import * as modernProxy from "./proxy"3-import {applyPatches, generatePatches} from "./patches"1+import {createES5Proxy, willFinalizeES5, markChangedES5} from "./es5"2+import {createProxy, markChanged} from "./proxy"3+4+import {applyPatches} from "./patches"5 import {5- assign,6 each,7- has,8- is,7 isDraft,8 isSet,11- get,9 isMap,10 isDraftable,14- isEnumerable,15- shallowCopy,11 DRAFT_STATE,12 NOTHING,18- freeze13+ die14 } from "./common"15 import {ImmerScope} from "./scope"21-import {ImmerState, IProduce, IProduceWithPatches, Objectish, PatchListener, Draft, Patch} from "./types"16+import {17+ ImmerState,18+ IProduce,19+ IProduceWithPatches,20+ Objectish,21+ PatchListener,22+ Draft,23+ Patch,24+ Drafted25+} from "./types"26+import {proxyMap} from "./map"27+import {proxySet} from "./set"28+import {processResult, maybeFreeze} from "./finalize"29 30+/* istanbul ignore next */31 function verifyMinified() {}32 33 const configDefaults = {34 useProxies:2 unmodified lines37 typeof Reflect !== "undefined",38 autoFreeze:39 typeof process !== "undefined"40 ? process.env.NODE_ENV !== "production"41+ : /* istanbul ignore next */33- : verifyMinified.name === "verifyMinified",42+ verifyMinified.name === "verifyMinified",43 onAssign: null,44 onDelete: null,45 onCopy: null37-}46+} as const47 48 interface ProducersFns {49 produce: IProduce50 produceWithPatches: IProduceWithPatches1 unmodified line52 53 export class Immer implements ProducersFns {54 useProxies: boolean = false55 autoFreeze: boolean = false47- onAssign?: (48- state: ImmerState,49- prop: string | number,50- value: unknown51- ) => void56+ onAssign?: (state: ImmerState, prop: string | number, value: unknown) => void57 onDelete?: (state: ImmerState, prop: string | number) => void58 onCopy?: (state: ImmerState) => void54- createProxy!:<T>(value: T) => T;55- willFinalize!: (scope: ImmerScope, thing: any, isReplaced: boolean) => void;59 60 constructor(config?: {61 useProxies?: boolean62 autoFreeze?: boolean4 unmodified lines67 ) => void68 onDelete?: (state: ImmerState, prop: string | number) => void69 onCopy?: (state: ImmerState) => void70 }) {68- assign(this, configDefaults, config)71+ each(configDefaults, (key, value) => {72+ // @ts-ignore73+ this[key] = config?.[key] ?? value74+ })75 this.setUseProxies(this.useProxies)76 this.produce = this.produce.bind(this)77 this.produceWithPatches = this.produceWithPatches.bind(this)78 }16 unmodified lines95 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified96 * @param {Function} patchListener - optional function that will be called with all the patches produced here97 * @returns {any} a new state, or the initial state if nothing was modified98 */93- produce(base, recipe?, patchListener?) {99+ produce(base: any, recipe?: any, patchListener?: any) {100 // curried invocation101 if (typeof base === "function" && typeof recipe !== "function") {102 const defaultBase = recipe103 recipe = base104 105 const self = this100- return function curriedProduce(this: any, base = defaultBase, ...args) {101- return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore106+ return function curriedProduce(107+ this: any,108+ base = defaultBase,109+ ...args: any[]110+ ) {111+ return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore112 }113 }114 115 // prettier-ignore9 unmodified lines125 let result126 127 // Only plain objects, arrays, and "immerable classes" are drafted.128 if (isDraftable(base)) {119- const scope = ImmerScope.enter()120- const proxy = this.createProxy(base)129+ const scope = ImmerScope.enter(this)130+ const proxy = this.createProxy(base, undefined)131 let hasError = true132 try {133 result = recipe(proxy)134 hasError = false5 unmodified lines140 if (typeof Promise !== "undefined" && result instanceof Promise) {141 return result.then(142 result => {143 scope.usePatches(patchListener)134- return this.processResult(result, scope)144+ return processResult(this, result, scope)145 },146 error => {147 scope.revoke()148 throw error149 }150 )151 }152 scope.usePatches(patchListener)143- return this.processResult(result, scope)153+ return processResult(this, result, scope)154 } else {155 result = recipe(base)156 if (result === NOTHING) return undefined157 if (result === undefined) result = base148- this.maybeFreeze(result, true)158+ maybeFreeze(this, result, true)159 return result160 }161 }162 153- produceWithPatches(arg1, arg2?, arg3?): any {163+ produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {164 if (typeof arg1 === "function") {155- const self = this156- return (state, ...args) =>157- this.produceWithPatches(state, draft => arg1(draft, ...args))165+ return (state: any, ...args: any[]) =>166+ this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))167 }168 // non-curried form160- if (arg3)161- throw new Error("A patch listener cannot be passed to produceWithPatches")162- let patches, inversePatches163- const nextState = this.produce(arg1, arg2, (p, ip) => {169+ /* istanbul ignore next */170+ if (arg3) die()171+ let patches: Patch[], inversePatches: Patch[]172+ const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {173 patches = p174 inversePatches = ip175 })167- return [nextState, patches, inversePatches]176+ return [nextState, patches!, inversePatches!]177 }178 170- createDraft<T extends Objectish>(base: T): Draft<T> {179+ createDraft<T extends Objectish>(base: T): Drafted<T> {180 if (!isDraftable(base)) {181 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore182 }174- const scope = ImmerScope.enter()175- const proxy = this.createProxy(base)183+ const scope = ImmerScope.enter(this)184+ const proxy = this.createProxy(base, undefined)185 proxy[DRAFT_STATE].isManual = true186 scope.leave()178- return proxy as any187+ return proxy188 }189 181- finishDraft<D extends Draft<any>>(draft: D, patchListener: PatchListener): D extends Draft<infer T> ? T : never {182- const state = draft && draft[DRAFT_STATE]190+ finishDraft<D extends Draft<any>>(191+ draft: D,192+ patchListener?: PatchListener193+ ): D extends Draft<infer T> ? T : never {194+ const state: ImmerState = draft && draft[DRAFT_STATE]195 if (!state || !state.isManual) {196 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore197 }198 if (state.finalized) {199 throw new Error("The given draft is already finalized") // prettier-ignore200 }201 const {scope} = state202 scope.usePatches(patchListener)191- return this.processResult(undefined, scope)203+ return processResult(this, undefined, scope)204 }205 206 /**207 * Pass true to automatically freeze all copies created by Immer.11 unmodified lines219 * By default, feature detection is used, so calling this is rarely necessary.220 */221 setUseProxies(value: boolean) {222 this.useProxies = value211- assign(this, value ? modernProxy : legacyProxy)223 }224 225 applyPatches(base: Objectish, patches: Patch[]) {226 // If a patch replaces the entire state, take that replacement as base227 // before applying patches217- let i228+ let i: number229 for (i = patches.length - 1; i >= 0; i--) {230 const patch = patches[i]231 if (patch.path.length === 0 && patch.op === "replace") {232 base = patch.value5 unmodified lines238 // N.B: never hits if some patch a replacement, patches are never drafts239 return applyPatches(base, patches)240 }241 // Otherwise, produce a copy of the base state.231- return this.produce(base, draft =>242+ return this.produce(base, (draft: Drafted) =>243 applyPatches(draft, patches.slice(i + 1))244 )245 }246 236- /** @internal */237- processResult(result: any, scope: ImmerScope) {238- const baseDraft = scope.drafts![0]239- const isReplaced = result !== undefined && result !== baseDraft240- this.willFinalize(scope, result, isReplaced)241- if (isReplaced) {242- if (baseDraft[DRAFT_STATE].modified) {243- scope.revoke()244- throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore245- }246- if (isDraftable(result)) {247- // Finalize the result in case it contains (or is) a subset of the draft.248- result = this.finalize(result, null, scope)249- this.maybeFreeze(result)250- }251- if (scope.patches) {252- scope.patches.push({253- op: "replace",254- path: [],255- value: result256- })257- scope.inversePatches!.push({258- op: "replace",259- path: [],260- value: baseDraft[DRAFT_STATE].base261- })262- }263- } else {264- // Finalize the base draft.265- result = this.finalize(baseDraft, [], scope)266- }267- scope.revoke()268- if (scope.patches) {269- scope.patchListener!(scope.patches, scope.inversePatches!)270- }271- return result !== NOTHING ? result : undefined247+ createProxy<T extends Objectish>(248+ value: T,249+ parent?: ImmerState250+ ): Drafted<T, ImmerState> {251+ // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft252+ const draft: Drafted = isMap(value)253+ ? proxyMap(value, parent)254+ : isSet(value)255+ ? proxySet(value, parent)256+ : this.useProxies257+ ? createProxy(value, parent)258+ : createES5Proxy(value, parent)259+260+ const scope = parent ? parent.scope : ImmerScope.current!261+ scope.drafts.push(draft)262+ return draft263 }264 274- /**275- * @internal276- * Finalize a draft, returning either the unmodified base state or a modified277- * copy of the base state.278- */279- finalize(draft: any, path: string[] | null, scope: ImmerScope) {280- const state = draft[DRAFT_STATE]281- if (!state) {282- if (Object.isFrozen(draft)) return draft283- return this.finalizeTree(draft, null, scope)284- }285- // Never finalize drafts owned by another scope.286- if (state.scope !== scope) {287- return draft288- }289- if (!state.modified) {290- this.maybeFreeze(state.base, true)291- return state.base292- }293- if (!state.finalized) {294- state.finalized = true295- this.finalizeTree(state.draft, path, scope)296-297- // We cannot really delete anything inside of a Set. We can only replace the whole Set.298- if (this.onDelete && !isSet(state.base)) {299- // The `assigned` object is unreliable with ES5 drafts.300- if (this.useProxies) {301- const {assigned} = state302- each(assigned, (prop, exists) => {303- if (!exists) this.onDelete?.(state, prop as any)304- })305- } else {306- // TODO: Figure it out for Maps and Sets if we need to support ES5307- const {base, copy} = state308- each(base, prop => {309- if (!has(copy, prop)) this.onDelete?.(state, prop as any)310- })311- }312- }313- if (this.onCopy) {314- this.onCopy(state)315- }316-317- // At this point, all descendants of `state.copy` have been finalized,318- // so we can be sure that `scope.canAutoFreeze` is accurate.319- if (this.autoFreeze && scope.canAutoFreeze) {320- freeze(state.copy, false)321- }322-323- if (path && scope.patches) {324- generatePatches(state, path, scope.patches, scope.inversePatches!)325- }326- }327- return state.copy265+ willFinalize(scope: ImmerScope, thing: any, isReplaced: boolean) {266+ if (!this.useProxies) willFinalizeES5(scope, thing, isReplaced)267 }268 330- /**331- * @internal332- * Finalize all drafts in the given state tree.333- */334- finalizeTree(root: any, rootPath: string[] | null, scope: ImmerScope) {335- const state = root[DRAFT_STATE]336- if (state) {337- if (!this.useProxies) {338- // Create the final copy, with added keys and without deleted keys.339- state.copy = shallowCopy(state.draft, true)340- }341- root = state.copy269+ markChanged(state: ImmerState) {270+ if (this.useProxies) {271+ markChanged(state)272+ } else {273+ markChangedES5(state)274 }343-344- const needPatches = !!rootPath && !!scope.patches345- const finalizeProperty = (prop, value, parent) => {346- if (value === parent) {347- throw Error("Immer forbids circular references")348- }349-350- // In the `finalizeTree` method, only the `root` object may be a draft.351- const isDraftProp = !!state && parent === root352- const isSetMember = isSet(parent)353-354- if (isDraft(value)) {355- const path =356- isDraftProp &&357- needPatches &&358- !isSetMember && // Set objects are atomic since they have no keys.359- !has(state.assigned, prop) // Skip deep patches for assigned keys.360- ? rootPath!.concat(prop)361- : null362-363- // Drafts owned by `scope` are finalized here.364- value = this.finalize(value, path, scope)365- replace(parent, prop, value)366-367- // Drafts from another scope must prevent auto-freezing.368- if (isDraft(value)) {369- scope.canAutoFreeze = false370- }371-372- // Unchanged drafts are never passed to the `onAssign` hook.373- if (isDraftProp && value === get(state.base, prop)) return374- }375- // Unchanged draft properties are ignored.376- else if (isDraftProp && is(value, get(state.base, prop))) {377- return378- }379- // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.380- else if (isDraftable(value) && !Object.isFrozen(value)) {381- each(value, finalizeProperty)382- this.maybeFreeze(value)383- }384-385- if (isDraftProp && this.onAssign && !isSetMember) {386- this.onAssign(state, prop, value)387- }388- }389-390- each(root, finalizeProperty)391- return root275 }393- maybeFreeze(value, deep = false) {394- if (this.autoFreeze && !isDraft(value)) {395- freeze(value, deep)396- }397- }276 }399-400-function replace(parent, prop, value) {401- if (isMap(parent)) {402- parent.set(prop, value)403- } else if (isSet(parent)) {404- // In this case, the `prop` is actually a draft.405- parent.delete(prop)406- parent.add(value)407- } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {408- // Preserve non-enumerable properties.409- parent[prop] = value410- } else {411- Object.defineProperty(parent, prop, {412- value,413- writable: true,414- configurable: true415- })416- }417-}added:src/map.ts+163 added
1+import {isDraftable, DRAFT_STATE, latest, iteratorSymbol} from "./common"2+3+import {ImmerScope} from "./scope"4+import {AnyMap, Drafted, ImmerState, ImmerBaseState, ProxyType} from "./types"5+import {assertUnrevoked} from "./es5"6+7+export interface MapState extends ImmerBaseState {8+ type: ProxyType.Map9+ copy: AnyMap | undefined10+ assigned: Map<any, boolean> | undefined11+ base: AnyMap12+ revoked: boolean13+ draft: Drafted<AnyMap, MapState>14+}15+16+// Make sure DraftMap declarion doesn't die if Map is not avialable...17+/* istanbul ignore next */18+const MapBase: MapConstructor =19+ typeof Map !== "undefined" ? Map : (function FakeMap() {} as any)20+21+export class DraftMap<K, V> extends MapBase implements Map<K, V> {22+ [DRAFT_STATE]: MapState23+ constructor(target: AnyMap, parent?: ImmerState) {24+ super()25+ this[DRAFT_STATE] = {26+ type: ProxyType.Map,27+ parent,28+ scope: parent ? parent.scope : ImmerScope.current!,29+ modified: false,30+ finalized: false,31+ copy: undefined,32+ assigned: undefined,33+ base: target,34+ draft: this,35+ isManual: false,36+ revoked: false37+ }38+ }39+40+ get size(): number {41+ return latest(this[DRAFT_STATE]).size42+ }43+44+ has(key: K): boolean {45+ return latest(this[DRAFT_STATE]).has(key)46+ }47+48+ set(key: K, value: V): this {49+ const state = this[DRAFT_STATE]50+ assertUnrevoked(state)51+ if (latest(state).get(key) !== value) {52+ prepareCopy(state)53+ state.scope.immer.markChanged(state)54+ state.assigned!.set(key, true)55+ state.copy!.set(key, value)56+ state.assigned!.set(key, true)57+ }58+ return this59+ }60+61+ delete(key: K): boolean {62+ if (!this.has(key)) {63+ return false64+ }65+66+ const state = this[DRAFT_STATE]67+ assertUnrevoked(state)68+ prepareCopy(state)69+ state.scope.immer.markChanged(state)70+ state.assigned!.set(key, false)71+ state.copy!.delete(key)72+ return true73+ }74+75+ clear() {76+ const state = this[DRAFT_STATE]77+ assertUnrevoked(state)78+ prepareCopy(state)79+ state.scope.immer.markChanged(state)80+ state.assigned = new Map()81+ for (const key of latest(state).keys()) {82+ state.assigned.set(key, false)83+ }84+ return state.copy!.clear()85+ }86+87+ forEach(cb: (value: V, key: K, self: this) => void, thisArg?: any) {88+ const state = this[DRAFT_STATE]89+ latest(state).forEach((_value: V, key: K, _map: this) => {90+ cb.call(thisArg, this.get(key), key, this)91+ })92+ }93+94+ get(key: K): V {95+ const state = this[DRAFT_STATE]96+ assertUnrevoked(state)97+ const value = latest(state).get(key)98+ if (state.finalized || !isDraftable(value)) {99+ return value100+ }101+ if (value !== state.base.get(key)) {102+ return value // either already drafted or reassigned103+ }104+ // despite what it looks, this creates a draft only once, see above condition105+ const draft = state.scope.immer.createProxy(value, state)106+ prepareCopy(state)107+ state.copy!.set(key, draft)108+ return draft109+ }110+111+ keys(): IterableIterator<K> {112+ return latest(this[DRAFT_STATE]).keys()113+ }114+115+ values(): IterableIterator<V> {116+ const iterator = this.keys()117+ return {118+ [iteratorSymbol]: () => this.values(),119+ next: () => {120+ const r = iterator.next()121+ /* istanbul ignore next */122+ if (r.done) return r123+ const value = this.get(r.value)124+ return {125+ done: false,126+ value127+ }128+ }129+ } as any130+ }131+132+ entries(): IterableIterator<[K, V]> {133+ const iterator = this.keys()134+ return {135+ [iteratorSymbol]: () => this.entries(),136+ next: () => {137+ const r = iterator.next()138+ /* istanbul ignore next */139+ if (r.done) return r140+ const value = this.get(r.value)141+ return {142+ done: false,143+ value: [r.value, value]144+ }145+ }146+ } as any147+ }148+149+ [iteratorSymbol]() {150+ return this.entries()151+ }152+}153+154+export function proxyMap(target: AnyMap, parent?: ImmerState) {155+ return new DraftMap(target, parent)156+}157+158+function prepareCopy(state: MapState) {159+ if (!state.copy) {160+ state.assigned = new Map()161+ state.copy = new Map(state.base)162+ }163+}modified:src/patches.ts+98 added-55 removed
1-import {get, each, isMap, isSet, has, clone} from "./common"2-import {Patch, ImmerState} from "./types"1+import {get, each, isMap, has, die, getArchtype} from "./common"2+import {Patch, ImmerState, ProxyType, Archtype} from "./types"3+import {SetState} from "./set"4+import {ES5ArrayState, ES5ObjectState} from "./es5"5+import {ProxyArrayState, ProxyObjectState} from "./proxy"6+import {MapState} from "./map"7 8+export type PatchPath = (string | number)[]9+10 export function generatePatches(11 state: ImmerState,6- basePath: (string | number)[],12+ basePath: PatchPath,13 patches: Patch[],14 inversePatches: Patch[]9-) {10- const generatePatchesFn = Array.isArray(state.base)11- ? generateArrayPatches12- : isSet(state.base)13- ? generateSetPatches14- : generatePatchesFromAssigned15-16- generatePatchesFn(state, basePath, patches, inversePatches)15+): void {16+ switch (state.type) {17+ case ProxyType.ProxyObject:18+ case ProxyType.ES5Object:19+ case ProxyType.Map:20+ return generatePatchesFromAssigned(21+ state,22+ basePath,23+ patches,24+ inversePatches25+ )26+ case ProxyType.ES5Array:27+ case ProxyType.ProxyArray:28+ return generateArrayPatches(state, basePath, patches, inversePatches)29+ case ProxyType.Set:30+ return generateSetPatches(31+ (state as any) as SetState,32+ basePath,33+ patches,34+ inversePatches35+ )36+ }37 }38 39 function generateArrayPatches(20- state: ImmerState,21- basePath: (string | number)[],40+ state: ES5ArrayState | ProxyArrayState,41+ basePath: PatchPath,42 patches: Patch[],43 inversePatches: Patch[]44 ) {25- let {base, copy, assigned} = state45+ let {base, assigned, copy} = state46+ /* istanbul ignore next */47+ if (!copy) die()48 49 // Reduce complexity by ensuring `base` is never longer.50 if (copy.length < base.length) {51+ // @ts-ignore52 ;[base, copy] = [copy, base]53 ;[patches, inversePatches] = [inversePatches, patches]54 }55 46 unmodified lines102 }103 104 // This is used for both Map objects and normal objects.105 function generatePatchesFromAssigned(83- state: ImmerState,84- basePath: (number | string)[],106+ state: MapState | ES5ObjectState | ProxyObjectState,107+ basePath: PatchPath,108 patches: Patch[],109 inversePatches: Patch[]110 ) {111 const {base, copy} = state89- each(state.assigned, (key, assignedValue) => {112+ each(state.assigned!, (key, assignedValue) => {113 const origValue = get(base, key)91- const value = get(copy, key)114+ const value = get(copy!, key)115 const op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add"116 if (origValue === value && op === "replace") return117 const path = basePath.concat(key as any)118 patches.push(op === "remove" ? {op, path} : {op, path, value})7 unmodified lines126 })127 }128 129 function generateSetPatches(107- state: ImmerState,108- basePath: (number | string)[],130+ state: SetState,131+ basePath: PatchPath,132 patches: Patch[],133 inversePatches: Patch[]134 ) {135 let {base, copy} = state136 137 let i = 0138 base.forEach(value => {116- if (!copy.has(value)) {139+ if (!copy!.has(value)) {140 const path = basePath.concat([i])141 patches.push({142 op: "remove",143 path,7 unmodified lines151 }152 i++153 })154 i = 0132- copy.forEach(value => {155+ copy!.forEach(value => {156 if (!base.has(value)) {157 const path = basePath.concat([i])158 patches.push({159 op: "add",13 unmodified lines173 export function applyPatches<T>(draft: T, patches: Patch[]): T {174 patches.forEach(patch => {175 const {path, op} = patch176 154- if (!path.length) throw new Error("Illegal state")177+ /* istanbul ignore next */178+ if (!path.length) die()179 156- let base = draft180+ let base: any = draft181 for (let i = 0; i < path.length - 1; i++) {182 base = get(base, path[i])183 if (!base || typeof base !== "object")184 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore185 }186 163- const value = clone(patch.value) // used to clone patch to ensure original patch is not modified, see #411164-187+ const type = getArchtype(base)188+ const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411189 const key = path[path.length - 1]190 switch (op) {191 case "replace":168- if (isMap(base)) {169- base.set(key, value)170- } else if (isSet(base)) {171- throw new Error('Sets cannot have "replace" patches.')172- } else {173- // if value is an object, then it's assigned by reference174- // in the following add or remove ops, the value field inside the patch will also be modifyed175- // so we use value from the cloned patch176- base[key] = value192+ switch (type) {193+ case Archtype.Map:194+ return base.set(key, value)195+ /* istanbul ignore next */196+ case Archtype.Set:197+ throw new Error('Sets cannot have "replace" patches.')198+ default:199+ // if value is an object, then it's assigned by reference200+ // in the following add or remove ops, the value field inside the patch will also be modifyed201+ // so we use value from the cloned patch202+ // @ts-ignore203+ return (base[key] = value)204 }178- break205 case "add":180- if (isSet(base)) {181- base.delete(patch.value)206+ switch (type) {207+ case Archtype.Array:208+ return base.splice(key as any, 0, value)209+ case Archtype.Map:210+ return base.set(key, value)211+ case Archtype.Set:212+ return base.add(value)213+ default:214+ return (base[key] = value)215 }183-184- Array.isArray(base)185- ? base.splice(key as any, 0, value)186- : isMap(base)187- ? base.set(key, value)188- : isSet(base)189- ? base.add(value)190- : (base[key] = value)191- break216 case "remove":193- Array.isArray(base)194- ? base.splice(key as any, 1)195- : isMap(base)196- ? base.delete(key)197- : isSet(base)198- ? base.delete(patch.value)199- : delete base[key]200- break217+ switch (type) {218+ case Archtype.Array:219+ return base.splice(key as any, 1)220+ case Archtype.Map:221+ return base.delete(key)222+ case Archtype.Set:223+ return base.delete(patch.value)224+ default:225+ return delete base[key]226+ }227 default:228 throw new Error("Unsupported patch operation: " + op)229 }230 })231 232 return draft233 }234+235+// TODO: optimize: this is quite a performance hit, can we detect intelligently when it is needed?236+// E.g. auto-draft when new objects from outside are assigned and modified?237+// (See failing test when deepClone just returns obj)238+function deepClonePatchValue<T>(obj: T): T239+function deepClonePatchValue(obj: any) {240+ if (!obj || typeof obj !== "object") return obj241+ if (Array.isArray(obj)) return obj.map(deepClonePatchValue)242+ if (isMap(obj))243+ return new Map(244+ Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])245+ )246+ // Not needed: if (isSet(obj)) return new Set(Array.from(obj.values()).map(deepClone))247+ const cloned = Object.create(Object.getPrototypeOf(obj))248+ for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])249+ return cloned250+}modified:src/proxy.ts+81 added-252 removed
1 "use strict"2 import {3- assign,3 each,4 has,5 is,6 isDraftable,8- isDraft,9- isMap,10- isSet,11- hasSymbol,7 shallowCopy,13- makeIterable,8 DRAFT_STATE,15- assignMap,16- assignSet,17- original,18- iterateMapValues,19- makeIterateSetValues9+ latest10 } from "./common"11 import {ImmerScope} from "./scope"12+import {13+ AnyObject,14+ Drafted,15+ ImmerState,16+ AnyArray,17+ Objectish,18+ ImmerBaseState,19+ ProxyType20+} from "./types"21 23-// Do nothing before being finalized.24-export function willFinalize() {}22+interface ProxyBaseState extends ImmerBaseState {23+ assigned: {24+ [property: string]: boolean25+ }26+ parent?: ImmerState27+ drafts?: {28+ [property: string]: Drafted<any, any>29+ }30+ revoke(): void31+}32 26-interface ES6Draft {}33+export interface ProxyObjectState extends ProxyBaseState {34+ type: ProxyType.ProxyObject35+ base: AnyObject36+ copy: AnyObject | null37+ draft: Drafted<AnyObject, ProxyObjectState>38+}39 28-interface ES6State<T = any> {29- scope: ImmerScope30- modified: boolean31- finalized: boolean32- assigned:33- | {34- [property: string]: boolean35- }36- | Map<string, boolean> // TODO: always use a Map?37- parent: ES6State38- base: T39- draft: ES6Draft | null40- drafts:41- | {42- [property: string]: ES6Draft43- }44- | Map<string, ES6Draft> // TODO: always use a Map?45- copy: T | null46- revoke: null | (() => void)40+export interface ProxyArrayState extends ProxyBaseState {41+ type: ProxyType.ProxyArray42+ base: AnyArray43+ copy: AnyArray | null44+ draft: Drafted<AnyArray, ProxyArrayState>45 }46 47+type ProxyState = ProxyObjectState | ProxyArrayState48+49 /**50 * Returns a new draft of the `base` object.51 *52 * The second argument is the parent draft-state (used internally).53 */54-export function createProxy<T extends object>(54+export function createProxy<T extends Objectish>(55 base: T,56- parent: ES6State57-): ES6Draft {58- const scope = parent ? parent.scope : ImmerScope.current!59- const state: ES6State<T> = {56+ parent?: ImmerState57+): Drafted<T, ProxyState> {58+ const isArray = Array.isArray(base)59+ const state: ProxyState = {60+ type: isArray ? ProxyType.ProxyArray : (ProxyType.ProxyObject as any),61 // Track which produce call this is associated with.61- scope,62+ scope: parent ? parent.scope : ImmerScope.current!,63 // True for both shallow and deep changes.64 modified: false,65 // Used during finalization.66 finalized: false,3 unmodified lines70 parent,71 // The base state.72 base,73 // The base proxy.73- draft: null,74+ draft: null as any, // set below75 // Any property proxies.76 drafts: {},77 // The base copy with any updated values.78 copy: null,79 // Called by the `produce` function.79- revoke: null80+ revoke: null as any,81+ isManual: false82 }83 84 // the traps must target something, a bit like the 'real' base.85 // but also, we need to be able to determine from the target what the relevant state is2 unmodified lines88 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)89 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb90 let target: T = state as any91 let traps: ProxyHandler<object | Array<any>> = objectTraps90- if (Array.isArray(base)) {92+ if (isArray) {93 target = [state] as any94 traps = arrayTraps95 }94- // Map drafts must support object keys, so we use Map objects to track changes.95- else if (isMap(base)) {96- traps = mapTraps97- state.drafts = new Map()98- state.assigned = new Map()99- }100- // Set drafts use a Map object to track which of its values are drafted.101- // And we don't need the "assigned" property, because Set objects have no keys.102- else if (isSet(base)) {103- traps = setTraps104- state.drafts = new Map()105- }96 97+ // TODO: optimization: might be faster, cheaper if we created a non-revocable proxy98+ // and administrate revoking ourselves99 const {revoke, proxy} = Proxy.revocable(target, traps)108-109- state.draft = proxy100+ state.draft = proxy as any101 state.revoke = revoke111-112- scope.drafts!.push(proxy)113- return proxy102+ return proxy as any103 }104 105 /**106 * Object drafts107 */119-const objectTraps: ProxyHandler<ES6State> = {108+const objectTraps: ProxyHandler<ProxyState> = {109 get(state, prop) {110 if (prop === DRAFT_STATE) return state111 let {drafts} = state112 113 // Check for existing draft in unmodified state.114 if (!state.modified && has(drafts, prop)) {126- return drafts[prop]115+ return drafts![prop as any]116 }117 118 const value = latest(state)[prop]119 if (state.finalized || !isDraftable(value)) {4 unmodified lines124 if (state.modified) {125 // Assigned values are never drafted. This catches any drafts we created, too.126 if (value !== peek(state.base, prop)) return value127 // Store drafts on the copy (when one exists).128+ // @ts-ignore129 drafts = state.copy130 }131 142- return (drafts[prop] = createProxy(value, state))132+ return (drafts![prop as any] = state.scope.immer.createProxy(value, state))133 },134 has(state, prop) {135 return prop in latest(state)136 },137 ownKeys(state) {138 return Reflect.ownKeys(latest(state))139 },150- set(state, prop, value) {140+ set(state, prop: string /* strictly not, but helps TS */, value) {141 if (!state.modified) {142 const baseValue = peek(state.base, prop)143 // Optimize based on value's truthiness. Truthy values are guaranteed to144 // never be undefined, so we can avoid the `in` operator. Lastly, truthy145 // values may be drafts, but falsy values are never drafts.146 const isUnchanged = value157- ? is(baseValue, value) || value === state.drafts[prop]147+ ? is(baseValue, value) || value === state.drafts![prop]148 : is(baseValue, value) && prop in state.base149 if (isUnchanged) return true150+ prepareCopy(state)151 markChanged(state)152 }153 state.assigned[prop] = true154+ // @ts-ignore163- state.copy[prop] = value155+ state.copy![prop] = value156 return true157 },166- deleteProperty(state, prop) {158+ deleteProperty(state, prop: string) {159 // The `undefined` check is a fast path for pre-existing keys.160 if (peek(state.base, prop) !== undefined || prop in state.base) {161 state.assigned[prop] = false162+ prepareCopy(state)163 markChanged(state)164 } else if (state.assigned[prop]) {165 // if an originally not assigned property was deleted166 delete state.assigned[prop]167 }168+ // @ts-ignore169 if (state.copy) delete state.copy[prop]170 return true171 },172 // Note: We never coerce `desc.value` into an Immer draft, because we can't make2 unmodified lines175 const owner = latest(state)176 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)177 if (desc) {178 desc.writable = true185- desc.configurable = !Array.isArray(owner) || prop !== "length"179+ desc.configurable =180+ state.type !== ProxyType.ProxyArray || prop !== "length"181 }182 return desc183 },184 defineProperty() {10 unmodified lines195 /**196 * Array drafts197 */198 204-const arrayTraps: ProxyHandler<[ES6State]> = {}199+const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}200 each(objectTraps, (key, fn) => {201+ // @ts-ignore202 arrayTraps[key] = function() {203 arguments[0] = arguments[0][0]204 return fn.apply(this, arguments)205 }10 unmodified lines216 }217 return objectTraps.set!.call(this, state[0], prop, value, state[0])218 }219 224-// Used by Map and Set drafts225-const reflectTraps = makeReflectTraps([226- "ownKeys",227- "has",228- "set",229- "deleteProperty",230- "defineProperty",231- "getOwnPropertyDescriptor",232- "preventExtensions",233- "isExtensible",234- "getPrototypeOf"235-])236-220 /**221 * Map drafts222 */223 241-const mapTraps = makeTrapsForGetters<Map<any, any>>({242- [DRAFT_STATE]: state => state,243- size: state => latest(state).size,244- has: state => key => latest(state).has(key),245- set: state => (key, value) => {246- const values = latest(state)247- if (!values.has(key) || values.get(key) !== value) {248- markChanged(state)249- // @ts-ignore250- state.assigned.set(key, true)251- state.copy!.set(key, value)252- }253- return state.draft254- },255- delete: state => key => {256- if (latest(state).has(key)) {257- markChanged(state)258- // @ts-ignore259- state.assigned.set(key, false)260- return state.copy!.delete(key)261- }262- return false263- },264- clear: state => () => {265- markChanged(state)266- state.assigned = new Map()267- each(latest(state).keys(), (_, key) => {268- // @ts-ignore269- state.assigned.set(key, false)270- })271- return state.copy!.clear()272- },273- // @ts-ignore274- forEach: (state, _, receiver) => (cb, thisArg) =>275- latest(state).forEach((_, key, map) => {276- const value = receiver.get(key)277- cb.call(thisArg, value, key, map)278- }),279- get: state => key => {280- const drafts = state.modified ? state.copy : state.drafts281-282- // @ts-ignore TODO: ...or fix by using different ES6Draft types (but better just unify to maps)283- if (drafts!.has(key)) {284- // @ts-ignore285- const value = drafts.get(key)286-287- if (isDraft(value) || !isDraftable(value)) return value288-289- const draft = createProxy(value, state)290- // @ts-ignore291- drafts.set(key, draft)292- return draft293- }294-295- const value = latest(state).get(key)296- if (state.finalized || !isDraftable(value)) {297- return value298- }299-300- const draft = createProxy(value, state)301- //@ts-ignore302- drafts.set(key, draft)303- return draft304- },305- keys: state => () => latest(state).keys(),306- //@ts-ignore307- values: iterateMapValues,308- //@ts-ignore309- entries: iterateMapValues,310- [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateMapValues311-})312-313-const iterateSetValues = makeIterateSetValues(createProxy)314-/**315- * Set drafts316- */317-318-const setTraps = makeTrapsForGetters<Set<any>>({319- //@ts-ignore320- [DRAFT_STATE]: state => state,321- size: state => latest(state).size,322- has: state => key => latest(state).has(key),323- add: state => value => {324- if (!latest(state).has(value)) {325- markChanged(state)326- //@ts-ignore327- state.copy.add(value)328- }329- return state.draft330- },331- delete: state => value => {332- markChanged(state)333- //@ts-ignore334- return state.copy.delete(value)335- },336- clear: state => () => {337- markChanged(state)338- //@ts-ignore339- return state.copy.clear()340- },341- forEach: state => (cb, thisArg) => {342- const iterator = iterateSetValues(state)()343- let result = iterator.next()344- while (!result.done) {345- cb.call(thisArg, result.value, result.value, state.draft)346- result = iterator.next()347- }348- },349- keys: iterateSetValues,350- values: iterateSetValues,351- entries: iterateSetValues,352- [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateSetValues353-})354-355-/**356- * Helpers357- */358-359-// Retrieve the latest values of the draft.360-function latest(state) {361- return state.copy || state.base362-}363-224 // Access a property without creating an Immer draft.365-function peek(draft, prop) {225+function peek(draft: Drafted, prop: PropertyKey): any {226 const state = draft[DRAFT_STATE]227 const desc = Reflect.getOwnPropertyDescriptor(228 state ? latest(state) : draft,229 prop230 )231 return desc && desc.value232 }233 374-function markChanged(state) {234+export function markChanged(state: ImmerState) {235 if (!state.modified) {236 state.modified = true377-378- const {base, drafts, parent} = state379- const copy = shallowCopy(base)380-381- if (isSet(base)) {382- // Note: The `drafts` property is preserved for Set objects, since383- // we need to keep track of which values are drafted.384- assignSet(copy, drafts)385- } else {386- // Merge nested drafts into the copy.387- if (isMap(base)) assignMap(copy, drafts)388- else assign(copy, drafts)389- state.drafts = null237+ if (238+ state.type === ProxyType.ProxyObject ||239+ state.type === ProxyType.ProxyArray240+ ) {241+ const copy = (state.copy = shallowCopy(state.base))242+ each(state.drafts!, (key, value) => {243+ // @ts-ignore244+ copy[key] = value245+ })246+ state.drafts = undefined247 }248 392- state.copy = copy393- if (parent) {394- markChanged(parent)249+ if (state.parent) {250+ markChanged(state.parent)251 }252 }253 }254 399-/** Create traps that all use the `Reflect` API on the `latest(state)` */400-function makeReflectTraps<T extends object>(401- names: (keyof typeof Reflect)[]402-): ProxyHandler<T> {403- return names.reduce(404- (traps, name) => {405- // @ts-ignore406- traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)407- return traps408- },409- {} as any410- )411-}412-413-function makeTrapsForGetters<T extends object>(414- getters: {415- [K in keyof T]: (416- state: ES6State<T>417- ) => /* Skip first arg of: ProxyHandler<T>[K] */ any255+function prepareCopy(state: ProxyState) {256+ if (!state.copy) {257+ state.copy = shallowCopy(state.base)258 }419-): ProxyHandler<T> {420- return assign({}, reflectTraps, {421- get(state, prop, receiver) {422- return getters.hasOwnProperty(prop)423- ? getters[prop](state, prop, receiver)424- : Reflect.get(state, prop, receiver)425- },426- setPrototypeOf(state) {427- throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore428- }429- })259 }modified:src/scope.ts+17 added-11 removed
1 import {DRAFT_STATE} from "./common"2-import {ImmerState, Patch, PatchListener} from "./types"2+import {Patch, PatchListener, Drafted, ProxyType} from "./types"3+import {Immer} from "./immer"4 5 /** Each scope represents a `produce` call. */6 export class ImmerScope {7 static current?: ImmerScope3 unmodified lines11 canAutoFreeze: boolean12 drafts: any[]13 parent?: ImmerScope14 patchListener?: PatchListener15+ immer: Immer16 15- constructor(parent?: ImmerScope) {17+ constructor(parent: ImmerScope | undefined, immer: Immer) {18 this.drafts = []19 this.parent = parent20+ this.immer = immer21 22 // Whenever the modified draft contains a draft from another scope, we23 // need to prevent auto-freezing so the unowned draft can be finalized.24 this.canAutoFreeze = true22-23- // To avoid prototype lookups:24- this.patches = null as any // TODO:25 }26 27- usePatches(patchListener: PatchListener) {27+ usePatches(patchListener?: PatchListener) {28 if (patchListener) {29 this.patches = []30 this.inversePatches = []31 this.patchListener = patchListener3 unmodified lines35 revoke() {36 this.leave()37 this.drafts.forEach(revoke)38 // @ts-ignore39- this.drafts = null // TODO: // Make draft-related methods throw.39+ this.drafts = null40 }41 42 leave() {43 if (this === ImmerScope.current) {44 ImmerScope.current = this.parent45 }46 }47 48- static enter() {49- const scope = new ImmerScope(ImmerScope.current)48+ static enter(immer: Immer) {49+ const scope = new ImmerScope(ImmerScope.current, immer)50 ImmerScope.current = scope51 return scope52 }53 }54 55-function revoke(draft) {56- draft[DRAFT_STATE].revoke()55+function revoke(draft: Drafted) {56+ const state = draft[DRAFT_STATE]57+ if (58+ state.type === ProxyType.ProxyObject ||59+ state.type === ProxyType.ProxyArray60+ )61+ state.revoke()62+ else state.revoked = true63 }added:src/set.ts+145 added
1+import {DRAFT_STATE, latest, isDraftable, iteratorSymbol} from "./common"2+3+import {ImmerScope} from "./scope"4+import {AnySet, Drafted, ImmerState, ImmerBaseState, ProxyType} from "./types"5+import {assertUnrevoked} from "./es5"6+7+export interface SetState extends ImmerBaseState {8+ type: ProxyType.Set9+ copy: AnySet | undefined10+ base: AnySet11+ drafts: Map<any, Drafted> // maps the original value to the draft value in the new set12+ revoked: boolean13+ draft: Drafted<AnySet, SetState>14+}15+16+// Make sure DraftSet declarion doesn't die if Map is not avialable...17+/* istanbul ignore next */18+const SetBase: SetConstructor =19+ typeof Set !== "undefined" ? Set : (function FakeSet() {} as any)20+21+export class DraftSet<K, V> extends SetBase implements Set<V> {22+ [DRAFT_STATE]: SetState23+ constructor(target: AnySet, parent?: ImmerState) {24+ super()25+ this[DRAFT_STATE] = {26+ type: ProxyType.Set,27+ parent,28+ scope: parent ? parent.scope : ImmerScope.current!,29+ modified: false,30+ finalized: false,31+ copy: undefined,32+ base: target,33+ draft: this,34+ drafts: new Map(),35+ revoked: false,36+ isManual: false37+ }38+ }39+40+ get size(): number {41+ return latest(this[DRAFT_STATE]).size42+ }43+44+ has(value: V): boolean {45+ const state = this[DRAFT_STATE]46+ assertUnrevoked(state)47+ // bit of trickery here, to be able to recognize both the value, and the draft of its value48+ if (!state.copy) {49+ return state.base.has(value)50+ }51+ if (state.copy.has(value)) return true52+ if (state.drafts.has(value) && state.copy.has(state.drafts.get(value)))53+ return true54+ return false55+ }56+57+ add(value: V): this {58+ const state = this[DRAFT_STATE]59+ assertUnrevoked(state)60+ if (state.copy) {61+ state.copy.add(value)62+ } else if (!state.base.has(value)) {63+ prepareCopy(state)64+ state.scope.immer.markChanged(state)65+ state.copy!.add(value)66+ }67+ return this68+ }69+70+ delete(value: V): boolean {71+ if (!this.has(value)) {72+ return false73+ }74+75+ const state = this[DRAFT_STATE]76+ assertUnrevoked(state)77+ prepareCopy(state)78+ state.scope.immer.markChanged(state)79+ return (80+ state.copy!.delete(value) ||81+ (state.drafts.has(value)82+ ? state.copy!.delete(state.drafts.get(value))83+ : /* istanbul ignore next */ false)84+ )85+ }86+87+ clear() {88+ const state = this[DRAFT_STATE]89+ assertUnrevoked(state)90+ prepareCopy(state)91+ state.scope.immer.markChanged(state)92+ return state.copy!.clear()93+ }94+95+ values(): IterableIterator<V> {96+ const state = this[DRAFT_STATE]97+ assertUnrevoked(state)98+ prepareCopy(state)99+ return state.copy!.values()100+ }101+102+ entries(): IterableIterator<[V, V]> {103+ const state = this[DRAFT_STATE]104+ assertUnrevoked(state)105+ prepareCopy(state)106+ return state.copy!.entries()107+ }108+109+ keys(): IterableIterator<V> {110+ return this.values()111+ }112+113+ [iteratorSymbol]() {114+ return this.values()115+ }116+117+ forEach(cb: (value: V, key: V, self: this) => void, thisArg?: any) {118+ const iterator = this.values()119+ let result = iterator.next()120+ while (!result.done) {121+ cb.call(thisArg, result.value, result.value, this)122+ result = iterator.next()123+ }124+ }125+}126+127+export function proxySet(target: AnySet, parent?: ImmerState) {128+ return new DraftSet(target, parent)129+}130+131+function prepareCopy(state: SetState) {132+ if (!state.copy) {133+ // create drafts for all entries to preserve insertion order134+ state.copy = new Set()135+ state.base.forEach(value => {136+ if (isDraftable(value)) {137+ const draft = state.scope.immer.createProxy(value, state)138+ state.drafts.set(value, draft)139+ state.copy!.add(draft)140+ } else {141+ state.copy!.add(value)142+ }143+ })144+ }145+}modified:src/types.ts+47 added-18 removed
1-import {Nothing} from "./common"1+import {Nothing, DRAFT_STATE} from "./common"2+import {SetState} from "./set"3+import {MapState} from "./map"4+import {ProxyObjectState, ProxyArrayState} from "./proxy"5+import {ES5ObjectState, ES5ArrayState} from "./es5"6+import {ImmerScope} from "./scope"7 3-export type Objectish = any[] | Map<any, any> | Set<any> | {}8+export type Objectish = AnyObject | AnyArray | AnyMap | AnySet9+export type ObjectishNoSet = AnyObject | AnyArray | AnyMap10 5-export type ObjectishNoSet = any[] | Map<any, any> | {}11+export type AnyObject = {[key: string]: any}12+export type AnyArray = Array<any>13+export type AnySet = Set<any>14+export type AnyMap = Map<any, any>15+export enum Archtype {16+ Object,17+ Array,18+ Map,19+ Set20+}21 7-export interface ImmerState<T = any> {22+export enum ProxyType {23+ ProxyObject,24+ ProxyArray,25+ ES5Object,26+ ES5Array,27+ Map,28+ Set29+}30+31+export interface ImmerBaseState {32 parent?: ImmerState9- base: T10- copy: T11- assigned: {[prop: string]: boolean; [index: number]: boolean}33+ scope: ImmerScope34+ modified: boolean35+ finalized: boolean36+ isManual: boolean37 }38 39+export type ImmerState =40+ | ProxyObjectState41+ | ProxyArrayState42+ | ES5ObjectState43+ | ES5ArrayState44+ | MapState45+ | SetState46+47+// The _internal_ type used for drafts (not to be confused with Draft, which is public facing)48+export type Drafted<Base = any, T extends ImmerState = ImmerState> = {49+ [DRAFT_STATE]: T50+} & Base51+14-type Tail<T extends any[]> = ((...t: T) => any) extends ((52+type Tail<T extends any[]> = ((...t: T) => any) extends (53 _: any,54 ...tail: infer TT17-) => any)55+) => any56 ? TT57 : []58 59 /** Object types that should never be mapped */153 unmodified lines213 base: Base,214 recipe: (draft: D) => Return215 ): [Produced<Base, Return>, Patch[], Patch[]]216 }179-180-// Backward compatibility with --target es5181-// TODO: still needed?182-// declare global {183-// interface Set<T> {}184-// interface Map<K, V> {}185-// interface WeakSet<T> {}186-// interface WeakMap<K extends object, V> {}187-// }modified:package.json+9 added-2 removed
68 unmodified lines69 "immutable": "^3.8.2",70 "jest": "^24.7.1",71 "lodash": "^4.17.4",72 "lodash.clonedeep": "^4.5.0",73- "prettier": "1.17.0",73+ "prettier": "1.19.1",74 "pretty-quick": "^1.8.0",75 "regenerator-runtime": "^0.11.1",76 "rimraf": "^2.6.2",77 "rollup-plugin-typescript2": "^0.25.3",12 unmodified lines90 "transform": {91 "\\.js$": "babel-jest",92 "\\.ts$": "ts-jest"93 },94- "preset": "ts-jest/presets/js-with-babel"94+ "preset": "ts-jest/presets/js-with-babel",95+ "globals": {96+ "ts-jest": {97+ "tsConfig": {98+ "noUnusedLocals": false99+ }100+ }101+ }102 }103 }modified:tsconfig.json+8 added-3 removed
1 {2- "include": ["src"],2 "compilerOptions": {3 "lib": ["es2015"],4+ "target": "ES6",5 "strict": true,6 "declaration": true,7 "importHelpers": false,8+ "noImplicitAny": true,9+ "esModuleInterop": true,10+ "noUnusedLocals": true,11 "sourceMap": true,12 "declarationMap": true,10- "noImplicitAny": false // TODO: true,11- }13+ "noEmit": true,14+ "moduleResolution": "node"15+ },16+ "files": ["./src/index.ts"]17 }modified:yarn.lock+4 added-4 removed
5874 unmodified lines5875 version "0.2.0"5876 resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b"5877 integrity sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=5878 5879-prettier@1.17.0:5880- version "1.17.0"5881- resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.17.0.tgz#53b303676eed22cc14a9f0cec09b477b3026c008"5882- integrity sha512-sXe5lSt2WQlCbydGETgfm1YBShgOX4HxQkFPvbxkcwgDvGDeqVau8h+12+lmSVlP3rHPz0oavfddSZg/q+Szjw==5879+prettier@1.19.1:5880+ version "1.19.1"5881+ resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.19.1.tgz#f7d7f5ff8a9cd872a7be4ca142095956a60797cb"5882+ integrity sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==5883 5884 pretty-format@^24.7.0:5885 version "24.7.0"5886 resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-24.7.0.tgz#d23106bc2edcd776079c2daa5da02bcb12ed0c10"1486 unmodified lines