TS migration in progress
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 91615b0 · Browse files · 13 files·+1445 added−1443 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+1445 added−1443 removed
- other:+1445 added−1443 removed
Provenance
- Commit
dd56639- Tree
a6a9d1c- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
91615b0
13 files changed+1445 added−1443 removed
modified:src/common.ts+22 added-8 removed
1-import {Objectish, ObjectishNoSet, State} from "./types"1+import {Objectish, ObjectishNoSet, ImmerState} from "./types"2 3+/**4+ * The sentinel value returned by producers to replace the draft with undefined.5+ */6 export const NOTHING =7 typeof Symbol !== "undefined"8 ? Symbol("immer-nothing")9 : {["immer-nothing"]: true}10 11+/**12+ * To let Immer treat your class instances as plain immutable objects13+ * (albeit with a custom prototype), you must define either an instance property14+ * or a static property on each of your custom classes.15+ *16+ * Otherwise, your class instance will never be drafted, which means it won't be17+ * safe to mutate in a produce callback.18+ */8-export const DRAFTABLE =19+export const DRAFTABLE: unique symbol =20 typeof Symbol !== "undefined" && Symbol.for21 ? Symbol.for("immer-draftable")11- : "__$immer_draftable"22+ : ("__$immer_draftable" as any)23 13-export const DRAFT_STATE =24+export const DRAFT_STATE: unique symbol =25 typeof Symbol !== "undefined" && Symbol.for26 ? Symbol.for("immer-state")16- : "__$immer_state"27+ : ("__$immer_state" as any)28 29+/** Returns true if the given value is an Immer draft */18-export function isDraft(value): boolean {30+export function isDraft(value: any): boolean {31 return !!value && !!value[DRAFT_STATE]32 }33 34+/** Returns true if the given value can be drafted by Immer */22-export function isDraftable(value): boolean {35+export function isDraftable(value: any): boolean {36 if (!value) return false37 return (38 isPlainObject(value) ||39 !!value[DRAFTABLE] ||9 unmodified lines49 const proto = Object.getPrototypeOf(value)50 return !proto || proto === Object.prototype51 }52 53+/** Get the underlying object that is represented by the given draft */54 export function original<T>(value: T): T | undefined {55 if (value && value[DRAFT_STATE]) {56 return value[DRAFT_STATE].base57 }183 unmodified lines241 242 return iterateSetValues243 }244 231-function latest<T = any>(state: State<T>): T {245+function latest<T = any>(state: ImmerState<T>): T {246 return state.copy || state.base247 }248 249 export function clone<T extends Objectish>(obj: T): T24 unmodified linesdeleted:src/es5.js-468 removed
1-"use strict"2-import {3- each,4- has,5- is,6- isDraft,7- isDraftable,8- isEnumerable,9- isMap,10- isSet,11- hasSymbol,12- shallowCopy,13- DRAFT_STATE,14- iterateMapValues,15- makeIterable,16- makeIterateSetValues17-} from "./common"18-import {ImmerScope} from "./scope"19-20-export function willFinalize(scope, result, isReplaced) {21- scope.drafts.forEach(draft => {22- draft[DRAFT_STATE].finalizing = true23- })24- if (!isReplaced) {25- if (scope.patches) {26- markChangesRecursively(scope.drafts[0])27- }28- // This is faster when we don't care about which attributes changed.29- markChangesSweep(scope.drafts)30- }31- // When a child draft is returned, look for changes.32- else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {33- markChangesSweep(scope.drafts)34- }35-}36-37-export function createProxy(base, parent) {38- const isArray = Array.isArray(base)39- const draft = clonePotentialDraft(base)40-41- if (isMap(base)) {42- proxyMap(draft)43- } else if (isSet(base)) {44- proxySet(draft)45- } else {46- each(draft, prop => {47- proxyProperty(draft, prop, isArray || isEnumerable(base, prop))48- })49- }50-51- // See "proxy.js" for property documentation.52- const scope = parent ? parent.scope : ImmerScope.current53- const state = {54- scope,55- modified: false,56- finalizing: false, // es5 only57- finalized: false,58- assigned: isMap(base) ? new Map() : {},59- parent,60- base,61- draft,62- drafts: isSet(base) ? new Map() : null,63- copy: null,64- revoke,65- revoked: false // es5 only66- }67-68- createHiddenProperty(draft, DRAFT_STATE, state)69- scope.drafts.push(draft)70- return draft71-}72-73-function revoke() {74- this.revoked = true75-}76-77-function latest(state) {78- return state.copy || state.base79-}80-81-// Access a property without creating an Immer draft.82-function peek(draft, prop) {83- const state = draft[DRAFT_STATE]84- if (state && !state.finalizing) {85- state.finalizing = true86- const value = draft[prop]87- state.finalizing = false88- return value89- }90- return draft[prop]91-}92-93-function get(state, prop) {94- assertUnrevoked(state)95- const value = peek(latest(state), prop)96- if (state.finalizing) return value97- // Create a draft if the value is unmodified.98- if (value === peek(state.base, prop) && isDraftable(value)) {99- prepareCopy(state)100- return (state.copy[prop] = createProxy(value, state))101- }102- return value103-}104-105-function set(state, prop, value) {106- assertUnrevoked(state)107- state.assigned[prop] = true108- if (!state.modified) {109- if (is(value, peek(latest(state), prop))) return110- markChanged(state)111- prepareCopy(state)112- }113- state.copy[prop] = value114-}115-116-function markChanged(state) {117- if (!state.modified) {118- state.modified = true119- if (state.parent) markChanged(state.parent)120- }121-}122-123-function prepareCopy(state) {124- if (!state.copy) state.copy = clonePotentialDraft(state.base)125-}126-127-function clonePotentialDraft(base) {128- const state = base && base[DRAFT_STATE]129- if (state) {130- state.finalizing = true131- const draft = shallowCopy(state.draft, true)132- state.finalizing = false133- return draft134- }135- return shallowCopy(base)136-}137-138-// property descriptors are recycled to make sure we don't create a get and set closure per property,139-// but share them all instead140-const descriptors = {}141-142-function proxyProperty(draft, prop, enumerable) {143- let desc = descriptors[prop]144- if (desc) {145- desc.enumerable = enumerable146- } else {147- descriptors[prop] = desc = {148- configurable: true,149- enumerable,150- get() {151- return get(this[DRAFT_STATE], prop)152- },153- set(value) {154- set(this[DRAFT_STATE], prop, value)155- }156- }157- }158- Object.defineProperty(draft, prop, desc)159-}160-161-function proxyMap(target) {162- Object.defineProperties(target, mapTraps)163-164- if (hasSymbol) {165- Object.defineProperty(166- target,167- Symbol.iterator,168- proxyMethod(iterateMapValues)169- )170- }171-}172-173-const mapTraps = finalizeTraps({174- size: state => latest(state).size,175- has: state => key => latest(state).has(key),176- set: state => (key, value) => {177- if (latest(state).get(key) !== value) {178- prepareCopy(state)179- markChanged(state)180- state.assigned.set(key, true)181- state.copy.set(key, value)182- }183- return state.draft184- },185- delete: state => key => {186- prepareCopy(state)187- markChanged(state)188- state.assigned.set(key, false)189- state.copy.delete(key)190- return false191- },192- clear: state => () => {193- if (!state.copy) {194- prepareCopy(state)195- }196- markChanged(state)197- state.assigned = new Map()198- for (const key of latest(state).keys()) {199- state.assigned.set(key, false)200- }201- return state.copy.clear()202- },203- forEach: (state, key, reciever) => cb => {204- latest(state).forEach((value, key, map) => {205- cb(reciever.get(key), key, map)206- })207- },208- get: state => key => {209- const value = latest(state).get(key)210-211- if (state.finalizing || state.finalized || !isDraftable(value)) {212- return value213- }214-215- if (value !== state.base.get(key)) {216- return value217- }218- const draft = createProxy(value, state)219- prepareCopy(state)220- state.copy.set(key, draft)221- return draft222- },223- keys: state => () => latest(state).keys(),224- values: iterateMapValues,225- entries: iterateMapValues226-})227-228-function proxySet(target) {229- Object.defineProperties(target, setTraps)230-231- if (hasSymbol) {232- Object.defineProperty(233- target,234- Symbol.iterator,235- proxyMethod(iterateSetValues)236- )237- }238-}239-240-const iterateSetValues = makeIterateSetValues(createProxy)241-242-const setTraps = finalizeTraps({243- size: state => {244- return latest(state).size245- },246- add: state => value => {247- if (!latest(state).has(value)) {248- markChanged(state)249- if (!state.copy) {250- prepareCopy(state)251- }252- state.copy.add(value)253- }254- return state.draft255- },256- delete: state => value => {257- markChanged(state)258- if (!state.copy) {259- prepareCopy(state)260- }261- return state.copy.delete(value)262- },263- has: state => key => {264- return latest(state).has(key)265- },266- clear: state => () => {267- markChanged(state)268- if (!state.copy) {269- prepareCopy(state)270- }271- return state.copy.clear()272- },273- keys: iterateSetValues,274- entries: iterateSetValues,275- values: iterateSetValues,276- forEach: state => (cb, thisArg) => {277- const iterator = iterateSetValues(state)()278- let result = iterator.next()279- while (!result.done) {280- cb.call(thisArg, result.value, result.value, state.draft)281- result = iterator.next()282- }283- }284-})285-286-function finalizeTraps(traps) {287- return Object.keys(traps).reduce(function(acc, key) {288- const builder = key === "size" ? proxyAttr : proxyMethod289- acc[key] = builder(traps[key], key)290- return acc291- }, {})292-}293-294-function proxyAttr(fn) {295- return {296- get() {297- const state = this[DRAFT_STATE]298- assertUnrevoked(state)299- return fn(state)300- }301- }302-}303-304-function proxyMethod(trap, key) {305- return {306- get() {307- return function(...args) {308- const state = this[DRAFT_STATE]309- assertUnrevoked(state)310- return trap(state, key, state.draft)(...args)311- }312- }313- }314-}315-316-function assertUnrevoked(state) {317- if (state.revoked === true)318- throw new Error(319- "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +320- JSON.stringify(latest(state))321- )322-}323-324-// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.325-function markChangesSweep(drafts) {326- // The natural order of drafts in the `scope` array is based on when they327- // were accessed. By processing drafts in reverse natural order, we have a328- // better chance of processing leaf nodes first. When a leaf node is known to329- // have changed, we can avoid any traversal of its ancestor nodes.330- for (let i = drafts.length - 1; i >= 0; i--) {331- const state = drafts[i][DRAFT_STATE]332- if (!state.modified) {333- if (Array.isArray(state.base)) {334- if (hasArrayChanges(state)) markChanged(state)335- } else if (isMap(state.base)) {336- if (hasMapChanges(state)) markChanged(state)337- } else if (isSet(state.base)) {338- if (hasSetChanges(state)) markChanged(state)339- } else if (hasObjectChanges(state)) {340- markChanged(state)341- }342- }343- }344-}345-346-function markChangesRecursively(object) {347- if (!object || typeof object !== "object") return348- const state = object[DRAFT_STATE]349- if (!state) return350- const {base, draft, assigned} = state351- if (!Array.isArray(object)) {352- // Look for added keys.353- Object.keys(draft).forEach(key => {354- // The `undefined` check is a fast path for pre-existing keys.355- if (base[key] === undefined && !has(base, key)) {356- assigned[key] = true357- markChanged(state)358- } else if (!assigned[key]) {359- // Only untouched properties trigger recursion.360- markChangesRecursively(draft[key])361- }362- })363- // Look for removed keys.364- Object.keys(base).forEach(key => {365- // The `undefined` check is a fast path for pre-existing keys.366- if (draft[key] === undefined && !has(draft, key)) {367- assigned[key] = false368- markChanged(state)369- }370- })371- } else if (hasArrayChanges(state)) {372- markChanged(state)373- assigned.length = true374- if (draft.length < base.length) {375- for (let i = draft.length; i < base.length; i++) assigned[i] = false376- } else {377- for (let i = base.length; i < draft.length; i++) assigned[i] = true378- }379- for (let i = 0; i < draft.length; i++) {380- // Only untouched indices trigger recursion.381- if (assigned[i] === undefined) markChangesRecursively(draft[i])382- }383- }384-}385-386-function hasObjectChanges(state) {387- const {base, draft} = state388-389- // Search for added keys and changed keys. Start at the back, because390- // non-numeric keys are ordered by time of definition on the object.391- const keys = Object.keys(draft)392- for (let i = keys.length - 1; i >= 0; i--) {393- const key = keys[i]394- const baseValue = base[key]395- // The `undefined` check is a fast path for pre-existing keys.396- if (baseValue === undefined && !has(base, key)) {397- return true398- }399- // Once a base key is deleted, future changes go undetected, because its400- // descriptor is erased. This branch detects any missed changes.401- else {402- const value = draft[key]403- const state = value && value[DRAFT_STATE]404- if (state ? state.base !== baseValue : !is(value, baseValue)) {405- return true406- }407- }408- }409-410- // At this point, no keys were added or changed.411- // Compare key count to determine if keys were deleted.412- return keys.length !== Object.keys(base).length413-}414-415-function hasArrayChanges(state) {416- const {draft} = state417- if (draft.length !== state.base.length) return true418- // See #116419- // If we first shorten the length, our array interceptors will be removed.420- // If after that new items are added, result in the same original length,421- // those last items will have no intercepting property.422- // So if there is no own descriptor on the last position, we know that items were removed and added423- // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check424- // the last one425- const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)426- // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)427- if (descriptor && !descriptor.get) return true428- // For all other cases, we don't have to compare, as they would have been picked up by the index setters429- return false430-}431-432-function hasMapChanges(state) {433- const {base, draft} = state434-435- if (base.size !== draft.size) return true436-437- // IE11 supports only forEach iteration438- let hasChanges = false439- draft.forEach(function(value, key) {440- if (!hasChanges) {441- hasChanges = isDraftable(value) ? value.modified : value !== base.get(key)442- }443- })444- return hasChanges445-}446-447-function hasSetChanges(state) {448- const {base, draft} = state449-450- if (base.size !== draft.size) return true451-452- // IE11 supports only forEach iteration453- let hasChanges = false454- draft.forEach(function(value, key) {455- if (!hasChanges) {456- hasChanges = isDraftable(value) ? value.modified : !base.has(key)457- }458- })459- return hasChanges460-}461-462-function createHiddenProperty(target, prop, value) {463- Object.defineProperty(target, prop, {464- value: value,465- enumerable: false,466- writable: true467- })468-}added:src/es5.ts+492 added
1+"use strict"2+import {3+ each,4+ has,5+ is,6+ isDraft,7+ isDraftable,8+ isEnumerable,9+ isMap,10+ isSet,11+ hasSymbol,12+ shallowCopy,13+ DRAFT_STATE,14+ iterateMapValues,15+ makeIterable,16+ makeIterateSetValues17+} from "./common"18+import {ImmerScope} from "./scope"19+import {ImmerState} from "./types"20+21+interface ES5Draft {22+ [DRAFT_STATE]: ES5State23+}24+25+interface ES5State<T = any> {26+ scope: ImmerScope27+ modified: boolean28+ finalizing: boolean29+ finalized: boolean30+ assigned: Map<any, any> | {[key: string]: any}31+ parent: ES5State32+ base: T33+ draft: T & ES5Draft34+ drafts: Map<any, any> | null35+ copy: T | null36+ revoke()37+ revoked: boolean38+}39+40+export function willFinalize(41+ scope: ImmerScope,42+ result: any,43+ isReplaced: boolean44+) {45+ scope.drafts!.forEach(draft => {46+ draft[DRAFT_STATE].finalizing = true47+ })48+ if (!isReplaced) {49+ if (scope.patches) {50+ markChangesRecursively(scope.drafts![0])51+ }52+ // This is faster when we don't care about which attributes changed.53+ markChangesSweep(scope.drafts)54+ }55+ // When a child draft is returned, look for changes.56+ else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {57+ markChangesSweep(scope.drafts)58+ }59+}60+61+export function createProxy(base: any, parent: ES5State) {62+ const isArray = Array.isArray(base)63+ const draft = clonePotentialDraft(base)64+65+ if (isMap(base)) {66+ proxyMap(draft)67+ } else if (isSet(base)) {68+ proxySet(draft)69+ } else {70+ each(draft, prop => {71+ proxyProperty(draft, prop, isArray || isEnumerable(base, prop))72+ })73+ }74+75+ // See "proxy.js" for property documentation.76+ const scope = parent ? parent.scope : ImmerScope.current!77+ const state: ES5State = {78+ scope,79+ modified: false,80+ finalizing: false, // es5 only81+ finalized: false,82+ assigned: isMap(base) ? new Map() : {},83+ parent,84+ base,85+ draft,86+ drafts: isSet(base) ? new Map() : null,87+ copy: null,88+ revoke,89+ revoked: false // es5 only90+ }91+92+ createHiddenProperty(draft, DRAFT_STATE, state)93+ scope.drafts!.push(draft)94+ return draft95+}96+97+function revoke(this: ES5State) {98+ this.revoked = true99+}100+101+function latest(state) {102+ return state.copy || state.base103+}104+105+// Access a property without creating an Immer draft.106+function peek(draft, prop) {107+ const state = draft[DRAFT_STATE]108+ if (state && !state.finalizing) {109+ state.finalizing = true110+ const value = draft[prop]111+ state.finalizing = false112+ return value113+ }114+ return draft[prop]115+}116+117+function get(state, prop) {118+ assertUnrevoked(state)119+ const value = peek(latest(state), prop)120+ if (state.finalizing) return value121+ // Create a draft if the value is unmodified.122+ if (value === peek(state.base, prop) && isDraftable(value)) {123+ prepareCopy(state)124+ return (state.copy[prop] = createProxy(value, state))125+ }126+ return value127+}128+129+function set(state, prop, value) {130+ assertUnrevoked(state)131+ state.assigned[prop] = true132+ if (!state.modified) {133+ if (is(value, peek(latest(state), prop))) return134+ markChanged(state)135+ prepareCopy(state)136+ }137+ state.copy[prop] = value138+}139+140+function markChanged(state) {141+ if (!state.modified) {142+ state.modified = true143+ if (state.parent) markChanged(state.parent)144+ }145+}146+147+function prepareCopy(state) {148+ if (!state.copy) state.copy = clonePotentialDraft(state.base)149+}150+151+function clonePotentialDraft(base) {152+ const state = base && base[DRAFT_STATE]153+ if (state) {154+ state.finalizing = true155+ const draft = shallowCopy(state.draft, true)156+ state.finalizing = false157+ return draft158+ }159+ return shallowCopy(base)160+}161+162+// property descriptors are recycled to make sure we don't create a get and set closure per property,163+// but share them all instead164+const descriptors = {}165+166+function proxyProperty(draft, prop, enumerable) {167+ let desc = descriptors[prop]168+ if (desc) {169+ desc.enumerable = enumerable170+ } else {171+ descriptors[prop] = desc = {172+ configurable: true,173+ enumerable,174+ get() {175+ return get(this[DRAFT_STATE], prop)176+ },177+ set(value) {178+ set(this[DRAFT_STATE], prop, value)179+ }180+ }181+ }182+ Object.defineProperty(draft, prop, desc)183+}184+185+function proxyMap(target) {186+ Object.defineProperties(target, mapTraps)187+188+ if (hasSymbol) {189+ Object.defineProperty(190+ target,191+ Symbol.iterator,192+ proxyMethod(iterateMapValues)193+ )194+ }195+}196+197+const mapTraps = finalizeTraps({198+ size: state => latest(state).size,199+ has: state => key => latest(state).has(key),200+ set: state => (key, value) => {201+ if (latest(state).get(key) !== value) {202+ prepareCopy(state)203+ markChanged(state)204+ state.assigned.set(key, true)205+ state.copy.set(key, value)206+ }207+ return state.draft208+ },209+ delete: state => key => {210+ prepareCopy(state)211+ markChanged(state)212+ state.assigned.set(key, false)213+ state.copy.delete(key)214+ return false215+ },216+ clear: state => () => {217+ if (!state.copy) {218+ prepareCopy(state)219+ }220+ markChanged(state)221+ state.assigned = new Map()222+ for (const key of latest(state).keys()) {223+ state.assigned.set(key, false)224+ }225+ return state.copy.clear()226+ },227+ forEach: (state, key, reciever) => cb => {228+ latest(state).forEach((value, key, map) => {229+ cb(reciever.get(key), key, map)230+ })231+ },232+ get: state => key => {233+ const value = latest(state).get(key)234+235+ if (state.finalizing || state.finalized || !isDraftable(value)) {236+ return value237+ }238+239+ if (value !== state.base.get(key)) {240+ return value241+ }242+ const draft = createProxy(value, state)243+ prepareCopy(state)244+ state.copy.set(key, draft)245+ return draft246+ },247+ keys: state => () => latest(state).keys(),248+ values: iterateMapValues,249+ entries: iterateMapValues250+})251+252+function proxySet(target) {253+ Object.defineProperties(target, setTraps)254+255+ if (hasSymbol) {256+ Object.defineProperty(257+ target,258+ Symbol.iterator,259+ proxyMethod(iterateSetValues)260+ )261+ }262+}263+264+const iterateSetValues = makeIterateSetValues(createProxy)265+266+const setTraps = finalizeTraps({267+ size: state => {268+ return latest(state).size269+ },270+ add: state => value => {271+ if (!latest(state).has(value)) {272+ markChanged(state)273+ if (!state.copy) {274+ prepareCopy(state)275+ }276+ state.copy.add(value)277+ }278+ return state.draft279+ },280+ delete: state => value => {281+ markChanged(state)282+ if (!state.copy) {283+ prepareCopy(state)284+ }285+ return state.copy.delete(value)286+ },287+ has: state => key => {288+ return latest(state).has(key)289+ },290+ clear: state => () => {291+ markChanged(state)292+ if (!state.copy) {293+ prepareCopy(state)294+ }295+ return state.copy.clear()296+ },297+ keys: iterateSetValues,298+ entries: iterateSetValues,299+ values: iterateSetValues,300+ forEach: state => (cb, thisArg) => {301+ const iterator = iterateSetValues(state)()302+ let result = iterator.next()303+ while (!result.done) {304+ cb.call(thisArg, result.value, result.value, state.draft)305+ result = iterator.next()306+ }307+ }308+})309+310+function finalizeTraps(traps) {311+ return Object.keys(traps).reduce(function(acc, key) {312+ const builder = key === "size" ? proxyAttr : proxyMethod313+ acc[key] = builder(traps[key], key)314+ return acc315+ }, {})316+}317+318+function proxyAttr(fn) {319+ return {320+ get() {321+ const state = this[DRAFT_STATE]322+ assertUnrevoked(state)323+ return fn(state)324+ }325+ }326+}327+328+function proxyMethod(trap, key) {329+ return {330+ get() {331+ return function(...args) {332+ const state = this[DRAFT_STATE]333+ assertUnrevoked(state)334+ return trap(state, key, state.draft)(...args)335+ }336+ }337+ }338+}339+340+function assertUnrevoked(state) {341+ if (state.revoked === true)342+ throw new Error(343+ "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +344+ JSON.stringify(latest(state))345+ )346+}347+348+// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.349+function markChangesSweep(drafts) {350+ // The natural order of drafts in the `scope` array is based on when they351+ // were accessed. By processing drafts in reverse natural order, we have a352+ // better chance of processing leaf nodes first. When a leaf node is known to353+ // have changed, we can avoid any traversal of its ancestor nodes.354+ for (let i = drafts.length - 1; i >= 0; i--) {355+ const state = drafts[i][DRAFT_STATE]356+ if (!state.modified) {357+ if (Array.isArray(state.base)) {358+ if (hasArrayChanges(state)) markChanged(state)359+ } else if (isMap(state.base)) {360+ if (hasMapChanges(state)) markChanged(state)361+ } else if (isSet(state.base)) {362+ if (hasSetChanges(state)) markChanged(state)363+ } else if (hasObjectChanges(state)) {364+ markChanged(state)365+ }366+ }367+ }368+}369+370+function markChangesRecursively(object) {371+ if (!object || typeof object !== "object") return372+ const state = object[DRAFT_STATE]373+ if (!state) return374+ const {base, draft, assigned} = state375+ if (!Array.isArray(object)) {376+ // Look for added keys.377+ Object.keys(draft).forEach(key => {378+ // The `undefined` check is a fast path for pre-existing keys.379+ if (base[key] === undefined && !has(base, key)) {380+ assigned[key] = true381+ markChanged(state)382+ } else if (!assigned[key]) {383+ // Only untouched properties trigger recursion.384+ markChangesRecursively(draft[key])385+ }386+ })387+ // Look for removed keys.388+ Object.keys(base).forEach(key => {389+ // The `undefined` check is a fast path for pre-existing keys.390+ if (draft[key] === undefined && !has(draft, key)) {391+ assigned[key] = false392+ markChanged(state)393+ }394+ })395+ } else if (hasArrayChanges(state)) {396+ markChanged(state)397+ assigned.length = true398+ if (draft.length < base.length) {399+ for (let i = draft.length; i < base.length; i++) assigned[i] = false400+ } else {401+ for (let i = base.length; i < draft.length; i++) assigned[i] = true402+ }403+ for (let i = 0; i < draft.length; i++) {404+ // Only untouched indices trigger recursion.405+ if (assigned[i] === undefined) markChangesRecursively(draft[i])406+ }407+ }408+}409+410+function hasObjectChanges(state) {411+ const {base, draft} = state412+413+ // Search for added keys and changed keys. Start at the back, because414+ // non-numeric keys are ordered by time of definition on the object.415+ const keys = Object.keys(draft)416+ for (let i = keys.length - 1; i >= 0; i--) {417+ const key = keys[i]418+ const baseValue = base[key]419+ // The `undefined` check is a fast path for pre-existing keys.420+ if (baseValue === undefined && !has(base, key)) {421+ return true422+ }423+ // Once a base key is deleted, future changes go undetected, because its424+ // descriptor is erased. This branch detects any missed changes.425+ else {426+ const value = draft[key]427+ const state = value && value[DRAFT_STATE]428+ if (state ? state.base !== baseValue : !is(value, baseValue)) {429+ return true430+ }431+ }432+ }433+434+ // At this point, no keys were added or changed.435+ // Compare key count to determine if keys were deleted.436+ return keys.length !== Object.keys(base).length437+}438+439+function hasArrayChanges(state) {440+ const {draft} = state441+ if (draft.length !== state.base.length) return true442+ // See #116443+ // If we first shorten the length, our array interceptors will be removed.444+ // If after that new items are added, result in the same original length,445+ // those last items will have no intercepting property.446+ // So if there is no own descriptor on the last position, we know that items were removed and added447+ // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check448+ // the last one449+ const descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1)450+ // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)451+ if (descriptor && !descriptor.get) return true452+ // For all other cases, we don't have to compare, as they would have been picked up by the index setters453+ return false454+}455+456+function hasMapChanges(state) {457+ const {base, draft} = state458+459+ if (base.size !== draft.size) return true460+461+ // IE11 supports only forEach iteration462+ let hasChanges = false463+ draft.forEach(function(value, key) {464+ if (!hasChanges) {465+ hasChanges = isDraftable(value) ? value.modified : value !== base.get(key)466+ }467+ })468+ return hasChanges469+}470+471+function hasSetChanges(state) {472+ const {base, draft} = state473+474+ if (base.size !== draft.size) return true475+476+ // IE11 supports only forEach iteration477+ let hasChanges = false478+ draft.forEach(function(value, key) {479+ if (!hasChanges) {480+ hasChanges = isDraftable(value) ? value.modified : !base.has(key)481+ }482+ })483+ return hasChanges484+}485+486+function createHiddenProperty(target, prop, value) {487+ Object.defineProperty(target, prop, {488+ value: value,489+ enumerable: false,490+ writable: true491+ })492+}deleted:src/immer.d.ts-309 removed
1-type Tail<T extends any[]> = ((...t: T) => any) extends ((2- _: any,3- ...tail: infer TT4-) => any)5- ? TT6- : []7-8-/** Object types that should never be mapped */9-type AtomicObject =10- | Function11- | WeakMap<any, any>12- | WeakSet<any>13- | Promise<any>14- | Date15- | RegExp16- | Boolean17- | Number18- | String19-20-export type Draft<T> = T extends AtomicObject21- ? T22- : T extends Map<infer K, infer V>23- ? DraftMap<K, V>24- : T extends Set<infer V>25- ? DraftSet<V>26- : T extends object27- ? {-readonly [K in keyof T]: Draft<T[K]>}28- : T29-30-// Inline these in ts 3.731-interface DraftMap<K, V> extends Map<Draft<K>, Draft<V>> {}32-33-// Inline these in ts 3.734-interface DraftSet<V> extends Set<Draft<V>> {}35-36-/** Convert a mutable type into a readonly type */37-export type Immutable<T> = T extends AtomicObject38- ? T39- : T extends Map<infer K, infer V>40- ? // Ideally, but wait for TS 3.7: ? Omit<ImmutableMap<K, V>, "set" | "delete" | "clear">41- ImmutableMap<K, V>42- : T extends Set<infer V>43- ? // Ideally, but wait for TS 3.7: ? Omit<ImmutableSet<V>, "add" | "delete" | "clear">44- ImmutableSet<V>45- : T extends object46- ? {readonly [K in keyof T]: Immutable<T[K]>}47- : T48-49-interface ImmutableMap<K, V> extends Map<Immutable<K>, Immutable<V>> {}50-51-interface ImmutableSet<V> extends Set<Immutable<V>> {}52-53-export interface Patch {54- op: "replace" | "remove" | "add"55- path: (string | number)[]56- value?: any57-}58-59-export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void60-61-/** Converts `nothing` into `undefined` */62-type FromNothing<T> = T extends Nothing ? undefined : T63-64-/** The inferred return type of `produce` */65-export type Produced<Base, Return> = Return extends void66- ? Base67- : Return extends Promise<infer Result>68- ? Promise<Result extends void ? Base : FromNothing<Result>>69- : FromNothing<Return>70-71-/**72- * The `produce` function takes a value and a "recipe function" (whose73- * return value often depends on the base state). The recipe function is74- * free to mutate its first argument however it wants. All mutations are75- * only ever applied to a __copy__ of the base state.76- *77- * Pass only a function to create a "curried producer" which relieves you78- * from passing the recipe function every time.79- *80- * Only plain objects and arrays are made mutable. All other objects are81- * considered uncopyable.82- *83- * Note: This function is __bound__ to its `Immer` instance.84- *85- * @param {any} base - the initial state86- * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified87- * @param {Function} patchListener - optional function that will be called with all the patches produced here88- * @returns {any} a new state, or the initial state if nothing was modified89- */90-export interface IProduce {91- /** Curried producer */92- <93- Recipe extends (...args: any[]) => any,94- Params extends any[] = Parameters<Recipe>,95- T = Params[0]96- >(97- recipe: Recipe98- ): <Base extends Immutable<T>>(99- base: Base,100- ...rest: Tail<Params>101- ) => Produced<Base, ReturnType<Recipe>>102- // ^ by making the returned type generic, the actual type of the passed in object is preferred103- // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe104- // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!105-106- /** Curried producer with initial state */107- <108- Recipe extends (...args: any[]) => any,109- Params extends any[] = Parameters<Recipe>,110- T = Params[0]111- >(112- recipe: Recipe,113- initialState: Immutable<T>114- ): <Base extends Immutable<T>>(115- base?: Base,116- ...rest: Tail<Params>117- ) => Produced<Base, ReturnType<Recipe>>118-119- /** Normal producer */120- <Base, D = Draft<Base>, Return = void>(121- base: Base,122- recipe: (draft: D) => Return,123- listener?: PatchListener124- ): Produced<Base, Return>125-}126-127-export const produce: IProduce128-export default produce129-130-/**131- * Like `produce`, but instead of just returning the new state,132- * a tuple is returned with [nextState, patches, inversePatches]133- *134- * Like produce, this function supports currying135- */136-export interface IProduceWithPatches {137- /** Curried producer */138- <139- Recipe extends (...args: any[]) => any,140- Params extends any[] = Parameters<Recipe>,141- T = Params[0]142- >(143- recipe: Recipe144- ): <Base extends Immutable<T>>(145- base: Base,146- ...rest: Tail<Params>147- ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]148- // ^ by making the returned type generic, the actual type of the passed in object is preferred149- // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe150- // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!151-152- /** Curried producer with initial state */153- <154- Recipe extends (...args: any[]) => any,155- Params extends any[] = Parameters<Recipe>,156- T = Params[0]157- >(158- recipe: Recipe,159- initialState: Immutable<T>160- ): <Base extends Immutable<T>>(161- base?: Base,162- ...rest: Tail<Params>163- ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]164-165- /** Normal producer */166- <Base, D = Draft<Base>, Return = void>(167- base: Base,168- recipe: (draft: D) => Return169- ): [Produced<Base, Return>, Patch[], Patch[]]170-}171-export const produceWithPatches: IProduceWithPatches172-173-/** Use a class type for `nothing` so its type is unique */174-declare class Nothing {175- // This lets us do `Exclude<T, Nothing>`176- private _: any177-}178-179-/**180- * The sentinel value returned by producers to replace the draft with undefined.181- */182-export const nothing: Nothing183-184-/**185- * To let Immer treat your class instances as plain immutable objects186- * (albeit with a custom prototype), you must define either an instance property187- * or a static property on each of your custom classes.188- *189- * Otherwise, your class instance will never be drafted, which means it won't be190- * safe to mutate in a produce callback.191- */192-export const immerable: unique symbol193-194-/**195- * Pass true to automatically freeze all copies created by Immer.196- *197- * By default, auto-freezing is disabled in production.198- */199-export function setAutoFreeze(autoFreeze: boolean): void200-201-/**202- * Pass true to use the ES2015 `Proxy` class when creating drafts, which is203- * always faster than using ES5 proxies.204- *205- * By default, feature detection is used, so calling this is rarely necessary.206- */207-export function setUseProxies(useProxies: boolean): void208-209-/**210- * Apply an array of Immer patches to the first argument.211- *212- * This function is a producer, which means copy-on-write is in effect.213- */214-export function applyPatches<S>(base: S, patches: Patch[]): S215-216-/**217- * Create an Immer draft from the given base state, which may be a draft itself.218- * The draft can be modified until you finalize it with the `finishDraft` function.219- */220-export function createDraft<T>(base: T): Draft<T>221-222-/**223- * Finalize an Immer draft from a `createDraft` call, returning the base state224- * (if no changes were made) or a modified copy. The draft must *not* be225- * mutated afterwards.226- *227- * Pass a function as the 2nd argument to generate Immer patches based on the228- * changes that were made.229- */230-export function finishDraft<T>(draft: T, listener?: PatchListener): Immutable<T>231-232-/** Get the underlying object that is represented by the given draft */233-export function original<T>(value: T): T | void234-235-/** Returns true if the given value is an Immer draft */236-export function isDraft(value: any): boolean237-238-/** Returns true if the given value can be drafted by Immer */239-export function isDraftable(value: any): boolean240-241-export class Immer {242- constructor(config: {243- useProxies?: boolean244- autoFreeze?: boolean245- onAssign?: (246- state: ImmerState,247- prop: string | number,248- value: unknown249- ) => void250- onDelete?: (state: ImmerState, prop: string | number) => void251- onCopy?: (state: ImmerState) => void252- })253- /**254- * The `produce` function takes a value and a "recipe function" (whose255- * return value often depends on the base state). The recipe function is256- * free to mutate its first argument however it wants. All mutations are257- * only ever applied to a __copy__ of the base state.258- *259- * Pass only a function to create a "curried producer" which relieves you260- * from passing the recipe function every time.261- *262- * Only plain objects and arrays are made mutable. All other objects are263- * considered uncopyable.264- *265- * Note: This function is __bound__ to its `Immer` instance.266- *267- * @param {any} base - the initial state268- * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified269- * @param {Function} patchListener - optional function that will be called with all the patches produced here270- * @returns {any} a new state, or the initial state if nothing was modified271- */272- produce: IProduce273- /**274- * When true, `produce` will freeze the copies it creates.275- */276- readonly autoFreeze: boolean277- /**278- * When true, drafts are ES2015 proxies.279- */280- readonly useProxies: boolean281- /**282- * Pass true to automatically freeze all copies created by Immer.283- *284- * By default, auto-freezing is disabled in production.285- */286- setAutoFreeze(autoFreeze: boolean): void287- /**288- * Pass true to use the ES2015 `Proxy` class when creating drafts, which is289- * always faster than using ES5 proxies.290- *291- * By default, feature detection is used, so calling this is rarely necessary.292- */293- setUseProxies(useProxies: boolean): void294-}295-296-export interface ImmerState<T = any> {297- parent?: ImmerState298- base: T299- copy: T300- assigned: {[prop: string]: boolean; [index: number]: boolean}301-}302-303-// Backward compatibility with --target es5304-declare global {305- interface Set<T> {}306- interface Map<K, V> {}307- interface WeakSet<T> {}308- interface WeakMap<K extends object, V> {}309-}deleted:src/immer.js-349 removed
1-import * as legacyProxy from "./es5"2-import * as modernProxy from "./proxy"3-import {applyPatches, generatePatches} from "./patches"4-import {5- assign,6- each,7- has,8- is,9- isDraft,10- isSet,11- get,12- isMap,13- isDraftable,14- isEnumerable,15- shallowCopy,16- DRAFT_STATE,17- NOTHING,18- freeze19-} from "./common"20-import {ImmerScope} from "./scope"21-22-function verifyMinified() {}23-24-const configDefaults = {25- useProxies:26- typeof Proxy !== "undefined" &&27- typeof Proxy.revocable !== "undefined" &&28- typeof Reflect !== "undefined",29- autoFreeze:30- typeof process !== "undefined"31- ? process.env.NODE_ENV !== "production"32- : verifyMinified.name === "verifyMinified",33- onAssign: null,34- onDelete: null,35- onCopy: null36-}37-38-export class Immer {39- constructor(config) {40- assign(this, configDefaults, config)41- this.setUseProxies(this.useProxies)42- this.produce = this.produce.bind(this)43- this.produceWithPatches = this.produceWithPatches.bind(this)44- }45- produce(base, recipe, patchListener) {46- // curried invocation47- if (typeof base === "function" && typeof recipe !== "function") {48- const defaultBase = recipe49- recipe = base50-51- const self = this52- return function curriedProduce(base = defaultBase, ...args) {53- return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore54- }55- }56-57- // prettier-ignore58- {59- if (typeof recipe !== "function") {60- throw new Error("The first or second argument to `produce` must be a function")61- }62- if (patchListener !== undefined && typeof patchListener !== "function") {63- throw new Error("The third argument to `produce` must be a function or undefined")64- }65- }66-67- let result68-69- // Only plain objects, arrays, and "immerable classes" are drafted.70- if (isDraftable(base)) {71- const scope = ImmerScope.enter()72- const proxy = this.createProxy(base)73- let hasError = true74- try {75- result = recipe(proxy)76- hasError = false77- } finally {78- // finally instead of catch + rethrow better preserves original stack79- if (hasError) scope.revoke()80- else scope.leave()81- }82- if (typeof Promise !== "undefined" && result instanceof Promise) {83- return result.then(84- result => {85- scope.usePatches(patchListener)86- return this.processResult(result, scope)87- },88- error => {89- scope.revoke()90- throw error91- }92- )93- }94- scope.usePatches(patchListener)95- return this.processResult(result, scope)96- } else {97- result = recipe(base)98- if (result === NOTHING) return undefined99- if (result === undefined) result = base100- this.maybeFreeze(result, true)101- return result102- }103- }104- produceWithPatches(arg1, arg2, arg3) {105- if (typeof arg1 === "function") {106- const self = this107- return (state, ...args) =>108- this.produceWithPatches(state, draft => arg1(draft, ...args))109- }110- // non-curried form111- if (arg3)112- throw new Error("A patch listener cannot be passed to produceWithPatches")113- let patches, inversePatches114- const nextState = this.produce(arg1, arg2, (p, ip) => {115- patches = p116- inversePatches = ip117- })118- return [nextState, patches, inversePatches]119- }120- createDraft(base) {121- if (!isDraftable(base)) {122- throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore123- }124- const scope = ImmerScope.enter()125- const proxy = this.createProxy(base)126- proxy[DRAFT_STATE].isManual = true127- scope.leave()128- return proxy129- }130- finishDraft(draft, patchListener) {131- const state = draft && draft[DRAFT_STATE]132- if (!state || !state.isManual) {133- throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore134- }135- if (state.finalized) {136- throw new Error("The given draft is already finalized") // prettier-ignore137- }138- const {scope} = state139- scope.usePatches(patchListener)140- return this.processResult(undefined, scope)141- }142- setAutoFreeze(value) {143- this.autoFreeze = value144- }145- setUseProxies(value) {146- this.useProxies = value147- assign(this, value ? modernProxy : legacyProxy)148- }149- applyPatches(base, patches) {150- // If a patch replaces the entire state, take that replacement as base151- // before applying patches152- let i153- for (i = patches.length - 1; i >= 0; i--) {154- const patch = patches[i]155- if (patch.path.length === 0 && patch.op === "replace") {156- base = patch.value157- break158- }159- }160-161- if (isDraft(base)) {162- // N.B: never hits if some patch a replacement, patches are never drafts163- return applyPatches(base, patches)164- }165- // Otherwise, produce a copy of the base state.166- return this.produce(base, draft =>167- applyPatches(draft, patches.slice(i + 1))168- )169- }170- /** @internal */171- processResult(result, scope) {172- const baseDraft = scope.drafts[0]173- const isReplaced = result !== undefined && result !== baseDraft174- this.willFinalize(scope, result, isReplaced)175- if (isReplaced) {176- if (baseDraft[DRAFT_STATE].modified) {177- scope.revoke()178- throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore179- }180- if (isDraftable(result)) {181- // Finalize the result in case it contains (or is) a subset of the draft.182- result = this.finalize(result, null, scope)183- this.maybeFreeze(result)184- }185- if (scope.patches) {186- scope.patches.push({187- op: "replace",188- path: [],189- value: result190- })191- scope.inversePatches.push({192- op: "replace",193- path: [],194- value: baseDraft[DRAFT_STATE].base195- })196- }197- } else {198- // Finalize the base draft.199- result = this.finalize(baseDraft, [], scope)200- }201- scope.revoke()202- if (scope.patches) {203- scope.patchListener(scope.patches, scope.inversePatches)204- }205- return result !== NOTHING ? result : undefined206- }207- /**208- * @internal209- * Finalize a draft, returning either the unmodified base state or a modified210- * copy of the base state.211- */212- finalize(draft, path, scope) {213- const state = draft[DRAFT_STATE]214- if (!state) {215- if (Object.isFrozen(draft)) return draft216- return this.finalizeTree(draft, null, scope)217- }218- // Never finalize drafts owned by another scope.219- if (state.scope !== scope) {220- return draft221- }222- if (!state.modified) {223- this.maybeFreeze(state.base, true)224- return state.base225- }226- if (!state.finalized) {227- state.finalized = true228- this.finalizeTree(state.draft, path, scope)229-230- // We cannot really delete anything inside of a Set. We can only replace the whole Set.231- if (this.onDelete && !isSet(state.base)) {232- // The `assigned` object is unreliable with ES5 drafts.233- if (this.useProxies) {234- const {assigned} = state235- each(assigned, (prop, exists) => {236- if (!exists) this.onDelete(state, prop)237- })238- } else {239- // TODO: Figure it out for Maps and Sets if we need to support ES5240- const {base, copy} = state241- each(base, prop => {242- if (!has(copy, prop)) this.onDelete(state, prop)243- })244- }245- }246- if (this.onCopy) {247- this.onCopy(state)248- }249-250- // At this point, all descendants of `state.copy` have been finalized,251- // so we can be sure that `scope.canAutoFreeze` is accurate.252- if (this.autoFreeze && scope.canAutoFreeze) {253- freeze(state.copy, false)254- }255-256- if (path && scope.patches) {257- generatePatches(state, path, scope.patches, scope.inversePatches)258- }259- }260- return state.copy261- }262- /**263- * @internal264- * Finalize all drafts in the given state tree.265- */266- finalizeTree(root, rootPath, scope) {267- const state = root[DRAFT_STATE]268- if (state) {269- if (!this.useProxies) {270- // Create the final copy, with added keys and without deleted keys.271- state.copy = shallowCopy(state.draft, true)272- }273- root = state.copy274- }275-276- const needPatches = !!rootPath && !!scope.patches277- const finalizeProperty = (prop, value, parent) => {278- if (value === parent) {279- throw Error("Immer forbids circular references")280- }281-282- // In the `finalizeTree` method, only the `root` object may be a draft.283- const isDraftProp = !!state && parent === root284- const isSetMember = isSet(parent)285-286- if (isDraft(value)) {287- const path =288- isDraftProp &&289- needPatches &&290- !isSetMember && // Set objects are atomic since they have no keys.291- !has(state.assigned, prop) // Skip deep patches for assigned keys.292- ? rootPath.concat(prop)293- : null294-295- // Drafts owned by `scope` are finalized here.296- value = this.finalize(value, path, scope)297- replace(parent, prop, value)298-299- // Drafts from another scope must prevent auto-freezing.300- if (isDraft(value)) {301- scope.canAutoFreeze = false302- }303-304- // Unchanged drafts are never passed to the `onAssign` hook.305- if (isDraftProp && value === get(state.base, prop)) return306- }307- // Unchanged draft properties are ignored.308- else if (isDraftProp && is(value, get(state.base, prop))) {309- return310- }311- // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.312- else if (isDraftable(value) && !Object.isFrozen(value)) {313- each(value, finalizeProperty)314- this.maybeFreeze(value)315- }316-317- if (isDraftProp && this.onAssign && !isSetMember) {318- this.onAssign(state, prop, value)319- }320- }321-322- each(root, finalizeProperty)323- return root324- }325- maybeFreeze(value, deep = false) {326- if (this.autoFreeze && !isDraft(value)) {327- freeze(value, deep)328- }329- }330-}331-332-function replace(parent, prop, value) {333- if (isMap(parent)) {334- parent.set(prop, value)335- } else if (isSet(parent)) {336- // In this case, the `prop` is actually a draft.337- parent.delete(prop)338- parent.add(value)339- } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {340- // Preserve non-enumerable properties.341- parent[prop] = value342- } else {343- Object.defineProperty(parent, prop, {344- value,345- writable: true,346- configurable: true347- })348- }349-}added:src/immer.ts+404 added
1+import * as legacyProxy from "./es5"2+import * as modernProxy from "./proxy"3+import {applyPatches, generatePatches} from "./patches"4+import {5+ assign,6+ each,7+ has,8+ is,9+ isDraft,10+ isSet,11+ get,12+ isMap,13+ isDraftable,14+ isEnumerable,15+ shallowCopy,16+ DRAFT_STATE,17+ NOTHING,18+ freeze19+} from "./common"20+import {ImmerScope} from "./scope"21+import {ImmerState, IProduce, IProduceWithPatches} from "./types"22+23+function verifyMinified() {}24+25+const configDefaults = {26+ useProxies:27+ typeof Proxy !== "undefined" &&28+ typeof Proxy.revocable !== "undefined" &&29+ typeof Reflect !== "undefined",30+ autoFreeze:31+ typeof process !== "undefined"32+ ? process.env.NODE_ENV !== "production"33+ : verifyMinified.name === "verifyMinified",34+ onAssign: null,35+ onDelete: null,36+ onCopy: null37+}38+39+interface ProducersFns {40+ produce: IProduce41+ produceWithPatches: IProduceWithPatches42+}43+44+export class Immer implements ProducersFns {45+ useProxies: boolean = false46+ autoFreeze: boolean = false47+48+ constructor(config?: {49+ useProxies?: boolean50+ autoFreeze?: boolean51+ onAssign?: (52+ state: ImmerState,53+ prop: string | number,54+ value: unknown55+ ) => void56+ onDelete?: (state: ImmerState, prop: string | number) => void57+ onCopy?: (state: ImmerState) => void58+ }) {59+ assign(this, configDefaults, config)60+ this.setUseProxies(this.useProxies)61+ this.produce = this.produce.bind(this)62+ this.produceWithPatches = this.produceWithPatches.bind(this)63+ }64+65+ /**66+ * The `produce` function takes a value and a "recipe function" (whose67+ * return value often depends on the base state). The recipe function is68+ * free to mutate its first argument however it wants. All mutations are69+ * only ever applied to a __copy__ of the base state.70+ *71+ * Pass only a function to create a "curried producer" which relieves you72+ * from passing the recipe function every time.73+ *74+ * Only plain objects and arrays are made mutable. All other objects are75+ * considered uncopyable.76+ *77+ * Note: This function is __bound__ to its `Immer` instance.78+ *79+ * @param {any} base - the initial state80+ * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified81+ * @param {Function} patchListener - optional function that will be called with all the patches produced here82+ * @returns {any} a new state, or the initial state if nothing was modified83+ */84+ produce(base, recipe, patchListener) {85+ // curried invocation86+ if (typeof base === "function" && typeof recipe !== "function") {87+ const defaultBase = recipe88+ recipe = base89+90+ const self = this91+ return function curriedProduce(base = defaultBase, ...args) {92+ return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore93+ }94+ }95+96+ // prettier-ignore97+ {98+ if (typeof recipe !== "function") {99+ throw new Error("The first or second argument to `produce` must be a function")100+ }101+ if (patchListener !== undefined && typeof patchListener !== "function") {102+ throw new Error("The third argument to `produce` must be a function or undefined")103+ }104+ }105+106+ let result107+108+ // Only plain objects, arrays, and "immerable classes" are drafted.109+ if (isDraftable(base)) {110+ const scope = ImmerScope.enter()111+ const proxy = this.createProxy(base)112+ let hasError = true113+ try {114+ result = recipe(proxy)115+ hasError = false116+ } finally {117+ // finally instead of catch + rethrow better preserves original stack118+ if (hasError) scope.revoke()119+ else scope.leave()120+ }121+ if (typeof Promise !== "undefined" && result instanceof Promise) {122+ return result.then(123+ result => {124+ scope.usePatches(patchListener)125+ return this.processResult(result, scope)126+ },127+ error => {128+ scope.revoke()129+ throw error130+ }131+ )132+ }133+ scope.usePatches(patchListener)134+ return this.processResult(result, scope)135+ } else {136+ result = recipe(base)137+ if (result === NOTHING) return undefined138+ if (result === undefined) result = base139+ this.maybeFreeze(result, true)140+ return result141+ }142+ }143+144+ produceWithPatches(arg1, arg2, arg3) {145+ if (typeof arg1 === "function") {146+ const self = this147+ return (state, ...args) =>148+ this.produceWithPatches(state, draft => arg1(draft, ...args))149+ }150+ // non-curried form151+ if (arg3)152+ throw new Error("A patch listener cannot be passed to produceWithPatches")153+ let patches, inversePatches154+ const nextState = this.produce(arg1, arg2, (p, ip) => {155+ patches = p156+ inversePatches = ip157+ })158+ return [nextState, patches, inversePatches]159+ }160+161+ createDraft(base) {162+ if (!isDraftable(base)) {163+ throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore164+ }165+ const scope = ImmerScope.enter()166+ const proxy = this.createProxy(base)167+ proxy[DRAFT_STATE].isManual = true168+ scope.leave()169+ return proxy170+ }171+172+ finishDraft(draft, patchListener) {173+ const state = draft && draft[DRAFT_STATE]174+ if (!state || !state.isManual) {175+ throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore176+ }177+ if (state.finalized) {178+ throw new Error("The given draft is already finalized") // prettier-ignore179+ }180+ const {scope} = state181+ scope.usePatches(patchListener)182+ return this.processResult(undefined, scope)183+ }184+185+ /**186+ * Pass true to automatically freeze all copies created by Immer.187+ *188+ * By default, auto-freezing is disabled in production.189+ */190+ setAutoFreeze(value) {191+ this.autoFreeze = value192+ }193+194+ /**195+ * Pass true to use the ES2015 `Proxy` class when creating drafts, which is196+ * always faster than using ES5 proxies.197+ *198+ * By default, feature detection is used, so calling this is rarely necessary.199+ */200+ setUseProxies(value) {201+ this.useProxies = value202+ assign(this, value ? modernProxy : legacyProxy)203+ }204+ applyPatches(base, patches) {205+ // If a patch replaces the entire state, take that replacement as base206+ // before applying patches207+ let i208+ for (i = patches.length - 1; i >= 0; i--) {209+ const patch = patches[i]210+ if (patch.path.length === 0 && patch.op === "replace") {211+ base = patch.value212+ break213+ }214+ }215+216+ if (isDraft(base)) {217+ // N.B: never hits if some patch a replacement, patches are never drafts218+ return applyPatches(base, patches)219+ }220+ // Otherwise, produce a copy of the base state.221+ return this.produce(base, draft =>222+ applyPatches(draft, patches.slice(i + 1))223+ )224+ }225+ /** @internal */226+ processResult(result, scope) {227+ const baseDraft = scope.drafts[0]228+ const isReplaced = result !== undefined && result !== baseDraft229+ this.willFinalize(scope, result, isReplaced)230+ if (isReplaced) {231+ if (baseDraft[DRAFT_STATE].modified) {232+ scope.revoke()233+ throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore234+ }235+ if (isDraftable(result)) {236+ // Finalize the result in case it contains (or is) a subset of the draft.237+ result = this.finalize(result, null, scope)238+ this.maybeFreeze(result)239+ }240+ if (scope.patches) {241+ scope.patches.push({242+ op: "replace",243+ path: [],244+ value: result245+ })246+ scope.inversePatches.push({247+ op: "replace",248+ path: [],249+ value: baseDraft[DRAFT_STATE].base250+ })251+ }252+ } else {253+ // Finalize the base draft.254+ result = this.finalize(baseDraft, [], scope)255+ }256+ scope.revoke()257+ if (scope.patches) {258+ scope.patchListener(scope.patches, scope.inversePatches)259+ }260+ return result !== NOTHING ? result : undefined261+ }262+ /**263+ * @internal264+ * Finalize a draft, returning either the unmodified base state or a modified265+ * copy of the base state.266+ */267+ finalize(draft, path, scope) {268+ const state = draft[DRAFT_STATE]269+ if (!state) {270+ if (Object.isFrozen(draft)) return draft271+ return this.finalizeTree(draft, null, scope)272+ }273+ // Never finalize drafts owned by another scope.274+ if (state.scope !== scope) {275+ return draft276+ }277+ if (!state.modified) {278+ this.maybeFreeze(state.base, true)279+ return state.base280+ }281+ if (!state.finalized) {282+ state.finalized = true283+ this.finalizeTree(state.draft, path, scope)284+285+ // We cannot really delete anything inside of a Set. We can only replace the whole Set.286+ if (this.onDelete && !isSet(state.base)) {287+ // The `assigned` object is unreliable with ES5 drafts.288+ if (this.useProxies) {289+ const {assigned} = state290+ each(assigned, (prop, exists) => {291+ if (!exists) this.onDelete(state, prop)292+ })293+ } else {294+ // TODO: Figure it out for Maps and Sets if we need to support ES5295+ const {base, copy} = state296+ each(base, prop => {297+ if (!has(copy, prop)) this.onDelete(state, prop)298+ })299+ }300+ }301+ if (this.onCopy) {302+ this.onCopy(state)303+ }304+305+ // At this point, all descendants of `state.copy` have been finalized,306+ // so we can be sure that `scope.canAutoFreeze` is accurate.307+ if (this.autoFreeze && scope.canAutoFreeze) {308+ freeze(state.copy, false)309+ }310+311+ if (path && scope.patches) {312+ generatePatches(state, path, scope.patches, scope.inversePatches)313+ }314+ }315+ return state.copy316+ }317+ /**318+ * @internal319+ * Finalize all drafts in the given state tree.320+ */321+ finalizeTree(root, rootPath, scope) {322+ const state = root[DRAFT_STATE]323+ if (state) {324+ if (!this.useProxies) {325+ // Create the final copy, with added keys and without deleted keys.326+ state.copy = shallowCopy(state.draft, true)327+ }328+ root = state.copy329+ }330+331+ const needPatches = !!rootPath && !!scope.patches332+ const finalizeProperty = (prop, value, parent) => {333+ if (value === parent) {334+ throw Error("Immer forbids circular references")335+ }336+337+ // In the `finalizeTree` method, only the `root` object may be a draft.338+ const isDraftProp = !!state && parent === root339+ const isSetMember = isSet(parent)340+341+ if (isDraft(value)) {342+ const path =343+ isDraftProp &&344+ needPatches &&345+ !isSetMember && // Set objects are atomic since they have no keys.346+ !has(state.assigned, prop) // Skip deep patches for assigned keys.347+ ? rootPath.concat(prop)348+ : null349+350+ // Drafts owned by `scope` are finalized here.351+ value = this.finalize(value, path, scope)352+ replace(parent, prop, value)353+354+ // Drafts from another scope must prevent auto-freezing.355+ if (isDraft(value)) {356+ scope.canAutoFreeze = false357+ }358+359+ // Unchanged drafts are never passed to the `onAssign` hook.360+ if (isDraftProp && value === get(state.base, prop)) return361+ }362+ // Unchanged draft properties are ignored.363+ else if (isDraftProp && is(value, get(state.base, prop))) {364+ return365+ }366+ // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.367+ else if (isDraftable(value) && !Object.isFrozen(value)) {368+ each(value, finalizeProperty)369+ this.maybeFreeze(value)370+ }371+372+ if (isDraftProp && this.onAssign && !isSetMember) {373+ this.onAssign(state, prop, value)374+ }375+ }376+377+ each(root, finalizeProperty)378+ return root379+ }380+ maybeFreeze(value, deep = false) {381+ if (this.autoFreeze && !isDraft(value)) {382+ freeze(value, deep)383+ }384+ }385+}386+387+function replace(parent, prop, value) {388+ if (isMap(parent)) {389+ parent.set(prop, value)390+ } else if (isSet(parent)) {391+ // In this case, the `prop` is actually a draft.392+ parent.delete(prop)393+ parent.add(value)394+ } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {395+ // Preserve non-enumerable properties.396+ parent[prop] = value397+ } else {398+ Object.defineProperty(parent, prop, {399+ value,400+ writable: true,401+ configurable: true402+ })403+ }404+}deleted:src/index.js-79 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879import {Immer} from "./immer"
const immer = new Immer()
/** * The `produce` function takes a value and a "recipe function" (whose * return value often depends on the base state). The recipe function is * free to mutate its first argument however it wants. All mutations are * only ever applied to a __copy__ of the base state. * * Pass only a function to create a "curried producer" which relieves you * from passing the recipe function every time. * * Only plain objects and arrays are made mutable. All other objects are * considered uncopyable. * * Note: This function is __bound__ to its `Immer` instance. * * @param {any} base - the initial state * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified * @param {Function} patchListener - optional function that will be called with all the patches produced here * @returns {any} a new state, or the initial state if nothing was modified */export const produce = immer.produceexport default produce
/** * Like `produce`, but `produceWithPatches` always returns a tuple * [nextState, patches, inversePatches] (instead of just the next state) */export const produceWithPatches = immer.produceWithPatches.bind(immer)
/** * Pass true to automatically freeze all copies created by Immer. * * By default, auto-freezing is disabled in production. */export const setAutoFreeze = immer.setAutoFreeze.bind(immer)
/** * Pass true to use the ES2015 `Proxy` class when creating drafts, which is * always faster than using ES5 proxies. * * By default, feature detection is used, so calling this is rarely necessary. */export const setUseProxies = immer.setUseProxies.bind(immer)
/** * Apply an array of Immer patches to the first argument. * * This function is a producer, which means copy-on-write is in effect. */export const applyPatches = immer.applyPatches.bind(immer)
/** * Create an Immer draft from the given base state, which may be a draft itself. * The draft can be modified until you finalize it with the `finishDraft` function. */export const createDraft = immer.createDraft.bind(immer)
/** * Finalize an Immer draft from a `createDraft` call, returning the base state * (if no changes were made) or a modified copy. The draft must *not* be * mutated afterwards. * * Pass a function as the 2nd argument to generate Immer patches based on the * changes that were made. */export const finishDraft = immer.finishDraft.bind(immer)
export { original, isDraft, isDraftable, NOTHING as nothing, DRAFTABLE as immerable} from "./common"
export {Immer}added:src/index.ts+81 added
1+import {Immer} from "./immer"2+3+export {Draft, Immutable, Patch, PatchListener} from "./types"4+5+const immer = new Immer()6+7+/**8+ * The `produce` function takes a value and a "recipe function" (whose9+ * return value often depends on the base state). The recipe function is10+ * free to mutate its first argument however it wants. All mutations are11+ * only ever applied to a __copy__ of the base state.12+ *13+ * Pass only a function to create a "curried producer" which relieves you14+ * from passing the recipe function every time.15+ *16+ * Only plain objects and arrays are made mutable. All other objects are17+ * considered uncopyable.18+ *19+ * Note: This function is __bound__ to its `Immer` instance.20+ *21+ * @param {any} base - the initial state22+ * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified23+ * @param {Function} patchListener - optional function that will be called with all the patches produced here24+ * @returns {any} a new state, or the initial state if nothing was modified25+ */26+export const produce = immer.produce27+export default produce28+29+/**30+ * Like `produce`, but `produceWithPatches` always returns a tuple31+ * [nextState, patches, inversePatches] (instead of just the next state)32+ */33+export const produceWithPatches = immer.produceWithPatches.bind(immer)34+35+/**36+ * Pass true to automatically freeze all copies created by Immer.37+ *38+ * By default, auto-freezing is disabled in production.39+ */40+export const setAutoFreeze = immer.setAutoFreeze.bind(immer)41+42+/**43+ * Pass true to use the ES2015 `Proxy` class when creating drafts, which is44+ * always faster than using ES5 proxies.45+ *46+ * By default, feature detection is used, so calling this is rarely necessary.47+ */48+export const setUseProxies = immer.setUseProxies.bind(immer)49+50+/**51+ * Apply an array of Immer patches to the first argument.52+ *53+ * This function is a producer, which means copy-on-write is in effect.54+ */55+export const applyPatches = immer.applyPatches.bind(immer)56+57+/**58+ * Create an Immer draft from the given base state, which may be a draft itself.59+ * The draft can be modified until you finalize it with the `finishDraft` function.60+ */61+export const createDraft = immer.createDraft.bind(immer)62+63+/**64+ * Finalize an Immer draft from a `createDraft` call, returning the base state65+ * (if no changes were made) or a modified copy. The draft must *not* be66+ * mutated afterwards.67+ *68+ * Pass a function as the 2nd argument to generate Immer patches based on the69+ * changes that were made.70+ */71+export const finishDraft = immer.finishDraft.bind(immer)72+73+export {74+ original,75+ isDraft,76+ isDraftable,77+ NOTHING as nothing,78+ DRAFTABLE as immerable79+} from "./common"80+81+export {Immer}deleted:src/patches.js-186 removed
1-import {get, each, isMap, isSet, has, clone} from "./common"2-3-export function generatePatches(state, basePath, patches, inversePatches) {4- const generatePatchesFn = Array.isArray(state.base)5- ? generateArrayPatches6- : isSet(state.base)7- ? generateSetPatches8- : generatePatchesFromAssigned9-10- generatePatchesFn(state, basePath, patches, inversePatches)11-}12-13-function generateArrayPatches(state, basePath, patches, inversePatches) {14- let {base, copy, assigned} = state15-16- // Reduce complexity by ensuring `base` is never longer.17- if (copy.length < base.length) {18- ;[base, copy] = [copy, base]19- ;[patches, inversePatches] = [inversePatches, patches]20- }21-22- const delta = copy.length - base.length23-24- // Find the first replaced index.25- let start = 026- while (base[start] === copy[start] && start < base.length) {27- ++start28- }29-30- // Find the last replaced index. Search from the end to optimize splice patches.31- let end = base.length32- while (end > start && base[end - 1] === copy[end + delta - 1]) {33- --end34- }35-36- // Process replaced indices.37- for (let i = start; i < end; ++i) {38- if (assigned[i] && copy[i] !== base[i]) {39- const path = basePath.concat([i])40- patches.push({41- op: "replace",42- path,43- value: copy[i]44- })45- inversePatches.push({46- op: "replace",47- path,48- value: base[i]49- })50- }51- }52-53- const replaceCount = patches.length54-55- // Process added indices.56- for (let i = end + delta - 1; i >= end; --i) {57- const path = basePath.concat([i])58- patches[replaceCount + i - end] = {59- op: "add",60- path,61- value: copy[i]62- }63- inversePatches.push({64- op: "remove",65- path66- })67- }68-}69-70-// This is used for both Map objects and normal objects.71-function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {72- const {base, copy} = state73- each(state.assigned, (key, assignedValue) => {74- const origValue = get(base, key)75- const value = get(copy, key)76- const op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add"77- if (origValue === value && op === "replace") return78- const path = basePath.concat(key)79- patches.push(op === "remove" ? {op, path} : {op, path, value})80- inversePatches.push(81- op === "add"82- ? {op: "remove", path}83- : op === "remove"84- ? {op: "add", path, value: origValue}85- : {op: "replace", path, value: origValue}86- )87- })88-}89-90-function generateSetPatches(state, basePath, patches, inversePatches) {91- let {base, copy} = state92-93- let i = 094- for (const value of base) {95- if (!copy.has(value)) {96- const path = basePath.concat([i])97- patches.push({98- op: "remove",99- path,100- value101- })102- inversePatches.unshift({103- op: "add",104- path,105- value106- })107- }108- i++109- }110- i = 0111- for (const value of copy) {112- if (!base.has(value)) {113- const path = basePath.concat([i])114- patches.push({115- op: "add",116- path,117- value118- })119- inversePatches.unshift({120- op: "remove",121- path,122- value123- })124- }125- i++126- }127-}128-129-export const applyPatches = (draft, patches) => {130- for (const patch of patches) {131- const {path, op} = patch132-133- if (!path.length) throw new Error("Illegal state")134-135- let base = draft136- for (let i = 0; i < path.length - 1; i++) {137- base = get(base, path[i])138- if (!base || typeof base !== "object")139- throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore140- }141-142- const value = clone(patch.value) // used to clone patch to ensure original patch is not modified, see #411143-144- const key = path[path.length - 1]145- switch (op) {146- case "replace":147- if (isMap(base)) {148- base.set(key, value)149- } else if (isSet(base)) {150- throw new Error('Sets cannot have "replace" patches.')151- } else {152- // if value is an object, then it's assigned by reference153- // in the following add or remove ops, the value field inside the patch will also be modifyed154- // so we use value from the cloned patch155- base[key] = value156- }157- break158- case "add":159- if (isSet(base)) {160- base.delete(patch.value)161- }162-163- Array.isArray(base)164- ? base.splice(key, 0, value)165- : isMap(base)166- ? base.set(key, value)167- : isSet(base)168- ? base.add(value)169- : (base[key] = value)170- break171- case "remove":172- Array.isArray(base)173- ? base.splice(key, 1)174- : isMap(base)175- ? base.delete(key)176- : isSet(base)177- ? base.delete(patch.value)178- : delete base[key]179- break180- default:181- throw new Error("Unsupported patch operation: " + op)182- }183- }184-185- return draft186-}added:src/patches.ts+207 added
1+import {get, each, isMap, isSet, has, clone} from "./common"2+import {Patch, ImmerState} from "./types"3+4+export function generatePatches(5+ state: ImmerState,6+ basePath: (string | number)[],7+ patches: Patch[],8+ inversePatches: Patch[]9+) {10+ const generatePatchesFn = Array.isArray(state.base)11+ ? generateArrayPatches12+ : isSet(state.base)13+ ? generateSetPatches14+ : generatePatchesFromAssigned15+16+ generatePatchesFn(state, basePath, patches, inversePatches)17+}18+19+function generateArrayPatches(20+ state: ImmerState,21+ basePath: (string | number)[],22+ patches: Patch[],23+ inversePatches: Patch[]24+) {25+ let {base, copy, assigned} = state26+27+ // Reduce complexity by ensuring `base` is never longer.28+ if (copy.length < base.length) {29+ ;[base, copy] = [copy, base]30+ ;[patches, inversePatches] = [inversePatches, patches]31+ }32+33+ const delta = copy.length - base.length34+35+ // Find the first replaced index.36+ let start = 037+ while (base[start] === copy[start] && start < base.length) {38+ ++start39+ }40+41+ // Find the last replaced index. Search from the end to optimize splice patches.42+ let end = base.length43+ while (end > start && base[end - 1] === copy[end + delta - 1]) {44+ --end45+ }46+47+ // Process replaced indices.48+ for (let i = start; i < end; ++i) {49+ if (assigned[i] && copy[i] !== base[i]) {50+ const path = basePath.concat([i])51+ patches.push({52+ op: "replace",53+ path,54+ value: copy[i]55+ })56+ inversePatches.push({57+ op: "replace",58+ path,59+ value: base[i]60+ })61+ }62+ }63+64+ const replaceCount = patches.length65+66+ // Process added indices.67+ for (let i = end + delta - 1; i >= end; --i) {68+ const path = basePath.concat([i])69+ patches[replaceCount + i - end] = {70+ op: "add",71+ path,72+ value: copy[i]73+ }74+ inversePatches.push({75+ op: "remove",76+ path77+ })78+ }79+}80+81+// This is used for both Map objects and normal objects.82+function generatePatchesFromAssigned(83+ state: ImmerState,84+ basePath: (number | string)[],85+ patches: Patch[],86+ inversePatches: Patch[]87+) {88+ const {base, copy} = state89+ each(state.assigned, (key, assignedValue) => {90+ const origValue = get(base, key)91+ const value = get(copy, key)92+ const op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add"93+ if (origValue === value && op === "replace") return94+ const path = basePath.concat(key as any)95+ patches.push(op === "remove" ? {op, path} : {op, path, value})96+ inversePatches.push(97+ op === "add"98+ ? {op: "remove", path}99+ : op === "remove"100+ ? {op: "add", path, value: origValue}101+ : {op: "replace", path, value: origValue}102+ )103+ })104+}105+106+function generateSetPatches(107+ state: ImmerState,108+ basePath: (number | string)[],109+ patches: Patch[],110+ inversePatches: Patch[]111+) {112+ let {base, copy} = state113+114+ let i = 0115+ for (const value of base) {116+ if (!copy.has(value)) {117+ const path = basePath.concat([i])118+ patches.push({119+ op: "remove",120+ path,121+ value122+ })123+ inversePatches.unshift({124+ op: "add",125+ path,126+ value127+ })128+ }129+ i++130+ }131+ i = 0132+ for (const value of copy) {133+ if (!base.has(value)) {134+ const path = basePath.concat([i])135+ patches.push({136+ op: "add",137+ path,138+ value139+ })140+ inversePatches.unshift({141+ op: "remove",142+ path,143+ value144+ })145+ }146+ i++147+ }148+}149+150+export function applyPatches<T>(draft: T, patches: Patch[]): T {151+ for (const patch of patches) {152+ const {path, op} = patch153+154+ if (!path.length) throw new Error("Illegal state")155+156+ let base = draft157+ for (let i = 0; i < path.length - 1; i++) {158+ base = get(base, path[i])159+ if (!base || typeof base !== "object")160+ throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore161+ }162+163+ const value = clone(patch.value) // used to clone patch to ensure original patch is not modified, see #411164+165+ const key = path[path.length - 1]166+ switch (op) {167+ case "replace":168+ if (isMap(base)) {169+ base.set(key, value)170+ } else if (isSet(base)) {171+ throw new Error('Sets cannot have "replace" patches.')172+ } else {173+ // if value is an object, then it's assigned by reference174+ // in the following add or remove ops, the value field inside the patch will also be modifyed175+ // so we use value from the cloned patch176+ base[key] = value177+ }178+ break179+ case "add":180+ if (isSet(base)) {181+ base.delete(patch.value)182+ }183+184+ Array.isArray(base)185+ ? base.splice(key as any, 0, value)186+ : isMap(base)187+ ? base.set(key, value)188+ : isSet(base)189+ ? base.add(value)190+ : (base[key] = value)191+ break192+ case "remove":193+ Array.isArray(base)194+ ? base.splice(key as any, 1)195+ : isMap(base)196+ ? base.delete(key)197+ : isSet(base)198+ ? base.delete(patch.value)199+ : delete base[key]200+ break201+ default:202+ throw new Error("Unsupported patch operation: " + op)203+ }204+ }205+206+ return draft207+}deleted:src/scope.js-42 removed
123456789101112131415161718192021222324252627282930313233343536373839404142import {DRAFT_STATE} from "./common"
/** Each scope represents a `produce` call. */export class ImmerScope { constructor(parent) { this.drafts = [] this.parent = parent
// Whenever the modified draft contains a draft from another scope, we // need to prevent auto-freezing so the unowned draft can be finalized. this.canAutoFreeze = true
// To avoid prototype lookups: this.patches = null } usePatches(patchListener) { if (patchListener) { this.patches = [] this.inversePatches = [] this.patchListener = patchListener } } revoke() { this.leave() this.drafts.forEach(revoke) this.drafts = null // Make draft-related methods throw. } leave() { if (this === ImmerScope.current) { ImmerScope.current = this.parent } }}
ImmerScope.current = nullImmerScope.enter = function() { return (this.current = new ImmerScope(this.current))}
function revoke(draft) { draft[DRAFT_STATE].revoke()}added:src/scope.ts+54 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354import {DRAFT_STATE} from "./common"import {ImmerState, Patch, PatchListener} from "./types"
/** Each scope represents a `produce` call. */export class ImmerScope { static current?: ImmerScope
patches?: Patch[] inversePatches?: Patch[] canAutoFreeze: boolean drafts?: any[] parent?: ImmerScope patchListener?: PatchListener
constructor(parent?: ImmerScope) { this.drafts = [] this.parent = parent
// Whenever the modified draft contains a draft from another scope, we // need to prevent auto-freezing so the unowned draft can be finalized. this.canAutoFreeze = true
// To avoid prototype lookups: this.patches = undefined }
usePatches(patchListener: PatchListener) { if (patchListener) { this.patches = [] this.inversePatches = [] this.patchListener = patchListener } }
revoke() { this.leave() this.drafts!.forEach(revoke) this.drafts = undefined // Make draft-related methods throw. }
leave() { if (this === ImmerScope.current) { ImmerScope.current = this.parent } }
static enter() { return (ImmerScope.current = new ImmerScope(ImmerScope.current)) }}
function revoke(draft) { draft[DRAFT_STATE].revoke()}modified:src/types.ts+185 added-2 removed
12345656789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191export type Objectish = any[] | Map<any, any> | Set<any> | {}
export type ObjectishNoSet = any[] | Map<any, any> | {}
export interface State<T = any> { copy: Texport interface ImmerState<T = any> { parent?: ImmerState base: T copy: T assigned: {[prop: string]: boolean; [index: number]: boolean}}
type Tail<T extends any[]> = ((...t: T) => any) extends (( _: any, ...tail: infer TT) => any) ? TT : []
/** Object types that should never be mapped */type AtomicObject = | Function | WeakMap<any, any> | WeakSet<any> | Promise<any> | Date | RegExp | Boolean | Number | String
export type Draft<T> = T extends AtomicObject ? T : T extends Map<infer K, infer V> ? DraftMap<K, V> : T extends Set<infer V> ? DraftSet<V> : T extends object ? {-readonly [K in keyof T]: Draft<T[K]>} : T
// Inline these in ts 3.7interface DraftMap<K, V> extends Map<Draft<K>, Draft<V>> {}
// Inline these in ts 3.7interface DraftSet<V> extends Set<Draft<V>> {}
/** Convert a mutable type into a readonly type */export type Immutable<T> = T extends AtomicObject ? T : T extends Map<infer K, infer V> // Ideally, but wait for TS 3.7: ? Omit<ImmutableMap<K, V>, "set" | "delete" | "clear"> ? ImmutableMap<K, V> : T extends Set<infer V> // Ideally, but wait for TS 3.7: ? Omit<ImmutableSet<V>, "add" | "delete" | "clear"> ? ImmutableSet<V> : T extends object ? {readonly [K in keyof T]: Immutable<T[K]>} : T
interface ImmutableMap<K, V> extends Map<Immutable<K>, Immutable<V>> {}
interface ImmutableSet<V> extends Set<Immutable<V>> {}
export interface Patch { op: "replace" | "remove" | "add" path: (string | number)[] value?: any}
export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void
/** Converts `nothing` into `undefined` */type FromNothing<T> = T extends Nothing ? undefined : T
/** The inferred return type of `produce` */export type Produced<Base, Return> = Return extends void ? Base : Return extends Promise<infer Result> ? Promise<Result extends void ? Base : FromNothing<Result>> : FromNothing<Return>
/** * The `produce` function takes a value and a "recipe function" (whose * return value often depends on the base state). The recipe function is * free to mutate its first argument however it wants. All mutations are * only ever applied to a __copy__ of the base state. * * Pass only a function to create a "curried producer" which relieves you * from passing the recipe function every time. * * Only plain objects and arrays are made mutable. All other objects are * considered uncopyable. * * Note: This function is __bound__ to its `Immer` instance. * * @param {any} base - the initial state * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified * @param {Function} patchListener - optional function that will be called with all the patches produced here * @returns {any} a new state, or the initial state if nothing was modified */export interface IProduce { /** Curried producer */ < Recipe extends (...args: any[]) => any, Params extends any[] = Parameters<Recipe>, T = Params[0] >( recipe: Recipe ): <Base extends Immutable<T>>( base: Base, ...rest: Tail<Params> ) => Produced<Base, ReturnType<Recipe>> // ^ by making the returned type generic, the actual type of the passed in object is preferred // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!
/** Curried producer with initial state */ < Recipe extends (...args: any[]) => any, Params extends any[] = Parameters<Recipe>, T = Params[0] >( recipe: Recipe, initialState: Immutable<T> ): <Base extends Immutable<T>>( base?: Base, ...rest: Tail<Params> ) => Produced<Base, ReturnType<Recipe>>
/** Normal producer */ <Base, D = Draft<Base>, Return = void>( base: Base, recipe: (draft: D) => Return, listener?: PatchListener ): Produced<Base, Return>}
/** * Like `produce`, but instead of just returning the new state, * a tuple is returned with [nextState, patches, inversePatches] * * Like produce, this function supports currying */export interface IProduceWithPatches { /** Curried producer */ < Recipe extends (...args: any[]) => any, Params extends any[] = Parameters<Recipe>, T = Params[0] >( recipe: Recipe ): <Base extends Immutable<T>>( base: Base, ...rest: Tail<Params> ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]] // ^ by making the returned type generic, the actual type of the passed in object is preferred // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!
/** Curried producer with initial state */ < Recipe extends (...args: any[]) => any, Params extends any[] = Parameters<Recipe>, T = Params[0] >( recipe: Recipe, initialState: Immutable<T> ): <Base extends Immutable<T>>( base?: Base, ...rest: Tail<Params> ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]
/** Normal producer */ <Base, D = Draft<Base>, Return = void>( base: Base, recipe: (draft: D) => Return ): [Produced<Base, Return>, Patch[], Patch[]]}
/** Use a class type for `nothing` so its type is unique */declare class Nothing { // This lets us do `Exclude<T, Nothing>` private _: any}
// Backward compatibility with --target es5// TODO: still needed?// declare global {// interface Set<T> {}// interface Map<K, V> {}// interface WeakSet<T> {}// interface WeakMap<K extends object, V> {}// }