Merge pull request #498 from immerjs/code-cleanup
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Code cleanup
authored by Michel Weststrate · committed by GitHub · parents 65a377f, 82298d4 · Browse files · 16 files·+987 added−1002 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+987 added−1002 removed
- tests:+120 added−46 removed
- other:+867 added−956 removed
Provenance
- Commit
b9cc802- Tree
219dd4d- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
65a377f- Parent 2
82298d4
16 files changed+987 added−1002 removed
modified:__tests__/base.js+118 added-18 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"])148 unmodified lines548 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 567 describe("set drafts", () => {568 it("supports iteration", () => {550- const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])569+ const base = new Set([570+ {id: 1, a: 1},571+ {id: 2, a: 1}572+ ])573 const findById = (set, id) => {574 for (const item of set) {575 if (item.id === id) return item576 }5 unmodified lines582 obj1.a = 2583 obj2.a = 2584 })585 expect(result).not.toBe(base)564- expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))565- expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))586+ expect(base).toEqual(587+ new Set([588+ {id: 1, a: 1},589+ {id: 2, a: 1}590+ ])591+ )592+ expect(result).toEqual(593+ new Set([594+ {id: 1, a: 2},595+ {id: 2, a: 2}596+ ])597+ )598 })599 600 it("supports 'entries'", () => {569- const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])601+ const base = new Set([602+ {id: 1, a: 1},603+ {id: 2, a: 1}604+ ])605 const findById = (set, id) => {606 for (const [item1, item2] of set.entries()) {607 expect(item1).toBe(item2)608 if (item1.id === id) return item16 unmodified lines615 obj1.a = 2616 obj2.a = 2617 })618 expect(result).not.toBe(base)584- expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))585- expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))619+ expect(base).toEqual(620+ new Set([621+ {id: 1, a: 1},622+ {id: 2, a: 1}623+ ])624+ )625+ expect(result).toEqual(626+ new Set([627+ {id: 1, a: 2},628+ {id: 2, a: 2}629+ ])630+ )631 })632 633 it("supports 'values'", () => {589- const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])634+ const base = new Set([635+ {id: 1, a: 1},636+ {id: 2, a: 1}637+ ])638 const findById = (set, id) => {639 for (const item of set.values()) {640 if (item.id === id) return item641 }5 unmodified lines647 obj1.a = 2648 obj2.a = 2649 })650 expect(result).not.toBe(base)603- expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))604- expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))651+ expect(base).toEqual(652+ new Set([653+ {id: 1, a: 1},654+ {id: 2, a: 1}655+ ])656+ )657+ expect(result).toEqual(658+ new Set([659+ {id: 1, a: 2},660+ {id: 2, a: 2}661+ ])662+ )663 })664 665 it("supports 'keys'", () => {608- const base = new Set([{id: 1, a: 1}, {id: 2, a: 1}])666+ const base = new Set([667+ {id: 1, a: 1},668+ {id: 2, a: 1}669+ ])670 const findById = (set, id) => {671 for (const item of set.keys()) {672 if (item.id === id) return item673 }5 unmodified lines679 obj1.a = 2680 obj2.a = 2681 })682 expect(result).not.toBe(base)622- expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 1}]))623- expect(result).toEqual(new Set([{id: 1, a: 2}, {id: 2, a: 2}]))683+ expect(base).toEqual(684+ new Set([685+ {id: 1, a: 1},686+ {id: 2, a: 1}687+ ])688+ )689+ expect(result).toEqual(690+ new Set([691+ {id: 1, a: 2},692+ {id: 2, a: 2}693+ ])694+ )695 })696 697 it("supports forEach with mutation after reads", () => {627- const base = new Set([{id: 1, a: 1}, {id: 2, a: 2}])698+ const base = new Set([699+ {id: 1, a: 1},700+ {id: 2, a: 2}701+ ])702 const result = produce(base, draft => {703 let sum1 = 0704 draft.forEach(({a}) => {705 sum1 += a6 unmodified lines712 })713 expect(sum2).toBe(23)714 })715 expect(result).not.toBe(base)642- expect(base).toEqual(new Set([{id: 1, a: 1}, {id: 2, a: 2}]))643- expect(result).toEqual(new Set([{id: 1, a: 11}, {id: 2, a: 12}]))716+ expect(base).toEqual(717+ new Set([718+ {id: 1, a: 1},719+ {id: 2, a: 2}720+ ])721+ )722+ expect(result).toEqual(723+ new Set([724+ {id: 1, a: 11},725+ {id: 2, a: 12}726+ ])727+ )728 })729 730 it("state stays the same if the same item is added", () => {731 const nextState = produce(baseState, s => {83 unmodified lines815 expect(d.has(obj)).toBe(false)816 })817 expect(next).toEqual(new Set([3]))818 })819+820+ it("revokes sets", () => {821+ let m822+ produce(baseState, s => {823+ m = s.aSet824+ })825+ expect(() => m.has("x")).toThrow(826+ "Cannot use a proxy that has been revoked"827+ )828+ expect(() => m.add("x")).toThrow(829+ "Cannot use a proxy that has been revoked"830+ )831+ })832 })833 834 it("supports `immerable` symbol on constructor", () => {835 class One {}880 unmodified lines1716 const b = {b: 2}1717 const c = {c: 3}1718 const set1 = new Set([a, b])1719 const set2 = new Set([c])1623- const map = new Map([["set1", set1], ["set2", set2]])1720+ const map = new Map([1721+ ["set1", set1],1722+ ["set2", set2]1723+ ])1724 const base = {map}1725 1726 function first(set) {1727 return Array.from(set.values())[0]166 unmodified linesmodified:__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:src/common.ts+141 added-156 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)88+ Object.getOwnPropertyNames(obj).concat(89+ Object.getOwnPropertySymbols(obj) as any90+ )91 : Object.getOwnPropertyNames92 108-// TODO: duplicate of clone? TODO: should be used by prepareCopy of map / set109-export function shallowCopy<T extends Objectish>(110- base: T,111- invokeGetters?: boolean112-): T113-export function shallowCopy(base, invokeGetters = false) {114- if (Array.isArray(base)) return base.slice()115- if (isMap(base)) return new Map(base)116- if (isSet(base)) return new Set(base)117- const clone = Object.create(Object.getPrototypeOf(base))118- ownKeys(base).forEach(key => {119- if (key === DRAFT_STATE) {120- return // Never copy over draft state.121- }122- const desc = Object.getOwnPropertyDescriptor(base, key)!123- let {value} = desc124- if (desc.get) {125- if (!invokeGetters) {126- throw new Error("Immer drafts cannot have computed properties")127- }128- value = desc.get.call(base)129- }130- if (desc.enumerable) {131- clone[key] = value132- } else {133- Object.defineProperty(clone, key, {134- value,135- writable: true,136- configurable: true137- })138- }139- })140- return clone141-}142-93 export function each<T extends Objectish>(94 obj: T,145- iter: (key: PropertyKey, value: any, source: T) => void146-)147-export function each(obj, iter) {148- if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {149- obj.forEach((entry, index) => iter(index, entry, obj))150- } else if (obj && typeof obj === "object") {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 {153- throw new Error("Cannot iterate primitive " + obj)101+ obj.forEach((entry: any, index: any) => iter(index, entry, obj))102 }103 }104 157-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 162-export function has(thing: ObjectishNoSet, prop: PropertyKey): boolean {163- return !thing164- ? false110+export function getArchtype(thing: any): Archtype {111+ if (!thing) die()112+ if (thing[DRAFT_STATE]) {113+ switch ((thing as Drafted)[DRAFT_STATE].type) {114+ case ProxyType.ES5Object:115+ case ProxyType.ProxyObject:116+ return Archtype.Object117+ case ProxyType.ES5Array:118+ case ProxyType.ProxyArray:119+ return Archtype.Array120+ case ProxyType.Map:121+ return Archtype.Map122+ case ProxyType.Set:123+ return Archtype.Set124+ }125+ }126+ return Array.isArray(thing)127+ ? Archtype.Array128 : isMap(thing)129+ ? Archtype.Map130+ : isSet(thing)131+ ? Archtype.Set132+ : Archtype.Object133+}134+135+export function has(thing: any, prop: PropertyKey): boolean {136+ return getArchtype(thing) === Archtype.Map137 ? thing.has(prop)138 : Object.prototype.hasOwnProperty.call(thing, prop)139 }140 170-export function get(thing: ObjectishNoSet, prop: PropertyKey) {171- return isMap(thing) ? thing.get(prop) : thing[prop]141+export function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {142+ // @ts-ignore143+ return getArchtype(thing) === Archtype.Map ? thing.get(prop) : thing[prop]144 }145 146+export function set(thing: any, propOrOldValue: PropertyKey, value: any) {147+ switch (getArchtype(thing)) {148+ case Archtype.Map:149+ thing.set(propOrOldValue, value)150+ break151+ case Archtype.Set:152+ thing.delete(propOrOldValue)153+ thing.add(value)154+ break155+ default:156+ thing[propOrOldValue] = value157+ }158+}159+174-export function is(x, y): boolean {160+export function is(x: any, y: any): boolean {161 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js162 if (x === y) {163 return x !== 0 || 1 / x === 1 / y164 } else {165 return x !== x && y !== y166 }167 }168 183-export const hasSymbol = typeof Symbol !== "undefined"184-185-export const hasMap = typeof Map !== "undefined"186-187-export function isMap(target): target is Map<any, any> {169+export function isMap(target: any): target is AnyMap {170 return hasMap && target instanceof Map171 }172 191-export const hasSet = typeof Set !== "undefined"192-193-export function isSet(target): target is Set<any> {173+export function isSet(target: any): target is AnySet {174 return hasSet && target instanceof Set175 }176 197-198-export function makeIterable2(baseIterator: Iterator<any>): IterableIterator<any> {199- // TODO: correct?200- // TODO: don't use symbol201- baseIterator[Symbol.iterator] = () => baseIterator202- return baseIterator as any177+export function latest(state: ImmerState): any {178+ return state.copy || state.base179 }180 205-export function makeIterable(next: () => {done: boolean; value: any}) {206- let self207- return (self = {208- [Symbol.iterator]: () => self,209- next181+export function shallowCopy<T extends AnyObject | AnyArray>(182+ base: T,183+ invokeGetters?: boolean184+): T185+export function shallowCopy(base: any, invokeGetters = false) {186+ if (Array.isArray(base)) return base.slice()187+ const clone = Object.create(Object.getPrototypeOf(base))188+ ownKeys(base).forEach(key => {189+ if (key === DRAFT_STATE) {190+ return // Never copy over draft state.191+ }192+ const desc = Object.getOwnPropertyDescriptor(base, key)!193+ let {value} = desc194+ if (desc.get) {195+ if (!invokeGetters) {196+ throw new Error("Immer drafts cannot have computed properties")197+ }198+ value = desc.get.call(base)199+ }200+ if (desc.enumerable) {201+ clone[key] = value202+ } else {203+ Object.defineProperty(clone, key, {204+ value,205+ writable: true,206+ configurable: true207+ })208+ }209 })210+ return clone211 }212 213-export function latest(state: any): any {214- return state.copy || state.base215-}216-217-// export function iterateCollection(collection: Map<any, any> | Set<any>, transformer: (key, value) => any) {218-// // TODO: create own iterator symbols for fallback219-// const iterator = collection.entries()220-// return makeIterable(() => {221-// const result = iterator.next()222-// if (!result.done) {223-// const value = wrapSetValue(state, result.value)224-// result.value = isEntries ? [value, value] : value225-// }226-// return result227-// } as any)228-// }229-230-// TODO: duplicate of shallow clone231-export function clone<T extends Objectish>(obj: T): T232-export function clone(obj) {233- if (!isDraftable(obj)) return obj234- if (Array.isArray(obj)) return obj.map(clone)235- if (isMap(obj)) return new Map(obj)236- if (isSet(obj)) return new Set(obj)237- const cloned = Object.create(Object.getPrototypeOf(obj))238- for (const key in obj) cloned[key] = clone(obj[key])239- return cloned240-}241-242-export function freeze<T extends Objectish>(243- obj: T,244- deep: boolean = false245-): void {213+export function freeze(obj: any, deep: boolean = false): void {214 if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) return247- if (isSet(obj)) {215+ const type = getArchtype(obj)216+ if (type === Archtype.Set) {217 obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any249- } else if (isMap(obj)) {218+ } else if (type === Archtype.Map) {219 obj.set = obj.clear = obj.delete = dontMutateFrozenCollections as any220 }221 Object.freeze(obj)222 if (deep) each(obj, (_, value) => freeze(value, true))1 unmodified line224 225 function dontMutateFrozenCollections() {226 throw new Error("This object has been frozen and should not be mutated")227 }228+229+export function createHiddenProperty(230+ target: AnyObject,231+ prop: PropertyKey,232+ value: any233+) {234+ Object.defineProperty(target, prop, {235+ value: value,236+ enumerable: false,237+ writable: true238+ })239+}240+241+export function die(): never {242+ throw new Error("Illegal state, please file a bug")243+}modified:src/es5.ts+90 added-139 removed
4 unmodified lines5 is,6 isDraft,7 isDraftable,8 isEnumerable,9- isMap,10- isSet,11- hasSymbol,9 shallowCopy,10 DRAFT_STATE,14- makeIterable,15- latest11+ latest,12+ createHiddenProperty13 } from "./common"17-import {proxyMap, hasMapChanges} from "./map"18-import {proxySet, hasSetChanges} from "./set"14 15 import {ImmerScope} from "./scope"21-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 23-export interface ES5Draft {24- [DRAFT_STATE]: ES5State25-}26-27-// TODO: merge with ImmerState?28-export interface ES5State<T = any> {29- scope: ImmerScope30- modified: boolean28+interface ES5BaseState extends ImmerBaseState {29 finalizing: boolean32- finalized: boolean33- assigned: Map<any, any> | {[key: string]: any}34- parent: ES5State30+ assigned: {[key: string]: any}31+ parent?: ImmerState35- base: T36- draft: T & ES5Draft37- drafts: Map<any, any> | null38- copy: T | null39- 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+43-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 64-export function createProxy<T>(base: T, parent: ES5State): ES5Draft {65- if (!base || typeof base !== "object" || !isDraftable(base)) {66- // TODO: || isDraft ?67- return base as any // TODO: fix68- }69- const scope = parent ? parent.scope : ImmerScope.current!70- if (isMap(base)) {71- const draft = proxyMap(base, parent) as any // TODO: typefix72- scope.drafts.push(draft)73- return draft74- }75- if (isSet(base)) {76- const draft = proxySet(base, parent) as any // TODO: typefix77- scope.drafts.push(draft)78- return draft79- }80-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 79 each(draft, prop => {80 proxyProperty(draft, prop, isArray || isEnumerable(base, prop))81 })82 88- const state: ES5State<T> = {89- 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,91- finalizing: false, // es5 only87+ finalizing: false,88 finalized: false,93- assigned: isMap(base) ? new Map() : {},89+ assigned: {},90 parent,91 base,92 draft,97- drafts: isSet(base) ? new Map() : null,93 copy: null,99- revoke,100- revoked: false // es5 only94+ revoked: false,95+ isManual: false96 }97 98 createHiddenProperty(draft, DRAFT_STATE, state)104- scope.drafts!.push(draft)99 return draft100 }101 108-function revoke(this: ES5State) {109- this.revoked = true110-}111-112-// TODO: type these methods102 // Access a property without creating an Immer draft.114-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 125-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-ignore132- return (state.copy[prop] = createProxy(value, state))122+ return (state.copy![prop] = state.scope.immer.createProxy(value, state))123 }124 return value125 }126 137-function set(state: ES5State, 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))) return142- markChanged(state)132+ markChangedES5(state)133 prepareCopy(state)134 }135+ // @ts-ignore145- state.copy[prop] = value136+ state.copy![prop] = value137 }138 148-export function markChanged(state) {139+export function markChangedES5(state: ImmerState) {140 if (!state.modified) {141 state.modified = true151- if (state.parent) markChanged(state.parent)142+ if (state.parent) markChangedES5(state.parent)143 }144 }145 155-// TODO: kill export156-function prepareCopy(state) {146+function prepareCopy(state: ES5State) {147 if (!state.copy) state.copy = clonePotentialDraft(state.base)148 }149 160-function clonePotentialDraft(base) {161- 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 instead173-const descriptors = {}163+const descriptors: {[prop: string]: PropertyDescriptor} = {}164 175-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,183- get() {177+ get(this: any) {178 return get(this[DRAFT_STATE], prop)179 },186- 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 194-export 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.203-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) {211- if (Array.isArray(state.base)) {212- if (hasArrayChanges(state)) markChanged(state)213- } else if (isMap(state.base)) {214- if (hasMapChanges(state)) markChanged(state)215- } else if (isSet(state.base)) {216- if (hasSetChanges(state)) markChanged(state)217- } else if (hasObjectChanges(state)) {218- 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 224-// TODO: refactor this to work per object-type225-// TODO: Set / Map shouldn't be ES specific226-function markChangesRecursively(object) {217+function markChangesRecursively(object: any) {218 if (!object || typeof object !== "object") return219 const state = object[DRAFT_STATE]220 if (!state) return230- const {base, draft, assigned} = state231- if (isSet(object)) {232- if (hasSetChanges(state)) {233- markChanged(state)234- object.forEach(v => {235- markChangesRecursively(v)236- })237- }238- } else if (isMap(object)) {239- // if (hasMapChanges(object)) {240- object.forEach((value, key) => {241- if (assigned && base.get(key) === undefined && !has(base, key)) {242- // TODO: this code seems invalid for Maps!243- assigned.set(key, true)244- markChanged(state)245- } else if (!assigned || !assigned.get(key)) {246- // TODO: === false?247- // Only untouched properties trigger recursion.248- markChangesRecursively(draft.get(key))249- }250- })251- // Look for removed keys.252- // TODO: is this code needed?253- // TODO: use each?254- if (assigned)255- base.forEach((value, key) => {256- // The `undefined` check is a fast path for pre-existing keys.257- if (draft.get(key) === undefined && !has(draft, key)) {258- assigned.set(key, false)259- markChanged(state)260- }261- })262- // }263- } else if (!Array.isArray(object)) {221+ const {base, draft, assigned, type} = state222+ if (type === ProxyType.ES5Object) {223 // Look for added keys.265- // TODO: use each?266- 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)) {269- // TODO: this code seems invalid for Maps!232 assigned[key] = true271- markChanged(state)233+ markChangedES5(state)234 } else if (!assigned[key]) {273- // TODO: === false ?235 // Only untouched properties trigger recursion.236 markChangesRecursively(draft[key])237 }238 })239 // Look for removed keys.279- // TODO: is this code needed?280- // TODO: use each?281- 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] = false285- markChanged(state)244+ markChangedES5(state)245 }246 })288- } else if (hasArrayChanges(state)) {289- 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 303-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 332-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 }348-349-function createHiddenProperty(target, prop, value) {350- Object.defineProperty(target, prop, {351- value: value,352- enumerable: false,353- writable: true354- })355-}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 && !isSet(state.base)) {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+71 added-225 removed
1-// TODO: destructure these, as the * as import makes it unclear which methods get installed on the Immer class2-import * as legacyProxy from "./es5"3-import * as modernProxy from "./proxy"1+import {createES5Proxy, willFinalizeES5, markChangedES5} from "./es5"2+import {createProxy, markChanged} from "./proxy"3 5-import {applyPatches, generatePatches} from "./patches"4+import {applyPatches} from "./patches"5 import {7- assign,6 each,9- has,10- is,7 isDraft,8 isSet,13- get,9 isMap,10 isDraftable,16- isEnumerable,17- shallowCopy,11 DRAFT_STATE,19- NOTHING,20- freeze,21- latest12+ NOTHING13 } from "./common"14 import {ImmerScope} from "./scope"24-import {ImmerState, IProduce, IProduceWithPatches, Objectish, PatchListener, Draft, Patch} from "./types"15+import {16+ ImmerState,17+ IProduce,18+ IProduceWithPatches,19+ Objectish,20+ PatchListener,21+ Draft,22+ Patch,23+ Drafted24+} from "./types"25+import {proxyMap} from "./map"26+import {proxySet} from "./set"27+import {processResult, maybeFreeze} from "./finalize"28 29 function verifyMinified() {}30 31 const configDefaults = {7 unmodified lines39 : verifyMinified.name === "verifyMinified",40 onAssign: null,41 onDelete: null,42 onCopy: null40-}43+} as const44 45 interface ProducersFns {46 produce: IProduce47 produceWithPatches: IProduceWithPatches1 unmodified line49 50 export class Immer implements ProducersFns {51 useProxies: boolean = false52 autoFreeze: boolean = false50- onAssign?: (51- state: ImmerState,52- prop: string | number,53- value: unknown54- ) => void53+ onAssign?: (state: ImmerState, prop: string | number, value: unknown) => void54 onDelete?: (state: ImmerState, prop: string | number) => void55 onCopy?: (state: ImmerState) => void57- createProxy!:<T>(value: T, parent: any) => T;58- willFinalize!: (scope: ImmerScope, thing: any, isReplaced: boolean) => void;59- markChanged!:(state: any) => void; // TODO: immerState?56 57 constructor(config?: {58 useProxies?: boolean59 autoFreeze?: boolean4 unmodified lines64 ) => void65 onDelete?: (state: ImmerState, prop: string | number) => void66 onCopy?: (state: ImmerState) => void67 }) {72- assign(this, configDefaults, config)68+ each(configDefaults, (key, value) => {69+ // @ts-ignore70+ this[key] = config?.[key] ?? value71+ })72 this.setUseProxies(this.useProxies)73 this.produce = this.produce.bind(this)74 this.produceWithPatches = this.produceWithPatches.bind(this)75 }16 unmodified lines92 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified93 * @param {Function} patchListener - optional function that will be called with all the patches produced here94 * @returns {any} a new state, or the initial state if nothing was modified95 */97- produce(base, recipe?, patchListener?) {96+ produce(base: any, recipe?: any, patchListener?: any) {97 // curried invocation98 if (typeof base === "function" && typeof recipe !== "function") {99 const defaultBase = recipe100 recipe = base101 102 const self = this104- return function curriedProduce(this: any, base = defaultBase, ...args) {105- return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore103+ return function curriedProduce(104+ this: any,105+ base = defaultBase,106+ ...args: any[]107+ ) {108+ return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore109 }110 }111 112 // prettier-ignore24 unmodified lines137 if (typeof Promise !== "undefined" && result instanceof Promise) {138 return result.then(139 result => {140 scope.usePatches(patchListener)138- return this.processResult(result, scope)141+ return processResult(this, result, scope)142 },143 error => {144 scope.revoke()145 throw error146 }147 )148 }149 scope.usePatches(patchListener)147- return this.processResult(result, scope)150+ return processResult(this, result, scope)151 } else {152 result = recipe(base)153 if (result === NOTHING) return undefined154 if (result === undefined) result = base152- this.maybeFreeze(result, true)155+ maybeFreeze(this, result, true)156 return result157 }158 }159 157- produceWithPatches(arg1, arg2?, arg3?): any {160+ produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {161 if (typeof arg1 === "function") {159- const self = this160- return (state, ...args) =>161- this.produceWithPatches(state, draft => arg1(draft, ...args))162+ return (state: any, ...args: any[]) =>163+ this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))164 }165 // non-curried form166 if (arg3)167 throw new Error("A patch listener cannot be passed to produceWithPatches")166- let patches, inversePatches167- const nextState = this.produce(arg1, arg2, (p, ip) => {168+ let patches: Patch[], inversePatches: Patch[]169+ const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {170 patches = p171 inversePatches = ip172 })171- return [nextState, patches, inversePatches]173+ return [nextState, patches!, inversePatches!]174 }175 174- createDraft<T extends Objectish>(base: T): Draft<T> {176+ createDraft<T extends Objectish>(base: T): Drafted<T> {177 if (!isDraftable(base)) {178 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore179 }180 const scope = ImmerScope.enter(this)181 const proxy = this.createProxy(base, undefined)182 proxy[DRAFT_STATE].isManual = true183 scope.leave()182- return proxy as any184+ return proxy185 }186 185- finishDraft<D extends Draft<any>>(draft: D, patchListener: PatchListener): D extends Draft<infer T> ? T : never {187+ finishDraft<D extends Draft<any>>(188+ draft: D,189+ patchListener: PatchListener190+ ): D extends Draft<infer T> ? T : never {191 const state = draft && draft[DRAFT_STATE]192 if (!state || !state.isManual) {193 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore194 }1 unmodified line196 throw new Error("The given draft is already finalized") // prettier-ignore197 }198 const {scope} = state199 scope.usePatches(patchListener)195- return this.processResult(undefined, scope)200+ return processResult(this, undefined, scope)201 }202 203 /**204 * Pass true to automatically freeze all copies created by Immer.11 unmodified lines216 * By default, feature detection is used, so calling this is rarely necessary.217 */218 setUseProxies(value: boolean) {219 this.useProxies = value215- assign(this, value ? modernProxy : legacyProxy)220 }221 222 applyPatches(base: Objectish, patches: Patch[]) {223 // If a patch replaces the entire state, take that replacement as base224 // before applying patches221- let i225+ let i: number226 for (i = patches.length - 1; i >= 0; i--) {227 const patch = patches[i]228 if (patch.path.length === 0 && patch.op === "replace") {229 base = patch.value5 unmodified lines235 // N.B: never hits if some patch a replacement, patches are never drafts236 return applyPatches(base, patches)237 }238 // Otherwise, produce a copy of the base state.235- return this.produce(base, draft =>239+ return this.produce(base, (draft: Drafted) =>240 applyPatches(draft, patches.slice(i + 1))241 )242 }243 240- /** @internal */241- processResult(result: any, scope: ImmerScope) {242- const baseDraft = scope.drafts![0]243- const isReplaced = result !== undefined && result !== baseDraft244- this.willFinalize(scope, result, isReplaced)245- if (isReplaced) {246- if (baseDraft[DRAFT_STATE].modified) {247- scope.revoke()248- throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore249- }250- if (isDraftable(result)) {251- // Finalize the result in case it contains (or is) a subset of the draft.252- result = this.finalize(result, null, scope)253- this.maybeFreeze(result)254- }255- if (scope.patches) {256- scope.patches.push({257- op: "replace",258- path: [],259- value: result260- })261- scope.inversePatches!.push({262- op: "replace",263- path: [],264- value: baseDraft[DRAFT_STATE].base265- })266- }267- } else {268- // Finalize the base draft.269- result = this.finalize(baseDraft, [], scope)270- }271- scope.revoke()272- if (scope.patches) {273- scope.patchListener!(scope.patches, scope.inversePatches!)274- }275- return result !== NOTHING ? result : undefined244+ createProxy<T extends Objectish>(245+ value: T,246+ parent?: ImmerState247+ ): Drafted<T, ImmerState> {248+ // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft249+ const draft: Drafted = isMap(value)250+ ? proxyMap(value, parent)251+ : isSet(value)252+ ? proxySet(value, parent)253+ : this.useProxies254+ ? createProxy(value, parent)255+ : createES5Proxy(value, parent)256+257+ const scope = parent ? parent.scope : ImmerScope.current!258+ scope.drafts.push(draft)259+ return draft260 }261 278- /**279- * @internal280- * Finalize a draft, returning either the unmodified base state or a modified281- * copy of the base state.282- */283- finalize(draft: any, path: string[] | null, scope: ImmerScope) {284- const state = draft[DRAFT_STATE]285- if (!state) {286- if (Object.isFrozen(draft)) return draft287- return this.finalizeTree(draft, null, scope)288- }289- // Never finalize drafts owned by another scope.290- if (state.scope !== scope) {291- return draft292- }293- if (!state.modified) {294- this.maybeFreeze(state.base, true)295- return state.base296- }297- if (!state.finalized) {298- state.finalized = true299- this.finalizeTree(state.draft, path, scope)300-301- // We cannot really delete anything inside of a Set. We can only replace the whole Set.302- if (this.onDelete && !isSet(state.base)) {303- // The `assigned` object is unreliable with ES5 drafts.304- if (this.useProxies) {305- const {assigned} = state306- each(assigned, (prop, exists) => {307- if (!exists) this.onDelete?.(state, prop as any)308- })309- } else {310- // TODO: Figure it out for Maps and Sets if we need to support ES5311- const {base, copy} = state312- each(base, prop => {313- if (!has(copy, prop)) this.onDelete?.(state, prop as any)314- })315- }316- }317- if (this.onCopy) {318- this.onCopy(state)319- }320-321- // At this point, all descendants of `state.copy` have been finalized,322- // so we can be sure that `scope.canAutoFreeze` is accurate.323- if (this.autoFreeze && scope.canAutoFreeze) {324- freeze(state.copy, false)325- }326-327- if (path && scope.patches) {328- generatePatches(state, path, scope.patches, scope.inversePatches!)329- }330- }331- return state.copy262+ willFinalize(scope: ImmerScope, thing: any, isReplaced: boolean) {263+ if (!this.useProxies) willFinalizeES5(scope, thing, isReplaced)264 }265 334- /**335- * @internal336- * Finalize all drafts in the given state tree.337- */338- finalizeTree(root: any, rootPath: string[] | null, scope: ImmerScope) {339- const state = root[DRAFT_STATE]340- if (state) {341- // TODO: remove crap342- // if (state.modified && !state.copy) {343- // state.copy = shallowCopy(state.base, false)344- // }345- // else346- if (!this.useProxies && !isMap(root) && !isSet(root)) {347- // Create the final copy, with added keys and without deleted keys.348- state.copy = shallowCopy(state.draft, true) // TODO: optimization, can we get rid of this and just use state.copy?349- }350-351- root = state.copy266+ markChanged(state: ImmerState) {267+ if (this.useProxies) {268+ markChanged(state)269+ } else {270+ markChangedES5(state)271 }353-354- const needPatches = !!rootPath && !!scope.patches355- const finalizeProperty = (prop, value, parent) => {356- if (value === parent) {357- throw Error("Immer forbids circular references")358- }359-360- // In the `finalizeTree` method, only the `root` object may be a draft.361- const isDraftProp = !!state && parent === root362- const isSetMember = isSet(parent)363-364- if (isDraft(value)) {365- const path =366- isDraftProp &&367- needPatches &&368- !isSetMember && // Set objects are atomic since they have no keys.369- !has(state.assigned, prop) // Skip deep patches for assigned keys.370- ? rootPath!.concat(prop)371- : null372-373- // Drafts owned by `scope` are finalized here.374- value = this.finalize(value, path, scope)375- replace(parent, prop, value)376-377- // Drafts from another scope must prevent auto-freezing.378- if (isDraft(value)) {379- scope.canAutoFreeze = false380- }381-382- // Unchanged drafts are never passed to the `onAssign` hook.383- if (isDraftProp && !isSet && value === get(state.base, prop)) return384- }385- // Unchanged draft properties are ignored.386- else if (isDraftProp && is(value, get(state.base, prop))) {387- return388- }389- // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.390- else if (isDraftable(value) && !Object.isFrozen(value)) {391- each(value, finalizeProperty)392- this.maybeFreeze(value)393- }394-395- if (isDraftProp && this.onAssign && !isSetMember) {396- this.onAssign(state, prop, value)397- }398- }399-400- each(root, finalizeProperty)401- return root272 }403- maybeFreeze(value, deep = false) {404- if (this.autoFreeze && !isDraft(value)) {405- freeze(value, deep)406- }407- }273 }409-410-function replace(parent, prop, value) {411- if (isMap(parent)) {412- parent.set(prop, value)413- } else if (isSet(parent)) {414- // In this case, the `prop` is actually a draft.415- parent.delete(prop)416- parent.add(value)417- } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {418- // Preserve non-enumerable properties.419- parent[prop] = value420- } else {421- Object.defineProperty(parent, prop, {422- value,423- writable: true,424- configurable: true425- })426- }427-}modified:src/map.ts+57 added-133 removed
1-import {2- each,3- has,4- is,5- isDraft,6- isDraftable,7- isEnumerable,8- isMap,9- isSet,10- hasSymbol,11- shallowCopy,12- DRAFT_STATE,13- makeIterable,14- latest15-} from "./common"1+import {isDraftable, DRAFT_STATE, latest, iteratorSymbol} from "./common"2 17-// TODO: kill:18-import {19- assertUnrevoked,20- ES5Draft,21-} from "./es5"22-import { ImmerScope } from "./scope";23-import { Immer } from "./immer";3+import {ImmerScope} from "./scope"4+import {AnyMap, Drafted, ImmerState, ImmerBaseState, ProxyType} from "./types"5+import {assertUnrevoked} from "./es5"6 25-// TODO: create own states26-// TODO: clean up the maps and such from ES5 / Proxy states27-28-export interface MapState {29- parent: any; // TODO: type30- scope: ImmerScope;31- modified: boolean;32- finalizing: boolean;33- finalized: boolean;34- copy: Map<any, any> | undefined;35- assigned: Map<any, boolean> | undefined;36- base: Map<any, any>;37- revoke(): void;38- draft: ES5Draft;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 41-function prepareCopy(state: MapState) {42- if (!state.copy) {43- state.assigned = new Map()44- state.copy = new Map(state.base);45- }46-}47-16 // Make sure DraftMap declarion doesn't die if Map is not avialable...49-const MapBase: MapConstructor = typeof Map !== "undefined" ? Map : function FakeMap() {} as any17+const MapBase: MapConstructor =18+ typeof Map !== "undefined" ? Map : (function FakeMap() {} as any)19 51-// TODO: fix types for drafts20 export class DraftMap<K, V> extends MapBase implements Map<K, V> {21 [DRAFT_STATE]: MapState54- constructor(target, parent) {22+ constructor(target: AnyMap, parent?: ImmerState) {23 super()24 this[DRAFT_STATE] = {25+ type: ProxyType.Map,26 parent,58- scope: parent ? parent.scope : ImmerScope.current,27+ scope: parent ? parent.scope : ImmerScope.current!,28 modified: false,29 finalized: false,61- finalizing: false,30 copy: undefined,31 assigned: undefined,32 base: target,65- draft: this as any, // TODO: fix typing66- revoke() {67- // TODO: make sure this marks the Map as revoked, and assert everywhere68- }69- };33+ draft: this,34+ isManual: false,35+ revoked: false36+ }37 }38 39 get size(): number {40 return latest(this[DRAFT_STATE]).size3 unmodified lines44 return latest(this[DRAFT_STATE]).has(key)45 }46 47 set(key: K, value: V): this {81- const state = this[DRAFT_STATE];48+ const state = this[DRAFT_STATE]49+ assertUnrevoked(state)50 if (latest(state).get(key) !== value) {51 prepareCopy(state)84- state.scope.immer.markChanged(state) // TODO: this needs to bubble up recursively correctly52+ state.scope.immer.markChanged(state)53 state.assigned!.set(key, true)54 state.copy!.set(key, value)87- state.assigned!.set(key, true);55+ state.assigned!.set(key, true)56 }57 return this58 }59 60 delete(key: K): boolean {61 if (!this.has(key)) {94- return false;62+ return false63 }64 97- const state = this[DRAFT_STATE];65+ const state = this[DRAFT_STATE]66+ assertUnrevoked(state)67 prepareCopy(state)68 state.scope.immer.markChanged(state)69 state.assigned!.set(key, false)70 state.copy!.delete(key)71 return true72 }73 74 clear() {106- const state = this[DRAFT_STATE];75+ const state = this[DRAFT_STATE]76+ assertUnrevoked(state)77 prepareCopy(state)78 state.scope.immer.markChanged(state)79 state.assigned = new Map()80 for (const key of latest(state).keys()) {1 unmodified line82 }83 return state.copy!.clear()84 }85 116- // @ts-ignore TODO:117- forEach(cb) {118- const state = this[DRAFT_STATE];119- latest(state).forEach((_value, key, _map) => {120- cb(this.get(key), key, this)86+ forEach(cb: (value: V, key: K, self: this) => void, thisArg?: any) {87+ const state = this[DRAFT_STATE]88+ latest(state).forEach((_value: V, key: K, _map: this) => {89+ cb.call(thisArg, this.get(key), key, this)90 })91 }92 124- get(key: K): V /* TODO: Draft<V> */ {125- const state = this[DRAFT_STATE];93+ get(key: K): V {94+ const state = this[DRAFT_STATE]95+ assertUnrevoked(state)96 const value = latest(state).get(key)127- if (state.finalizing || state.finalized || !isDraftable(value)) {97+ if (state.finalized || !isDraftable(value)) {98 return value99 }100 if (value !== state.base.get(key)) {101 return value // either already drafted or reassigned4 unmodified lines106 state.copy!.set(key, draft)107 return draft108 }109 140- keys() {141- return latest(this[DRAFT_STATE]).keys();110+ keys(): IterableIterator<K> {111+ return latest(this[DRAFT_STATE]).keys()112 }113 144- values() {114+ values(): IterableIterator<V> {115 const iterator = this.keys()116 return {147- [Symbol.iterator]: () => this.values(), // TODO: don't use symbol directly117+ [iteratorSymbol]: () => this.values(),118 next: () => {119 const r = iterator.next()150- if (r.done) return r;151- const value = this.get(r.value);120+ if (r.done) return r121+ const value = this.get(r.value)122 return {153- done: false, value123+ done: false,124+ value125 }126 }127 } as any128 }129 159- entries() {130+ entries(): IterableIterator<[K, V]> {131 const iterator = this.keys()132 return {162- [Symbol.iterator]: () => this.entries(), // TODO: don't use symbol directly133+ [iteratorSymbol]: () => this.entries(),134 next: () => {135 const r = iterator.next()165- if (r.done) return r;166- const value = this.get(r.value);136+ if (r.done) return r137+ const value = this.get(r.value)138 return {168- done: false, value: [r.value, value]139+ done: false,140+ value: [r.value, value]141 }142 }143 } as any144 }145 174- [Symbol.iterator]() { // TODO: don't use symbol directly146+ [iteratorSymbol]() {147 return this.entries()148 }149 }150 179-180-/** Map.prototype.values _-or-_ Map.prototype.entries */181-export function iterateMapValues(state, prop, receiver) {182- const isEntries = prop !== "values"183- return () => {184- const iterator = latest(state)[Symbol.iterator]()185- return makeIterable(() => {186- const result = iterator.next()187- if (!result.done) {188- const [key] = result.value189- const value = receiver.get(key)190- result.value = isEntries ? [key, value] : value191- }192- return result193- })194- }195-}196-197-198-199-export function proxyMap(target, parent) {151+export function proxyMap(target: AnyMap, parent?: ImmerState) {200- if (target instanceof DraftMap) {201- return target; // TODO: or copy?202- }152 return new DraftMap(target, parent)204- // Object.defineProperties(target, mapTraps)205-153 }154 208-// TODO: kill?209-function proxyMethod(trap, key) {210- return {211- get() {212- return function(this: ES5Draft, ...args) {213- const state = this[DRAFT_STATE]214- assertUnrevoked(state)215- return trap(state, key, state.draft)(...args)216- }217- }155+function prepareCopy(state: MapState) {156+ if (!state.copy) {157+ state.assigned = new Map()158+ state.copy = new Map(state.base)159 }160 }220-221-// TODO: used?222-export function hasMapChanges(state) {223- const {base, draft} = state224-225- if (base.size !== draft.size) return true226-227- // IE11 supports only forEach iteration228- let hasChanges = false229- // TODO: optimize: break on first difference230- draft.forEach(function(value, key) {231- if (!hasChanges) {232- hasChanges = isDraftable(value) ? value.modified : value !== base.get(key)233- }234- })235- return hasChanges236-}modified:src/patches.ts+96 added-56 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+ if (!copy) die()47 48 // Reduce complexity by ensuring `base` is never longer.28- if (copy.length < base.length) {49+ if (copy!.length < base.length) {50+ // @ts-ignore51 ;[base, copy] = [copy, base]52 ;[patches, inversePatches] = [inversePatches, patches]53 }54 46 unmodified lines101 }102 103 // This is used for both Map objects and normal objects.104 function generatePatchesFromAssigned(83- state: ImmerState,84- basePath: (number | string)[],105+ state: MapState | ES5ObjectState | ProxyObjectState,106+ basePath: PatchPath,107 patches: Patch[],108 inversePatches: Patch[]109 ) {110 const {base, copy} = state89- if (state.assigned) each(state.assigned, (key, assignedValue) => {111+ each(state.assigned!, (key, assignedValue) => {112 const origValue = get(base, key)91- const value = get(copy, key)113+ const value = get(copy!, key)114 const op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add"115 if (origValue === value && op === "replace") return116 const path = basePath.concat(key as any)117 patches.push(op === "remove" ? {op, path} : {op, path, value})7 unmodified lines125 })126 }127 128 function generateSetPatches(107- state: ImmerState,108- basePath: (number | string)[],129+ state: SetState,130+ basePath: PatchPath,131 patches: Patch[],132 inversePatches: Patch[]133 ) {112- // TODO: if this doesn't use assigned, drop assigned from SetState stuff134 let {base, copy} = state135 136 let i = 0137 base.forEach(value => {117- if (!copy.has(value)) {138+ if (!copy!.has(value)) {139 const path = basePath.concat([i])140 patches.push({141 op: "remove",142 path,7 unmodified lines150 }151 i++152 })153 i = 0133- copy.forEach(value => {154+ copy!.forEach(value => {155 if (!base.has(value)) {156 const path = basePath.concat([i])157 patches.push({158 op: "add",13 unmodified lines172 export function applyPatches<T>(draft: T, patches: Patch[]): T {173 patches.forEach(patch => {174 const {path, op} = patch175 155- if (!path.length) throw new Error("Illegal state")176+ if (!path.length) die()177 157- let base = draft178+ let base: any = draft179 for (let i = 0; i < path.length - 1; i++) {180 base = get(base, path[i])181 if (!base || typeof base !== "object")182 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore183 }184 164- const value = clone(patch.value) // used to clone patch to ensure original patch is not modified, see #411165-185+ const type = getArchtype(base)186+ const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411187 const key = path[path.length - 1]188 switch (op) {189 case "replace":190+ switch (type) {169- if (isMap(base)) {170- base.set(key, value)171- } else if (isSet(base)) {172- throw new Error('Sets cannot have "replace" patches.')173- } else {174- // if value is an object, then it's assigned by reference175- // in the following add or remove ops, the value field inside the patch will also be modifyed176- // so we use value from the cloned patch177- base[key] = value191+ case Archtype.Map:192+ return base.set(key, value)193+ case Archtype.Set:194+ throw new Error('Sets cannot have "replace" patches.')195+ default:196+ // if value is an object, then it's assigned by reference197+ // in the following add or remove ops, the value field inside the patch will also be modifyed198+ // so we use value from the cloned patch199+ // @ts-ignore200+ return (base[key] = value)201 }202 break203 case "add":181- if (isSet(base)) {182- base.delete(patch.value)204+ switch (type) {205+ case Archtype.Array:206+ return base.splice(key as any, 0, value)207+ case Archtype.Map:208+ return base.set(key, value)209+ case Archtype.Set:210+ return base.add(value)211+ default:212+ return (base[key] = value)213 }184-185- Array.isArray(base)186- ? base.splice(key as any, 0, value)187- : isMap(base)188- ? base.set(key, value)189- : isSet(base)190- ? base.add(value)191- : (base[key] = value)192- break214 case "remove":194- Array.isArray(base)195- ? base.splice(key as any, 1)196- : isMap(base)197- ? base.delete(key)198- : isSet(base)199- ? base.delete(patch.value)200- : delete base[key]201- break215+ switch (type) {216+ case Archtype.Array:217+ return base.splice(key as any, 1)218+ case Archtype.Map:219+ return base.delete(key)220+ case Archtype.Set:221+ return base.delete(patch.value)222+ default:223+ return delete base[key]224+ }225 default:226 throw new Error("Unsupported patch operation: " + op)227 }228 })229 230 return draft231 }232+233+// TODO: optimize: this is quite a performance hit, can we detect intelligently when it is needed?234+// E.g. auto-draft when new objects from outside are assigned and modified?235+// (See failing test when deepClone just returns obj)236+function deepClonePatchValue<T>(obj: T): T237+function deepClonePatchValue(obj: any) {238+ if (!obj || typeof obj !== "object") return obj239+ if (Array.isArray(obj)) return obj.map(deepClonePatchValue)240+ if (isMap(obj))241+ return new Map(242+ Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])243+ )244+ // Not needed: if (isSet(obj)) return new Set(Array.from(obj.values()).map(deepClone))245+ const cloned = Object.create(Object.getPrototypeOf(obj))246+ for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])247+ return cloned248+}modified:src/proxy.ts+76 added-115 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,9 latest10 } from "./common"11 import {ImmerScope} from "./scope"21-import {proxyMap} from "./map"22-import {proxySet} from "./set"12+import {13+ AnyObject,14+ Drafted,15+ ImmerState,16+ AnyArray,17+ Objectish,18+ ImmerBaseState,19+ ProxyType20+} from "./types"21 24-// Do nothing before being finalized.25-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 27-interface ES6Draft {}33+export interface ProxyObjectState extends ProxyBaseState {34+ type: ProxyType.ProxyObject35+ base: AnyObject36+ copy: AnyObject | null37+ draft: Drafted<AnyObject, ProxyObjectState>38+}39 29-interface ES6State<T = any> {30- scope: ImmerScope31- modified: boolean32- finalized: boolean33- assigned:34- | {35- [property: string]: boolean36- }37- | Map<string, boolean> // TODO: always use a Map?38- parent: ES6State39- base: T40- draft: ES6Draft | null41- drafts:42- | {43- [property: string]: ES6Draft44- }45- | Map<string, ES6Draft> // TODO: always use a Map?46- copy: T | null47- 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 */55-export function createProxy<T extends object>(54+export function createProxy<T extends Objectish>(55 base: T,57- parent: ES6State58-): ES6Draft {59- // TODO: dedupe60- if (!base || typeof base !== "object" || !isDraftable(base)) {61- // TODO: || isDraft ?62- return base as any // TODO: fix63- }64-65- const scope = parent ? parent.scope : ImmerScope.current!66-67- // TODO: dedupe this, it is the same for ES568- if (isMap(base)) {69- const draft = proxyMap(base, parent) as any // TODO: typefix70- scope.drafts.push(draft)71- return draft72- }73- if (isSet(base)) {74- const draft = proxySet(base, parent) as any // TODO: typefix75- scope.drafts.push(draft)76- return draft77- }78-79- 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.81- 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.93- 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.99- 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>> = objectTraps110- if (Array.isArray(base)) {92+ if (isArray) {93 target = [state] as any94 traps = arrayTraps95 }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)116-117- state.draft = proxy100+ state.draft = proxy as any101 state.revoke = revoke119-120- scope.drafts!.push(proxy)121- return proxy102+ return proxy as any103 }104 105 /**106 * Object drafts107 */127-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)) {134- 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 150- 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 },158- 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 = value165- ? 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-ignore172- state.copy[prop] = value155+ state.copy![prop] = value156 return true157 },175- 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)1 unmodified line164 } 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 = true195- 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 214-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 234-// Used by Map and Set drafts235-const reflectTraps = makeReflectTraps([236- "ownKeys",237- "has",238- "set",239- "deleteProperty",240- "defineProperty",241- "getOwnPropertyDescriptor",242- "preventExtensions",243- "isExtensible",244- "getPrototypeOf"245-])246-220 /**221 * Map drafts222 */223 224 // Access a property without creating an Immer draft.252-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 261-// TODO: unify with ES5 version, by getting rid of the drafts vs copy distinction?262-export function markChanged(state) {234+export function markChanged(state: ImmerState) {235 if (!state.modified) {236 state.modified = true265- const {base, drafts, parent} = state266- if (!isMap(base) && !isSet(base)) {267- // TODO: drop creating copies here?268- const copy = (state.copy = shallowCopy(base))269- assign(copy, drafts)270- 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 273- if (parent) {274- markChanged(parent)249+ if (state.parent) {250+ markChanged(state.parent)251 }252 }253 }254 279-// TODO: unify with ES5 version280-function prepareCopy(state) {255+function prepareCopy(state: ProxyState) {256 if (!state.copy) {257 state.copy = shallowCopy(state.base)258 }259 }285-286-/** Create traps that all use the `Reflect` API on the `latest(state)` */287-function makeReflectTraps<T extends object>(288- names: (keyof typeof Reflect)[]289-): ProxyHandler<T> {290- return names.reduce(291- (traps, name) => {292- // @ts-ignore293- traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)294- return traps295- },296- {} as any297- )298-}modified:src/scope.ts+11 added-8 removed
1 import {DRAFT_STATE} from "./common"2-import {ImmerState, Patch, PatchListener} from "./types"3-import { Immer } from "./immer"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?: ImmerScope13 unmodified lines21 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 = true25-26- // To avoid prototype lookups:27- this.patches = null as any // TODO:25 }26 27 usePatches(patchListener: PatchListener) {28 if (patchListener) {6 unmodified lines35 revoke() {36 this.leave()37 this.drafts.forEach(revoke)38 // @ts-ignore42- this.drafts = null // TODO: // Make draft-related methods throw.39+ this.drafts = null40 }41 42 leave() {43 if (this === ImmerScope.current) {7 unmodified lines51 return scope52 }53 }54 58-function revoke(draft) {59- 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 }modified:src/set.ts+59 added-98 removed
1-import {2- each,3- has,4- is,5- isDraft,6- isDraftable,7- isEnumerable,8- isMap,9- isSet,10- hasSymbol,11- shallowCopy,12- DRAFT_STATE,13- makeIterable,14- latest,15- original,16- makeIterable217-} from "./common"1+import {DRAFT_STATE, latest, isDraftable, iteratorSymbol} from "./common"2 19-// TODO: kill:20-import {21- assertUnrevoked,22- ES5Draft,23-} from "./es5"24-import { ImmerScope } from "./scope";25-import { Immer } from "./immer";3+import {ImmerScope} from "./scope"4+import {AnySet, Drafted, ImmerState, ImmerBaseState, ProxyType} from "./types"5+import {assertUnrevoked} from "./es5"6 27-// TODO: create own states28-// TODO: clean up the maps and such from ES5 / Proxy states29-30-export interface SetState {31- parent: any; // TODO: type32- scope: ImmerScope;33- modified: boolean;34- finalizing: boolean;35- finalized: boolean;36- copy: Set<any> | undefined;37- // assigned: Map<any, boolean> | undefined;38- base: Set<any>;39- drafts: Map<any, any>; // maps the original value to the draft value in the new set40- revoke(): void;41- draft: ES5Draft;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 44-function prepareCopy(state: SetState) {45- if (!state.copy) {46- // create drafts for all entries to preserve insertion order47- state.copy = new Set()48- state.base.forEach(value => {49- const draft = state.scope.immer.createProxy(value, state);50- state.copy!.add(draft)51- state.drafts.set(value, draft)52- })53- }54-}55-16 // Make sure DraftSet declarion doesn't die if Map is not avialable...57-const SetBase: SetConstructor = typeof Set !== "undefined" ? Set : function FakeSet() {} as any17+const SetBase: SetConstructor =18+ typeof Set !== "undefined" ? Set : (function FakeSet() {} as any)19 59-// TODO: fix types for drafts20 export class DraftSet<K, V> extends SetBase implements Set<V> {21 [DRAFT_STATE]: SetState62- constructor(target, parent) {22+ constructor(target: AnySet, parent?: ImmerState) {23 super()24 this[DRAFT_STATE] = {25+ type: ProxyType.Set,26 parent,66- scope: parent ? parent.scope : ImmerScope.current,27+ scope: parent ? parent.scope : ImmerScope.current!,28 modified: false,29 finalized: false,69- finalizing: false,30 copy: undefined,31 base: target,72- draft: this as any, // TODO: fix typing32+ draft: this,33 drafts: new Map(),74- revoke() {75- // TODO: make sure this marks the Map as revoked, and assert everywhere76- }77- };34+ revoked: false,35+ isManual: false36+ }37 }38 39 get size(): number {40 return latest(this[DRAFT_STATE]).size41 }42 43 has(value: V): boolean {44 const state = this[DRAFT_STATE]45+ assertUnrevoked(state)46 // bit of trickery here, to be able to recognize both the value, and the draft of its value47 if (!state.copy) {48 return state.base.has(value)49 }90- if (state.copy.has(value)) return true;91- if (state.drafts.has(value) && state.copy.has(state.drafts.get(value))) return true;92- return false;50+ if (state.copy.has(value)) return true51+ if (state.drafts.has(value) && state.copy.has(state.drafts.get(value)))52+ return true53+ return false54 }55 56 add(value: V): this {96- const state = this[DRAFT_STATE];57+ const state = this[DRAFT_STATE]58+ assertUnrevoked(state)59 if (state.copy) {60 state.copy.add(value)61 } else if (!state.base.has(value)) {62 prepareCopy(state)101- state.scope.immer.markChanged(state) // TODO: this needs to bubble up recursively correctly63+ state.scope.immer.markChanged(state)64 state.copy!.add(value)65 }66 return this67 }68 69 delete(value: V): boolean {108- const state = this[DRAFT_STATE];70 if (!this.has(value)) {110- return false;71+ return false72 }73 74+ const state = this[DRAFT_STATE]75+ assertUnrevoked(state)76 prepareCopy(state)77 state.scope.immer.markChanged(state)115- return state.copy!.delete(value) || (state.drafts.has(value) ? state.copy!.delete(state.drafts.get(value)) : false)78+ return (79+ state.copy!.delete(value) ||80+ (state.drafts.has(value)81+ ? state.copy!.delete(state.drafts.get(value))82+ : false)83+ )84 }85 86 clear() {119- const state = this[DRAFT_STATE];87+ const state = this[DRAFT_STATE]88+ assertUnrevoked(state)89 prepareCopy(state)90 state.scope.immer.markChanged(state)91 return state.copy!.clear()92 }93 94 values(): IterableIterator<V> {95 const state = this[DRAFT_STATE]96+ assertUnrevoked(state)97 prepareCopy(state)98 return state.copy!.values()99 }100 101 entries(): IterableIterator<[V, V]> {102 const state = this[DRAFT_STATE]103+ assertUnrevoked(state)104 prepareCopy(state)105 return state.copy!.entries()106 }107 108 keys(): IterableIterator<V> {109 return this.values()110 }111 141- // TODO: factor out symbol142- [Symbol.iterator]() {112+ [iteratorSymbol]() {113 return this.values()114 }115 146- forEach(cb, thisArg) {147- const state = this[DRAFT_STATE]116+ forEach(cb: (value: V, key: V, self: this) => void, thisArg?: any) {117 const iterator = this.values()118 let result = iterator.next()119 while (!result.done) {151- cb.call(thisArg, result.value, result.value, state.draft)120+ cb.call(thisArg, result.value, result.value, this)121 result = iterator.next()122 }123 }124 }125 157-158-export function proxySet(target, parent) {126+export function proxySet(target: AnySet, parent?: ImmerState) {159- if (target instanceof DraftSet) {160- return target; // TODO: or copy?161- }127 return new DraftSet(target, parent)128 }129 165-// const iterateSetValues = makeIterateSetValues()166-167-168-169-export function hasSetChanges(state) {170- const {base, draft} = state171-172- if (base.size !== draft.size) return true173-174- // IE11 supports only forEach iteration175- let hasChanges = false176- // TODO: optimize: break on first diff177- draft.forEach(function(value, key) {178- if (!hasChanges) {179- hasChanges = isDraftable(value) ? value.modified : !base.has(key)180- }181- })182- return hasChanges130+function prepareCopy(state: SetState) {131+ if (!state.copy) {132+ // create drafts for all entries to preserve insertion order133+ state.copy = new Set()134+ state.base.forEach(value => {135+ if (isDraftable(value)) {136+ const draft = state.scope.immer.createProxy(value, state)137+ state.drafts.set(value, draft)138+ state.copy!.add(draft)139+ } else {140+ state.copy!.add(value)141+ }142+ })143+ }144 }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+3 added-2 removed
5 unmodified lines6 "target": "ES6",7 "strict": true,8 "declaration": true,9 "importHelpers": false,10- "noImplicitAny": false, // TODO: true,11- "esModuleInterop": true10+ "noImplicitAny": true,11+ "esModuleInterop": true,12+ "noUnusedLocals": true13 }14 }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