Skip to content
Myr

Moving files into folders

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 67565dd · Browse files · 29 files+1462 added−1458 removed
This commit

State

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

Diff stats

29 files+1462 added−1458 removed

  • other:+1462 added−1458 removed

29 files+1462 added−1458 removed

added:src/core/finalize.ts+162 added
1import {2 ImmerScope,3 DRAFT_STATE,4 isDraftable,5 NOTHING,6 PatchPath,7 each,8 has,9 freeze,10 shallowCopy,11 ImmerState,12 isDraft,13 SetState,14 set,15 is,16 get,17 ProxyTypeES5Object,18 ProxyTypeES5Array,19 ProxyTypeSet,20 getPlugin,21 die22} from "../internal"2324export function processResult(result: any, scope: ImmerScope) {25 scope.unfinalizedDrafts_ = scope.drafts_.length26 const baseDraft = scope.drafts_![0]27 const isReplaced = result !== undefined && result !== baseDraft28 if (!scope.immer_.useProxies_)29 getPlugin("es5").willFinalizeES5_(scope, result, isReplaced)30 if (isReplaced) {31 if (baseDraft[DRAFT_STATE].modified_) {32 scope.revoke_()33 die(4)34 }35 if (isDraftable(result)) {36 // Finalize the result in case it contains (or is) a subset of the draft.37 result = finalize(scope, result)38 if (!scope.parent_) maybeFreeze(scope, result)39 }40 // TODO: move to plugin?41 if (scope.patches_) {42 scope.patches_.push({43 op: "replace",44 path: [],45 value: result46 })47 scope.inversePatches_!.push({48 op: "replace",49 path: [],50 value: (baseDraft[DRAFT_STATE] as ImmerState).base_51 })52 }53 } else {54 // Finalize the base draft.55 result = finalize(scope, baseDraft, [])56 }57 scope.revoke_()58 if (scope.patches_) {59 scope.patchListener_!(scope.patches_, scope.inversePatches_!)60 }61 return result !== NOTHING ? result : undefined62}6364function finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {65 // Don't recurse in tho recursive data structures66 if (Object.isFrozen(value)) return value6768 const state: ImmerState = value[DRAFT_STATE]69 // A plain object, might need freezing, might contain drafts70 if (!state) {71 each(value, (key, childValue) =>72 finalizeProperty(rootScope, state, value, key, childValue, path)73 )74 return value75 }76 // Never finalize drafts owned by another scope.77 if (state.scope_ !== rootScope) return value78 // Unmodified draft, return the (frozen) original79 if (!state.modified_) {80 maybeFreeze(rootScope, state.base_, true)81 return state.base_82 }83 // Not finalized yet, let's do that now84 if (!state.finalized_) {85 state.finalized_ = true86 state.scope_.unfinalizedDrafts_--87 const result =88 // For ES5, create a good copy from the draft first, with added keys and without deleted keys.89 state.type_ === ProxyTypeES5Object || state.type_ === ProxyTypeES5Array90 ? (state.copy_ = shallowCopy(state.draft_, true))91 : state.copy_92 // finalize all children of the copy93 each(result as any, (key, childValue) =>94 finalizeProperty(rootScope, state, result, key, childValue, path)95 )96 // everything inside is frozen, we can freeze here97 maybeFreeze(rootScope, result, false)98 // first time finalizing, let's create those patches99 if (path && rootScope.patches_) {100 getPlugin("patches").generatePatches_(101 state,102 path,103 rootScope.patches_,104 rootScope.inversePatches_!105 )106 }107 }108 return state.copy_109}110111function finalizeProperty(112 rootScope: ImmerScope,113 parentState: undefined | ImmerState,114 targetObject: any,115 prop: string | number,116 childValue: any,117 rootPath?: PatchPath118) {119 if (__DEV__ && childValue === targetObject) die(5)120 if (isDraft(childValue)) {121 const path =122 rootPath &&123 parentState &&124 parentState!.type_ !== ProxyTypeSet && // Set objects are atomic since they have no keys.125 !has((parentState as Exclude<ImmerState, SetState>).assigned_!, prop) // Skip deep patches for assigned keys.126 ? rootPath!.concat(prop)127 : undefined128 // Drafts owned by `scope` are finalized here.129 const res = finalize(rootScope, childValue, path)130 set(targetObject, prop, res)131 // Drafts from another scope must prevented to be frozen132 // if we got a draft back from finalize, we're in a nested produce and shouldn't freeze133 if (isDraft(res)) {134 rootScope.canAutoFreeze_ = false135 } else return136 }137 // Unchanged draft properties are ignored.138 if (parentState && is(childValue, get(parentState!.base_, prop))) {139 return140 }141 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.142 if (isDraftable(childValue)) {143 if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {144 // optimization: if an object is not a draft, and we don't have to145 // deepfreeze everything, and we are sure that no drafts are left in the remaining object146 // cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.147 // This benefits especially adding large data tree's without further processing.148 // See add-data.js perf test149 return150 }151 finalize(rootScope, childValue)152 // immer deep freezes plain objects, so if there is no parent state, we freeze as well153 if (!parentState || !parentState.scope_.parent_)154 maybeFreeze(rootScope, childValue)155 }156}157158function maybeFreeze(scope: ImmerScope, value: any, deep = false) {159 if (scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {160 freeze(value, deep)161 }162}
added:src/core/immerClass.ts+233 added
1import {2 IProduceWithPatches,3 IProduce,4 ImmerState,5 Drafted,6 isDraftable,7 ImmerScope,8 processResult,9 NOTHING,10 Patch,11 Objectish,12 DRAFT_STATE,13 Draft,14 PatchListener,15 isDraft,16 isMap,17 isSet,18 markChangedProxy,19 createProxyProxy,20 freeze,21 getPlugin,22 die23} from "../internal"2425/* istanbul ignore next */26function verifyMinified() {}2728interface ProducersFns {29 produce: IProduce30 produceWithPatches: IProduceWithPatches31}3233export class Immer implements ProducersFns {34 useProxies_: boolean =35 typeof Proxy !== "undefined" &&36 typeof Proxy.revocable !== "undefined" &&37 typeof Reflect !== "undefined"38 autoFreeze_: boolean = __DEV__39 ? false /* istanbul ignore next */40 : verifyMinified.name === "verifyMinified"4142 constructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {43 if (typeof config?.useProxies === "boolean")44 this.setUseProxies(config!.useProxies)45 if (typeof config?.autoFreeze === "boolean")46 this.setAutoFreeze(config!.autoFreeze)47 this.produce = this.produce.bind(this)48 this.produceWithPatches = this.produceWithPatches.bind(this)49 }5051 /**52 * The `produce` function takes a value and a "recipe function" (whose53 * return value often depends on the base state). The recipe function is54 * free to mutate its first argument however it wants. All mutations are55 * only ever applied to a __copy__ of the base state.56 *57 * Pass only a function to create a "curried producer" which relieves you58 * from passing the recipe function every time.59 *60 * Only plain objects and arrays are made mutable. All other objects are61 * considered uncopyable.62 *63 * Note: This function is __bound__ to its `Immer` instance.64 *65 * @param {any} base - the initial state66 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified67 * @param {Function} patchListener - optional function that will be called with all the patches produced here68 * @returns {any} a new state, or the initial state if nothing was modified69 */70 produce(base: any, recipe?: any, patchListener?: any) {71 // curried invocation72 if (typeof base === "function" && typeof recipe !== "function") {73 const defaultBase = recipe74 recipe = base7576 const self = this77 return function curriedProduce(78 this: any,79 base = defaultBase,80 ...args: any[]81 ) {82 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore83 }84 }8586 if (typeof recipe !== "function") die(6)87 if (patchListener !== undefined && typeof patchListener !== "function")88 die(7)8990 let result9192 // Only plain objects, arrays, and "immerable classes" are drafted.93 if (isDraftable(base)) {94 const scope = ImmerScope.enter_(this)95 const proxy = createProxy(this, base, undefined)96 let hasError = true97 try {98 result = recipe(proxy)99 hasError = false100 } finally {101 // finally instead of catch + rethrow better preserves original stack102 if (hasError) scope.revoke_()103 else scope.leave_()104 }105 if (typeof Promise !== "undefined" && result instanceof Promise) {106 return result.then(107 result => {108 scope.usePatches_(patchListener)109 return processResult(result, scope)110 },111 error => {112 scope.revoke_()113 throw error114 }115 )116 }117 scope.usePatches_(patchListener)118 return processResult(result, scope)119 } else {120 result = recipe(base)121 if (result === NOTHING) return undefined122 if (result === undefined) result = base123 if (this.autoFreeze_) freeze(result, true)124 return result125 }126 }127128 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {129 if (typeof arg1 === "function") {130 return (state: any, ...args: any[]) =>131 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))132 }133134 let patches: Patch[], inversePatches: Patch[]135 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {136 patches = p137 inversePatches = ip138 })139 return [nextState, patches!, inversePatches!]140 }141142 createDraft<T extends Objectish>(base: T): Draft<T> {143 if (!isDraftable(base)) die(8)144 const scope = ImmerScope.enter_(this)145 const proxy = createProxy(this, base, undefined)146 proxy[DRAFT_STATE].isManual_ = true147 scope.leave_()148 return proxy as any149 }150151 finishDraft<D extends Draft<any>>(152 draft: D,153 patchListener?: PatchListener154 ): D extends Draft<infer T> ? T : never {155 const state: ImmerState = draft && draft[DRAFT_STATE]156 if (__DEV__) {157 if (!state || !state.isManual_) die(9)158 if (state.finalized_) die(10)159 }160 const {scope_: scope} = state161 scope.usePatches_(patchListener)162 return processResult(undefined, scope)163 }164165 /**166 * Pass true to automatically freeze all copies created by Immer.167 *168 * By default, auto-freezing is disabled in production.169 */170 setAutoFreeze(value: boolean) {171 this.autoFreeze_ = value172 }173174 /**175 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is176 * always faster than using ES5 proxies.177 *178 * By default, feature detection is used, so calling this is rarely necessary.179 */180 setUseProxies(value: boolean) {181 this.useProxies_ = value182 }183184 applyPatches(base: Objectish, patches: Patch[]) {185 // If a patch replaces the entire state, take that replacement as base186 // before applying patches187 let i: number188 for (i = patches.length - 1; i >= 0; i--) {189 const patch = patches[i]190 if (patch.path.length === 0 && patch.op === "replace") {191 base = patch.value192 break193 }194 }195196 const applyPatchesImpl = getPlugin("patches").applyPatches_197 if (isDraft(base)) {198 // N.B: never hits if some patch a replacement, patches are never drafts199 return applyPatchesImpl(base, patches)200 }201 // Otherwise, produce a copy of the base state.202 return this.produce(base, (draft: Drafted) =>203 applyPatchesImpl(draft, patches.slice(i + 1))204 )205 }206}207208export function createProxy<T extends Objectish>(209 immer: Immer,210 value: T,211 parent?: ImmerState212): Drafted<T, ImmerState> {213 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft214 const draft: Drafted = isMap(value)215 ? getPlugin("mapset").proxyMap_(value, parent)216 : isSet(value)217 ? getPlugin("mapset").proxySet_(value, parent)218 : immer.useProxies_219 ? createProxyProxy(value, parent)220 : getPlugin("es5").createES5Proxy_(value, parent)221222 const scope = parent ? parent.scope_ : ImmerScope.current_!223 scope.drafts_.push(draft)224 return draft225}226227export function markChanged(immer: Immer, state: ImmerState) {228 if (immer.useProxies_) {229 markChangedProxy(state)230 } else {231 getPlugin("es5").markChangedES5_(state)232 }233}
added:src/core/proxy.ts+260 added
1"use strict"2import {3 each,4 has,5 is,6 isDraftable,7 shallowCopy,8 latest,9 ImmerBaseState,10 ImmerState,11 Drafted,12 AnyObject,13 AnyArray,14 Objectish,15 ImmerScope,16 DRAFT_STATE,17 die,18 createProxy,19 ProxyTypeProxyObject,20 ProxyTypeProxyArray21} from "../internal"2223interface ProxyBaseState extends ImmerBaseState {24 assigned_: {25 [property: string]: boolean26 }27 parent_?: ImmerState28 drafts_?: {29 [property: string]: Drafted<any, any>30 }31 revoke_(): void32}3334export interface ProxyObjectState extends ProxyBaseState {35 type_: typeof ProxyTypeProxyObject36 base_: AnyObject37 copy_: AnyObject | null38 draft_: Drafted<AnyObject, ProxyObjectState>39}4041export interface ProxyArrayState extends ProxyBaseState {42 type_: typeof ProxyTypeProxyArray43 base_: AnyArray44 copy_: AnyArray | null45 draft_: Drafted<AnyArray, ProxyArrayState>46}4748type ProxyState = ProxyObjectState | ProxyArrayState4950/**51 * Returns a new draft of the `base` object.52 *53 * The second argument is the parent draft-state (used internally).54 */55export function createProxyProxy<T extends Objectish>(56 base: T,57 parent?: ImmerState58): Drafted<T, ProxyState> {59 const isArray = Array.isArray(base)60 const state: ProxyState = {61 type_: isArray ? ProxyTypeProxyArray : (ProxyTypeProxyObject as any),62 // Track which produce call this is associated with.63 scope_: parent ? parent.scope_ : ImmerScope.current_!,64 // True for both shallow and deep changes.65 modified_: false,66 // Used during finalization.67 finalized_: false,68 // Track which properties have been assigned (true) or deleted (false).69 assigned_: {},70 // The parent draft state.71 parent_: parent,72 // The base state.73 base_: base,74 // The base proxy.75 draft_: null as any, // set below76 // Any property proxies.77 drafts_: {},78 // The base copy with any updated values.79 copy_: null,80 // Called by the `produce` function.81 revoke_: null as any,82 isManual_: false83 }8485 // the traps must target something, a bit like the 'real' base.86 // but also, we need to be able to determine from the target what the relevant state is87 // (to avoid creating traps per instance to capture the state in closure,88 // and to avoid creating weird hidden properties as well)89 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)90 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb91 let target: T = state as any92 let traps: ProxyHandler<object | Array<any>> = objectTraps93 if (isArray) {94 target = [state] as any95 traps = arrayTraps96 }9798 // TODO: optimization: might be faster, cheaper if we created a non-revocable proxy99 // and administrate revoking ourselves100 const {revoke, proxy} = Proxy.revocable(target, traps)101 state.draft_ = proxy as any102 state.revoke_ = revoke103 return proxy as any104}105106/**107 * Object drafts108 */109const objectTraps: ProxyHandler<ProxyState> = {110 get(state, prop) {111 if (prop === DRAFT_STATE) return state112 let {drafts_: drafts} = state113114 // Check for existing draft in unmodified state.115 if (!state.modified_ && has(drafts, prop)) {116 return drafts![prop as any]117 }118119 const value = latest(state)[prop]120 if (state.finalized_ || !isDraftable(value)) {121 return value122 }123124 // Check for existing draft in modified state.125 if (state.modified_) {126 // Assigned values are never drafted. This catches any drafts we created, too.127 if (value !== peek(state.base_, prop)) return value128 // Store drafts on the copy (when one exists).129 // @ts-ignore130 drafts = state.copy_131 }132133 return (drafts![prop as any] = createProxy(134 state.scope_.immer_,135 value,136 state137 ))138 },139 has(state, prop) {140 return prop in latest(state)141 },142 ownKeys(state) {143 return Reflect.ownKeys(latest(state))144 },145 set(state, prop: string /* strictly not, but helps TS */, value) {146 if (!state.modified_) {147 const baseValue = peek(state.base_, prop)148 // Optimize based on value's truthiness. Truthy values are guaranteed to149 // never be undefined, so we can avoid the `in` operator. Lastly, truthy150 // values may be drafts, but falsy values are never drafts.151 const isUnchanged = value152 ? is(baseValue, value) || value === state.drafts_![prop]153 : is(baseValue, value) && prop in state.base_154 if (isUnchanged) return true155 prepareCopy(state)156 markChangedProxy(state)157 }158 state.assigned_[prop] = true159 // @ts-ignore160 state.copy_![prop] = value161 return true162 },163 deleteProperty(state, prop: string) {164 // The `undefined` check is a fast path for pre-existing keys.165 if (peek(state.base_, prop) !== undefined || prop in state.base_) {166 state.assigned_[prop] = false167 prepareCopy(state)168 markChangedProxy(state)169 } else if (state.assigned_[prop]) {170 // if an originally not assigned property was deleted171 delete state.assigned_[prop]172 }173 // @ts-ignore174 if (state.copy_) delete state.copy_[prop]175 return true176 },177 // Note: We never coerce `desc.value` into an Immer draft, because we can't make178 // the same guarantee in ES5 mode.179 getOwnPropertyDescriptor(state, prop) {180 const owner = latest(state)181 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)182 if (desc) {183 desc.writable = true184 desc.configurable =185 state.type_ !== ProxyTypeProxyArray || prop !== "length"186 }187 return desc188 },189 defineProperty() {190 die(11)191 },192 getPrototypeOf(state) {193 return Object.getPrototypeOf(state.base_)194 },195 setPrototypeOf() {196 die(12)197 }198}199200/**201 * Array drafts202 */203204const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}205each(objectTraps, (key, fn) => {206 // @ts-ignore207 arrayTraps[key] = function() {208 arguments[0] = arguments[0][0]209 return fn.apply(this, arguments)210 }211})212arrayTraps.deleteProperty = function(state, prop) {213 if (__DEV__ && isNaN(parseInt(prop as any))) die(13)214 return objectTraps.deleteProperty!.call(this, state[0], prop)215}216arrayTraps.set = function(state, prop, value) {217 if (__DEV__ && prop !== "length" && isNaN(parseInt(prop as any))) die(14)218 return objectTraps.set!.call(this, state[0], prop, value, state[0])219}220221/**222 * Map drafts223 */224225// Access a property without creating an Immer draft.226function peek(draft: Drafted, prop: PropertyKey): any {227 const state = draft[DRAFT_STATE]228 const desc = Reflect.getOwnPropertyDescriptor(229 state ? latest(state) : draft,230 prop231 )232 return desc && desc.value233}234235export function markChangedProxy(state: ImmerState) {236 if (!state.modified_) {237 state.modified_ = true238 if (239 state.type_ === ProxyTypeProxyObject ||240 state.type_ === ProxyTypeProxyArray241 ) {242 const copy = (state.copy_ = shallowCopy(state.base_))243 each(state.drafts_!, (key, value) => {244 // @ts-ignore245 copy[key] = value246 })247 state.drafts_ = undefined248 }249250 if (state.parent_) {251 markChangedProxy(state.parent_)252 }253 }254}255256function prepareCopy(state: ProxyState) {257 if (!state.copy_) {258 state.copy_ = shallowCopy(state.base_)259 }260}
added:src/core/scope.ts+72 added
added:src/crap/common.ts+192 added
1import {2 DRAFT_STATE,3 DRAFTABLE,4 hasSet,5 Objectish,6 Drafted,7 AnyObject,8 AnyArray,9 AnyMap,10 AnySet,11 ImmerState,12 hasMap,13 ArchtypeObject,14 ArchtypeArray,15 ArchtypeMap,16 ArchtypeSet,17 die18} from "../internal"1920/** Returns true if the given value is an Immer draft */21/*#__PURE__*/22export function isDraft(value: any): boolean {23 return !!value && !!value[DRAFT_STATE]24}2526/** Returns true if the given value can be drafted by Immer */27/*#__PURE__*/28export function isDraftable(value: any): boolean {29 if (!value) return false30 return (31 isPlainObject(value) ||32 Array.isArray(value) ||33 !!value[DRAFTABLE] ||34 !!value.constructor[DRAFTABLE] ||35 isMap(value) ||36 isSet(value)37 )38}3940/*#__PURE__*/41export function isPlainObject(value: any): boolean {42 if (!value || typeof value !== "object") return false43 const proto = Object.getPrototypeOf(value)44 return !proto || proto === Object.prototype45}4647/** Get the underlying object that is represented by the given draft */48/*#__PURE__*/49export function original<T>(value: T): T | undefined50export function original(value: Drafted<any>): any {51 if (value && value[DRAFT_STATE]) {52 return value[DRAFT_STATE].base_ as any53 }54 // otherwise return undefined55}5657/*#__PURE__*/58export const ownKeys: (target: AnyObject) => PropertyKey[] =59 typeof Reflect !== "undefined" && Reflect.ownKeys60 ? Reflect.ownKeys61 : typeof Object.getOwnPropertySymbols !== "undefined"62 ? obj =>63 Object.getOwnPropertyNames(obj).concat(64 Object.getOwnPropertySymbols(obj) as any65 )66 : /* istanbul ignore next */ Object.getOwnPropertyNames6768export function each<T extends Objectish>(69 obj: T,70 iter: (key: string | number, value: any, source: T) => void71): void72export function each(obj: any, iter: any) {73 if (getArchtype(obj) === ArchtypeObject) {74 ownKeys(obj).forEach(key => iter(key, obj[key], obj))75 } else {76 obj.forEach((entry: any, index: any) => iter(index, entry, obj))77 }78}7980/*#__PURE__*/81export function getArchtype(thing: any): 0 | 1 | 2 | 3 {82 /* istanbul ignore next */83 const state: undefined | ImmerState = thing[DRAFT_STATE]84 return state85 ? state.type_ > 386 ? state.type_ - 4 // cause Object and Array map back from 4 and 587 : (state.type_ as any) // others are the same88 : Array.isArray(thing)89 ? ArchtypeArray90 : isMap(thing)91 ? ArchtypeMap92 : isSet(thing)93 ? ArchtypeSet94 : ArchtypeObject95}9697/*#__PURE__*/98export function has(thing: any, prop: PropertyKey): boolean {99 return getArchtype(thing) === ArchtypeMap100 ? thing.has(prop)101 : Object.prototype.hasOwnProperty.call(thing, prop)102}103104/*#__PURE__*/105export function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {106 // @ts-ignore107 return getArchtype(thing) === ArchtypeMap ? thing.get(prop) : thing[prop]108}109110/*#__PURE__*/111export function set(thing: any, propOrOldValue: PropertyKey, value: any) {112 switch (getArchtype(thing)) {113 case ArchtypeMap:114 thing.set(propOrOldValue, value)115 break116 case ArchtypeSet:117 thing.delete(propOrOldValue)118 thing.add(value)119 break120 default:121 thing[propOrOldValue] = value122 }123}124125/*#__PURE__*/126export function is(x: any, y: any): boolean {127 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js128 if (x === y) {129 return x !== 0 || 1 / x === 1 / y130 } else {131 return x !== x && y !== y132 }133}134135/*#__PURE__*/136export function isMap(target: any): target is AnyMap {137 return hasMap && target instanceof Map138}139140/*#__PURE__*/141export function isSet(target: any): target is AnySet {142 return hasSet && target instanceof Set143}144/*#__PURE__*/145export function latest(state: ImmerState): any {146 return state.copy_ || state.base_147}148149/*#__PURE__*/150export function shallowCopy<T extends AnyObject | AnyArray>(151 base: T,152 invokeGetters?: boolean153): T154export function shallowCopy(base: any, invokeGetters = false) {155 if (Array.isArray(base)) return base.slice()156 const clone = Object.create(Object.getPrototypeOf(base))157 // TODO: each?158 ownKeys(base).forEach(key => {159 if (key === DRAFT_STATE) {160 return // Never copy over draft state.161 }162 const desc = Object.getOwnPropertyDescriptor(base, key)!163 let {value} = desc164 if (desc.get) {165 if (!invokeGetters) die(1)166 value = desc.get.call(base)167 }168 if (desc.enumerable) {169 clone[key] = value170 } else {171 Object.defineProperty(clone, key, {172 value,173 writable: true,174 configurable: true175 })176 }177 })178 return clone179}180181export function freeze(obj: any, deep: boolean): void {182 if (isDraft(obj) || Object.isFrozen(obj) || !isDraftable(obj)) return183 if (getArchtype(obj) > 1 /* Map or Set */) {184 obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any185 }186 Object.freeze(obj)187 if (deep) each(obj, (_, value) => freeze(value, true))188}189190function dontMutateFrozenCollections() {191 die(2)192}
added:src/crap/env.ts+40 added
added:src/crap/errors.ts+52 added
added:src/crap/plugins.ts+108 added
1import {2 ImmerState,3 Patch,4 ImmerScope,5 Drafted,6 AnyObject,7 ImmerBaseState,8 AnyArray,9 AnyMap,10 AnySet,11 ProxyTypeES5Array,12 ProxyTypeES5Object,13 ProxyTypeMap,14 ProxyTypeSet,15 die16} from "../internal"1718/** Plugin utilities */19const plugins: {20 patches?: {21 generatePatches_(22 state: ImmerState,23 basePath: PatchPath,24 patches: Patch[],25 inversePatches: Patch[]26 ): void27 applyPatches_<T>(draft: T, patches: Patch[]): T28 }29 es5?: {30 willFinalizeES5_(scope: ImmerScope, result: any, isReplaced: boolean): void31 createES5Proxy_<T>(32 base: T,33 parent?: ImmerState34 ): Drafted<T, ES5ObjectState | ES5ArrayState>35 markChangedES5_(state: ImmerState): void36 }37 mapset?: {38 proxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T39 proxySet_<T extends AnySet>(target: T, parent?: ImmerState): T40 }41} = {}4243type Plugins = typeof plugins4445export function getPlugin<K extends keyof Plugins>(46 pluginKey: K47): Exclude<Plugins[K], undefined> {48 const plugin = plugins[pluginKey]49 if (!plugin) {50 die(__DEV__ ? 18 : 19, plugin)51 }52 // @ts-ignore53 return plugin54}5556export function loadPlugin<K extends keyof Plugins>(57 pluginKey: K,58 implementation: Plugins[K]59): void {60 plugins[pluginKey] = implementation61}6263/** ES5 Plugin */6465interface ES5BaseState extends ImmerBaseState {66 finalizing_: boolean67 assigned_: {[key: string]: any}68 parent_?: ImmerState69 revoked_: boolean70}7172export interface ES5ObjectState extends ES5BaseState {73 type_: typeof ProxyTypeES5Object74 draft_: Drafted<AnyObject, ES5ObjectState>75 base_: AnyObject76 copy_: AnyObject | null77}7879export interface ES5ArrayState extends ES5BaseState {80 type_: typeof ProxyTypeES5Array81 draft_: Drafted<AnyObject, ES5ArrayState>82 base_: AnyArray83 copy_: AnyArray | null84}8586/** Map / Set plugin */8788export interface MapState extends ImmerBaseState {89 type_: typeof ProxyTypeMap90 copy_: AnyMap | undefined91 assigned_: Map<any, boolean> | undefined92 base_: AnyMap93 revoked_: boolean94 draft_: Drafted<AnyMap, MapState>95}9697export interface SetState extends ImmerBaseState {98 type_: typeof ProxyTypeSet99 copy_: AnySet | undefined100 base_: AnySet101 drafts_: Map<any, Drafted> // maps the original value to the draft value in the new set102 revoked_: boolean103 draft_: Drafted<AnySet, SetState>104}105106/** Patches plugin */107108export type PatchPath = (string | number)[]
modified:src/plugins/patches.ts+2 added-2 removed
154 unmodified lines
155 ) {156 let {base_, copy_} = state157158 let i = 0159 base_.forEach(value => {159 base_.forEach((value: any) => {160 if (!copy_!.has(value)) {161 const path = basePath.concat([i])162 patches.push({163 op: "remove",
8 unmodified lines
172 }173 i++174 })175 i = 0176 copy_!.forEach(value => {176 copy_!.forEach((value: any) => {177 if (!base_.has(value)) {178 const path = basePath.concat([i])179 patches.push({180 op: "add",
90 unmodified lines
added:src/types/globals.d.ts+1 added
added:src/types/immer.js.flow+107 added
1// @flow23export interface Patch {4 op: "replace" | "remove" | "add",5 path: (string|number)[],6 value?: any7}89export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void1011interface IProduce {12 /**13 * Immer takes a state, and runs a function against it.14 * That function can freely mutate the state, as it will create copies-on-write.15 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.16 *17 * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe18 * any time it is called with the current state.19 *20 * @param currentState - the state to start with21 * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified22 * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined23 * @returns The next state: a new state, or the current state if nothing was modified24 */25 <S>(26 currentState: S,27 recipe: (draftState: S) => S | void,28 patchListener?: PatchListener29 ): S;30 // curried invocations with inital state31 <S, A, B, C>(32 recipe: (draftState: S, a: A, b: B, c: C) => S | void,33 initialState: S34 ): (currentState: S | void, a: A, b: B, c: C) => S;35 <S, A, B>(36 recipe: (draftState: S, a: A, b: B) => S | void,37 initialState: S38 ): (currentState: S | void, a: A, b: B) => S;39 <S, A>(40 recipe: (draftState: S, a: A) => S | void,41 initialState: S42 ): (currentState: S | void, a: A) => S;43 <S>(44 recipe: (draftState: S) => S | void,45 initialState: S46 ): (currentState: S | void) => S;47 <S>(48 recipe: (draftState: S, ...extraArgs: any[]) => S | void,49 initialState: S50 ): (currentState: S | void, ...extraArgs: any[]) => S;51 // curried invocations without inital state52 <S, A, B, C>(53 recipe: (draftState: S, a: A, b: B, c: C) => S | void54 ): (currentState: S, a: A, b: B, c: C) => S;55 <S, A, B>(56 recipe: (draftState: S, a: A, b: B) => S | void57 ): (currentState: S, a: A, b: B) => S;58 <S, A>(59 recipe: (draftState: S, a: A) => S | void60 ): (currentState: S, a: A) => S;61 <S>(62 recipe: (draftState: S) => S | void63 ): (currentState: S) => S;64 <S>(65 recipe: (draftState: S, ...extraArgs: any[]) => S | void66 ): (currentState: S, ...extraArgs: any[]) => S;67}6869declare export var produce: IProduce70declare export default IProduce7172declare export var nothing: typeof undefined7374declare export var immerable: Symbol7576/**77 * Automatically freezes any state trees generated by immer.78 * This protects against accidental modifications of the state tree outside of an immer function.79 * This comes with a performance impact, so it is recommended to disable this option in production.80 * By default it is turned on during local development, and turned off in production.81 */82declare export function setAutoFreeze(autoFreeze: boolean): void8384/**85 * Manually override whether proxies should be used.86 * By default done by using feature detection87 */88declare export function setUseProxies(useProxies: boolean): void8990declare export function applyPatches<S>(state: S, patches: Patch[]): S9192declare export function original<S>(value: S): ?S9394declare export function isDraft(value: any): boolean9596/**97 * Creates a mutable draft from an (immutable) object / array. 98 * The draft can be modified until `finishDraft` is called99 */100declare export function createDraft<T>(base: T): T101102/**103 * Given a draft that was created using `createDraft`, 104 * finalizes the draft into a new immutable object.105 * Optionally a patch-listener can be provided to gather the patches that are needed to construct the object.106 */107declare export function finishDraft<T>(base: T, listener?: PatchListener): T
added:src/types/types-external.ts+169 added
1import {Nothing} from "../internal"23type Tail<T extends any[]> = ((...t: T) => any) extends (4 _: any,5 ...tail: infer TT6) => any7 ? TT8 : []910/** Object types that should never be mapped */11type AtomicObject =12 | Function13 | Promise<any>14 | Date15 | RegExp16 | Boolean17 | Number18 | String1920/**21 * These should also never be mapped but must be tested after regular Map and22 * Set23 */24type WeakReferences = WeakMap<any, any> | WeakSet<any>2526export type Draft<T> = T extends AtomicObject27 ? T28 : T extends ReadonlyMap<infer K, infer V> // Map extends ReadonlyMap29 ? Map<Draft<K>, Draft<V>>30 : T extends ReadonlySet<infer V> // Set extends ReadonlySet31 ? Set<Draft<V>>32 : T extends WeakReferences33 ? T34 : T extends object35 ? {-readonly [K in keyof T]: Draft<T[K]>}36 : T3738/** Convert a mutable type into a readonly type */39export type Immutable<T> = T extends AtomicObject40 ? T41 : T extends ReadonlyMap<infer K, infer V> // Map extends ReadonlyMap42 ? ReadonlyMap<Immutable<K>, Immutable<V>>43 : T extends ReadonlySet<infer V> // Set extends ReadonlySet44 ? ReadonlySet<Immutable<V>>45 : T extends WeakReferences46 ? T47 : T extends object48 ? {readonly [K in keyof T]: Immutable<T[K]>}49 : T5051export interface Patch {52 op: "replace" | "remove" | "add"53 path: (string | number)[]54 value?: any55}5657export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void5859/** Converts `nothing` into `undefined` */60type FromNothing<T> = T extends Nothing ? undefined : T6162/** The inferred return type of `produce` */63export type Produced<Base, Return> = Return extends void64 ? Base65 : Return extends Promise<infer Result>66 ? Promise<Result extends void ? Base : FromNothing<Result>>67 : FromNothing<Return>6869/**70 * The `produce` function takes a value and a "recipe function" (whose71 * return value often depends on the base state). The recipe function is72 * free to mutate its first argument however it wants. All mutations are73 * only ever applied to a __copy__ of the base state.74 *75 * Pass only a function to create a "curried producer" which relieves you76 * from passing the recipe function every time.77 *78 * Only plain objects and arrays are made mutable. All other objects are79 * considered uncopyable.80 *81 * Note: This function is __bound__ to its `Immer` instance.82 *83 * @param {any} base - the initial state84 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified85 * @param {Function} patchListener - optional function that will be called with all the patches produced here86 * @returns {any} a new state, or the initial state if nothing was modified87 */88export interface IProduce {89 /** Curried producer */90 <91 Recipe extends (...args: any[]) => any,92 Params extends any[] = Parameters<Recipe>,93 T = Params[0]94 >(95 recipe: Recipe96 ): <Base extends Immutable<T>>(97 base: Base,98 ...rest: Tail<Params>99 ) => Produced<Base, ReturnType<Recipe>>100 // ^ by making the returned type generic, the actual type of the passed in object is preferred101 // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe102 // 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!103104 /** Curried producer with initial state */105 <106 Recipe extends (...args: any[]) => any,107 Params extends any[] = Parameters<Recipe>,108 T = Params[0]109 >(110 recipe: Recipe,111 initialState: Immutable<T>112 ): <Base extends Immutable<T>>(113 base?: Base,114 ...rest: Tail<Params>115 ) => Produced<Base, ReturnType<Recipe>>116117 /** Normal producer */118 <Base, D = Draft<Base>, Return = void>(119 base: Base,120 recipe: (draft: D) => Return,121 listener?: PatchListener122 ): Produced<Base, Return>123}124125/**126 * Like `produce`, but instead of just returning the new state,127 * a tuple is returned with [nextState, patches, inversePatches]128 *129 * Like produce, this function supports currying130 */131export interface IProduceWithPatches {132 /** Curried producer */133 <134 Recipe extends (...args: any[]) => any,135 Params extends any[] = Parameters<Recipe>,136 T = Params[0]137 >(138 recipe: Recipe139 ): <Base extends Immutable<T>>(140 base: Base,141 ...rest: Tail<Params>142 ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]143 // ^ by making the returned type generic, the actual type of the passed in object is preferred144 // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe145 // 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!146147 /** Curried producer with initial state */148 <149 Recipe extends (...args: any[]) => any,150 Params extends any[] = Parameters<Recipe>,151 T = Params[0]152 >(153 recipe: Recipe,154 initialState: Immutable<T>155 ): <Base extends Immutable<T>>(156 base?: Base,157 ...rest: Tail<Params>158 ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]159160 /** Normal producer */161 <Base, D = Draft<Base>, Return = void>(162 base: Base,163 recipe: (draft: D) => Return164 ): [Produced<Base, Return>, Patch[], Patch[]]165}166167// Fixes #507: bili doesn't export the types of this file if there is no actual source in it..168// hopefully it get's tree-shaken away for everyone :)169export function never_used() {}
added:src/types/types-internal.ts+51 added
deleted:src/common.ts-192 removed
1import {2 DRAFT_STATE,3 DRAFTABLE,4 hasSet,5 Objectish,6 Drafted,7 AnyObject,8 AnyArray,9 AnyMap,10 AnySet,11 ImmerState,12 hasMap,13 ArchtypeObject,14 ArchtypeArray,15 ArchtypeMap,16 ArchtypeSet,17 die18} from "./internal"1920/** Returns true if the given value is an Immer draft */21/*#__PURE__*/22export function isDraft(value: any): boolean {23 return !!value && !!value[DRAFT_STATE]24}2526/** Returns true if the given value can be drafted by Immer */27/*#__PURE__*/28export function isDraftable(value: any): boolean {29 if (!value) return false30 return (31 isPlainObject(value) ||32 Array.isArray(value) ||33 !!value[DRAFTABLE] ||34 !!value.constructor[DRAFTABLE] ||35 isMap(value) ||36 isSet(value)37 )38}3940/*#__PURE__*/41export function isPlainObject(value: any): boolean {42 if (!value || typeof value !== "object") return false43 const proto = Object.getPrototypeOf(value)44 return !proto || proto === Object.prototype45}4647/** Get the underlying object that is represented by the given draft */48/*#__PURE__*/49export function original<T>(value: T): T | undefined50export function original(value: Drafted<any>): any {51 if (value && value[DRAFT_STATE]) {52 return value[DRAFT_STATE].base_ as any53 }54 // otherwise return undefined55}5657/*#__PURE__*/58export const ownKeys: (target: AnyObject) => PropertyKey[] =59 typeof Reflect !== "undefined" && Reflect.ownKeys60 ? Reflect.ownKeys61 : typeof Object.getOwnPropertySymbols !== "undefined"62 ? obj =>63 Object.getOwnPropertyNames(obj).concat(64 Object.getOwnPropertySymbols(obj) as any65 )66 : /* istanbul ignore next */ Object.getOwnPropertyNames6768export function each<T extends Objectish>(69 obj: T,70 iter: (key: string | number, value: any, source: T) => void71): void72export function each(obj: any, iter: any) {73 if (getArchtype(obj) === ArchtypeObject) {74 ownKeys(obj).forEach(key => iter(key, obj[key], obj))75 } else {76 obj.forEach((entry: any, index: any) => iter(index, entry, obj))77 }78}7980/*#__PURE__*/81export function getArchtype(thing: any): 0 | 1 | 2 | 3 {82 /* istanbul ignore next */83 const state: undefined | ImmerState = thing[DRAFT_STATE]84 return state85 ? state.type_ > 386 ? state.type_ - 4 // cause Object and Array map back from 4 and 587 : (state.type_ as any) // others are the same88 : Array.isArray(thing)89 ? ArchtypeArray90 : isMap(thing)91 ? ArchtypeMap92 : isSet(thing)93 ? ArchtypeSet94 : ArchtypeObject95}9697/*#__PURE__*/98export function has(thing: any, prop: PropertyKey): boolean {99 return getArchtype(thing) === ArchtypeMap100 ? thing.has(prop)101 : Object.prototype.hasOwnProperty.call(thing, prop)102}103104/*#__PURE__*/105export function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {106 // @ts-ignore107 return getArchtype(thing) === ArchtypeMap ? thing.get(prop) : thing[prop]108}109110/*#__PURE__*/111export function set(thing: any, propOrOldValue: PropertyKey, value: any) {112 switch (getArchtype(thing)) {113 case ArchtypeMap:114 thing.set(propOrOldValue, value)115 break116 case ArchtypeSet:117 thing.delete(propOrOldValue)118 thing.add(value)119 break120 default:121 thing[propOrOldValue] = value122 }123}124125/*#__PURE__*/126export function is(x: any, y: any): boolean {127 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js128 if (x === y) {129 return x !== 0 || 1 / x === 1 / y130 } else {131 return x !== x && y !== y132 }133}134135/*#__PURE__*/136export function isMap(target: any): target is AnyMap {137 return hasMap && target instanceof Map138}139140/*#__PURE__*/141export function isSet(target: any): target is AnySet {142 return hasSet && target instanceof Set143}144/*#__PURE__*/145export function latest(state: ImmerState): any {146 return state.copy_ || state.base_147}148149/*#__PURE__*/150export function shallowCopy<T extends AnyObject | AnyArray>(151 base: T,152 invokeGetters?: boolean153): T154export function shallowCopy(base: any, invokeGetters = false) {155 if (Array.isArray(base)) return base.slice()156 const clone = Object.create(Object.getPrototypeOf(base))157 // TODO: each?158 ownKeys(base).forEach(key => {159 if (key === DRAFT_STATE) {160 return // Never copy over draft state.161 }162 const desc = Object.getOwnPropertyDescriptor(base, key)!163 let {value} = desc164 if (desc.get) {165 if (!invokeGetters) die(1)166 value = desc.get.call(base)167 }168 if (desc.enumerable) {169 clone[key] = value170 } else {171 Object.defineProperty(clone, key, {172 value,173 writable: true,174 configurable: true175 })176 }177 })178 return clone179}180181export function freeze(obj: any, deep: boolean): void {182 if (isDraft(obj) || Object.isFrozen(obj) || !isDraftable(obj)) return183 if (getArchtype(obj) > 1 /* Map or Set */) {184 obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any185 }186 Object.freeze(obj)187 if (deep) each(obj, (_, value) => freeze(value, true))188}189190function dontMutateFrozenCollections() {191 die(2)192}
deleted:src/env.ts-40 removed
deleted:src/errors.ts-52 removed
deleted:src/finalize.ts-162 removed
1import {2 ImmerScope,3 DRAFT_STATE,4 isDraftable,5 NOTHING,6 PatchPath,7 each,8 has,9 freeze,10 shallowCopy,11 ImmerState,12 isDraft,13 SetState,14 set,15 is,16 get,17 ProxyTypeES5Object,18 ProxyTypeES5Array,19 ProxyTypeSet,20 getPlugin,21 die22} from "./internal"2324export function processResult(result: any, scope: ImmerScope) {25 scope.unfinalizedDrafts_ = scope.drafts_.length26 const baseDraft = scope.drafts_![0]27 const isReplaced = result !== undefined && result !== baseDraft28 if (!scope.immer_.useProxies_)29 getPlugin("es5").willFinalizeES5_(scope, result, isReplaced)30 if (isReplaced) {31 if (baseDraft[DRAFT_STATE].modified_) {32 scope.revoke_()33 die(4)34 }35 if (isDraftable(result)) {36 // Finalize the result in case it contains (or is) a subset of the draft.37 result = finalize(scope, result)38 if (!scope.parent_) maybeFreeze(scope, result)39 }40 // TODO: move to plugin?41 if (scope.patches_) {42 scope.patches_.push({43 op: "replace",44 path: [],45 value: result46 })47 scope.inversePatches_!.push({48 op: "replace",49 path: [],50 value: (baseDraft[DRAFT_STATE] as ImmerState).base_51 })52 }53 } else {54 // Finalize the base draft.55 result = finalize(scope, baseDraft, [])56 }57 scope.revoke_()58 if (scope.patches_) {59 scope.patchListener_!(scope.patches_, scope.inversePatches_!)60 }61 return result !== NOTHING ? result : undefined62}6364function finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {65 // Don't recurse in tho recursive data structures66 if (Object.isFrozen(value)) return value6768 const state: ImmerState = value[DRAFT_STATE]69 // A plain object, might need freezing, might contain drafts70 if (!state) {71 each(value, (key, childValue) =>72 finalizeProperty(rootScope, state, value, key, childValue, path)73 )74 return value75 }76 // Never finalize drafts owned by another scope.77 if (state.scope_ !== rootScope) return value78 // Unmodified draft, return the (frozen) original79 if (!state.modified_) {80 maybeFreeze(rootScope, state.base_, true)81 return state.base_82 }83 // Not finalized yet, let's do that now84 if (!state.finalized_) {85 state.finalized_ = true86 state.scope_.unfinalizedDrafts_--87 const result =88 // For ES5, create a good copy from the draft first, with added keys and without deleted keys.89 state.type_ === ProxyTypeES5Object || state.type_ === ProxyTypeES5Array90 ? (state.copy_ = shallowCopy(state.draft_, true))91 : state.copy_92 // finalize all children of the copy93 each(result as any, (key, childValue) =>94 finalizeProperty(rootScope, state, result, key, childValue, path)95 )96 // everything inside is frozen, we can freeze here97 maybeFreeze(rootScope, result, false)98 // first time finalizing, let's create those patches99 if (path && rootScope.patches_) {100 getPlugin("patches").generatePatches_(101 state,102 path,103 rootScope.patches_,104 rootScope.inversePatches_!105 )106 }107 }108 return state.copy_109}110111function finalizeProperty(112 rootScope: ImmerScope,113 parentState: undefined | ImmerState,114 targetObject: any,115 prop: string | number,116 childValue: any,117 rootPath?: PatchPath118) {119 if (__DEV__ && childValue === targetObject) die(5)120 if (isDraft(childValue)) {121 const path =122 rootPath &&123 parentState &&124 parentState!.type_ !== ProxyTypeSet && // Set objects are atomic since they have no keys.125 !has((parentState as Exclude<ImmerState, SetState>).assigned_!, prop) // Skip deep patches for assigned keys.126 ? rootPath!.concat(prop)127 : undefined128 // Drafts owned by `scope` are finalized here.129 const res = finalize(rootScope, childValue, path)130 set(targetObject, prop, res)131 // Drafts from another scope must prevented to be frozen132 // if we got a draft back from finalize, we're in a nested produce and shouldn't freeze133 if (isDraft(res)) {134 rootScope.canAutoFreeze_ = false135 } else return136 }137 // Unchanged draft properties are ignored.138 if (parentState && is(childValue, get(parentState!.base_, prop))) {139 return140 }141 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.142 if (isDraftable(childValue)) {143 if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {144 // optimization: if an object is not a draft, and we don't have to145 // deepfreeze everything, and we are sure that no drafts are left in the remaining object146 // cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.147 // This benefits especially adding large data tree's without further processing.148 // See add-data.js perf test149 return150 }151 finalize(rootScope, childValue)152 // immer deep freezes plain objects, so if there is no parent state, we freeze as well153 if (!parentState || !parentState.scope_.parent_)154 maybeFreeze(rootScope, childValue)155 }156}157158function maybeFreeze(scope: ImmerScope, value: any, deep = false) {159 if (scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {160 freeze(value, deep)161 }162}
deleted:src/globals.d.ts-1 removed
1declare const __DEV__: boolean
deleted:src/immer.js.flow-107 removed
1// @flow23export interface Patch {4 op: "replace" | "remove" | "add",5 path: (string|number)[],6 value?: any7}89export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void1011interface IProduce {12 /**13 * Immer takes a state, and runs a function against it.14 * That function can freely mutate the state, as it will create copies-on-write.15 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.16 *17 * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe18 * any time it is called with the current state.19 *20 * @param currentState - the state to start with21 * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified22 * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined23 * @returns The next state: a new state, or the current state if nothing was modified24 */25 <S>(26 currentState: S,27 recipe: (draftState: S) => S | void,28 patchListener?: PatchListener29 ): S;30 // curried invocations with inital state31 <S, A, B, C>(32 recipe: (draftState: S, a: A, b: B, c: C) => S | void,33 initialState: S34 ): (currentState: S | void, a: A, b: B, c: C) => S;35 <S, A, B>(36 recipe: (draftState: S, a: A, b: B) => S | void,37 initialState: S38 ): (currentState: S | void, a: A, b: B) => S;39 <S, A>(40 recipe: (draftState: S, a: A) => S | void,41 initialState: S42 ): (currentState: S | void, a: A) => S;43 <S>(44 recipe: (draftState: S) => S | void,45 initialState: S46 ): (currentState: S | void) => S;47 <S>(48 recipe: (draftState: S, ...extraArgs: any[]) => S | void,49 initialState: S50 ): (currentState: S | void, ...extraArgs: any[]) => S;51 // curried invocations without inital state52 <S, A, B, C>(53 recipe: (draftState: S, a: A, b: B, c: C) => S | void54 ): (currentState: S, a: A, b: B, c: C) => S;55 <S, A, B>(56 recipe: (draftState: S, a: A, b: B) => S | void57 ): (currentState: S, a: A, b: B) => S;58 <S, A>(59 recipe: (draftState: S, a: A) => S | void60 ): (currentState: S, a: A) => S;61 <S>(62 recipe: (draftState: S) => S | void63 ): (currentState: S) => S;64 <S>(65 recipe: (draftState: S, ...extraArgs: any[]) => S | void66 ): (currentState: S, ...extraArgs: any[]) => S;67}6869declare export var produce: IProduce70declare export default IProduce7172declare export var nothing: typeof undefined7374declare export var immerable: Symbol7576/**77 * Automatically freezes any state trees generated by immer.78 * This protects against accidental modifications of the state tree outside of an immer function.79 * This comes with a performance impact, so it is recommended to disable this option in production.80 * By default it is turned on during local development, and turned off in production.81 */82declare export function setAutoFreeze(autoFreeze: boolean): void8384/**85 * Manually override whether proxies should be used.86 * By default done by using feature detection87 */88declare export function setUseProxies(useProxies: boolean): void8990declare export function applyPatches<S>(state: S, patches: Patch[]): S9192declare export function original<S>(value: S): ?S9394declare export function isDraft(value: any): boolean9596/**97 * Creates a mutable draft from an (immutable) object / array. 98 * The draft can be modified until `finishDraft` is called99 */100declare export function createDraft<T>(base: T): T101102/**103 * Given a draft that was created using `createDraft`, 104 * finalizes the draft into a new immutable object.105 * Optionally a patch-listener can be provided to gather the patches that are needed to construct the object.106 */107declare export function finishDraft<T>(base: T, listener?: PatchListener): T
deleted:src/immerClass.ts-233 removed
1import {2 IProduceWithPatches,3 IProduce,4 ImmerState,5 Drafted,6 isDraftable,7 ImmerScope,8 processResult,9 NOTHING,10 Patch,11 Objectish,12 DRAFT_STATE,13 Draft,14 PatchListener,15 isDraft,16 isMap,17 isSet,18 markChangedProxy,19 createProxyProxy,20 freeze,21 getPlugin,22 die23} from "./internal"2425/* istanbul ignore next */26function verifyMinified() {}2728interface ProducersFns {29 produce: IProduce30 produceWithPatches: IProduceWithPatches31}3233export class Immer implements ProducersFns {34 useProxies_: boolean =35 typeof Proxy !== "undefined" &&36 typeof Proxy.revocable !== "undefined" &&37 typeof Reflect !== "undefined"38 autoFreeze_: boolean = __DEV__39 ? false /* istanbul ignore next */40 : verifyMinified.name === "verifyMinified"4142 constructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {43 if (typeof config?.useProxies === "boolean")44 this.setUseProxies(config!.useProxies)45 if (typeof config?.autoFreeze === "boolean")46 this.setAutoFreeze(config!.autoFreeze)47 this.produce = this.produce.bind(this)48 this.produceWithPatches = this.produceWithPatches.bind(this)49 }5051 /**52 * The `produce` function takes a value and a "recipe function" (whose53 * return value often depends on the base state). The recipe function is54 * free to mutate its first argument however it wants. All mutations are55 * only ever applied to a __copy__ of the base state.56 *57 * Pass only a function to create a "curried producer" which relieves you58 * from passing the recipe function every time.59 *60 * Only plain objects and arrays are made mutable. All other objects are61 * considered uncopyable.62 *63 * Note: This function is __bound__ to its `Immer` instance.64 *65 * @param {any} base - the initial state66 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified67 * @param {Function} patchListener - optional function that will be called with all the patches produced here68 * @returns {any} a new state, or the initial state if nothing was modified69 */70 produce(base: any, recipe?: any, patchListener?: any) {71 // curried invocation72 if (typeof base === "function" && typeof recipe !== "function") {73 const defaultBase = recipe74 recipe = base7576 const self = this77 return function curriedProduce(78 this: any,79 base = defaultBase,80 ...args: any[]81 ) {82 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore83 }84 }8586 if (typeof recipe !== "function") die(6)87 if (patchListener !== undefined && typeof patchListener !== "function")88 die(7)8990 let result9192 // Only plain objects, arrays, and "immerable classes" are drafted.93 if (isDraftable(base)) {94 const scope = ImmerScope.enter_(this)95 const proxy = createProxy(this, base, undefined)96 let hasError = true97 try {98 result = recipe(proxy)99 hasError = false100 } finally {101 // finally instead of catch + rethrow better preserves original stack102 if (hasError) scope.revoke_()103 else scope.leave_()104 }105 if (typeof Promise !== "undefined" && result instanceof Promise) {106 return result.then(107 result => {108 scope.usePatches_(patchListener)109 return processResult(result, scope)110 },111 error => {112 scope.revoke_()113 throw error114 }115 )116 }117 scope.usePatches_(patchListener)118 return processResult(result, scope)119 } else {120 result = recipe(base)121 if (result === NOTHING) return undefined122 if (result === undefined) result = base123 if (this.autoFreeze_) freeze(result, true)124 return result125 }126 }127128 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {129 if (typeof arg1 === "function") {130 return (state: any, ...args: any[]) =>131 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))132 }133134 let patches: Patch[], inversePatches: Patch[]135 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {136 patches = p137 inversePatches = ip138 })139 return [nextState, patches!, inversePatches!]140 }141142 createDraft<T extends Objectish>(base: T): Draft<T> {143 if (!isDraftable(base)) die(8)144 const scope = ImmerScope.enter_(this)145 const proxy = createProxy(this, base, undefined)146 proxy[DRAFT_STATE].isManual_ = true147 scope.leave_()148 return proxy as any149 }150151 finishDraft<D extends Draft<any>>(152 draft: D,153 patchListener?: PatchListener154 ): D extends Draft<infer T> ? T : never {155 const state: ImmerState = draft && draft[DRAFT_STATE]156 if (__DEV__) {157 if (!state || !state.isManual_) die(9)158 if (state.finalized_) die(10)159 }160 const {scope_: scope} = state161 scope.usePatches_(patchListener)162 return processResult(undefined, scope)163 }164165 /**166 * Pass true to automatically freeze all copies created by Immer.167 *168 * By default, auto-freezing is disabled in production.169 */170 setAutoFreeze(value: boolean) {171 this.autoFreeze_ = value172 }173174 /**175 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is176 * always faster than using ES5 proxies.177 *178 * By default, feature detection is used, so calling this is rarely necessary.179 */180 setUseProxies(value: boolean) {181 this.useProxies_ = value182 }183184 applyPatches(base: Objectish, patches: Patch[]) {185 // If a patch replaces the entire state, take that replacement as base186 // before applying patches187 let i: number188 for (i = patches.length - 1; i >= 0; i--) {189 const patch = patches[i]190 if (patch.path.length === 0 && patch.op === "replace") {191 base = patch.value192 break193 }194 }195196 const applyPatchesImpl = getPlugin("patches").applyPatches_197 if (isDraft(base)) {198 // N.B: never hits if some patch a replacement, patches are never drafts199 return applyPatchesImpl(base, patches)200 }201 // Otherwise, produce a copy of the base state.202 return this.produce(base, (draft: Drafted) =>203 applyPatchesImpl(draft, patches.slice(i + 1))204 )205 }206}207208export function createProxy<T extends Objectish>(209 immer: Immer,210 value: T,211 parent?: ImmerState212): Drafted<T, ImmerState> {213 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft214 const draft: Drafted = isMap(value)215 ? getPlugin("mapset").proxyMap_(value, parent)216 : isSet(value)217 ? getPlugin("mapset").proxySet_(value, parent)218 : immer.useProxies_219 ? createProxyProxy(value, parent)220 : getPlugin("es5").createES5Proxy_(value, parent)221222 const scope = parent ? parent.scope_ : ImmerScope.current_!223 scope.drafts_.push(draft)224 return draft225}226227export function markChanged(immer: Immer, state: ImmerState) {228 if (immer.useProxies_) {229 markChangedProxy(state)230 } else {231 getPlugin("es5").markChangedES5_(state)232 }233}
modified:src/internal.ts+10 added-10 removed
1export * from "./env"2export * from "./errors"3export * from "./types-external"4export * from "./types-internal"5export * from "./common"6export * from "./plugins"7export * from "./scope"8export * from "./finalize"9export * from "./proxy"10export * from "./immerClass"1export * from "./crap/env"2export * from "./crap/errors"3export * from "./types/types-external"4export * from "./types/types-internal"5export * from "./crap/common"6export * from "./crap/plugins"7export * from "./core/scope"8export * from "./core/finalize"9export * from "./core/proxy"10export * from "./core/immerClass"
deleted:src/plugins.ts-108 removed
1import {2 ImmerState,3 Patch,4 ImmerScope,5 Drafted,6 AnyObject,7 ImmerBaseState,8 AnyArray,9 AnyMap,10 AnySet,11 ProxyTypeES5Array,12 ProxyTypeES5Object,13 ProxyTypeMap,14 ProxyTypeSet,15 die16} from "./internal"1718/** Plugin utilities */19const plugins: {20 patches?: {21 generatePatches_(22 state: ImmerState,23 basePath: PatchPath,24 patches: Patch[],25 inversePatches: Patch[]26 ): void27 applyPatches_<T>(draft: T, patches: Patch[]): T28 }29 es5?: {30 willFinalizeES5_(scope: ImmerScope, result: any, isReplaced: boolean): void31 createES5Proxy_<T>(32 base: T,33 parent?: ImmerState34 ): Drafted<T, ES5ObjectState | ES5ArrayState>35 markChangedES5_(state: ImmerState): void36 }37 mapset?: {38 proxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T39 proxySet_<T extends AnySet>(target: T, parent?: ImmerState): T40 }41} = {}4243type Plugins = typeof plugins4445export function getPlugin<K extends keyof Plugins>(46 pluginKey: K47): Exclude<Plugins[K], undefined> {48 const plugin = plugins[pluginKey]49 if (!plugin) {50 die(__DEV__ ? 18 : 19, plugin)51 }52 // @ts-ignore53 return plugin54}5556export function loadPlugin<K extends keyof Plugins>(57 pluginKey: K,58 implementation: Plugins[K]59): void {60 plugins[pluginKey] = implementation61}6263/** ES5 Plugin */6465interface ES5BaseState extends ImmerBaseState {66 finalizing_: boolean67 assigned_: {[key: string]: any}68 parent_?: ImmerState69 revoked_: boolean70}7172export interface ES5ObjectState extends ES5BaseState {73 type_: typeof ProxyTypeES5Object74 draft_: Drafted<AnyObject, ES5ObjectState>75 base_: AnyObject76 copy_: AnyObject | null77}7879export interface ES5ArrayState extends ES5BaseState {80 type_: typeof ProxyTypeES5Array81 draft_: Drafted<AnyObject, ES5ArrayState>82 base_: AnyArray83 copy_: AnyArray | null84}8586/** Map / Set plugin */8788export interface MapState extends ImmerBaseState {89 type_: typeof ProxyTypeMap90 copy_: AnyMap | undefined91 assigned_: Map<any, boolean> | undefined92 base_: AnyMap93 revoked_: boolean94 draft_: Drafted<AnyMap, MapState>95}9697export interface SetState extends ImmerBaseState {98 type_: typeof ProxyTypeSet99 copy_: AnySet | undefined100 base_: AnySet101 drafts_: Map<any, Drafted> // maps the original value to the draft value in the new set102 revoked_: boolean103 draft_: Drafted<AnySet, SetState>104}105106/** Patches plugin */107108export type PatchPath = (string | number)[]
deleted:src/proxy.ts-260 removed
1"use strict"2import {3 each,4 has,5 is,6 isDraftable,7 shallowCopy,8 latest,9 ImmerBaseState,10 ImmerState,11 Drafted,12 AnyObject,13 AnyArray,14 Objectish,15 ImmerScope,16 DRAFT_STATE,17 createProxy,18 ProxyTypeProxyObject,19 ProxyTypeProxyArray20} from "./internal"21import {die} from "./errors"2223interface ProxyBaseState extends ImmerBaseState {24 assigned_: {25 [property: string]: boolean26 }27 parent_?: ImmerState28 drafts_?: {29 [property: string]: Drafted<any, any>30 }31 revoke_(): void32}3334export interface ProxyObjectState extends ProxyBaseState {35 type_: typeof ProxyTypeProxyObject36 base_: AnyObject37 copy_: AnyObject | null38 draft_: Drafted<AnyObject, ProxyObjectState>39}4041export interface ProxyArrayState extends ProxyBaseState {42 type_: typeof ProxyTypeProxyArray43 base_: AnyArray44 copy_: AnyArray | null45 draft_: Drafted<AnyArray, ProxyArrayState>46}4748type ProxyState = ProxyObjectState | ProxyArrayState4950/**51 * Returns a new draft of the `base` object.52 *53 * The second argument is the parent draft-state (used internally).54 */55export function createProxyProxy<T extends Objectish>(56 base: T,57 parent?: ImmerState58): Drafted<T, ProxyState> {59 const isArray = Array.isArray(base)60 const state: ProxyState = {61 type_: isArray ? ProxyTypeProxyArray : (ProxyTypeProxyObject as any),62 // Track which produce call this is associated with.63 scope_: parent ? parent.scope_ : ImmerScope.current_!,64 // True for both shallow and deep changes.65 modified_: false,66 // Used during finalization.67 finalized_: false,68 // Track which properties have been assigned (true) or deleted (false).69 assigned_: {},70 // The parent draft state.71 parent_: parent,72 // The base state.73 base_: base,74 // The base proxy.75 draft_: null as any, // set below76 // Any property proxies.77 drafts_: {},78 // The base copy with any updated values.79 copy_: null,80 // Called by the `produce` function.81 revoke_: null as any,82 isManual_: false83 }8485 // the traps must target something, a bit like the 'real' base.86 // but also, we need to be able to determine from the target what the relevant state is87 // (to avoid creating traps per instance to capture the state in closure,88 // and to avoid creating weird hidden properties as well)89 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)90 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb91 let target: T = state as any92 let traps: ProxyHandler<object | Array<any>> = objectTraps93 if (isArray) {94 target = [state] as any95 traps = arrayTraps96 }9798 // TODO: optimization: might be faster, cheaper if we created a non-revocable proxy99 // and administrate revoking ourselves100 const {revoke, proxy} = Proxy.revocable(target, traps)101 state.draft_ = proxy as any102 state.revoke_ = revoke103 return proxy as any104}105106/**107 * Object drafts108 */109const objectTraps: ProxyHandler<ProxyState> = {110 get(state, prop) {111 if (prop === DRAFT_STATE) return state112 let {drafts_: drafts} = state113114 // Check for existing draft in unmodified state.115 if (!state.modified_ && has(drafts, prop)) {116 return drafts![prop as any]117 }118119 const value = latest(state)[prop]120 if (state.finalized_ || !isDraftable(value)) {121 return value122 }123124 // Check for existing draft in modified state.125 if (state.modified_) {126 // Assigned values are never drafted. This catches any drafts we created, too.127 if (value !== peek(state.base_, prop)) return value128 // Store drafts on the copy (when one exists).129 // @ts-ignore130 drafts = state.copy_131 }132133 return (drafts![prop as any] = createProxy(134 state.scope_.immer_,135 value,136 state137 ))138 },139 has(state, prop) {140 return prop in latest(state)141 },142 ownKeys(state) {143 return Reflect.ownKeys(latest(state))144 },145 set(state, prop: string /* strictly not, but helps TS */, value) {146 if (!state.modified_) {147 const baseValue = peek(state.base_, prop)148 // Optimize based on value's truthiness. Truthy values are guaranteed to149 // never be undefined, so we can avoid the `in` operator. Lastly, truthy150 // values may be drafts, but falsy values are never drafts.151 const isUnchanged = value152 ? is(baseValue, value) || value === state.drafts_![prop]153 : is(baseValue, value) && prop in state.base_154 if (isUnchanged) return true155 prepareCopy(state)156 markChangedProxy(state)157 }158 state.assigned_[prop] = true159 // @ts-ignore160 state.copy_![prop] = value161 return true162 },163 deleteProperty(state, prop: string) {164 // The `undefined` check is a fast path for pre-existing keys.165 if (peek(state.base_, prop) !== undefined || prop in state.base_) {166 state.assigned_[prop] = false167 prepareCopy(state)168 markChangedProxy(state)169 } else if (state.assigned_[prop]) {170 // if an originally not assigned property was deleted171 delete state.assigned_[prop]172 }173 // @ts-ignore174 if (state.copy_) delete state.copy_[prop]175 return true176 },177 // Note: We never coerce `desc.value` into an Immer draft, because we can't make178 // the same guarantee in ES5 mode.179 getOwnPropertyDescriptor(state, prop) {180 const owner = latest(state)181 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)182 if (desc) {183 desc.writable = true184 desc.configurable =185 state.type_ !== ProxyTypeProxyArray || prop !== "length"186 }187 return desc188 },189 defineProperty() {190 die(11)191 },192 getPrototypeOf(state) {193 return Object.getPrototypeOf(state.base_)194 },195 setPrototypeOf() {196 die(12)197 }198}199200/**201 * Array drafts202 */203204const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}205each(objectTraps, (key, fn) => {206 // @ts-ignore207 arrayTraps[key] = function() {208 arguments[0] = arguments[0][0]209 return fn.apply(this, arguments)210 }211})212arrayTraps.deleteProperty = function(state, prop) {213 if (__DEV__ && isNaN(parseInt(prop as any))) die(13)214 return objectTraps.deleteProperty!.call(this, state[0], prop)215}216arrayTraps.set = function(state, prop, value) {217 if (__DEV__ && prop !== "length" && isNaN(parseInt(prop as any))) die(14)218 return objectTraps.set!.call(this, state[0], prop, value, state[0])219}220221/**222 * Map drafts223 */224225// Access a property without creating an Immer draft.226function peek(draft: Drafted, prop: PropertyKey): any {227 const state = draft[DRAFT_STATE]228 const desc = Reflect.getOwnPropertyDescriptor(229 state ? latest(state) : draft,230 prop231 )232 return desc && desc.value233}234235export function markChangedProxy(state: ImmerState) {236 if (!state.modified_) {237 state.modified_ = true238 if (239 state.type_ === ProxyTypeProxyObject ||240 state.type_ === ProxyTypeProxyArray241 ) {242 const copy = (state.copy_ = shallowCopy(state.base_))243 each(state.drafts_!, (key, value) => {244 // @ts-ignore245 copy[key] = value246 })247 state.drafts_ = undefined248 }249250 if (state.parent_) {251 markChangedProxy(state.parent_)252 }253 }254}255256function prepareCopy(state: ProxyState) {257 if (!state.copy_) {258 state.copy_ = shallowCopy(state.base_)259 }260}
deleted:src/scope.ts-68 removed
1import {Patch, PatchListener, Drafted, Immer, DRAFT_STATE} from "./internal"2import {3 ImmerState,4 ProxyTypeProxyObject,5 ProxyTypeProxyArray6} from "./types-internal"78/** Each scope represents a `produce` call. */9// TODO: non-class?10export class ImmerScope {11 static current_?: ImmerScope1213 patches_?: Patch[]14 inversePatches_?: Patch[]15 canAutoFreeze_: boolean16 drafts_: any[]17 parent_?: ImmerScope18 patchListener_?: PatchListener19 immer_: Immer20 unfinalizedDrafts_ = 02122 constructor(parent: ImmerScope | undefined, immer: Immer) {23 this.drafts_ = []24 this.parent_ = parent25 this.immer_ = immer2627 // Whenever the modified draft contains a draft from another scope, we28 // need to prevent auto-freezing so the unowned draft can be finalized.29 this.canAutoFreeze_ = true30 }3132 usePatches_(patchListener?: PatchListener) {33 if (patchListener) {34 this.patches_ = []35 this.inversePatches_ = []36 this.patchListener_ = patchListener37 }38 }3940 revoke_() {41 this.leave_()42 this.drafts_.forEach(revoke)43 // @ts-ignore44 this.drafts_ = null45 }4647 leave_() {48 if (this === ImmerScope.current_) {49 ImmerScope.current_ = this.parent_50 }51 }5253 static enter_(immer: Immer) {54 const scope = new ImmerScope(ImmerScope.current_, immer)55 ImmerScope.current_ = scope56 return scope57 }58}5960function revoke(draft: Drafted) {61 const state: ImmerState = draft[DRAFT_STATE]62 if (63 state.type_ === ProxyTypeProxyObject ||64 state.type_ === ProxyTypeProxyArray65 )66 state.revoke_()67 else state.revoked_ = true68}
deleted:src/types-external.ts-169 removed
1import {Nothing} from "./internal"23type Tail<T extends any[]> = ((...t: T) => any) extends (4 _: any,5 ...tail: infer TT6) => any7 ? TT8 : []910/** Object types that should never be mapped */11type AtomicObject =12 | Function13 | Promise<any>14 | Date15 | RegExp16 | Boolean17 | Number18 | String1920/**21 * These should also never be mapped but must be tested after regular Map and22 * Set23 */24type WeakReferences = WeakMap<any, any> | WeakSet<any>2526export type Draft<T> = T extends AtomicObject27 ? T28 : T extends ReadonlyMap<infer K, infer V> // Map extends ReadonlyMap29 ? Map<Draft<K>, Draft<V>>30 : T extends ReadonlySet<infer V> // Set extends ReadonlySet31 ? Set<Draft<V>>32 : T extends WeakReferences33 ? T34 : T extends object35 ? {-readonly [K in keyof T]: Draft<T[K]>}36 : T3738/** Convert a mutable type into a readonly type */39export type Immutable<T> = T extends AtomicObject40 ? T41 : T extends ReadonlyMap<infer K, infer V> // Map extends ReadonlyMap42 ? ReadonlyMap<Immutable<K>, Immutable<V>>43 : T extends ReadonlySet<infer V> // Set extends ReadonlySet44 ? ReadonlySet<Immutable<V>>45 : T extends WeakReferences46 ? T47 : T extends object48 ? {readonly [K in keyof T]: Immutable<T[K]>}49 : T5051export interface Patch {52 op: "replace" | "remove" | "add"53 path: (string | number)[]54 value?: any55}5657export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void5859/** Converts `nothing` into `undefined` */60type FromNothing<T> = T extends Nothing ? undefined : T6162/** The inferred return type of `produce` */63export type Produced<Base, Return> = Return extends void64 ? Base65 : Return extends Promise<infer Result>66 ? Promise<Result extends void ? Base : FromNothing<Result>>67 : FromNothing<Return>6869/**70 * The `produce` function takes a value and a "recipe function" (whose71 * return value often depends on the base state). The recipe function is72 * free to mutate its first argument however it wants. All mutations are73 * only ever applied to a __copy__ of the base state.74 *75 * Pass only a function to create a "curried producer" which relieves you76 * from passing the recipe function every time.77 *78 * Only plain objects and arrays are made mutable. All other objects are79 * considered uncopyable.80 *81 * Note: This function is __bound__ to its `Immer` instance.82 *83 * @param {any} base - the initial state84 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified85 * @param {Function} patchListener - optional function that will be called with all the patches produced here86 * @returns {any} a new state, or the initial state if nothing was modified87 */88export interface IProduce {89 /** Curried producer */90 <91 Recipe extends (...args: any[]) => any,92 Params extends any[] = Parameters<Recipe>,93 T = Params[0]94 >(95 recipe: Recipe96 ): <Base extends Immutable<T>>(97 base: Base,98 ...rest: Tail<Params>99 ) => Produced<Base, ReturnType<Recipe>>100 // ^ by making the returned type generic, the actual type of the passed in object is preferred101 // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe102 // 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!103104 /** Curried producer with initial state */105 <106 Recipe extends (...args: any[]) => any,107 Params extends any[] = Parameters<Recipe>,108 T = Params[0]109 >(110 recipe: Recipe,111 initialState: Immutable<T>112 ): <Base extends Immutable<T>>(113 base?: Base,114 ...rest: Tail<Params>115 ) => Produced<Base, ReturnType<Recipe>>116117 /** Normal producer */118 <Base, D = Draft<Base>, Return = void>(119 base: Base,120 recipe: (draft: D) => Return,121 listener?: PatchListener122 ): Produced<Base, Return>123}124125/**126 * Like `produce`, but instead of just returning the new state,127 * a tuple is returned with [nextState, patches, inversePatches]128 *129 * Like produce, this function supports currying130 */131export interface IProduceWithPatches {132 /** Curried producer */133 <134 Recipe extends (...args: any[]) => any,135 Params extends any[] = Parameters<Recipe>,136 T = Params[0]137 >(138 recipe: Recipe139 ): <Base extends Immutable<T>>(140 base: Base,141 ...rest: Tail<Params>142 ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]143 // ^ by making the returned type generic, the actual type of the passed in object is preferred144 // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe145 // 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!146147 /** Curried producer with initial state */148 <149 Recipe extends (...args: any[]) => any,150 Params extends any[] = Parameters<Recipe>,151 T = Params[0]152 >(153 recipe: Recipe,154 initialState: Immutable<T>155 ): <Base extends Immutable<T>>(156 base?: Base,157 ...rest: Tail<Params>158 ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]159160 /** Normal producer */161 <Base, D = Draft<Base>, Return = void>(162 base: Base,163 recipe: (draft: D) => Return164 ): [Produced<Base, Return>, Patch[], Patch[]]165}166167// Fixes #507: bili doesn't export the types of this file if there is no actual source in it..168// hopefully it get's tree-shaken away for everyone :)169export function never_used() {}
deleted:src/types-internal.ts-51 removed
1import {2 SetState,3 ImmerScope,4 ProxyObjectState,5 ProxyArrayState,6 ES5ObjectState,7 ES5ArrayState,8 MapState,9 DRAFT_STATE10} from "./internal"1112export type Objectish = AnyObject | AnyArray | AnyMap | AnySet13export type ObjectishNoSet = AnyObject | AnyArray | AnyMap1415export type AnyObject = {[key: string]: any}16export type AnyArray = Array<any>17export type AnySet = Set<any>18export type AnyMap = Map<any, any>1920export const ArchtypeObject = 021export const ArchtypeArray = 122export const ArchtypeMap = 223export const ArchtypeSet = 32425export const ProxyTypeProxyObject = 026export const ProxyTypeProxyArray = 127export const ProxyTypeES5Object = 428export const ProxyTypeES5Array = 529export const ProxyTypeMap = 230export const ProxyTypeSet = 33132export interface ImmerBaseState {33 parent_?: ImmerState34 scope_: ImmerScope35 modified_: boolean36 finalized_: boolean37 isManual_: boolean38}3940export type ImmerState =41 | ProxyObjectState42 | ProxyArrayState43 | ES5ObjectState44 | ES5ArrayState45 | MapState46 | SetState4748// The _internal_ type used for drafts (not to be confused with Draft, which is public facing)49export type Drafted<Base = any, T extends ImmerState = ImmerState> = {50 [DRAFT_STATE]: T51} & Base
modified:notes.txt+1 added-1 removed
112 unmodified lines
113add draft optimization1143199115116invariant11732061173094
modified:package.json+1 added-1 removed
19 unmodified lines
20 "watch": "jest --watch",21 "coverage": "jest --coverage",22 "coveralls": "jest --coverage && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls && rm -rf ./coverage",23 "build": "rimraf dist/ && tsdx build --name immer --format esm,cjs,umd && yarn build:flow",24 "build:flow": "cpx 'src/immer.js.flow' dist -v",24 "build:flow": "cpx 'src/types/immer.js.flow' dist -v",25 "publish-docs": "cd website && GIT_USER=mweststrate USE_SSH=true yarn run publish-gh-pages",26 "start": "cd website && yarn start",27 "test:size": "yarn build && yarn import-size --report . produce enableES5 enableMapSet enablePatches"28 },
57 unmodified lines
modified:tsconfig.json+1 added-1 removed
13 unmodified lines
14 "moduleResolution": "node",15 "module": "esnext",16 "allowJs": true17 },18 "files": ["./src/immer.ts", "./src/plugins/es5.ts", "./src/plugins/mapset.ts", "./src/plugins/patches.ts", "./src/globals.d.ts"]18 "files": ["./src/immer.ts", "./src/plugins/es5.ts", "./src/plugins/mapset.ts", "./src/plugins/patches.ts", "src/types/globals.d.ts"]19}