Sub topic 10
Proxy Invariants: Rules Traps Cannot Break
This chapter assumes you know property descriptors (writable, configurable), frozen and non-extensible objects, and how to write traps that forward with Reflect.
Traps give you a lot of control, but some limits apply. Each time a trap returns, the engine compares the result with the real state of the target. If the result contradicts a promise the target has already made, the engine throws a TypeError. These checks are called invariants.
Why invariants exist
Some facts about an object are meant to be permanent. A non-configurable property can never be deleted. A frozen property's value can never change. A non-extensible object can never gain new properties. Code that depends on these guarantees, such as security sandboxes or Object.freeze, would break if a proxy could report something different. Invariants keep a proxy honest about anything the target has locked down.
The rule behind the rules
Almost every invariant follows from one idea. Configurable properties and extensible targets are flexible. Non-configurable properties and non-extensible targets are fixed. A trap can freely misreport anything flexible. It cannot misreport anything fixed.
This is why the hiding pattern from the has and ownKeys chapter works: ordinary properties created by assignment are configurable. Make the same property non-configurable and the pattern breaks.
Seeing invariants fire
function attempt(label, fn) {
try {
console.log(label, fn());
} catch (err) {
console.log(label, `${err.constructor.name}: ${err.message}`);
}
}
const target = {};
Object.defineProperty(target, 'id', {
value: 1,
writable: false,
configurable: false,
enumerable: true
});
target.note = 'flexible';
const proxy = new Proxy(target, {
get(t, prop, r) { return prop === 'id' ? 999 : Reflect.get(t, prop, r); },
has(t, prop) { return false; },
ownKeys(t) { return []; },
set(t, prop, value, r) { return true; },
deleteProperty(t, prop) { return true; }
});
attempt('get note:', () => proxy.note); // 'flexible'
attempt('get id:', () => proxy.id); // TypeError
attempt('in note:', () => 'note' in proxy); // false (allowed)
attempt('in id:', () => 'id' in proxy); // TypeError
attempt('keys:', () => Object.keys(proxy)); // TypeError
attempt('set id:', () => Reflect.set(proxy, 'id', 2)); // TypeError
attempt('delete id:', () => delete proxy.id); // TypeErrorEach lie about note passes, because note is configurable. Each lie about id fails, because id is fixed. Calling proxy.note works even with the misbehaving has trap, since the get trap forwards normally.
Common invariants
| Trap | It throws if the trap... |
|---|---|
| `get` | returns a different value for a non-writable, non-configurable data property |
| `set` | reports success when changing a non-writable, non-configurable property to a new value |
| `has` | reports a non-configurable own property as absent, or hides any own property of a non-extensible target |
| `deleteProperty` | reports a non-configurable property as deleted |
| `ownKeys` | omits a non-configurable key, returns duplicates or non-key values, or (for a non-extensible target) adds or omits any key |
| `defineProperty` | reports adding a property to a non-extensible target |
| `getPrototypeOf` | returns a different prototype for a non-extensible target |
| `isExtensible` | returns a different answer from `Reflect.isExtensible(target)` |
| `construct` | returns a non-object |
The construct trap must return an object
class Point {}
const P = new Proxy(Point, {
construct(target, args, newTarget) {
return 42;
}
});
try {
new P();
} catch (err) {
console.log(err instanceof TypeError); // true
}Working with invariants
- If you plan to lie about a property, keep it configurable on the target. Do not freeze the target.
- To present values that differ from a frozen object, proxy a separate, unfrozen target and read the real data from a closure.
- Forwarding with
Reflectcan never violate an invariant, because it reports the target's true state.
Exercise
A target is created with Object.preventExtensions({ a: 1, b: 2 }). Its proxy has an ownKeys trap that returns ['a']. What does Object.keys(proxy) do, and why? Would the result change if the target were extensible?
Show answer
It throws a TypeError. For a non-extensible target, ownKeys must return exactly the target's own keys, and 'b' is missing. If the target were extensible, and 'a' and 'b' are configurable (as they are when created with an object literal), the trap could omit 'b' and Object.keys(proxy) would return ['a'].
Exercise
A get trap always returns 'hidden'. The target is Object.freeze({ token: 'abc', other: 'x' }). What does proxy.token return?
Show answer
It throws a TypeError. Freezing makes every property non-writable and non-configurable, so get must report the real value 'abc'. The same applies to proxy.other.