Skip to content
Myr

proxy.ts

This file

Path

src/proxy.ts

307 lines · 8.0 KiB · TypeScript

Last changed by

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

lines 23–26why, one step back
23
24// Do nothing before being finalized.25export function willFinalize() {}26

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 27why, one step back
27interface ProxyBaseState {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 28–30why, one step back
28 scope: ImmerScope
29 modified: boolean30 finalized: boolean

Introduced proper state typesMichel Weststratebefore adoption3842f85

lines 31–37why, one step back
31 assigned: {
32 [property: string]: boolean33 }34 parent: ImmerState35 drafts: {36 [property: string]: Drafted<any, any>37 }

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 38–40why, one step back
38 revoke: null | (() => void)
39}40

Introduced proper state typesMichel Weststratebefore adoption3842f85

lines 41–54why, one step back
41export interface ProxyObjectState extends ProxyBaseState {
42 type: "proxy_object"43 base: AnyObject44 copy: AnyObject | null45 draft: Drafted<AnyObject, ProxyObjectState>46}4748export interface ProxyArrayState extends ProxyBaseState {49 type: "proxy_array"50 base: AnyArray51 copy: AnyArray | null52 draft: Drafted<AnyArray, ProxyArrayState>53}54

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

fixed most testsMichel Weststratebefore adoption385c0a4

lines 65–70why, one step back
65 // TODO: dedupe
66 if (!base || typeof base !== "object" || !isDraftable(base)) {67 // TODO: || isDraft ?68 return base as any // TODO: fix69 }70

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

basic map tests succeedingMichel Weststratebefore adoption735c402

line 72why, one step back
72

fixed most testsMichel Weststratebefore adoption385c0a4

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

basic map tests succeedingMichel Weststratebefore adoption735c402

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

some build fixesMichel Weststratebefore adoption65a377f

lines 76–77why, one step back
76 scope.drafts.push(draft)
77 return draft

basic map tests succeedingMichel Weststratebefore adoption735c402

line 78why, one step back
78 }

fixed most testsMichel Weststratebefore adoption385c0a4

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

some build fixesMichel Weststratebefore adoption65a377f

lines 81–82why, one step back
81 scope.drafts.push(draft)
82 return draft

fixed most testsMichel Weststratebefore adoption385c0a4

line 83why, one step back
83 }

basic map tests succeedingMichel Weststratebefore adoption735c402

line 84why, one step back
84

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 102–121why, one step back
102 // Any property proxies.
103 drafts: {},104 // The base copy with any updated values.105 copy: null,106 // Called by the `produce` function.107 revoke: null108 }109110 // the traps must target something, a bit like the 'real' base.111 // but also, we need to be able to determine from the target what the relevant state is112 // (to avoid creating traps per instance to capture the state in closure,113 // and to avoid creating weird hidden properties as well)114 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)115 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb116 let target: T = state as any117 let traps: ProxyHandler<object | Array<any>> = objectTraps118 if (Array.isArray(base)) {119 target = [state] as any120 traps = arrayTraps121 }

basic map tests succeedingMichel Weststratebefore adoption735c402

line 122why, one step back
122

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 126–128why, one step back
126 state.revoke = revoke
127128 scope.drafts!.push(proxy)

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 130–134why, one step back
130}
131132/**133 * Object drafts134 */

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 136–141why, one step back
136 get(state, prop) {
137 if (prop === DRAFT_STATE) return state138 let {drafts} = state139140 // Check for existing draft in unmodified state.141 if (!state.modified && has(drafts, prop)) {

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 143–154why, one step back
143 }
144145 const value = latest(state)[prop]146 if (state.finalized || !isDraftable(value)) {147 return value148 }149150 // Check for existing draft in modified state.151 if (state.modified) {152 // Assigned values are never drafted. This catches any drafts we created, too.153 if (value !== peek(state.base, prop)) return value154 // Store drafts on the copy (when one exists).

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 156–158why, one step back
156 drafts = state.copy
157 }158

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 168–176why, one step back
168 if (!state.modified) {
169 const baseValue = peek(state.base, prop)170 // Optimize based on value's truthiness. Truthy values are guaranteed to171 // never be undefined, so we can avoid the `in` operator. Lastly, truthy172 // values may be drafts, but falsy values are never drafts.173 const isUnchanged = value174 ? is(baseValue, value) || value === state.drafts[prop]175 : is(baseValue, value) && prop in state.base176 if (isUnchanged) return true

basic map tests succeedingMichel Weststratebefore adoption735c402

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 178–180why, one step back
178 markChanged(state)
179 }180 state.assigned[prop] = true

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 182–183why, one step back
182 return true
183 },

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

basic map tests succeedingMichel Weststratebefore adoption735c402

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 189–222why, one step back
189 markChanged(state)
190 } else if (state.assigned[prop]) {191 // if an originally not assigned property was deleted192 delete state.assigned[prop]193 }194 if (state.copy) delete state.copy[prop]195 return true196 },197 // Note: We never coerce `desc.value` into an Immer draft, because we can't make198 // the same guarantee in ES5 mode.199 getOwnPropertyDescriptor(state, prop) {200 const owner = latest(state)201 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)202 if (desc) {203 desc.writable = true204 desc.configurable = !Array.isArray(owner) || prop !== "length"205 }206 return desc207 },208 defineProperty() {209 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore210 },211 getPrototypeOf(state) {212 return Object.getPrototypeOf(state.base)213 },214 setPrototypeOf() {215 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore216 }217}218219/**220 * Array drafts221 */222

Introduced proper state typesMichel Weststratebefore adoption3842f85

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 224–269why, one step back
224each(objectTraps, (key, fn) => {
225 arrayTraps[key] = function() {226 arguments[0] = arguments[0][0]227 return fn.apply(this, arguments)228 }229})230arrayTraps.deleteProperty = function(state, prop) {231 if (isNaN(parseInt(prop as any))) {232 throw new Error("Immer only supports deleting array indices") // prettier-ignore233 }234 return objectTraps.deleteProperty!.call(this, state[0], prop)235}236arrayTraps.set = function(state, prop, value) {237 if (prop !== "length" && isNaN(parseInt(prop as any))) {238 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore239 }240 return objectTraps.set!.call(this, state[0], prop, value, state[0])241}242243// Used by Map and Set drafts244const reflectTraps = makeReflectTraps([245 "ownKeys",246 "has",247 "set",248 "deleteProperty",249 "defineProperty",250 "getOwnPropertyDescriptor",251 "preventExtensions",252 "isExtensible",253 "getPrototypeOf"254])255256/**257 * Map drafts258 */259260// Access a property without creating an Immer draft.261function peek(draft, prop) {262 const state = draft[DRAFT_STATE]263 const desc = Reflect.getOwnPropertyDescriptor(264 state ? latest(state) : draft,265 prop266 )267 return desc && desc.value268}269

basic map tests succeedingMichel Weststratebefore adoption735c402

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 272–274why, one step back
272 if (!state.modified) {
273 state.modified = true274 const {base, drafts, parent} = state

basic map tests succeedingMichel Weststratebefore adoption735c402

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

some build fixesMichel Weststratebefore adoption65a377f

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

basic map tests succeedingMichel Weststratebefore adoption735c402

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 279–284why, one step back
279 state.drafts = null
280 }281282 if (parent) {283 markChanged(parent)284 }

basic map tests succeedingMichel Weststratebefore adoption735c402

lines 285–291why, one step back
285 }
286}287288// TODO: unify with ES5 version289function prepareCopy(state) {290 if (!state.copy) {291 state.copy = shallowCopy(state.base)

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 292–307why, one step back
292 }
293}294295/** Create traps that all use the `Reflect` API on the `latest(state)` */296function makeReflectTraps<T extends object>(297 names: (keyof typeof Reflect)[]298): ProxyHandler<T> {299 return names.reduce(300 (traps, name) => {301 // @ts-ignore302 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)303 return traps304 },305 {} as any306 )307}