Skip to content
Myr

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

13 files+1445 added−1443 removed

modified:src/common.ts+22 added-8 removed
1import {Objectish, ObjectishNoSet, State} from "./types"1import {Objectish, ObjectishNoSet, ImmerState} from "./types"23/**4 * The sentinel value returned by producers to replace the draft with undefined.5 */6export const NOTHING =7 typeof Symbol !== "undefined"8 ? Symbol("immer-nothing")9 : {["immer-nothing"]: true}1011/**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 */8export const DRAFTABLE =19export const DRAFTABLE: unique symbol =20 typeof Symbol !== "undefined" && Symbol.for21 ? Symbol.for("immer-draftable")11 : "__$immer_draftable"22 : ("__$immer_draftable" as any)2313export const DRAFT_STATE =24export const DRAFT_STATE: unique symbol =25 typeof Symbol !== "undefined" && Symbol.for26 ? Symbol.for("immer-state")16 : "__$immer_state"27 : ("__$immer_state" as any)2829/** Returns true if the given value is an Immer draft */18export function isDraft(value): boolean {30export function isDraft(value: any): boolean {31 return !!value && !!value[DRAFT_STATE]32}3334/** Returns true if the given value can be drafted by Immer */22export function isDraftable(value): boolean {35export function isDraftable(value: any): boolean {36 if (!value) return false37 return (38 isPlainObject(value) ||39 !!value[DRAFTABLE] ||
9 unmodified lines
49 const proto = Object.getPrototypeOf(value)50 return !proto || proto === Object.prototype51}5253/** Get the underlying object that is represented by the given draft */54export function original<T>(value: T): T | undefined {55 if (value && value[DRAFT_STATE]) {56 return value[DRAFT_STATE].base57 }
183 unmodified lines
241242 return iterateSetValues243}244231function latest<T = any>(state: State<T>): T {245function latest<T = any>(state: ImmerState<T>): T {246 return state.copy || state.base247}248249export function clone<T extends Objectish>(obj: T): T
24 unmodified lines
deleted:src/es5.js-468 removed
1"use strict"2import {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"18import {ImmerScope} from "./scope"1920export 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}3637export function createProxy(base, parent) {38 const isArray = Array.isArray(base)39 const draft = clonePotentialDraft(base)4041 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 }5051 // 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 }6768 createHiddenProperty(draft, DRAFT_STATE, state)69 scope.drafts.push(draft)70 return draft71}7273function revoke() {74 this.revoked = true75}7677function latest(state) {78 return state.copy || state.base79}8081// Access a property without creating an Immer draft.82function 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}9293function 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}104105function 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}115116function markChanged(state) {117 if (!state.modified) {118 state.modified = true119 if (state.parent) markChanged(state.parent)120 }121}122123function prepareCopy(state) {124 if (!state.copy) state.copy = clonePotentialDraft(state.base)125}126127function 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}137138// property descriptors are recycled to make sure we don't create a get and set closure per property,139// but share them all instead140const descriptors = {}141142function 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}160161function proxyMap(target) {162 Object.defineProperties(target, mapTraps)163164 if (hasSymbol) {165 Object.defineProperty(166 target,167 Symbol.iterator,168 proxyMethod(iterateMapValues)169 )170 }171}172173const 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)210211 if (state.finalizing || state.finalized || !isDraftable(value)) {212 return value213 }214215 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})227228function proxySet(target) {229 Object.defineProperties(target, setTraps)230231 if (hasSymbol) {232 Object.defineProperty(233 target,234 Symbol.iterator,235 proxyMethod(iterateSetValues)236 )237 }238}239240const iterateSetValues = makeIterateSetValues(createProxy)241242const 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})285286function 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}293294function proxyAttr(fn) {295 return {296 get() {297 const state = this[DRAFT_STATE]298 assertUnrevoked(state)299 return fn(state)300 }301 }302}303304function 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}315316function 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}323324// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.325function 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}345346function 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}385386function hasObjectChanges(state) {387 const {base, draft} = state388389 // 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 }409410 // 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}414415function 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}431432function hasMapChanges(state) {433 const {base, draft} = state434435 if (base.size !== draft.size) return true436437 // 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}446447function hasSetChanges(state) {448 const {base, draft} = state449450 if (base.size !== draft.size) return true451452 // 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}461462function 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"2import {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"18import {ImmerScope} from "./scope"19import {ImmerState} from "./types"2021interface ES5Draft {22 [DRAFT_STATE]: ES5State23}2425interface 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}3940export 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}6061export function createProxy(base: any, parent: ES5State) {62 const isArray = Array.isArray(base)63 const draft = clonePotentialDraft(base)6465 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 }7475 // 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 }9192 createHiddenProperty(draft, DRAFT_STATE, state)93 scope.drafts!.push(draft)94 return draft95}9697function revoke(this: ES5State) {98 this.revoked = true99}100101function latest(state) {102 return state.copy || state.base103}104105// Access a property without creating an Immer draft.106function 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}116117function 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}128129function 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}139140function markChanged(state) {141 if (!state.modified) {142 state.modified = true143 if (state.parent) markChanged(state.parent)144 }145}146147function prepareCopy(state) {148 if (!state.copy) state.copy = clonePotentialDraft(state.base)149}150151function 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}161162// property descriptors are recycled to make sure we don't create a get and set closure per property,163// but share them all instead164const descriptors = {}165166function 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}184185function proxyMap(target) {186 Object.defineProperties(target, mapTraps)187188 if (hasSymbol) {189 Object.defineProperty(190 target,191 Symbol.iterator,192 proxyMethod(iterateMapValues)193 )194 }195}196197const 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)234235 if (state.finalizing || state.finalized || !isDraftable(value)) {236 return value237 }238239 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})251252function proxySet(target) {253 Object.defineProperties(target, setTraps)254255 if (hasSymbol) {256 Object.defineProperty(257 target,258 Symbol.iterator,259 proxyMethod(iterateSetValues)260 )261 }262}263264const iterateSetValues = makeIterateSetValues(createProxy)265266const 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})309310function 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}317318function proxyAttr(fn) {319 return {320 get() {321 const state = this[DRAFT_STATE]322 assertUnrevoked(state)323 return fn(state)324 }325 }326}327328function 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}339340function 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}347348// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.349function 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}369370function 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}409410function hasObjectChanges(state) {411 const {base, draft} = state412413 // 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 }433434 // 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}438439function 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}455456function hasMapChanges(state) {457 const {base, draft} = state458459 if (base.size !== draft.size) return true460461 // 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}470471function hasSetChanges(state) {472 const {base, draft} = state473474 if (base.size !== draft.size) return true475476 // 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}485486function 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
1type Tail<T extends any[]> = ((...t: T) => any) extends ((2 _: any,3 ...tail: infer TT4) => any)5 ? TT6 : []78/** Object types that should never be mapped */9type AtomicObject =10 | Function11 | WeakMap<any, any>12 | WeakSet<any>13 | Promise<any>14 | Date15 | RegExp16 | Boolean17 | Number18 | String1920export 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 : T2930// Inline these in ts 3.731interface DraftMap<K, V> extends Map<Draft<K>, Draft<V>> {}3233// Inline these in ts 3.734interface DraftSet<V> extends Set<Draft<V>> {}3536/** Convert a mutable type into a readonly type */37export 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 : T4849interface ImmutableMap<K, V> extends Map<Immutable<K>, Immutable<V>> {}5051interface ImmutableSet<V> extends Set<Immutable<V>> {}5253export interface Patch {54 op: "replace" | "remove" | "add"55 path: (string | number)[]56 value?: any57}5859export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void6061/** Converts `nothing` into `undefined` */62type FromNothing<T> = T extends Nothing ? undefined : T6364/** The inferred return type of `produce` */65export type Produced<Base, Return> = Return extends void66 ? Base67 : Return extends Promise<infer Result>68 ? Promise<Result extends void ? Base : FromNothing<Result>>69 : FromNothing<Return>7071/**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 */90export 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!105106 /** 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>>118119 /** Normal producer */120 <Base, D = Draft<Base>, Return = void>(121 base: Base,122 recipe: (draft: D) => Return,123 listener?: PatchListener124 ): Produced<Base, Return>125}126127export const produce: IProduce128export default produce129130/**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 */136export 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!151152 /** 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[]]164165 /** Normal producer */166 <Base, D = Draft<Base>, Return = void>(167 base: Base,168 recipe: (draft: D) => Return169 ): [Produced<Base, Return>, Patch[], Patch[]]170}171export const produceWithPatches: IProduceWithPatches172173/** Use a class type for `nothing` so its type is unique */174declare class Nothing {175 // This lets us do `Exclude<T, Nothing>`176 private _: any177}178179/**180 * The sentinel value returned by producers to replace the draft with undefined.181 */182export const nothing: Nothing183184/**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 */192export const immerable: unique symbol193194/**195 * Pass true to automatically freeze all copies created by Immer.196 *197 * By default, auto-freezing is disabled in production.198 */199export function setAutoFreeze(autoFreeze: boolean): void200201/**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 */207export function setUseProxies(useProxies: boolean): void208209/**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 */214export function applyPatches<S>(base: S, patches: Patch[]): S215216/**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 */220export function createDraft<T>(base: T): Draft<T>221222/**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 */230export function finishDraft<T>(draft: T, listener?: PatchListener): Immutable<T>231232/** Get the underlying object that is represented by the given draft */233export function original<T>(value: T): T | void234235/** Returns true if the given value is an Immer draft */236export function isDraft(value: any): boolean237238/** Returns true if the given value can be drafted by Immer */239export function isDraftable(value: any): boolean240241export 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}295296export interface ImmerState<T = any> {297 parent?: ImmerState298 base: T299 copy: T300 assigned: {[prop: string]: boolean; [index: number]: boolean}301}302303// Backward compatibility with --target es5304declare 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
1import * as legacyProxy from "./es5"2import * as modernProxy from "./proxy"3import {applyPatches, generatePatches} from "./patches"4import {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"20import {ImmerScope} from "./scope"2122function verifyMinified() {}2324const 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}3738export 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 = base5051 const self = this52 return function curriedProduce(base = defaultBase, ...args) {53 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore54 }55 }5657 // 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 }6667 let result6869 // 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 }160161 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)229230 // 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 }249250 // 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 }255256 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 }275276 const needPatches = !!rootPath && !!scope.patches277 const finalizeProperty = (prop, value, parent) => {278 if (value === parent) {279 throw Error("Immer forbids circular references")280 }281282 // In the `finalizeTree` method, only the `root` object may be a draft.283 const isDraftProp = !!state && parent === root284 const isSetMember = isSet(parent)285286 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 : null294295 // Drafts owned by `scope` are finalized here.296 value = this.finalize(value, path, scope)297 replace(parent, prop, value)298299 // Drafts from another scope must prevent auto-freezing.300 if (isDraft(value)) {301 scope.canAutoFreeze = false302 }303304 // 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 }316317 if (isDraftProp && this.onAssign && !isSetMember) {318 this.onAssign(state, prop, value)319 }320 }321322 each(root, finalizeProperty)323 return root324 }325 maybeFreeze(value, deep = false) {326 if (this.autoFreeze && !isDraft(value)) {327 freeze(value, deep)328 }329 }330}331332function 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
1import * as legacyProxy from "./es5"2import * as modernProxy from "./proxy"3import {applyPatches, generatePatches} from "./patches"4import {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"20import {ImmerScope} from "./scope"21import {ImmerState, IProduce, IProduceWithPatches} from "./types"2223function verifyMinified() {}2425const 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}3839interface ProducersFns {40 produce: IProduce41 produceWithPatches: IProduceWithPatches42}4344export class Immer implements ProducersFns {45 useProxies: boolean = false46 autoFreeze: boolean = false4748 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 }6465 /**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 = base8990 const self = this91 return function curriedProduce(base = defaultBase, ...args) {92 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore93 }94 }9596 // 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 }105106 let result107108 // 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 }143144 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 }160161 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 }171172 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 }184185 /**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 }193194 /**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 }215216 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)284285 // 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 }304305 // 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 }310311 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 }330331 const needPatches = !!rootPath && !!scope.patches332 const finalizeProperty = (prop, value, parent) => {333 if (value === parent) {334 throw Error("Immer forbids circular references")335 }336337 // In the `finalizeTree` method, only the `root` object may be a draft.338 const isDraftProp = !!state && parent === root339 const isSetMember = isSet(parent)340341 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 : null349350 // Drafts owned by `scope` are finalized here.351 value = this.finalize(value, path, scope)352 replace(parent, prop, value)353354 // Drafts from another scope must prevent auto-freezing.355 if (isDraft(value)) {356 scope.canAutoFreeze = false357 }358359 // 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 }371372 if (isDraftProp && this.onAssign && !isSetMember) {373 this.onAssign(state, prop, value)374 }375 }376377 each(root, finalizeProperty)378 return root379 }380 maybeFreeze(value, deep = false) {381 if (this.autoFreeze && !isDraft(value)) {382 freeze(value, deep)383 }384 }385}386387function 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
added:src/index.ts+81 added
1import {Immer} from "./immer"23export {Draft, Immutable, Patch, PatchListener} from "./types"45const immer = new Immer()67/**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 */26export const produce = immer.produce27export default produce2829/**30 * Like `produce`, but `produceWithPatches` always returns a tuple31 * [nextState, patches, inversePatches] (instead of just the next state)32 */33export const produceWithPatches = immer.produceWithPatches.bind(immer)3435/**36 * Pass true to automatically freeze all copies created by Immer.37 *38 * By default, auto-freezing is disabled in production.39 */40export const setAutoFreeze = immer.setAutoFreeze.bind(immer)4142/**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 */48export const setUseProxies = immer.setUseProxies.bind(immer)4950/**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 */55export const applyPatches = immer.applyPatches.bind(immer)5657/**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 */61export const createDraft = immer.createDraft.bind(immer)6263/**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 */71export const finishDraft = immer.finishDraft.bind(immer)7273export {74 original,75 isDraft,76 isDraftable,77 NOTHING as nothing,78 DRAFTABLE as immerable79} from "./common"8081export {Immer}
deleted:src/patches.js-186 removed
1import {get, each, isMap, isSet, has, clone} from "./common"23export function generatePatches(state, basePath, patches, inversePatches) {4 const generatePatchesFn = Array.isArray(state.base)5 ? generateArrayPatches6 : isSet(state.base)7 ? generateSetPatches8 : generatePatchesFromAssigned910 generatePatchesFn(state, basePath, patches, inversePatches)11}1213function generateArrayPatches(state, basePath, patches, inversePatches) {14 let {base, copy, assigned} = state1516 // 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 }2122 const delta = copy.length - base.length2324 // Find the first replaced index.25 let start = 026 while (base[start] === copy[start] && start < base.length) {27 ++start28 }2930 // 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 }3536 // 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 }5253 const replaceCount = patches.length5455 // 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}6970// This is used for both Map objects and normal objects.71function 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}8990function generateSetPatches(state, basePath, patches, inversePatches) {91 let {base, copy} = state9293 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}128129export const applyPatches = (draft, patches) => {130 for (const patch of patches) {131 const {path, op} = patch132133 if (!path.length) throw new Error("Illegal state")134135 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 }141142 const value = clone(patch.value) // used to clone patch to ensure original patch is not modified, see #411143144 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 }162163 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 }184185 return draft186}
added:src/patches.ts+207 added
1import {get, each, isMap, isSet, has, clone} from "./common"2import {Patch, ImmerState} from "./types"34export 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 : generatePatchesFromAssigned1516 generatePatchesFn(state, basePath, patches, inversePatches)17}1819function generateArrayPatches(20 state: ImmerState,21 basePath: (string | number)[],22 patches: Patch[],23 inversePatches: Patch[]24) {25 let {base, copy, assigned} = state2627 // 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 }3233 const delta = copy.length - base.length3435 // Find the first replaced index.36 let start = 037 while (base[start] === copy[start] && start < base.length) {38 ++start39 }4041 // 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 }4647 // 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 }6364 const replaceCount = patches.length6566 // 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}8081// This is used for both Map objects and normal objects.82function 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}105106function generateSetPatches(107 state: ImmerState,108 basePath: (number | string)[],109 patches: Patch[],110 inversePatches: Patch[]111) {112 let {base, copy} = state113114 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}149150export function applyPatches<T>(draft: T, patches: Patch[]): T {151 for (const patch of patches) {152 const {path, op} = patch153154 if (!path.length) throw new Error("Illegal state")155156 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 }162163 const value = clone(patch.value) // used to clone patch to ensure original patch is not modified, see #411164165 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 }183184 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 }205206 return draft207}
deleted:src/scope.js-42 removed
added:src/scope.ts+54 added
modified:src/types.ts+185 added-2 removed