Removed some coupling
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent 9217809 · Browse files · 9 files·+900 added−843 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+900 added−843 removed
- other:+900 added−843 removed
Provenance
- Commit
70e77aa- Tree
24570a6- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
9217809
9 files changed+900 added−843 removed
modified:src/plugins/es5/es5.ts+262 added-248 removed
1-"use strict"1+// types only!2 import {3- each,4- has,5- is,6- isDraft,7- isDraftable,8- isEnumerable,9- shallowCopy,10- latest,11- createHiddenProperty,12- ImmerScope,3 ImmerState,4 Drafted,5 Objectish,16- ProxyType,17- DRAFT_STATE,18- loadPlugin,6 ES5ArrayState,20- ES5ObjectState,21- assertUnrevoked7+ ES5ObjectState8 } from "../../internal"9 10+import {__loadPlugin} from "../../../"11+12 type ES5State = ES5ArrayState | ES5ObjectState13 26-export function willFinalizeES5(27- scope: ImmerScope,28- result: any,29- isReplaced: boolean30-) {31- scope.drafts!.forEach(draft => {32- draft[DRAFT_STATE].finalizing = true33- })34- if (!isReplaced) {35- if (scope.patches) {36- markChangesRecursively(scope.drafts![0])37- }38- // This is faster when we don't care about which attributes changed.39- markChangesSweep(scope.drafts)40- }41- // When a child draft is returned, look for changes.42- else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {43- markChangesSweep(scope.drafts)44- }45-}14+// TODO: needs type import in TS 3.815+type ImmerScope = any // InstanceType<typeof ImmerScope>16 47-export function createES5Proxy<T>(48- base: T,49- parent?: ImmerState50-): Drafted<T, ES5ObjectState | ES5ArrayState> {51- const isArray = Array.isArray(base)52- const draft = clonePotentialDraft(base)53-54- each(draft, prop => {55- proxyProperty(draft, prop, isArray || isEnumerable(base, prop))56- })57-58- const state: ES5ObjectState | ES5ArrayState = {59- type: isArray ? ProxyType.ES5Array : (ProxyType.ES5Object as any),60- scope: parent ? parent.scope : ImmerScope.current!,61- modified: false,62- finalizing: false,63- finalized: false,64- assigned: {},65- parent,66- base,67- draft,68- copy: null,69- revoked: false,70- isManual: false71- }72-73- createHiddenProperty(draft, DRAFT_STATE, state)74- return draft75-}76-77-// Access a property without creating an Immer draft.78-function peek(draft: Drafted, prop: PropertyKey) {79- const state = draft[DRAFT_STATE]80- if (state && !state.finalizing) {81- state.finalizing = true82- const value = draft[prop]83- state.finalizing = false84- return value85- }86- return draft[prop]87-}88-89-function get(state: ES5State, prop: string | number) {90- assertUnrevoked(state)91- const value = peek(latest(state), prop)92- if (state.finalizing) return value93- // Create a draft if the value is unmodified.94- if (value === peek(state.base, prop) && isDraftable(value)) {95- prepareCopy(state)96- // @ts-ignore97- return (state.copy![prop] = state.scope.immer.createProxy(value, state))98- }99- return value100-}101-102-function set(state: ES5State, prop: string | number, value: any) {103- assertUnrevoked(state)104- state.assigned[prop] = true105- if (!state.modified) {106- if (is(value, peek(latest(state), prop))) return107- markChangedES5(state)108- prepareCopy(state)109- }17+__loadPlugin(18+ "es5",19 // @ts-ignore111- state.copy![prop] = value112-}20+ ({21+ each,22+ has,23+ isDraft,24+ isDraftable,25+ isEnumerable,26+ shallowCopy,27+ latest,28+ createHiddenProperty,29+ ProxyType,30+ DRAFT_STATE,31+ assertUnrevoked,32+ ImmerScope,33+ is34+ }) => {35+ function willFinalizeES5(36+ scope: ImmerScope,37+ result: any,38+ isReplaced: boolean39+ ) {40+ scope.drafts!.forEach(draft => {41+ draft[DRAFT_STATE].finalizing = true42+ })43+ if (!isReplaced) {44+ if (scope.patches) {45+ markChangesRecursively(scope.drafts![0])46+ }47+ // This is faster when we don't care about which attributes changed.48+ markChangesSweep(scope.drafts)49+ }50+ // When a child draft is returned, look for changes.51+ else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {52+ markChangesSweep(scope.drafts)53+ }54+ }55 114-export function markChangedES5(state: ImmerState) {115- if (!state.modified) {116- state.modified = true117- if (state.parent) markChangedES5(state.parent)118- }119-}56+ function createES5Proxy<T>(57+ base: T,58+ parent?: ImmerState59+ ): Drafted<T, ES5ObjectState | ES5ArrayState> {60+ const isArray = Array.isArray(base)61+ const draft = clonePotentialDraft(base)62 121-function prepareCopy(state: ES5State) {122- if (!state.copy) state.copy = clonePotentialDraft(state.base)123-}63+ each(draft, prop => {64+ proxyProperty(draft, prop, isArray || isEnumerable(base, prop))65+ })66 125-function clonePotentialDraft(base: Objectish) {126- const state = base && (base as any)[DRAFT_STATE]127- if (state) {128- state.finalizing = true129- const draft = shallowCopy(state.draft, true)130- state.finalizing = false131- return draft132- }133- return shallowCopy(base)134-}67+ const state: ES5ObjectState | ES5ArrayState = {68+ type: isArray ? ProxyType.ES5Array : (ProxyType.ES5Object as any),69+ scope: parent ? parent.scope : (ImmerScope as any).current!,70+ modified: false,71+ finalizing: false,72+ finalized: false,73+ assigned: {},74+ parent,75+ base,76+ draft,77+ copy: null,78+ revoked: false,79+ isManual: false80+ }81 136-// property descriptors are recycled to make sure we don't create a get and set closure per property,137-// but share them all instead138-const descriptors: {[prop: string]: PropertyDescriptor} = {}82+ createHiddenProperty(draft, DRAFT_STATE, state)83+ return draft84+ }85 140-function proxyProperty(141- draft: Drafted<any, ES5State>,142- prop: string | number,143- enumerable: boolean144-) {145- let desc = descriptors[prop]146- if (desc) {147- desc.enumerable = enumerable148- } else {149- descriptors[prop] = desc = {150- configurable: true,151- enumerable,152- get(this: any) {153- return get(this[DRAFT_STATE], prop)154- },155- set(this: any, value) {156- set(this[DRAFT_STATE], prop, value)86+ // Access a property without creating an Immer draft.87+ function peek(draft: Drafted, prop: PropertyKey) {88+ const state = draft[DRAFT_STATE]89+ if (state && !state.finalizing) {90+ state.finalizing = true91+ const value = draft[prop]92+ state.finalizing = false93+ return value94 }95+ return draft[prop]96 }159- }160- Object.defineProperty(draft, prop, desc)161-}97 163-// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.164-function markChangesSweep(drafts: Drafted<any, ImmerState>[]) {165- // The natural order of drafts in the `scope` array is based on when they166- // were accessed. By processing drafts in reverse natural order, we have a167- // better chance of processing leaf nodes first. When a leaf node is known to168- // have changed, we can avoid any traversal of its ancestor nodes.169- for (let i = drafts.length - 1; i >= 0; i--) {170- const state = drafts[i][DRAFT_STATE]171- if (!state.modified) {172- switch (state.type) {173- case ProxyType.ES5Array:174- if (hasArrayChanges(state)) markChangedES5(state)175- break176- case ProxyType.ES5Object:177- if (hasObjectChanges(state)) markChangedES5(state)178- break98+ function get(state: ES5State, prop: string | number) {99+ assertUnrevoked(state)100+ const value = peek(latest(state as any), prop)101+ if (state.finalizing) return value102+ // Create a draft if the value is unmodified.103+ if (value === peek(state.base, prop) && isDraftable(value)) {104+ prepareCopy(state)105+ // @ts-ignore106+ return (state.copy![prop] = state.scope.immer.createProxy(value, state))107 }108+ return value109 }181- }182-}110 184-function markChangesRecursively(object: any) {185- if (!object || typeof object !== "object") return186- const state = object[DRAFT_STATE]187- if (!state) return188- const {base, draft, assigned, type} = state189- if (type === ProxyType.ES5Object) {190- // Look for added keys.191- // TODO: looks quite duplicate to hasObjectChanges,192- // probably there is a faster way to detect changes, as sweep + recurse seems to do some193- // unnecessary work.194- // also: probably we can store the information we detect here, to speed up tree finalization!195- each(draft, key => {196- if ((key as any) === DRAFT_STATE) return197- // The `undefined` check is a fast path for pre-existing keys.198- if (base[key] === undefined && !has(base, key)) {199- assigned[key] = true111+ function set(state: ES5State, prop: string | number, value: any) {112+ assertUnrevoked(state)113+ state.assigned[prop] = true114+ if (!state.modified) {115+ if (is(value, peek(latest(state as any), prop))) return116 markChangedES5(state)201- } else if (!assigned[key]) {202- // Only untouched properties trigger recursion.203- markChangesRecursively(draft[key])117+ prepareCopy(state)118 }205- })206- // Look for removed keys.207- each(base, key => {208- // The `undefined` check is a fast path for pre-existing keys.209- if (draft[key] === undefined && !has(draft, key)) {210- assigned[key] = false211- markChangedES5(state)119+ // @ts-ignore120+ state.copy![prop] = value121+ }122+123+ function markChangedES5(state: ImmerState) {124+ if (!state.modified) {125+ state.modified = true126+ if (state.parent) markChangedES5(state.parent)127 }213- })214- } else if (type === ProxyType.ES5Array) {215- if (hasArrayChanges(state)) {216- markChangedES5(state)217- assigned.length = true128 }129 220- if (draft.length < base.length) {221- for (let i = draft.length; i < base.length; i++) assigned[i] = false222- } else {223- for (let i = base.length; i < draft.length; i++) assigned[i] = true130+ function prepareCopy(state: ES5State) {131+ if (!state.copy) state.copy = clonePotentialDraft(state.base)132 }133 226- // Minimum count is enough, the other parts has been processed.227- const min = Math.min(draft.length, base.length)228-229- for (let i = 0; i < min; i++) {230- // Only untouched indices trigger recursion.231- if (assigned[i] === undefined) markChangesRecursively(draft[i])134+ function clonePotentialDraft(base: Objectish) {135+ const state = base && (base as any)[DRAFT_STATE]136+ if (state) {137+ state.finalizing = true138+ const draft = shallowCopy(state.draft, true)139+ state.finalizing = false140+ return draft141+ }142+ return shallowCopy(base)143 }233- }234-}144 236-function hasObjectChanges(state: ES5ObjectState) {237- const {base, draft} = state145+ // property descriptors are recycled to make sure we don't create a get and set closure per property,146+ // but share them all instead147+ const descriptors: {[prop: string]: PropertyDescriptor} = {}148 239- // Search for added keys and changed keys. Start at the back, because240- // non-numeric keys are ordered by time of definition on the object.241- const keys = Object.keys(draft)242- for (let i = keys.length - 1; i >= 0; i--) {243- const key = keys[i]244- const baseValue = base[key]245- // The `undefined` check is a fast path for pre-existing keys.246- if (baseValue === undefined && !has(base, key)) {247- return true149+ function proxyProperty(150+ draft: Drafted<any, ES5State>,151+ prop: string | number,152+ enumerable: boolean153+ ) {154+ let desc = descriptors[prop]155+ if (desc) {156+ desc.enumerable = enumerable157+ } else {158+ descriptors[prop] = desc = {159+ configurable: true,160+ enumerable,161+ get(this: any) {162+ return get(this[DRAFT_STATE], prop)163+ },164+ set(this: any, value) {165+ set(this[DRAFT_STATE], prop, value)166+ }167+ }168+ }169+ Object.defineProperty(draft, prop, desc)170 }249- // Once a base key is deleted, future changes go undetected, because its250- // descriptor is erased. This branch detects any missed changes.251- else {252- const value = draft[key]253- const state = value && value[DRAFT_STATE]254- if (state ? state.base !== baseValue : !is(value, baseValue)) {255- return true171+172+ // This looks expensive, but only proxies are visited, and only objects without known changes are scanned.173+ function markChangesSweep(drafts: Drafted<any, ImmerState>[]) {174+ // The natural order of drafts in the `scope` array is based on when they175+ // were accessed. By processing drafts in reverse natural order, we have a176+ // better chance of processing leaf nodes first. When a leaf node is known to177+ // have changed, we can avoid any traversal of its ancestor nodes.178+ for (let i = drafts.length - 1; i >= 0; i--) {179+ const state = drafts[i][DRAFT_STATE]180+ if (!state.modified) {181+ switch (state.type) {182+ case ProxyType.ES5Array:183+ if (hasArrayChanges(state)) markChangedES5(state)184+ break185+ case ProxyType.ES5Object:186+ if (hasObjectChanges(state)) markChangedES5(state)187+ break188+ }189+ }190 }191 }258- }192 260- // At this point, no keys were added or changed.261- // Compare key count to determine if keys were deleted.262- return keys.length !== Object.keys(base).length263-}193+ function markChangesRecursively(object: any) {194+ if (!object || typeof object !== "object") return195+ const state = object[DRAFT_STATE]196+ if (!state) return197+ const {base, draft, assigned, type} = state198+ if (type === ProxyType.ES5Object) {199+ // Look for added keys.200+ // TODO: looks quite duplicate to hasObjectChanges,201+ // probably there is a faster way to detect changes, as sweep + recurse seems to do some202+ // unnecessary work.203+ // also: probably we can store the information we detect here, to speed up tree finalization!204+ each(draft, key => {205+ if ((key as any) === DRAFT_STATE) return206+ // The `undefined` check is a fast path for pre-existing keys.207+ if (base[key] === undefined && !has(base, key)) {208+ assigned[key] = true209+ markChangedES5(state)210+ } else if (!assigned[key]) {211+ // Only untouched properties trigger recursion.212+ markChangesRecursively(draft[key])213+ }214+ })215+ // Look for removed keys.216+ each(base, key => {217+ // The `undefined` check is a fast path for pre-existing keys.218+ if (draft[key] === undefined && !has(draft, key)) {219+ assigned[key] = false220+ markChangedES5(state)221+ }222+ })223+ } else if (type === ProxyType.ES5Array) {224+ if (hasArrayChanges(state)) {225+ markChangedES5(state)226+ assigned.length = true227+ }228 265-function hasArrayChanges(state: ES5ArrayState) {266- const {draft} = state267- if (draft.length !== state.base.length) return true268- // See #116269- // If we first shorten the length, our array interceptors will be removed.270- // If after that new items are added, result in the same original length,271- // those last items will have no intercepting property.272- // So if there is no own descriptor on the last position, we know that items were removed and added273- // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check274- // the last one275- const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)276- // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)277- if (descriptor && !descriptor.get) return true278- // For all other cases, we don't have to compare, as they would have been picked up by the index setters279- return false280-}229+ if (draft.length < base.length) {230+ for (let i = draft.length; i < base.length; i++) assigned[i] = false231+ } else {232+ for (let i = base.length; i < draft.length; i++) assigned[i] = true233+ }234 235+ // Minimum count is enough, the other parts has been processed.236+ const min = Math.min(draft.length, base.length)237+238+ for (let i = 0; i < min; i++) {239+ // Only untouched indices trigger recursion.240+ if (assigned[i] === undefined) markChangesRecursively(draft[i])241+ }242+ }243+ }244+245+ function hasObjectChanges(state: ES5ObjectState) {246+ const {base, draft} = state247+248+ // Search for added keys and changed keys. Start at the back, because249+ // non-numeric keys are ordered by time of definition on the object.250+ const keys = Object.keys(draft)251+ for (let i = keys.length - 1; i >= 0; i--) {252+ const key = keys[i]253+ const baseValue = base[key]254+ // The `undefined` check is a fast path for pre-existing keys.255+ if (baseValue === undefined && !has(base, key)) {256+ return true257+ }258+ // Once a base key is deleted, future changes go undetected, because its259+ // descriptor is erased. This branch detects any missed changes.260+ else {261+ const value = draft[key]262+ const state = value && value[DRAFT_STATE]263+ if (state ? state.base !== baseValue : !is(value, baseValue)) {264+ return true265+ }266+ }267+ }268+269+ // At this point, no keys were added or changed.270+ // Compare key count to determine if keys were deleted.271+ return keys.length !== Object.keys(base).length272+ }273+274+ function hasArrayChanges(state: ES5ArrayState) {275+ const {draft} = state276+ if (draft.length !== state.base.length) return true277+ // See #116278+ // If we first shorten the length, our array interceptors will be removed.279+ // If after that new items are added, result in the same original length,280+ // those last items will have no intercepting property.281+ // So if there is no own descriptor on the last position, we know that items were removed and added282+ // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check283+ // the last one284+ const descriptor = Object.getOwnPropertyDescriptor(285+ draft,286+ draft.length - 1287+ )288+ // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)289+ if (descriptor && !descriptor.get) return true290+ // For all other cases, we don't have to compare, as they would have been picked up by the index setters291+ return false292+ }293+282-loadPlugin("es5", {283- createES5Proxy,284- markChangedES5,285- willFinalizeES5286-})294+ return {295+ createES5Proxy,296+ markChangedES5,297+ willFinalizeES5298+ }299+ }300+)deleted:src/plugins/mapset/extends.ts-24 removed
123456789101112131415161718192021222324/* istanbul ignore next */var extendStatics = function(d: any, b: any): any { extendStatics = Object.setPrototypeOf || ({__proto__: []} instanceof Array && function(d, b) { d.__proto__ = b }) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p] } return extendStatics(d, b)}
// Ugly hack to resolve #502 and inherit built in Map / Setexport function __extends(d: any, b: any): any { extendStatics(d, b) function __(this: any): any { this.constructor = d } d.prototype = // @ts-ignore ((__.prototype = b.prototype), new __())}deleted:src/plugins/mapset/map.ts-178 removed
1-import {__extends} from "./extends"2-import {proxySet} from "./set"3-import {4- ProxyType,5- AnyMap,6- ImmerState,7- DRAFT_STATE,8- ImmerScope,9- latest,10- assertUnrevoked,11- isDraftable,12- iteratorSymbol,13- MapState14-} from "../../internal"15-import {loadPlugin} from "../../plugins"16-17-const DraftMap = (function(_super) {18- if (!_super) {19- /* istanbul ignore next */20- throw new Error("Map is not polyfilled")21- }22- __extends(DraftMap, _super)23- // Create class manually, cause #50224- function DraftMap(this: any, target: AnyMap, parent?: ImmerState): any {25- this[DRAFT_STATE] = {26- type: ProxyType.Map,27- parent,28- scope: parent ? parent.scope : ImmerScope.current!,29- modified: false,30- finalized: false,31- copy: undefined,32- assigned: undefined,33- base: target,34- draft: this as any,35- isManual: false,36- revoked: false37- }38- return this39- }40- const p = DraftMap.prototype41-42- // TODO: smaller build size if we create a util for Object.defineProperty43- Object.defineProperty(p, "size", {44- get: function() {45- return latest(this[DRAFT_STATE]).size46- },47- enumerable: true,48- configurable: true49- })50-51- p.has = function(key: any): boolean {52- return latest(this[DRAFT_STATE]).has(key)53- }54-55- p.set = function(key: any, value: any) {56- const state = this[DRAFT_STATE]57- assertUnrevoked(state)58- if (latest(state).get(key) !== value) {59- prepareCopy(state)60- state.scope.immer.markChanged(state)61- state.assigned!.set(key, true)62- state.copy!.set(key, value)63- state.assigned!.set(key, true)64- }65- return this66- }67-68- p.delete = function(key: any): boolean {69- if (!this.has(key)) {70- return false71- }72-73- const state = this[DRAFT_STATE]74- assertUnrevoked(state)75- prepareCopy(state)76- state.scope.immer.markChanged(state)77- state.assigned!.set(key, false)78- state.copy!.delete(key)79- return true80- }81-82- p.clear = function() {83- const state = this[DRAFT_STATE]84- assertUnrevoked(state)85- prepareCopy(state)86- state.scope.immer.markChanged(state)87- state.assigned = new Map()88- return state.copy!.clear()89- }90-91- p.forEach = function(92- cb: (value: any, key: any, self: any) => void,93- thisArg?: any94- ) {95- const state = this[DRAFT_STATE]96- latest(state).forEach((_value: any, key: any, _map: any) => {97- cb.call(thisArg, this.get(key), key, this)98- })99- }100-101- p.get = function(key: any): any {102- const state = this[DRAFT_STATE]103- assertUnrevoked(state)104- const value = latest(state).get(key)105- if (state.finalized || !isDraftable(value)) {106- return value107- }108- if (value !== state.base.get(key)) {109- return value // either already drafted or reassigned110- }111- // despite what it looks, this creates a draft only once, see above condition112- const draft = state.scope.immer.createProxy(value, state)113- prepareCopy(state)114- state.copy!.set(key, draft)115- return draft116- }117-118- p.keys = function(): IterableIterator<any> {119- return latest(this[DRAFT_STATE]).keys()120- }121-122- p.values = function(): IterableIterator<any> {123- const iterator = this.keys()124- return {125- [iteratorSymbol]: () => this.values(),126- next: () => {127- const r = iterator.next()128- /* istanbul ignore next */129- if (r.done) return r130- const value = this.get(r.value)131- return {132- done: false,133- value134- }135- }136- } as any137- }138-139- p.entries = function(): IterableIterator<[any, any]> {140- const iterator = this.keys()141- return {142- [iteratorSymbol]: () => this.entries(),143- next: () => {144- const r = iterator.next()145- /* istanbul ignore next */146- if (r.done) return r147- const value = this.get(r.value)148- return {149- done: false,150- value: [r.value, value]151- }152- }153- } as any154- }155-156- p[iteratorSymbol] = function() {157- return this.entries()158- }159-160- return DraftMap161-})(Map)162-163-export function proxyMap<T extends AnyMap>(164- target: T,165- parent?: ImmerState166-): T & {[DRAFT_STATE]: MapState} {167- // @ts-ignore168- return new DraftMap(target, parent)169-}170-171-function prepareCopy(state: MapState) {172- if (!state.copy) {173- state.assigned = new Map()174- state.copy = new Map(state.base)175- }176-}177-178-loadPlugin("mapset", {proxyMap, proxySet})added:src/plugins/mapset/mapset.ts+347 added
1+// types only!2+import {ImmerState, AnyMap, AnySet, MapState, SetState} from "../../internal"3+4+import {__loadPlugin} from "../../../"5+6+__loadPlugin(7+ "mapset",8+ // @ts-ignore9+ ({10+ DRAFT_STATE,11+ ProxyType,12+ ImmerScope,13+ latest,14+ assertUnrevoked,15+ iteratorSymbol,16+ isDraftable,17+ createProxy18+ }) => {19+ /* istanbul ignore next */20+ var extendStatics = function(d: any, b: any): any {21+ extendStatics =22+ Object.setPrototypeOf ||23+ ({__proto__: []} instanceof Array &&24+ function(d, b) {25+ d.__proto__ = b26+ }) ||27+ function(d, b) {28+ for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]29+ }30+ return extendStatics(d, b)31+ }32+33+ // Ugly hack to resolve #502 and inherit built in Map / Set34+ function __extends(d: any, b: any): any {35+ extendStatics(d, b)36+ function __(this: any): any {37+ this.constructor = d38+ }39+ d.prototype =40+ // @ts-ignore41+ ((__.prototype = b.prototype), new __())42+ }43+44+ const DraftMap = (function(_super) {45+ if (!_super) {46+ /* istanbul ignore next */47+ throw new Error("Map is not polyfilled")48+ }49+ __extends(DraftMap, _super)50+ // Create class manually, cause #50251+ function DraftMap(this: any, target: AnyMap, parent?: ImmerState): any {52+ this[DRAFT_STATE] = {53+ type: ProxyType.Map,54+ parent,55+ scope: parent ? parent.scope : ImmerScope.current!,56+ modified: false,57+ finalized: false,58+ copy: undefined,59+ assigned: undefined,60+ base: target,61+ draft: this as any,62+ isManual: false,63+ revoked: false64+ }65+ return this66+ }67+ const p = DraftMap.prototype68+69+ // TODO: smaller build size if we create a util for Object.defineProperty70+ Object.defineProperty(p, "size", {71+ get: function() {72+ return latest(this[DRAFT_STATE]).size73+ },74+ enumerable: true,75+ configurable: true76+ })77+78+ p.has = function(key: any): boolean {79+ return latest(this[DRAFT_STATE]).has(key)80+ }81+82+ p.set = function(key: any, value: any) {83+ const state = this[DRAFT_STATE]84+ assertUnrevoked(state)85+ if (latest(state).get(key) !== value) {86+ prepareMapCopy(state)87+ state.scope.immer.markChanged(state)88+ state.assigned!.set(key, true)89+ state.copy!.set(key, value)90+ state.assigned!.set(key, true)91+ }92+ return this93+ }94+95+ p.delete = function(key: any): boolean {96+ if (!this.has(key)) {97+ return false98+ }99+100+ const state = this[DRAFT_STATE]101+ assertUnrevoked(state)102+ prepareMapCopy(state)103+ state.scope.immer.markChanged(state)104+ state.assigned!.set(key, false)105+ state.copy!.delete(key)106+ return true107+ }108+109+ p.clear = function() {110+ const state = this[DRAFT_STATE]111+ assertUnrevoked(state)112+ prepareMapCopy(state)113+ state.scope.immer.markChanged(state)114+ state.assigned = new Map()115+ return state.copy!.clear()116+ }117+118+ p.forEach = function(119+ cb: (value: any, key: any, self: any) => void,120+ thisArg?: any121+ ) {122+ const state = this[DRAFT_STATE]123+ latest(state).forEach((_value: any, key: any, _map: any) => {124+ cb.call(thisArg, this.get(key), key, this)125+ })126+ }127+128+ p.get = function(key: any): any {129+ const state = this[DRAFT_STATE]130+ assertUnrevoked(state)131+ const value = latest(state).get(key)132+ if (state.finalized || !isDraftable(value)) {133+ return value134+ }135+ if (value !== state.base.get(key)) {136+ return value // either already drafted or reassigned137+ }138+ // despite what it looks, this creates a draft only once, see above condition139+ const draft = state.scope.immer.createProxy(value, state)140+ prepareMapCopy(state)141+ state.copy!.set(key, draft)142+ return draft143+ }144+145+ p.keys = function(): IterableIterator<any> {146+ return latest(this[DRAFT_STATE]).keys()147+ }148+149+ p.values = function(): IterableIterator<any> {150+ const iterator = this.keys()151+ return {152+ [iteratorSymbol]: () => this.values(),153+ next: () => {154+ const r = iterator.next()155+ /* istanbul ignore next */156+ if (r.done) return r157+ const value = this.get(r.value)158+ return {159+ done: false,160+ value161+ }162+ }163+ } as any164+ }165+166+ p.entries = function(): IterableIterator<[any, any]> {167+ const iterator = this.keys()168+ return {169+ [iteratorSymbol]: () => this.entries(),170+ next: () => {171+ const r = iterator.next()172+ /* istanbul ignore next */173+ if (r.done) return r174+ const value = this.get(r.value)175+ return {176+ done: false,177+ value: [r.value, value]178+ }179+ }180+ } as any181+ }182+183+ p[iteratorSymbol] = function() {184+ return this.entries()185+ }186+187+ return DraftMap188+ })(Map)189+190+ function proxyMap<T extends AnyMap>(target: T, parent?: ImmerState): T {191+ // @ts-ignore192+ return new DraftMap(target, parent)193+ }194+195+ function prepareMapCopy(state: MapState) {196+ if (!state.copy) {197+ state.assigned = new Map()198+ state.copy = new Map(state.base)199+ }200+ }201+202+ const DraftSet = (function(_super) {203+ if (!_super) {204+ /* istanbul ignore next */205+ throw new Error("Set is not polyfilled")206+ }207+ __extends(DraftSet, _super)208+ // Create class manually, cause #502209+ function DraftSet(this: any, target: AnySet, parent?: ImmerState) {210+ this[DRAFT_STATE] = {211+ type: ProxyType.Set,212+ parent,213+ scope: parent ? parent.scope : ImmerScope.current!,214+ modified: false,215+ finalized: false,216+ copy: undefined,217+ base: target,218+ draft: this,219+ drafts: new Map(),220+ revoked: false,221+ isManual: false222+ }223+ return this224+ }225+ const p = DraftSet.prototype226+227+ Object.defineProperty(p, "size", {228+ get: function() {229+ return latest(this[DRAFT_STATE]).size230+ },231+ enumerable: true,232+ configurable: true233+ })234+235+ p.has = function(value: any): boolean {236+ const state = this[DRAFT_STATE]237+ assertUnrevoked(state)238+ // bit of trickery here, to be able to recognize both the value, and the draft of its value239+ if (!state.copy) {240+ return state.base.has(value)241+ }242+ if (state.copy.has(value)) return true243+ if (state.drafts.has(value) && state.copy.has(state.drafts.get(value)))244+ return true245+ return false246+ }247+248+ p.add = function(value: any): any {249+ const state = this[DRAFT_STATE]250+ assertUnrevoked(state)251+ if (state.copy) {252+ state.copy.add(value)253+ } else if (!state.base.has(value)) {254+ prepareSetCopy(state)255+ state.scope.immer.markChanged(state)256+ state.copy!.add(value)257+ }258+ return this259+ }260+261+ p.delete = function(value: any): any {262+ if (!this.has(value)) {263+ return false264+ }265+266+ const state = this[DRAFT_STATE]267+ assertUnrevoked(state)268+ prepareSetCopy(state)269+ state.scope.immer.markChanged(state)270+ return (271+ state.copy!.delete(value) ||272+ (state.drafts.has(value)273+ ? state.copy!.delete(state.drafts.get(value))274+ : /* istanbul ignore next */ false)275+ )276+ }277+278+ p.clear = function() {279+ const state = this[DRAFT_STATE]280+ assertUnrevoked(state)281+ prepareSetCopy(state)282+ state.scope.immer.markChanged(state)283+ return state.copy!.clear()284+ }285+286+ p.values = function(): IterableIterator<any> {287+ const state = this[DRAFT_STATE]288+ assertUnrevoked(state)289+ prepareSetCopy(state)290+ return state.copy!.values()291+ }292+293+ p.entries = function entries(): IterableIterator<[any, any]> {294+ const state = this[DRAFT_STATE]295+ assertUnrevoked(state)296+ prepareSetCopy(state)297+ return state.copy!.entries()298+ }299+300+ p.keys = function(): IterableIterator<any> {301+ return this.values()302+ }303+304+ p[iteratorSymbol] = function() {305+ return this.values()306+ }307+308+ p.forEach = function forEach(cb: any, thisArg?: any) {309+ const iterator = this.values()310+ let result = iterator.next()311+ while (!result.done) {312+ cb.call(thisArg, result.value, result.value, this)313+ result = iterator.next()314+ }315+ }316+317+ return DraftSet318+ })(Set)319+320+ function proxySet<T extends AnySet>(target: T, parent?: ImmerState): T {321+ // @ts-ignore322+ return new DraftSet(target, parent)323+ }324+325+ function prepareSetCopy(state: SetState) {326+ if (!state.copy) {327+ // create drafts for all entries to preserve insertion order328+ state.copy = new Set()329+ state.base.forEach(value => {330+ if (isDraftable(value)) {331+ const draft = createProxy(332+ state.scope.immer as any,333+ value,334+ state as any335+ )336+ state.drafts.set(value, draft)337+ state.copy!.add(draft)338+ } else {339+ state.copy!.add(value)340+ }341+ })342+ }343+ }344+345+ return {proxyMap, proxySet}346+ }347+)deleted:src/plugins/mapset/set.ts-156 removed
1-import {__extends} from "./extends"2-import {3- ProxyType,4- AnySet,5- ImmerState,6- DRAFT_STATE,7- ImmerScope,8- latest,9- assertUnrevoked,10- iteratorSymbol,11- isDraftable,12- SetState,13- createProxy14-} from "../../internal"15-16-const DraftSet = (function(_super) {17- if (!_super) {18- /* istanbul ignore next */19- throw new Error("Set is not polyfilled")20- }21- __extends(DraftSet, _super)22- // Create class manually, cause #50223- function DraftSet(this: any, target: AnySet, parent?: ImmerState) {24- this[DRAFT_STATE] = {25- type: ProxyType.Set,26- parent,27- scope: parent ? parent.scope : ImmerScope.current!,28- modified: false,29- finalized: false,30- copy: undefined,31- base: target,32- draft: this,33- drafts: new Map(),34- revoked: false,35- isManual: false36- }37- return this38- }39- const p = DraftSet.prototype40-41- Object.defineProperty(p, "size", {42- get: function() {43- return latest(this[DRAFT_STATE]).size44- },45- enumerable: true,46- configurable: true47- })48-49- p.has = function(value: any): boolean {50- const state = this[DRAFT_STATE]51- assertUnrevoked(state)52- // bit of trickery here, to be able to recognize both the value, and the draft of its value53- if (!state.copy) {54- return state.base.has(value)55- }56- if (state.copy.has(value)) return true57- if (state.drafts.has(value) && state.copy.has(state.drafts.get(value)))58- return true59- return false60- }61-62- p.add = function(value: any): any {63- const state = this[DRAFT_STATE]64- assertUnrevoked(state)65- if (state.copy) {66- state.copy.add(value)67- } else if (!state.base.has(value)) {68- prepareCopy(state)69- state.scope.immer.markChanged(state)70- state.copy!.add(value)71- }72- return this73- }74-75- p.delete = function(value: any): any {76- if (!this.has(value)) {77- return false78- }79-80- const state = this[DRAFT_STATE]81- assertUnrevoked(state)82- prepareCopy(state)83- state.scope.immer.markChanged(state)84- return (85- state.copy!.delete(value) ||86- (state.drafts.has(value)87- ? state.copy!.delete(state.drafts.get(value))88- : /* istanbul ignore next */ false)89- )90- }91-92- p.clear = function() {93- const state = this[DRAFT_STATE]94- assertUnrevoked(state)95- prepareCopy(state)96- state.scope.immer.markChanged(state)97- return state.copy!.clear()98- }99-100- p.values = function(): IterableIterator<any> {101- const state = this[DRAFT_STATE]102- assertUnrevoked(state)103- prepareCopy(state)104- return state.copy!.values()105- }106-107- p.entries = function entries(): IterableIterator<[any, any]> {108- const state = this[DRAFT_STATE]109- assertUnrevoked(state)110- prepareCopy(state)111- return state.copy!.entries()112- }113-114- p.keys = function(): IterableIterator<any> {115- return this.values()116- }117-118- p[iteratorSymbol] = function() {119- return this.values()120- }121-122- p.forEach = function forEach(cb: any, thisArg?: any) {123- const iterator = this.values()124- let result = iterator.next()125- while (!result.done) {126- cb.call(thisArg, result.value, result.value, this)127- result = iterator.next()128- }129- }130-131- return DraftSet132-})(Set)133-134-export function proxySet<T extends AnySet>(135- target: T,136- parent?: ImmerState137-): T & {[DRAFT_STATE]: SetState} {138- // @ts-ignore139- return new DraftSet(target, parent)140-}141-142-function prepareCopy(state: SetState) {143- if (!state.copy) {144- // create drafts for all entries to preserve insertion order145- state.copy = new Set()146- state.base.forEach(value => {147- if (isDraftable(value)) {148- const draft = createProxy(state.scope.immer, value, state)149- state.drafts.set(value, draft)150- state.copy!.add(draft)151- } else {152- state.copy!.add(value)153- }154- })155- }156-}modified:src/plugins/patches/patches.ts+232 added-229 removed
1+// Import types only! TODO: force in TS 3.82 import {2- get,3- each,4- has,5- die,6- getArchtype,3 ImmerState,4 Patch,9- ProxyType,5 SetState,6 ES5ArrayState,7 ProxyArrayState,8 MapState,9 ES5ObjectState,10 ProxyObjectState,16- Archtype,17- isMap,18- isSet,19- PatchPath,11+ PatchPath20- loadPlugin12 } from "../../internal"13 23-export function generatePatches(24- state: ImmerState,25- basePath: PatchPath,26- patches: Patch[],27- inversePatches: Patch[]28-): void {29- switch (state.type) {30- case ProxyType.ProxyObject:31- case ProxyType.ES5Object:32- case ProxyType.Map:33- return generatePatchesFromAssigned(34- state,35- basePath,36- patches,37- inversePatches38- )39- case ProxyType.ES5Array:40- case ProxyType.ProxyArray:41- return generateArrayPatches(state, basePath, patches, inversePatches)42- case ProxyType.Set:43- return generateSetPatches(44- (state as any) as SetState,45- basePath,46- patches,47- inversePatches48- )49- }50-}14+import {__loadPlugin} from "../../../"15 52-function generateArrayPatches(53- state: ES5ArrayState | ProxyArrayState,54- basePath: PatchPath,55- patches: Patch[],56- inversePatches: Patch[]57-) {58- let {base, assigned, copy} = state59- /* istanbul ignore next */60- if (!copy) die()16+// @ts-ignore didn't understand the error :-P17+__loadPlugin(18+ "patches",19+ ({get, each, has, die, getArchtype, ProxyType, Archtype, isSet, isMap}) => {20+ function generatePatches(21+ state: ImmerState,22+ basePath: PatchPath,23+ patches: Patch[],24+ inversePatches: Patch[]25+ ): void {26+ switch (state.type) {27+ case ProxyType.ProxyObject:28+ case ProxyType.ES5Object:29+ case ProxyType.Map:30+ return generatePatchesFromAssigned(31+ state,32+ basePath,33+ patches,34+ inversePatches35+ )36+ case ProxyType.ES5Array:37+ case ProxyType.ProxyArray:38+ return generateArrayPatches(state, basePath, patches, inversePatches)39+ case ProxyType.Set:40+ return generateSetPatches(41+ (state as any) as SetState,42+ basePath,43+ patches,44+ inversePatches45+ )46+ }47+ }48 62- // Reduce complexity by ensuring `base` is never longer.63- if (copy.length < base.length) {64- // @ts-ignore65- ;[base, copy] = [copy, base]66- ;[patches, inversePatches] = [inversePatches, patches]67- }49+ function generateArrayPatches(50+ state: ES5ArrayState | ProxyArrayState,51+ basePath: PatchPath,52+ patches: Patch[],53+ inversePatches: Patch[]54+ ) {55+ let {base, assigned, copy} = state56+ /* istanbul ignore next */57+ if (!copy) die()58 69- const delta = copy.length - base.length59+ // Reduce complexity by ensuring `base` is never longer.60+ if (copy.length < base.length) {61+ // @ts-ignore62+ ;[base, copy] = [copy, base]63+ ;[patches, inversePatches] = [inversePatches, patches]64+ }65 71- // Find the first replaced index.72- let start = 073- while (base[start] === copy[start] && start < base.length) {74- ++start75- }66+ const delta = copy.length - base.length67 77- // Find the last replaced index. Search from the end to optimize splice patches.78- let end = base.length79- while (end > start && base[end - 1] === copy[end + delta - 1]) {80- --end81- }68+ // Find the first replaced index.69+ let start = 070+ while (base[start] === copy[start] && start < base.length) {71+ ++start72+ }73 83- // Process replaced indices.84- for (let i = start; i < end; ++i) {85- if (assigned[i] && copy[i] !== base[i]) {86- const path = basePath.concat([i])87- patches.push({88- op: "replace",89- path,90- value: copy[i]91- })92- inversePatches.push({93- op: "replace",94- path,95- value: base[i]96- })97- }98- }74+ // Find the last replaced index. Search from the end to optimize splice patches.75+ let end = base.length76+ while (end > start && base[end - 1] === copy[end + delta - 1]) {77+ --end78+ }79 100- const replaceCount = patches.length80+ // Process replaced indices.81+ for (let i = start; i < end; ++i) {82+ if (assigned[i] && copy[i] !== base[i]) {83+ const path = basePath.concat([i])84+ patches.push({85+ op: "replace",86+ path,87+ value: copy[i]88+ })89+ inversePatches.push({90+ op: "replace",91+ path,92+ value: base[i]93+ })94+ }95+ }96 97+ const replaceCount = patches.length98+102- // Process added indices.103- for (let i = end + delta - 1; i >= end; --i) {104- const path = basePath.concat([i])105- patches[replaceCount + i - end] = {106- op: "add",107- path,108- value: copy[i]99+ // Process added indices.100+ for (let i = end + delta - 1; i >= end; --i) {101+ const path = basePath.concat([i])102+ patches[replaceCount + i - end] = {103+ op: "add",104+ path,105+ value: copy[i]106+ }107+ inversePatches.push({108+ op: "remove",109+ path110+ })111+ }112 }110- inversePatches.push({111- op: "remove",112- path113- })114- }115-}113 117-// This is used for both Map objects and normal objects.118-function generatePatchesFromAssigned(119- state: MapState | ES5ObjectState | ProxyObjectState,120- basePath: PatchPath,121- patches: Patch[],122- inversePatches: Patch[]123-) {124- const {base, copy} = state125- each(state.assigned!, (key, assignedValue) => {126- const origValue = get(base, key)127- const value = get(copy!, key)128- const op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add"129- if (origValue === value && op === "replace") return130- const path = basePath.concat(key as any)131- patches.push(op === "remove" ? {op, path} : {op, path, value})132- inversePatches.push(133- op === "add"134- ? {op: "remove", path}135- : op === "remove"136- ? {op: "add", path, value: origValue}137- : {op: "replace", path, value: origValue}138- )139- })140-}114+ // This is used for both Map objects and normal objects.115+ function generatePatchesFromAssigned(116+ state: MapState | ES5ObjectState | ProxyObjectState,117+ basePath: PatchPath,118+ patches: Patch[],119+ inversePatches: Patch[]120+ ) {121+ const {base, copy} = state122+ each(state.assigned!, (key, assignedValue) => {123+ const origValue = get(base, key)124+ const value = get(copy!, key)125+ const op = !assignedValue126+ ? "remove"127+ : has(base, key)128+ ? "replace"129+ : "add"130+ if (origValue === value && op === "replace") return131+ const path = basePath.concat(key as any)132+ patches.push(op === "remove" ? {op, path} : {op, path, value})133+ inversePatches.push(134+ op === "add"135+ ? {op: "remove", path}136+ : op === "remove"137+ ? {op: "add", path, value: origValue}138+ : {op: "replace", path, value: origValue}139+ )140+ })141+ }142 142-function generateSetPatches(143- state: SetState,144- basePath: PatchPath,145- patches: Patch[],146- inversePatches: Patch[]147-) {148- let {base, copy} = state143+ function generateSetPatches(144+ state: SetState,145+ basePath: PatchPath,146+ patches: Patch[],147+ inversePatches: Patch[]148+ ) {149+ let {base, copy} = state150 150- let i = 0151- base.forEach(value => {152- if (!copy!.has(value)) {153- const path = basePath.concat([i])154- patches.push({155- op: "remove",156- path,157- value151+ let i = 0152+ base.forEach(value => {153+ if (!copy!.has(value)) {154+ const path = basePath.concat([i])155+ patches.push({156+ op: "remove",157+ path,158+ value159+ })160+ inversePatches.unshift({161+ op: "add",162+ path,163+ value164+ })165+ }166+ i++167 })168+ i = 0169+ copy!.forEach(value => {170+ if (!base.has(value)) {171+ const path = basePath.concat([i])172+ patches.push({173+ op: "add",174+ path,175+ value176+ })159- inversePatches.unshift({160- op: "add",161- path,162- value177+ inversePatches.unshift({178+ op: "remove",179+ path,180+ value181+ })182+ }183+ i++184 })185 }165- i++166- })167- i = 0168- copy!.forEach(value => {169- if (!base.has(value)) {170- const path = basePath.concat([i])171- patches.push({172- op: "add",173- path,174- value175- })176- inversePatches.unshift({177- op: "remove",178- path,179- value180- })181- }182- i++183- })184-}186 186-export function applyPatches<T>(draft: T, patches: Patch[]): T {187- patches.forEach(patch => {188- const {path, op} = patch187+ function applyPatches<T>(draft: T, patches: Patch[]): T {188+ patches.forEach(patch => {189+ const {path, op} = patch190 190- /* istanbul ignore next */191- if (!path.length) die()191+ /* istanbul ignore next */192+ if (!path.length) die()193 193- let base: any = draft194- for (let i = 0; i < path.length - 1; i++) {195- base = get(base, path[i])196- if (!base || typeof base !== "object")194+ let base: any = draft195+ for (let i = 0; i < path.length - 1; i++) {196+ base = get(base, path[i])197+ if (!base || typeof base !== "object")198 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore198- }199+ }200 200- const type = getArchtype(base)201- const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411202- const key = path[path.length - 1]203- switch (op) {204- case "replace":205- switch (type) {206- case Archtype.Map:207- return base.set(key, value)208- /* istanbul ignore next */209- case Archtype.Set:210- throw new Error('Sets cannot have "replace" patches.')201+ const type = getArchtype(base)202+ const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411203+ const key = path[path.length - 1]204+ switch (op) {205+ case "replace":206+ switch (type) {207+ case Archtype.Map:208+ return base.set(key, value)209+ /* istanbul ignore next */210+ case Archtype.Set:211+ throw new Error('Sets cannot have "replace" patches.')212+ default:213+ // if value is an object, then it's assigned by reference214+ // in the following add or remove ops, the value field inside the patch will also be modifyed215+ // so we use value from the cloned patch216+ // @ts-ignore217+ return (base[key] = value)218+ }219+ case "add":220+ switch (type) {221+ case Archtype.Array:222+ return base.splice(key as any, 0, value)223+ case Archtype.Map:224+ return base.set(key, value)225+ case Archtype.Set:226+ return base.add(value)227+ default:228+ return (base[key] = value)229+ }230+ case "remove":231+ switch (type) {232+ case Archtype.Array:233+ return base.splice(key as any, 1)234+ case Archtype.Map:235+ return base.delete(key)236+ case Archtype.Set:237+ return base.delete(patch.value)238+ default:239+ return delete base[key]240+ }241 default:212- // if value is an object, then it's assigned by reference213- // in the following add or remove ops, the value field inside the patch will also be modifyed214- // so we use value from the cloned patch215- // @ts-ignore216- return (base[key] = value)242+ throw new Error("Unsupported patch operation: " + op)243 }218- case "add":219- switch (type) {220- case Archtype.Array:221- return base.splice(key as any, 0, value)222- case Archtype.Map:223- return base.set(key, value)224- case Archtype.Set:225- return base.add(value)226- default:227- return (base[key] = value)228- }229- case "remove":230- switch (type) {231- case Archtype.Array:232- return base.splice(key as any, 1)233- case Archtype.Map:234- return base.delete(key)235- case Archtype.Set:236- return base.delete(patch.value)237- default:238- return delete base[key]239- }240- default:241- throw new Error("Unsupported patch operation: " + op)244+ })245+246+ return draft247 }243- })248 249+ // TODO: optimize: this is quite a performance hit, can we detect intelligently when it is needed?250+ // E.g. auto-draft when new objects from outside are assigned and modified?251+ // (See failing test when deepClone just returns obj)252+ function deepClonePatchValue<T>(obj: T): T253+ function deepClonePatchValue(obj: any) {254+ if (!obj || typeof obj !== "object") return obj255+ if (Array.isArray(obj)) return obj.map(deepClonePatchValue)256+ if (isMap(obj))257+ return new Map(258+ Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])259+ )260+ if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))261+ const cloned = Object.create(Object.getPrototypeOf(obj))262+ for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])245- return draft246-}263+ return cloned264+ }265 248-// TODO: optimize: this is quite a performance hit, can we detect intelligently when it is needed?249-// E.g. auto-draft when new objects from outside are assigned and modified?250-// (See failing test when deepClone just returns obj)251-function deepClonePatchValue<T>(obj: T): T252-function deepClonePatchValue(obj: any) {253- if (!obj || typeof obj !== "object") return obj254- if (Array.isArray(obj)) return obj.map(deepClonePatchValue)255- if (isMap(obj))256- return new Map(257- Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])258- )259- if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))260- const cloned = Object.create(Object.getPrototypeOf(obj))261- for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])262- return cloned263-}264-265-loadPlugin("patches", {applyPatches, generatePatches})266+ return {applyPatches, generatePatches}267+ }268+)modified:src/index.ts+2 added-1 removed
13 unmodified lines141516171818192021222388 unmodified lines13 unmodified lines original, isDraft, isDraftable, NOTHING as nothing, DRAFTABLE as immerable DRAFTABLE as immerable, __loadPlugin} from "./internal"
const immer = new Immer()
88 unmodified linesmodified:src/plugins.ts+55 added-6 removed
4 unmodified lines5 Drafted,6 AnyObject,7 ImmerBaseState,8 AnyArray,9- ProxyType,9 AnyMap,10 DRAFT_STATE,12- AnySet11+ AnySet,12+ get,13+ each,14+ has,15+ die,16+ getArchtype,17+ ProxyType,18+ Archtype,19+ isSet,20+ isMap,21+ isDraft,22+ isDraftable,23+ isEnumerable,24+ shallowCopy,25+ latest,26+ createHiddenProperty,27+ assertUnrevoked,28+ is,29+ createProxy,30+ iteratorSymbol31 } from "./internal"32 33 /** Plugin utilities */34 const plugins: {26 unmodified lines61 // @ts-ignore62 return plugin63 }64 65+function buildUtilities() {66+ return {67+ get,68+ each,69+ has,70+ die,71+ getArchtype,72+ ProxyType,73+ Archtype,74+ isSet,75+ isMap,76+ isDraft,77+ isDraftable,78+ isEnumerable,79+ shallowCopy,80+ latest,81+ createHiddenProperty,82+ ImmerScope,83+ DRAFT_STATE,84+ assertUnrevoked,85+ is,86+ iteratorSymbol,87+ createProxy88+ } as const89+}90+91+let utilities: ReturnType<typeof buildUtilities> | undefined = undefined92+47-export function loadPlugin<K extends keyof Plugins>(93+export function __loadPlugin<K extends keyof Plugins>(94 pluginKey: K,49- implementation: Plugins[K]50-) {51- plugins[pluginKey] = implementation95+ getImplementation: (core: typeof utilities) => Plugins[K]96+): void {97+ if (!utilities) {98+ utilities = buildUtilities()99+ }100+ plugins[pluginKey] = getImplementation(utilities)101 }102 103 /** ES5 Plugin */104 90 unmodified linesmodified:package.json+2 added-1 removed
1 unmodified line2 "name": "immer",3 "version": "5.3.2",4 "description": "Create your next immutable state by mutating the current one",5 "main": "dist/immer.js",6+ "module": "dist/immer.module.js",7 "umd:main": "dist/immer.umd.js",8 "unpkg": "dist/immer.umd.js",9 "jsdelivr": "dist/immer.umd.js",9- "module": "dist/immer.module.js",10 "jsnext:main": "dist/immer.module.js",11 "react-native": "dist/immer.module.js",12+ "source": "src/index.ts",13 "types": "./dist/index.d.ts",14 "scripts": {15 "test": "jest && yarn-or-npm test:build && yarn-or-npm test:flow",16 "test:perf": "NODE_ENV=production yarn-or-npm build && cd __performance_tests__ && babel-node add-data.js && babel-node todo.js && babel-node incremental.js",92 unmodified lines