Skip to content
Myr

proxy.ts

This file

Path

src/core/proxy.ts

359 lines · 10.1 KiB · TypeScript

Last changed by

fix: draft relocated base refs after reverse/sort in array-methods plugin (#1255)spokodevbefore adoptiona73672a

History of this file

Take it

The walk stopped after 200 commits: lines older than 607b994 point at it.

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 1–13why, one step back
1import {
2 has,3 is,4 isDraftable,5 shallowCopy,6 latest,7 ImmerBaseState,8 ImmerState,9 Drafted,10 AnyObject,11 AnyArray,12 Objectish,13 getCurrentScope,

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 14why, one step back
14 getPrototypeOf,

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 15–17why, one step back
15 DRAFT_STATE,
16 die,17 createProxy,

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 18why, one step back
18 ArchType,

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 19–23why, one step back
19 handleCrossReference,
20 WRITABLE,21 CONFIGURABLE,22 ENUMERABLE,23 VALUE,

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 24–25why, one step back
24 isArray,
25 isArrayIndex

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 26–33why, one step back
26} from "../internal"
2728interface ProxyBaseState extends ImmerBaseState {29 parent_?: ImmerState30 revoke_(): void31}3233export interface ProxyObjectState extends ProxyBaseState {

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 34why, one step back
34 type_: ArchType.Object

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 35–40why, one step back
35 base_: any
36 copy_: any37 draft_: Drafted<AnyObject, ProxyObjectState>38}3940export interface ProxyArrayState extends ProxyBaseState {

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 41why, one step back
41 type_: ArchType.Array

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 42–44why, one step back
42 base_: AnyArray
43 copy_: AnyArray | null44 draft_: Drafted<AnyArray, ProxyArrayState>

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 45–46why, one step back
45 operationMethod?: string
46 allIndicesReassigned_?: boolean

fix: draft relocated base refs after reverse/sort in array-methods plugin (#1255)spokodevbefore adoptiona73672a

line 47why, one step back
47 baseRefs_?: Set<any>

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 48–59why, one step back
48}
4950type ProxyState = ProxyObjectState | ProxyArrayState5152/**53 * Returns a new draft of the `base` object.54 *55 * The second argument is the parent draft-state (used internally).56 */57export function createProxyProxy<T extends Objectish>(58 base: T,59 parent?: ImmerState

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 60–61why, one step back
60): [Drafted<T, ProxyState>, ProxyState] {
61 const baseIsArray = isArray(base)

chore: added unit test for #897Michel Weststratebefore adoption607b994

line 62why, one step back
62 const state: ProxyState = {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 63why, one step back
63 type_: baseIsArray ? ArchType.Array : (ArchType.Object as any),

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 64–70why, one step back
64 // Track which produce call this is associated with.
65 scope_: parent ? parent.scope_ : getCurrentScope()!,66 // True for both shallow and deep changes.67 modified_: false,68 // Used during finalization.69 finalized_: false,70 // Track which properties have been assigned (true) or deleted (false).

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 71–72why, one step back
71 // actually instantiated in `prepareCopy()`
72 assigned_: undefined,

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 73–82why, one step back
73 // The parent draft state.
74 parent_: parent,75 // The base state.76 base_: base,77 // The base proxy.78 draft_: null as any, // set below79 // The base copy with any updated values.80 copy_: null,81 // Called by the `produce` function.82 revoke_: null as any,

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 83–85why, one step back
83 isManual_: false,
84 // `callbacks` actually gets assigned in `createProxy`85 callbacks_: undefined as any

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 86–95why, one step back
86 }
8788 // the traps must target something, a bit like the 'real' base.89 // but also, we need to be able to determine from the target what the relevant state is90 // (to avoid creating traps per instance to capture the state in closure,91 // and to avoid creating weird hidden properties as well)92 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)93 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb94 let target: T = state as any95 let traps: ProxyHandler<object | Array<any>> = objectTraps

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 96why, one step back
96 if (baseIsArray) {

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 97–103why, one step back
97 target = [state] as any
98 traps = arrayTraps99 }100101 const {revoke, proxy} = Proxy.revocable(target, traps)102 state.draft_ = proxy as any103 state.revoke_ = revoke

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 104why, one step back
104 return [proxy as any, state]

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 105–113why, one step back
105}
106107/**108 * Object drafts109 */110export const objectTraps: ProxyHandler<ProxyState> = {111 get(state, prop) {112 if (prop === DRAFT_STATE) return state113

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 114–124why, one step back
114 let arrayPlugin = state.scope_.arrayMethodsPlugin_
115 const isArrayWithStringProp =116 state.type_ === ArchType.Array && typeof prop === "string"117 // Intercept array methods so that we can override118 // behavior and skip proxy creation for perf119 if (isArrayWithStringProp) {120 if (arrayPlugin?.isArrayOperationMethod(prop)) {121 return arrayPlugin.createMethodInterceptor(state, prop)122 }123 }124

chore: added unit test for #897Michel Weststratebefore adoption607b994

line 125why, one step back
125 const source = latest(state)

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 126why, one step back
126 if (!has(source, prop, state.type_)) {

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 127–131why, one step back
127 // non-existing or non-own property...
128 return readPropFromProto(state, source, prop)129 }130 const value = source[prop]131 if (state.finalized_ || !isDraftable(value)) {

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 132–145why, one step back
132 return value
133 }134135 // During mutating array operations, defer proxy creation for array elements136 // This optimization avoids creating unnecessary proxies during sort/reverse137 if (138 isArrayWithStringProp &&139 (state as ProxyArrayState).operationMethod &&140 arrayPlugin?.isMutatingArrayMethod(141 (state as ProxyArrayState).operationMethod!142 ) &&143 isArrayIndex(prop)144 ) {145 // Return raw value during mutating operations, create proxy only if modified

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 146–149why, one step back
146 return value
147 }148 // Check for existing draft in modified state.149 // Assigned values are never drafted. This catches any drafts we created, too.

fix: draft relocated base refs after reverse/sort in array-methods plugin (#1255)spokodevbefore adoptiona73672a

lines 150–153why, one step back
150 if (
151 value === peek(state.base_, prop) ||152 isRelocatedBaseRef(state, prop, value)153 ) {

chore: added unit test for #897Michel Weststratebefore adoption607b994

line 154why, one step back
154 prepareCopy(state)

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 155–159why, one step back
155 // Ensure array keys are always numbers
156 const childKey = state.type_ === ArchType.Array ? +(prop as string) : prop157 const childDraft = createProxy(state.scope_, value, state, childKey)158159 return (state.copy_![childKey] = childDraft)

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 160–188why, one step back
160 }
161 return value162 },163 has(state, prop) {164 return prop in latest(state)165 },166 ownKeys(state) {167 return Reflect.ownKeys(latest(state))168 },169 set(170 state: ProxyObjectState,171 prop: string /* strictly not, but helps TS */,172 value173 ) {174 const desc = getDescriptorFromProto(latest(state), prop)175 if (desc?.set) {176 // special case: if this write is captured by a setter, we have177 // to trigger it with the correct context178 desc.set.call(state.draft_, value)179 return true180 }181 if (!state.modified_) {182 // the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)183 // from setting an existing property with value undefined to undefined (which is not a change)184 const current = peek(latest(state), prop)185 // special case, if we assigning the original value to a draft, we can ignore the assignment186 const currentState: ProxyObjectState = current?.[DRAFT_STATE]187 if (currentState && currentState.base_ === value) {188 state.copy_![prop] = value

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 189why, one step back
189 state.assigned_!.set(prop, false)

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 190–191why, one step back
190 return true
191 }

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 192–195why, one step back
192 if (
193 is(value, current) &&194 (value !== undefined || has(state.base_, prop, state.type_))195 )

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 196–201why, one step back
196 return true
197 prepareCopy(state)198 markChanged(state)199 }200201 if (

fix: special case NaN in setter (#912)Raybefore adoption5721bb7

lines 202–203why, one step back
202 (state.copy_![prop] === value &&
203 // special case: handle new props with value 'undefined'

fix: undefined assigned to a prototype-inherited key gets dropped (#1262)Alexander Kireyevbefore adoption16e225b

line 204why, one step back
204 (value !== undefined || has(state.copy_, prop, state.type_))) ||

chore: added unit test for #897Michel Weststratebefore adoption607b994

line 205why, one step back
205 // special case: NaN

fix: special case NaN in setter (#912)Raybefore adoption5721bb7

line 206why, one step back
206 (Number.isNaN(value) && Number.isNaN(state.copy_![prop]))

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 207–211why, one step back
207 )
208 return true209210 // @ts-ignore211 state.copy_![prop] = value

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 212–214why, one step back
212 state.assigned_!.set(prop, true)
213214 handleCrossReference(state, prop, value)

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 215–217why, one step back
215 return true
216 },217 deleteProperty(state, prop: string) {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 218why, one step back
218 prepareCopy(state)

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 219–220why, one step back
219 // The `undefined` check is a fast path for pre-existing keys.
220 if (peek(state.base_, prop) !== undefined || prop in state.base_) {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 221why, one step back
221 state.assigned_!.set(prop, false)

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 222–224why, one step back
222 markChanged(state)
223 } else {224 // if an originally not assigned property was deleted

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 225why, one step back
225 state.assigned_!.delete(prop)

chore: added unit test for #897Michel Weststratebefore adoption607b994

line 226why, one step back
226 }

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

lines 227–229why, one step back
227 if (state.copy_) {
228 delete state.copy_[prop]229 }

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 230–238why, one step back
230 return true
231 },232 // Note: We never coerce `desc.value` into an Immer draft, because we can't make233 // the same guarantee in ES5 mode.234 getOwnPropertyDescriptor(state, prop) {235 const owner = latest(state)236 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)237 if (!desc) return desc238 return {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 239–242why, one step back
239 [WRITABLE]: true,
240 [CONFIGURABLE]: state.type_ !== ArchType.Array || prop !== "length",241 [ENUMERABLE]: desc[ENUMERABLE],242 [VALUE]: owner[prop]

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 243–248why, one step back
243 }
244 },245 defineProperty() {246 die(11)247 },248 getPrototypeOf(state) {

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 249why, one step back
249 return getPrototypeOf(state.base_)

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 250–260why, one step back
250 },
251 setPrototypeOf() {252 die(12)253 }254}255256/**257 * Array drafts258 */259260const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}

fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)Mark Eriksonbefore adoptionb208d58

lines 261–264why, one step back
261// Use `for..in` instead of `each` to work around a weird
262// prod test suite issue263for (let key in objectTraps) {264 let fn = objectTraps[key as keyof typeof objectTraps] as Function

chore: added unit test for #897Michel Weststratebefore adoption607b994

line 265why, one step back
265 // @ts-ignore

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

line 266why, one step back
266 arrayTraps[key] = function () {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 267–269why, one step back
267 const args = arguments
268 args[0] = args[0][0]269 return fn.apply(this, args)

chore: added unit test for #897Michel Weststratebefore adoption607b994

line 270why, one step back
270 }

fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)Mark Eriksonbefore adoptionb208d58

line 271why, one step back
271}

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

line 272why, one step back
272arrayTraps.deleteProperty = function (state, prop) {

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

lines 273–274why, one step back
273 if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop as any)))
274 die(13)

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 275–277why, one step back
275 // @ts-ignore
276 return arrayTraps.set!.call(this, state, prop, undefined)277}

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

line 278why, one step back
278arrayTraps.set = function (state, prop, value) {

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

lines 279–284why, one step back
279 if (
280 process.env.NODE_ENV !== "production" &&281 prop !== "length" &&282 isNaN(parseInt(prop as any))283 )284 die(14)

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 285–292why, one step back
285 return objectTraps.set!.call(this, state[0], prop, value, state[0])
286}287288// Access a property without creating an Immer draft.289function peek(draft: Drafted, prop: PropertyKey) {290 const state = draft[DRAFT_STATE]291 const source = state ? latest(state) : draft292 return source[prop]

fix: draft relocated base refs after reverse/sort in array-methods plugin (#1255)spokodevbefore adoptiona73672a

lines 293–311why, one step back
293}
294295// Reordering array methods (reverse, sort) from the array-methods plugin run296// natively on `copy_`, which still holds raw base references. This relocates an297// un-drafted base object to a position where it no longer matches `base_[prop]`,298// so the normal positional check above misses it and the get trap would hand back299// the raw base object, breaking the guarantee that the base state is never mutated.300// Detect such a relocated base reference so it is drafted before being exposed.301function isRelocatedBaseRef(state: ImmerState, prop: PropertyKey, value: any) {302 if (303 state.type_ !== ArchType.Array ||304 !(state as ProxyArrayState).allIndicesReassigned_ ||305 state.assigned_?.get(prop) ||306 !isDraftable(value) ||307 value[DRAFT_STATE]308 ) {309 return false310 }311 return (state as ProxyArrayState).baseRefs_!.has(value)

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 312–316why, one step back
312}
313314function readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {315 const desc = getDescriptorFromProto(source, prop)316 return desc

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 317–318why, one step back
317 ? VALUE in desc
318 ? desc[VALUE]

chore: added unit test for #897Michel Weststratebefore adoption607b994

line 319why, one step back
319 : // This is a very special case, if the prop is a getter defined by the

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

lines 320–321why, one step back
320 // prototype, we should invoke it with the draft as context!
321 desc.get?.call(state.draft_)

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 322–330why, one step back
322 : undefined
323}324325function getDescriptorFromProto(326 source: any,327 prop: PropertyKey328): PropertyDescriptor | undefined {329 // 'in' checks proto!330 if (!(prop in source)) return undefined

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 331why, one step back
331 let proto = getPrototypeOf(source)

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 332–334why, one step back
332 while (proto) {
333 const desc = Object.getOwnPropertyDescriptor(proto, prop)334 if (desc) return desc

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 335why, one step back
335 proto = getPrototypeOf(proto)

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 336–348why, one step back
336 }
337 return undefined338}339340export function markChanged(state: ImmerState) {341 if (!state.modified_) {342 state.modified_ = true343 if (state.parent_) {344 markChanged(state.parent_)345 }346 }347}348

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

line 349why, one step back
349export function prepareCopy(state: ImmerState) {

chore: added unit test for #897Michel Weststratebefore adoption607b994

line 350why, one step back
350 if (!state.copy_) {

perf: Rewrite finalization system to use a callback approach instead of tree traversal (#1183)Mark Eriksonbefore adoptiond6c1202

lines 351–353why, one step back
351 // Actually create the `assigned_` map now that we
352 // know this is a modified draft.353 state.assigned_ = new Map()

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

lines 354–357why, one step back
354 state.copy_ = shallowCopy(
355 state.base_,356 state.scope_.immer_.useStrictShallowCopy_357 )

chore: added unit test for #897Michel Weststratebefore adoption607b994

lines 358–359why, one step back
358 }
359}