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 fileTake it
Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 1–16why, one step back1"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 back17 latestMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 18–19why, one step back18} from "./common"19import {ImmerScope} from "./scope"some build fixesMichel Weststratebefore adoption65a377f
lines 20–21why, one step back20import {proxyMap} from "./map"21import {proxySet} from "./set"Introduced proper state typesMichel Weststratebefore adoption3842f85
line 22why, one step back22import {AnyObject, Drafted, ImmerState, AnyArray} from "./types"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 23why, one step back23Introduced proper state typesMichel Weststratebefore adoption3842f85
line 24why, one step back24interface ProxyBaseState {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 25–27why, one step back25 scope: ImmerScope26 modified: boolean27 finalized: booleanIntroduced proper state typesMichel Weststratebefore adoption3842f85
lines 28–34why, one step back28 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 back35 revoke: null | (() => void)36}37Introduced proper state typesMichel Weststratebefore adoption3842f85
lines 38–51why, one step back38export 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}51Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 52–58why, one step back52/**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 back59 parent: ProxyObjectState | ProxyArrayState60): Drafted<T, ProxyObjectState | ProxyArrayState> {61 // TODO: extract create proxy and refinefixed most testsMichel Weststratebefore adoption385c0a4
lines 62–67why, one step back62 // TODO: dedupe63 if (!base || typeof base !== "object" || !isDraftable(base)) {64 // TODO: || isDraft ?65 return base as any // TODO: fix66 }67Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 68why, one step back68 const scope = parent ? parent.scope : ImmerScope.current!basic map tests succeedingMichel Weststratebefore adoption735c402
line 69why, one step back69fixed most testsMichel Weststratebefore adoption385c0a4
line 70why, one step back70 // TODO: dedupe this, it is the same for ES5basic map tests succeedingMichel Weststratebefore adoption735c402
lines 71–72why, one step back71 if (isMap(base)) {72 const draft = proxyMap(base, parent) as any // TODO: typefixsome build fixesMichel Weststratebefore adoption65a377f
lines 73–74why, one step back73 scope.drafts.push(draft)74 return draftbasic map tests succeedingMichel Weststratebefore adoption735c402
line 75why, one step back75 }fixed most testsMichel Weststratebefore adoption385c0a4
lines 76–77why, one step back76 if (isSet(base)) {77 const draft = proxySet(base, parent) as any // TODO: typefixsome build fixesMichel Weststratebefore adoption65a377f
lines 78–79why, one step back78 scope.drafts.push(draft)79 return draftfixed most testsMichel Weststratebefore adoption385c0a4
line 80why, one step back80 }basic map tests succeedingMichel Weststratebefore adoption735c402
line 81why, one step back81Introduced proper state typesMichel Weststratebefore adoption3842f85
lines 82–84why, one step back82 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 back85 // 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 back98 draft: null as any, // set belowMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 99–118why, one step back99 // 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 back119Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 120–121why, one step back120 const {revoke, proxy} = Proxy.revocable(target, traps)121Introduced proper state typesMichel Weststratebefore adoption3842f85
line 122why, one step back122 state.draft = proxy as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 123–125why, one step back123 state.revoke = revoke124125 scope.drafts!.push(proxy)Introduced proper state typesMichel Weststratebefore adoption3842f85
line 126why, one step back126 return proxy as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 127–131why, one step back127}128129/**130 * Object drafts131 */Introduced proper state typesMichel Weststratebefore adoption3842f85
line 132why, one step back132const objectTraps: ProxyHandler<ProxyObjectState | ProxyArrayState> = {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 133–138why, one step back133 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 back139 return drafts[prop as any]Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 140–151why, one step back140 }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 back152 // @ts-ignore TODO: this line seems of?Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 153–155why, one step back153 drafts = state.copy154 }155Introduced proper state typesMichel Weststratebefore adoption3842f85
line 156why, one step back156 return (drafts[prop as any] = createProxy(value, state))Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 157–163why, one step back157 },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 back164 set(state, prop: string /* strictly not, but helps TS */, value) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 165–173why, one step back165 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 truebasic map tests succeedingMichel Weststratebefore adoption735c402
line 174why, one step back174 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 175–177why, one step back175 markChanged(state)176 }177 state.assigned[prop] = trueIntroduced proper state typesMichel Weststratebefore adoption3842f85
line 178why, one step back178 state.copy![prop] = valueMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 179–180why, one step back179 return true180 },Introduced proper state typesMichel Weststratebefore adoption3842f85
line 181why, one step back181 deleteProperty(state, prop: string) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 182–184why, one step back182 // 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] = falsebasic map tests succeedingMichel Weststratebefore adoption735c402
line 185why, one step back185 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 186–219why, one step back186 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 */219Introduced proper state typesMichel Weststratebefore adoption3842f85
line 220why, one step back220const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 221–266why, one step back221each(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}266basic map tests succeedingMichel Weststratebefore adoption735c402
lines 267–268why, one step back267// 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 back269 if (!state.modified) {270 state.modified = true271 const {base, drafts, parent} = statebasic map tests succeedingMichel Weststratebefore adoption735c402
lines 272–273why, one step back272 if (!isMap(base) && !isSet(base)) {273 // TODO: drop creating copies here?some build fixesMichel Weststratebefore adoption65a377f
line 274why, one step back274 const copy = (state.copy = shallowCopy(base))basic map tests succeedingMichel Weststratebefore adoption735c402
line 275why, one step back275 assign(copy, drafts)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 276–281why, one step back276 state.drafts = null277 }278279 if (parent) {280 markChanged(parent)281 }basic map tests succeedingMichel Weststratebefore adoption735c402
lines 282–288why, one step back282 }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 back289 }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 back296 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 back301}