|
| 1 | +/** |
| 2 | + * Creates a proxy that forwards EVERYTHING to the current target. |
| 3 | + * The proxy has a stable identity, and you can update the target at runtime. |
| 4 | + */ |
| 5 | +export function createForwardingProxy<T extends object>(params: { |
| 6 | + accessBeforeSetErrorMessage?: string; |
| 7 | + isFunction: boolean; |
| 8 | +}) { |
| 9 | + const { |
| 10 | + accessBeforeSetErrorMessage = "Assertion error: Forwarded proxy accessed too early", |
| 11 | + isFunction, |
| 12 | + } = params; |
| 13 | + |
| 14 | + const checkSet = () => { |
| 15 | + if (target === undefined) { |
| 16 | + throw new Error(accessBeforeSetErrorMessage); |
| 17 | + } |
| 18 | + }; |
| 19 | + |
| 20 | + let target: any = undefined; |
| 21 | + |
| 22 | + const handler: ProxyHandler<any> = { |
| 23 | + get(_t, prop, receiver) { |
| 24 | + checkSet(); |
| 25 | + return Reflect.get(target, prop, receiver); |
| 26 | + }, |
| 27 | + set(_t, prop, value, receiver) { |
| 28 | + checkSet(); |
| 29 | + return Reflect.set(target, prop, value, receiver); |
| 30 | + }, |
| 31 | + has(_t, prop) { |
| 32 | + checkSet(); |
| 33 | + return Reflect.has(target, prop); |
| 34 | + }, |
| 35 | + deleteProperty(_t, prop) { |
| 36 | + checkSet(); |
| 37 | + return Reflect.deleteProperty(target, prop); |
| 38 | + }, |
| 39 | + ownKeys(_t) { |
| 40 | + checkSet(); |
| 41 | + return Reflect.ownKeys(target); |
| 42 | + }, |
| 43 | + getOwnPropertyDescriptor(_t, prop) { |
| 44 | + checkSet(); |
| 45 | + return Reflect.getOwnPropertyDescriptor(target, prop); |
| 46 | + }, |
| 47 | + defineProperty(_t, prop, descriptor) { |
| 48 | + checkSet(); |
| 49 | + return Reflect.defineProperty(target, prop, descriptor); |
| 50 | + }, |
| 51 | + getPrototypeOf(_t) { |
| 52 | + checkSet(); |
| 53 | + return Reflect.getPrototypeOf(target); |
| 54 | + }, |
| 55 | + setPrototypeOf(_t, proto) { |
| 56 | + checkSet(); |
| 57 | + return Reflect.setPrototypeOf(target, proto); |
| 58 | + }, |
| 59 | + isExtensible(_t) { |
| 60 | + checkSet(); |
| 61 | + return Reflect.isExtensible(target); |
| 62 | + }, |
| 63 | + preventExtensions(_t) { |
| 64 | + checkSet(); |
| 65 | + return Reflect.preventExtensions(target); |
| 66 | + }, |
| 67 | + apply(_t, thisArg, args) { |
| 68 | + checkSet(); |
| 69 | + return Reflect.apply(target, thisArg, args); |
| 70 | + }, |
| 71 | + construct(_t, args, newTarget) { |
| 72 | + checkSet(); |
| 73 | + return Reflect.construct(target, args, newTarget); |
| 74 | + }, |
| 75 | + }; |
| 76 | + |
| 77 | + // Use a dummy callable so proxy can stand in for both functions and objects |
| 78 | + const proxy = new Proxy(isFunction ? function () {} : {}, handler) as T; |
| 79 | + |
| 80 | + return { |
| 81 | + proxy, |
| 82 | + updateTarget(newTarget: T) { |
| 83 | + target = newTarget; |
| 84 | + }, |
| 85 | + }; |
| 86 | +} |
0 commit comments