Skip to content
Myr

proxy.ts

This file

Path

src/proxy.ts

301 lines · 7.9 KiB · TypeScript

Last changed by

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

History of this file

Take it

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 1–16why, one step back
1"use strict"
2import {3 assign,4 each,5 has,6 is,7 isDraftable,8 isDraft,9 isMap,10 isSet,11 hasSymbol,12 shallowCopy,13 DRAFT_STATE,14 assignMap,15 assignSet,16 original,

map unification WIPMichel Weststratebefore adoption9bcefb6

line 17why, one step back
17 latest

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 18–19why, one step back
18} from "./common"
19import {ImmerScope} from "./scope"

some build fixesMichel Weststratebefore adoption65a377f

lines 20–21why, one step back
20import {proxyMap} from "./map"
21import {proxySet} from "./set"

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 22why, one step back
22import {AnyObject, Drafted, ImmerState, AnyArray} from "./types"

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 23why, one step back
23

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 24why, one step back
24interface ProxyBaseState {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 25–27why, one step back
25 scope: ImmerScope
26 modified: boolean27 finalized: boolean

Introduced proper state typesMichel Weststratebefore adoption3842f85

lines 28–34why, one step back
28 assigned: {
29 [property: string]: boolean30 }31 parent: ImmerState32 drafts: {33 [property: string]: Drafted<any, any>34 }

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 35–37why, one step back
35 revoke: null | (() => void)
36}37

Introduced proper state typesMichel Weststratebefore adoption3842f85

lines 38–51why, one step back
38export interface ProxyObjectState extends ProxyBaseState {
39 type: "proxy_object"40 base: AnyObject41 copy: AnyObject | null42 draft: Drafted<AnyObject, ProxyObjectState>43}4445export interface ProxyArrayState extends ProxyBaseState {46 type: "proxy_array"47 base: AnyArray48 copy: AnyArray | null49 draft: Drafted<AnyArray, ProxyArrayState>50}51

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 52–58why, one step back
52/**
53 * Returns a new draft of the `base` object.54 *55 * The second argument is the parent draft-state (used internally).56 */57export function createProxy<T extends object>(58 base: T,

Introduced proper state typesMichel Weststratebefore adoption3842f85

lines 59–61why, one step back
59 parent: ProxyObjectState | ProxyArrayState
60): Drafted<T, ProxyObjectState | ProxyArrayState> {61 // TODO: extract create proxy and refine

fixed most testsMichel Weststratebefore adoption385c0a4

lines 62–67why, one step back
62 // TODO: dedupe
63 if (!base || typeof base !== "object" || !isDraftable(base)) {64 // TODO: || isDraft ?65 return base as any // TODO: fix66 }67

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 68why, one step back
68 const scope = parent ? parent.scope : ImmerScope.current!

basic map tests succeedingMichel Weststratebefore adoption735c402

line 69why, one step back
69

fixed most testsMichel Weststratebefore adoption385c0a4

line 70why, one step back
70 // TODO: dedupe this, it is the same for ES5

basic map tests succeedingMichel Weststratebefore adoption735c402

lines 71–72why, one step back
71 if (isMap(base)) {
72 const draft = proxyMap(base, parent) as any // TODO: typefix

some build fixesMichel Weststratebefore adoption65a377f

lines 73–74why, one step back
73 scope.drafts.push(draft)
74 return draft

basic map tests succeedingMichel Weststratebefore adoption735c402

line 75why, one step back
75 }

fixed most testsMichel Weststratebefore adoption385c0a4

lines 76–77why, one step back
76 if (isSet(base)) {
77 const draft = proxySet(base, parent) as any // TODO: typefix

some build fixesMichel Weststratebefore adoption65a377f

lines 78–79why, one step back
78 scope.drafts.push(draft)
79 return draft

fixed most testsMichel Weststratebefore adoption385c0a4

line 80why, one step back
80 }

basic map tests succeedingMichel Weststratebefore adoption735c402

line 81why, one step back
81

Introduced proper state typesMichel Weststratebefore adoption3842f85

lines 82–84why, one step back
82 const isArray = Array.isArray(base)
83 const state: ProxyObjectState | ProxyArrayState = {84 type: isArray ? "proxy_array" : ("proxy_object" as any),

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 85–97why, one step back
85 // Track which produce call this is associated with.
86 scope,87 // True for both shallow and deep changes.88 modified: false,89 // Used during finalization.90 finalized: false,91 // Track which properties have been assigned (true) or deleted (false).92 assigned: {},93 // The parent draft state.94 parent,95 // The base state.96 base,97 // The base proxy.

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 98why, one step back
98 draft: null as any, // set below

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 99–118why, one step back
99 // Any property proxies.
100 drafts: {},101 // The base copy with any updated values.102 copy: null,103 // Called by the `produce` function.104 revoke: null105 }106107 // the traps must target something, a bit like the 'real' base.108 // but also, we need to be able to determine from the target what the relevant state is109 // (to avoid creating traps per instance to capture the state in closure,110 // and to avoid creating weird hidden properties as well)111 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)112 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb113 let target: T = state as any114 let traps: ProxyHandler<object | Array<any>> = objectTraps115 if (Array.isArray(base)) {116 target = [state] as any117 traps = arrayTraps118 }

basic map tests succeedingMichel Weststratebefore adoption735c402

line 119why, one step back
119

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 120–121why, one step back
120 const {revoke, proxy} = Proxy.revocable(target, traps)
121

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 122why, one step back
122 state.draft = proxy as any

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 123–125why, one step back
123 state.revoke = revoke
124125 scope.drafts!.push(proxy)

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 126why, one step back
126 return proxy as any

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 127–131why, one step back
127}
128129/**130 * Object drafts131 */

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 132why, one step back
132const objectTraps: ProxyHandler<ProxyObjectState | ProxyArrayState> = {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 133–138why, one step back
133 get(state, prop) {
134 if (prop === DRAFT_STATE) return state135 let {drafts} = state136137 // Check for existing draft in unmodified state.138 if (!state.modified && has(drafts, prop)) {

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 139why, one step back
139 return drafts[prop as any]

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 140–151why, one step back
140 }
141142 const value = latest(state)[prop]143 if (state.finalized || !isDraftable(value)) {144 return value145 }146147 // Check for existing draft in modified state.148 if (state.modified) {149 // Assigned values are never drafted. This catches any drafts we created, too.150 if (value !== peek(state.base, prop)) return value151 // Store drafts on the copy (when one exists).

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 152why, one step back
152 // @ts-ignore TODO: this line seems of?

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 153–155why, one step back
153 drafts = state.copy
154 }155

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 156why, one step back
156 return (drafts[prop as any] = createProxy(value, state))

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 157–163why, one step back
157 },
158 has(state, prop) {159 return prop in latest(state)160 },161 ownKeys(state) {162 return Reflect.ownKeys(latest(state))163 },

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 164why, one step back
164 set(state, prop: string /* strictly not, but helps TS */, value) {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 165–173why, one step back
165 if (!state.modified) {
166 const baseValue = peek(state.base, prop)167 // Optimize based on value's truthiness. Truthy values are guaranteed to168 // never be undefined, so we can avoid the `in` operator. Lastly, truthy169 // values may be drafts, but falsy values are never drafts.170 const isUnchanged = value171 ? is(baseValue, value) || value === state.drafts[prop]172 : is(baseValue, value) && prop in state.base173 if (isUnchanged) return true

basic map tests succeedingMichel Weststratebefore adoption735c402

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 175–177why, one step back
175 markChanged(state)
176 }177 state.assigned[prop] = true

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 178why, one step back
178 state.copy![prop] = value

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 179–180why, one step back
179 return true
180 },

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 181why, one step back
181 deleteProperty(state, prop: string) {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 182–184why, one step back
182 // The `undefined` check is a fast path for pre-existing keys.
183 if (peek(state.base, prop) !== undefined || prop in state.base) {184 state.assigned[prop] = false

basic map tests succeedingMichel Weststratebefore adoption735c402

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 186–219why, one step back
186 markChanged(state)
187 } else if (state.assigned[prop]) {188 // if an originally not assigned property was deleted189 delete state.assigned[prop]190 }191 if (state.copy) delete state.copy[prop]192 return true193 },194 // Note: We never coerce `desc.value` into an Immer draft, because we can't make195 // the same guarantee in ES5 mode.196 getOwnPropertyDescriptor(state, prop) {197 const owner = latest(state)198 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)199 if (desc) {200 desc.writable = true201 desc.configurable = !Array.isArray(owner) || prop !== "length"202 }203 return desc204 },205 defineProperty() {206 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore207 },208 getPrototypeOf(state) {209 return Object.getPrototypeOf(state.base)210 },211 setPrototypeOf() {212 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore213 }214}215216/**217 * Array drafts218 */219

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 220why, one step back
220const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 221–266why, one step back
221each(objectTraps, (key, fn) => {
222 arrayTraps[key] = function() {223 arguments[0] = arguments[0][0]224 return fn.apply(this, arguments)225 }226})227arrayTraps.deleteProperty = function(state, prop) {228 if (isNaN(parseInt(prop as any))) {229 throw new Error("Immer only supports deleting array indices") // prettier-ignore230 }231 return objectTraps.deleteProperty!.call(this, state[0], prop)232}233arrayTraps.set = function(state, prop, value) {234 if (prop !== "length" && isNaN(parseInt(prop as any))) {235 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore236 }237 return objectTraps.set!.call(this, state[0], prop, value, state[0])238}239240// Used by Map and Set drafts241const reflectTraps = makeReflectTraps([242 "ownKeys",243 "has",244 "set",245 "deleteProperty",246 "defineProperty",247 "getOwnPropertyDescriptor",248 "preventExtensions",249 "isExtensible",250 "getPrototypeOf"251])252253/**254 * Map drafts255 */256257// Access a property without creating an Immer draft.258function peek(draft, prop) {259 const state = draft[DRAFT_STATE]260 const desc = Reflect.getOwnPropertyDescriptor(261 state ? latest(state) : draft,262 prop263 )264 return desc && desc.value265}266

basic map tests succeedingMichel Weststratebefore adoption735c402

lines 267–268why, one step back
267// TODO: unify with ES5 version, by getting rid of the drafts vs copy distinction?
268export function markChanged(state) {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 269–271why, one step back
269 if (!state.modified) {
270 state.modified = true271 const {base, drafts, parent} = state

basic map tests succeedingMichel Weststratebefore adoption735c402

lines 272–273why, one step back
272 if (!isMap(base) && !isSet(base)) {
273 // TODO: drop creating copies here?

some build fixesMichel Weststratebefore adoption65a377f

line 274why, one step back
274 const copy = (state.copy = shallowCopy(base))

basic map tests succeedingMichel Weststratebefore adoption735c402

line 275why, one step back
275 assign(copy, drafts)

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 276–281why, one step back
276 state.drafts = null
277 }278279 if (parent) {280 markChanged(parent)281 }

basic map tests succeedingMichel Weststratebefore adoption735c402

lines 282–288why, one step back
282 }
283}284285// TODO: unify with ES5 version286function prepareCopy(state) {287 if (!state.copy) {288 state.copy = shallowCopy(state.base)

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 289–295why, one step back
289 }
290}291292/** Create traps that all use the `Reflect` API on the `latest(state)` */293function makeReflectTraps<T extends object>(294 names: (keyof typeof Reflect)[]295): ProxyHandler<T> {

Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53

lines 296–300why, one step back
296 return names.reduce((traps, name) => {
297 // @ts-ignore298 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)299 return traps300 }, {} as any)

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 301why, one step back
301}