Skip to content
Myr

fix: Map and Set instantions won't work on certain environments, fixes #502

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Michel Weststrate · committed by GitHub · parents 49ff121, 7639c29 · Browse files · 18 files+307 added−184 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

18 files+307 added−184 removed

  • tests:+18 added−3 removed
  • other:+289 added−181 removed

18 files+307 added−184 removed

modified:__tests__/base.js+15 added-1 removed
1"use strict"2import {Immer, nothing, original, isDraft, immerable} from "../src/index"3import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/common"3import {each, shallowCopy, isEnumerable, DRAFT_STATE} from "../src/internal"4import deepFreeze from "deep-freeze"5import cloneDeep from "lodash.clonedeep"6import * as lodash from "lodash"7
573 unmodified lines
581 expect(entries).toEqual([[key, 4]])582 expect(entries[0][0]).toBe(key)583 expect(entries[0][0].a).toBe(2)584 })585586 it("does support instanceof Map", () => {587 const map = new Map()588 produce(map, d => {589 expect(d instanceof Map).toBeTruthy()590 })591 })592 })593594 describe("set drafts", () => {595 it("supports iteration", () => {
259 unmodified lines
855 expect(() => m.add("x")).toThrow(856 "Cannot use a proxy that has been revoked"857 )858 })859860 it("does support instanceof Set", () => {861 const set = new Set()862 produce(set, d => {863 expect(d instanceof Set).toBeTruthy()864 })865 })866 })867868 it("supports `immerable` symbol on constructor", () => {869 class One {}
1105 unmodified lines
modified:__tests__/empty.ts+2 added-1 removed
modified:__tests__/polyfills.js+1 added-1 removed
modified:src/common.ts+6 added-40 removed
1import {2 DRAFT_STATE,3 DRAFTABLE,4 hasSet,5 Objectish,6 Drafted,7 AnyObject,8 AnyArray,9 AnyMap,10 AnySet,11 ImmerState,12 ProxyType,10 Archtype11} from "./types"13 Archtype,14 hasMap15} from "./internal"1613/** Use a class type for `nothing` so its type is unique */14export class Nothing {15 // This lets us do `Exclude<T, Nothing>`16 // @ts-ignore17 private _!: unique symbol18}1920const hasSymbol = typeof Symbol !== "undefined"21export const hasMap = typeof Map !== "undefined"22export const hasSet = typeof Set !== "undefined"2324/**25 * The sentinel value returned by producers to replace the draft with undefined.26 */27export const NOTHING: Nothing = hasSymbol28 ? Symbol("immer-nothing")29 : ({["immer-nothing"]: true} as any)3031/**32 * To let Immer treat your class instances as plain immutable objects33 * (albeit with a custom prototype), you must define either an instance property34 * or a static property on each of your custom classes.35 *36 * Otherwise, your class instance will never be drafted, which means it won't be37 * safe to mutate in a produce callback.38 */39export const DRAFTABLE: unique symbol = hasSymbol40 ? Symbol("immer-draftable")41 : ("__$immer_draftable" as any)4243export const DRAFT_STATE: unique symbol = hasSymbol44 ? Symbol("immer-state")45 : ("__$immer_state" as any)4647export const iteratorSymbol: typeof Symbol.iterator = hasSymbol48 ? Symbol.iterator49 : ("@@iterator" as any)5017/** Returns true if the given value is an Immer draft */18export function isDraft(value: any): boolean {19 return !!value && !!value[DRAFT_STATE]20}
191 unmodified lines
added:src/env.ts+40 added
1// Should be no imports here!23// SOme things that should be evaluated before all else...4const hasSymbol = typeof Symbol !== "undefined"5export const hasMap = typeof Map !== "undefined"6export const hasSet = typeof Set !== "undefined"78/**9 * The sentinel value returned by producers to replace the draft with undefined.10 */11export const NOTHING: Nothing = hasSymbol12 ? Symbol("immer-nothing")13 : ({["immer-nothing"]: true} as any)1415/**16 * To let Immer treat your class instances as plain immutable objects17 * (albeit with a custom prototype), you must define either an instance property18 * or a static property on each of your custom classes.19 *20 * Otherwise, your class instance will never be drafted, which means it won't be21 * safe to mutate in a produce callback.22 */23export const DRAFTABLE: unique symbol = hasSymbol24 ? Symbol("immer-draftable")25 : ("__$immer_draftable" as any)2627export const DRAFT_STATE: unique symbol = hasSymbol28 ? Symbol("immer-state")29 : ("__$immer_state" as any)3031export const iteratorSymbol: typeof Symbol.iterator = hasSymbol32 ? Symbol.iterator33 : ("@@iterator" as any)3435/** Use a class type for `nothing` so its type is unique */36export class Nothing {37 // This lets us do `Exclude<T, Nothing>`38 // @ts-ignore39 private _!: unique symbol40}
modified:src/es5.ts+7 added-10 removed
5 unmodified lines
6 isDraft,7 isDraftable,8 isEnumerable,9 shallowCopy,10 DRAFT_STATE,10 latest,12 createHiddenProperty13} from "./common"1415import {ImmerScope} from "./scope"16import {11 createHiddenProperty,12 ImmerScope,13 ImmerState,14 Drafted,15 AnyObject,16 Objectish,17 ImmerBaseState,18 AnyArray,23 ProxyType24} from "./types"25import {MapState} from "./map"26import {SetState} from "./set"19 ProxyType,20 MapState,21 SetState,22 DRAFT_STATE23} from "./internal"2425interface ES5BaseState extends ImmerBaseState {26 finalizing: boolean27 assigned: {[key: string]: any}
276 unmodified lines
added:src/extends.ts+23 added
1var extendStatics = function(d: any, b: any): any {2 extendStatics =3 Object.setPrototypeOf ||4 ({__proto__: []} instanceof Array &&5 function(d, b) {6 d.__proto__ = b7 }) ||8 function(d, b) {9 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]10 }11 return extendStatics(d, b)12}1314// Ugly hack to resolve #502 and inherit built in Map / Set15export function __extends(d: any, b: any): any {16 extendStatics(d, b)17 function __(this: any): any {18 this.constructor = d19 }20 d.prototype =21 // @ts-ignore22 ((__.prototype = b.prototype), new __())23}
modified:src/finalize.ts+17 added-13 removed
1import {Immer} from "./immer"2import {ImmerState, Drafted, ProxyType} from "./types"3import {ImmerScope} from "./scope"1import {5 isSet,6 has,7 is,8 get,9 each,2 Immer,3 ImmerScope,4 DRAFT_STATE,5 isDraftable,6 NOTHING,7 Drafted,8 PatchPath,9 ProxyType,10 each,11 has,12 freeze,13 generatePatches,14 shallowCopy,14 set15} from "./common"16import {isDraft, isDraftable} from "./index"17import {SetState} from "./set"18import {generatePatches, PatchPath} from "./patches"15 ImmerState,16 isSet,17 isDraft,18 SetState,19 set,20 is,21 get22} from "./internal"2324export function processResult(immer: Immer, result: any, scope: ImmerScope) {25 const baseDraft = scope.drafts![0]26 const isReplaced = result !== undefined && result !== baseDraft
181 unmodified lines
modified:src/immer.ts+23 added-22 removed
1import {createES5Proxy, willFinalizeES5, markChangedES5} from "./es5"2import {createProxy, markChanged} from "./proxy"34import {applyPatches} from "./patches"1import {2 createES5Proxy,3 willFinalizeES5,4 markChangedES5,5 IProduceWithPatches,6 IProduce,7 ImmerState,8 each,7 isDraft,8 isSet,9 isMap,9 Drafted,10 isDraftable,11 DRAFT_STATE,11 ImmerScope,12 processResult,13 NOTHING,13 die14} from "./common"15import {ImmerScope} from "./scope"16import {17 ImmerState,18 IProduce,19 IProduceWithPatches,14 maybeFreeze,15 die,16 Patch,17 Objectish,21 PatchListener,18 DRAFT_STATE,19 Draft,23 Patch,24 Drafted25} from "./types"26import {proxyMap} from "./map"27import {proxySet} from "./set"28import {processResult, maybeFreeze} from "./finalize"20 PatchListener,21 isDraft,22 applyPatches,23 isMap,24 proxyMap,25 isSet,26 proxySet,27 createProxy,28 markChanged29} from "./internal"3031/* istanbul ignore next */32function verifyMinified() {}33
244 unmodified lines
modified:src/index.ts+12 added-11 removed
1import {Immer} from "./immer"2import {IProduce, IProduceWithPatches} from "./types"1import {IProduce, IProduceWithPatches, Immer} from "./internal"24export {Draft, Immutable, Patch, PatchListener} from "./types"3export {4 Draft,5 Immutable,6 Patch,7 PatchListener,8 original,9 isDraft,10 isDraftable,11 NOTHING as nothing,12 DRAFTABLE as immerable13} from "./internal"1415const immer = new Immer()1617/**
63 unmodified lines
81 * changes that were made.82 */83export const finishDraft = immer.finishDraft.bind(immer)8476export {77 original,78 isDraft,79 isDraftable,80 NOTHING as nothing,81 DRAFTABLE as immerable82} from "./common"8385export {Immer}
added:src/internal.ts+12 added
1export * from "./env"2export * from "./extends"3export * from "./types"4export * from "./common"5export * from "./scope"6export * from "./finalize"7export * from "./proxy"8export * from "./es5"9export * from "./map"10export * from "./set"11export * from "./patches"12export * from "./immer"
modified:src/map.ts+55 added-31 removed
1import {isDraftable, DRAFT_STATE, latest, iteratorSymbol} from "./common"1import {2 __extends,3 ImmerBaseState,4 ProxyType,5 AnyMap,6 Drafted,7 ImmerState,8 DRAFT_STATE,9 ImmerScope,10 latest,11 assertUnrevoked,12 isDraftable,13 iteratorSymbol14} from "./internal"153import {ImmerScope} from "./scope"4import {AnyMap, Drafted, ImmerState, ImmerBaseState, ProxyType} from "./types"5import {assertUnrevoked} from "./es5"616export interface MapState extends ImmerBaseState {17 type: ProxyType.Map18 copy: AnyMap | undefined19 assigned: Map<any, boolean> | undefined
1 unmodified line
21 revoked: boolean22 draft: Drafted<AnyMap, MapState>23}2416// Make sure DraftMap declarion doesn't die if Map is not avialable...17/* istanbul ignore next */18const MapBase: MapConstructor =19 typeof Map !== "undefined" ? Map : (function FakeMap() {} as any)2021export class DraftMap<K, V> extends MapBase implements Map<K, V> {22 [DRAFT_STATE]: MapState23 constructor(target: AnyMap, parent?: ImmerState) {24 super()25const DraftMap = (function(_super) {26 if (!_super) {27 /* istanbul ignore next */28 throw new Error("Map is not polyfilled")29 }30 __extends(DraftMap, _super)31 // Create class manually, cause #50232 function DraftMap(this: any, target: AnyMap, parent?: ImmerState): any {33 this[DRAFT_STATE] = {34 type: ProxyType.Map,35 parent,36 scope: parent ? parent.scope : ImmerScope.current!,
1 unmodified line
38 finalized: false,39 copy: undefined,40 assigned: undefined,41 base: target,34 draft: this,42 draft: this as any,43 isManual: false,44 revoked: false45 }46 return this47 }48 const p = DraftMap.prototype4950 // TODO: smaller build size if we create a util for Object.defineProperty51 Object.defineProperty(p, "size", {40 get size(): number {41 return latest(this[DRAFT_STATE]).size42 }52 get: function() {53 return latest(this[DRAFT_STATE]).size54 },55 enumerable: true,56 configurable: true57 })5844 has(key: K): boolean {59 p.has = function(key: any): boolean {60 return latest(this[DRAFT_STATE]).has(key)61 }6248 set(key: K, value: V): this {63 p.set = function(key: any, value: any) {64 const state = this[DRAFT_STATE]65 assertUnrevoked(state)66 if (latest(state).get(key) !== value) {67 prepareCopy(state)
4 unmodified lines
72 }73 return this74 }7561 delete(key: K): boolean {76 p.delete = function(key: any): boolean {77 if (!this.has(key)) {78 return false79 }80
5 unmodified lines
86 state.copy!.delete(key)87 return true88 }8975 clear() {90 p.clear = function() {91 const state = this[DRAFT_STATE]92 assertUnrevoked(state)93 prepareCopy(state)94 state.scope.immer.markChanged(state)
3 unmodified lines
98 }99 return state.copy!.clear()100 }10187 forEach(cb: (value: V, key: K, self: this) => void, thisArg?: any) {102 p.forEach = function(103 cb: (value: any, key: any, self: any) => void,104 thisArg?: any105 ) {106 const state = this[DRAFT_STATE]89 latest(state).forEach((_value: V, key: K, _map: this) => {107 latest(state).forEach((_value: any, key: any, _map: any) => {108 cb.call(thisArg, this.get(key), key, this)109 })110 }11194 get(key: K): V {112 p.get = function(key: any): any {113 const state = this[DRAFT_STATE]114 assertUnrevoked(state)115 const value = latest(state).get(key)116 if (state.finalized || !isDraftable(value)) {
8 unmodified lines
125 state.copy!.set(key, draft)126 return draft127 }128111 keys(): IterableIterator<K> {129 p.keys = function(): IterableIterator<any> {130 return latest(this[DRAFT_STATE]).keys()131 }132115 values(): IterableIterator<V> {133 p.values = function(): IterableIterator<any> {134 const iterator = this.keys()135 return {136 [iteratorSymbol]: () => this.values(),137 next: () => {
8 unmodified lines
146 }147 } as any148 }149132 entries(): IterableIterator<[K, V]> {150 p.entries = function(): IterableIterator<[any, any]> {151 const iterator = this.keys()152 return {153 [iteratorSymbol]: () => this.entries(),154 next: () => {
8 unmodified lines
163 }164 } as any165 }166149 [iteratorSymbol]() {167 p[iteratorSymbol] = function() {168 return this.entries()169 }152}170154export function proxyMap(target: AnyMap, parent?: ImmerState) {171 return DraftMap172})(Map)173174export function proxyMap<T extends AnyMap>(175 target: T,176 parent?: ImmerState177): T & {[DRAFT_STATE]: MapState} {178 // @ts-ignore179 return new DraftMap(target, parent)180}181182function prepareCopy(state: MapState) {
5 unmodified lines
modified:src/patches.ts+18 added-6 removed
1import {get, each, isMap, has, die, getArchtype} from "./common"2import {Patch, ImmerState, ProxyType, Archtype} from "./types"3import {SetState} from "./set"4import {ES5ArrayState, ES5ObjectState} from "./es5"5import {ProxyArrayState, ProxyObjectState} from "./proxy"6import {MapState} from "./map"1import {2 get,3 each,4 has,5 die,6 getArchtype,7 ImmerState,8 Patch,9 ProxyType,10 SetState,11 ES5ArrayState,12 ProxyArrayState,13 MapState,14 ES5ObjectState,15 ProxyObjectState,16 Archtype,17 isMap18} from "./internal"1920export type PatchPath = (string | number)[]2122export function generatePatches(
240 unmodified lines
modified:src/proxy.ts+8 added-10 removed
3 unmodified lines
4 has,5 is,6 isDraftable,7 shallowCopy,8 DRAFT_STATE,9 latest10} from "./common"11import {ImmerScope} from "./scope"12import {13 AnyObject,14 Drafted,8 latest,9 ImmerBaseState,10 ImmerState,11 Drafted,12 ProxyType,13 AnyObject,14 AnyArray,15 Objectish,18 ImmerBaseState,19 ProxyType20} from "./types"16 ImmerScope,17 DRAFT_STATE18} from "./internal"1920interface ProxyBaseState extends ImmerBaseState {21 assigned: {22 [property: string]: boolean
235 unmodified lines
modified:src/scope.ts+8 added-3 removed
1import {DRAFT_STATE} from "./common"2import {Patch, PatchListener, Drafted, ProxyType} from "./types"3import {Immer} from "./immer"1import {2 Patch,3 PatchListener,4 Drafted,5 ProxyType,6 Immer,7 DRAFT_STATE8} from "./internal"910/** Each scope represents a `produce` call. */11export class ImmerScope {12 static current?: ImmerScope
56 unmodified lines
modified:src/set.ts+48 added-28 removed
1import {DRAFT_STATE, latest, isDraftable, iteratorSymbol} from "./common"1import {2 __extends,3 ImmerBaseState,4 ProxyType,5 AnySet,6 Drafted,7 ImmerState,8 DRAFT_STATE,9 ImmerScope,10 latest,11 assertUnrevoked,12 iteratorSymbol,13 isDraftable14} from "./internal"153import {ImmerScope} from "./scope"4import {AnySet, Drafted, ImmerState, ImmerBaseState, ProxyType} from "./types"5import {assertUnrevoked} from "./es5"616export interface SetState extends ImmerBaseState {17 type: ProxyType.Set18 copy: AnySet | undefined19 base: AnySet
1 unmodified line
21 revoked: boolean22 draft: Drafted<AnySet, SetState>23}2416// Make sure DraftSet declarion doesn't die if Map is not avialable...17/* istanbul ignore next */18const SetBase: SetConstructor =19 typeof Set !== "undefined" ? Set : (function FakeSet() {} as any)2021export class DraftSet<K, V> extends SetBase implements Set<V> {22 [DRAFT_STATE]: SetState23 constructor(target: AnySet, parent?: ImmerState) {24 super()25const DraftSet = (function(_super) {26 if (!_super) {27 /* istanbul ignore next */28 throw new Error("Set is not polyfilled")29 }30 __extends(DraftSet, _super)31 // Create class manually, cause #50232 function DraftSet(this: any, target: AnySet, parent?: ImmerState) {33 this[DRAFT_STATE] = {34 type: ProxyType.Set,35 parent,36 scope: parent ? parent.scope : ImmerScope.current!,
5 unmodified lines
42 drafts: new Map(),43 revoked: false,44 isManual: false45 }46 return this47 }48 const p = DraftSet.prototype4950 Object.defineProperty(p, "size", {40 get size(): number {41 return latest(this[DRAFT_STATE]).size42 }51 get: function() {52 return latest(this[DRAFT_STATE]).size53 },54 enumerable: true,55 configurable: true56 })5744 has(value: V): boolean {58 p.has = function(value: any): boolean {59 const state = this[DRAFT_STATE]60 assertUnrevoked(state)61 // bit of trickery here, to be able to recognize both the value, and the draft of its value62 if (!state.copy) {
4 unmodified lines
67 return true68 return false69 }7057 add(value: V): this {71 p.add = function(value: any): any {72 const state = this[DRAFT_STATE]73 assertUnrevoked(state)74 if (state.copy) {75 state.copy.add(value)
4 unmodified lines
80 }81 return this82 }8370 delete(value: V): boolean {84 p.delete = function(value: any): any {85 if (!this.has(value)) {86 return false87 }88
8 unmodified lines
97 : /* istanbul ignore next */ false)98 )99 }10087 clear() {101 p.clear = function() {102 const state = this[DRAFT_STATE]103 assertUnrevoked(state)104 prepareCopy(state)105 state.scope.immer.markChanged(state)106 return state.copy!.clear()107 }10895 values(): IterableIterator<V> {109 p.values = function(): IterableIterator<any> {110 const state = this[DRAFT_STATE]111 assertUnrevoked(state)112 prepareCopy(state)113 return state.copy!.values()114 }115102 entries(): IterableIterator<[V, V]> {116 p.entries = function entries(): IterableIterator<[any, any]> {117 const state = this[DRAFT_STATE]118 assertUnrevoked(state)119 prepareCopy(state)120 return state.copy!.entries()121 }122109 keys(): IterableIterator<V> {123 p.keys = function(): IterableIterator<any> {124 return this.values()125 }126113 [iteratorSymbol]() {127 p[iteratorSymbol] = function() {128 return this.values()129 }130117 forEach(cb: (value: V, key: V, self: this) => void, thisArg?: any) {131 p.forEach = function forEach(cb: any, thisArg?: any) {132 const iterator = this.values()133 let result = iterator.next()134 while (!result.done) {135 cb.call(thisArg, result.value, result.value, this)136 result = iterator.next()137 }138 }125}139127export function proxySet(target: AnySet, parent?: ImmerState) {140 return DraftSet141})(Set)142143export function proxySet<T extends AnySet>(144 target: T,145 parent?: ImmerState146): T & {[DRAFT_STATE]: SetState} {147 // @ts-ignore148 return new DraftSet(target, parent)149}150151function prepareCopy(state: SetState) {
14 unmodified lines
modified:src/types.ts+11 added-6 removed
1import {Nothing, DRAFT_STATE} from "./common"2import {SetState} from "./set"3import {MapState} from "./map"4import {ProxyObjectState, ProxyArrayState} from "./proxy"5import {ES5ObjectState, ES5ArrayState} from "./es5"6import {ImmerScope} from "./scope"1import {2 SetState,3 ImmerScope,4 ProxyObjectState,5 ProxyArrayState,6 ES5ObjectState,7 ES5ArrayState,8 MapState,9 DRAFT_STATE,10 Nothing11} from "./internal"1213export type Objectish = AnyObject | AnyArray | AnyMap | AnySet14export type ObjectishNoSet = AnyObject | AnyArray | AnyMap15
206 unmodified lines
modified:tsconfig.json+1 added-1 removed
1{2 "compilerOptions": {3 "lib": ["es2015"],4 "target": "ES6",4 "target": "ES5",5 "strict": true,6 "declaration": true,7 "importHelpers": false,8 "noImplicitAny": true,
9 unmodified lines