Skip to main content

nodejs/
proxy.rs

1//! `Proxy` — the ECMAScript exotic object (10.5) whose essential internal
2//! methods are redirected to a handler's traps.
3//!
4//! A Proxy is not a shape node-js could fake with a property map: every one of
5//! its internal methods has to be diverted, so it is its own heap variant
6//! (`JsObj::Proxy`) and this module is the single place the diversion happens.
7//! The funnels the rest of the runtime already routes through —
8//! `builtins::get_property` / `set_property` / `has_property` /
9//! `delete_property` / `object_keys`, `host::invoke` / `construct_nt` — each
10//! call into here first; when the handler has no trap for the operation, the
11//! `no_trap` fallback re-runs the SAME funnel against the target, which is what
12//! makes `new Proxy(t, {})` observationally indistinguishable from `t`.
13//!
14//! Not implemented, deliberately, and recorded in BUGS.md rather than faked: the
15//! spec's trap-result *invariant* checks (10.5.x steps that throw when a trap
16//! contradicts a non-configurable/non-extensible target property). node-js
17//! reports the trap's answer as given. Every trap itself is real.
18
19use crate::host::{self, with_host, JsObj};
20use fusevm::Value;
21
22/// `(target, handler)` when `v` is a Proxy — revoked or not.
23pub fn parts(v: &Value) -> Option<(Value, Value)> {
24    with_host(|h| match h.get(v) {
25        Some(JsObj::Proxy {
26            target, handler, ..
27        }) => Some((target.clone(), handler.clone())),
28        _ => None,
29    })
30}
31
32/// Whether `v` is a Proxy whose `[[ProxyHandler]]` is still live.
33fn revoked(v: &Value) -> bool {
34    with_host(|h| matches!(h.get(v), Some(JsObj::Proxy { revoked, .. }) if *revoked))
35}
36
37/// The proxy chain's ultimate non-proxy target — what `Array.isArray`,
38/// `Object.prototype.toString` and `typeof` classify by (10.5.x defer those to
39/// `[[ProxyTarget]]`, and a proxy of a proxy defers again).
40pub fn ultimate_target(v: &Value) -> Option<Value> {
41    let mut cur = parts(v)?.0;
42    for _ in 0..100 {
43        match parts(&cur) {
44            Some((t, _)) => cur = t,
45            None => return Some(cur),
46        }
47    }
48    Some(cur)
49}
50
51/// The object `IsArray` (7.2.2) decides on: `v`, or the end of its proxy chain.
52/// Every proxy passed on the way must still be live.
53pub fn is_array_subject(v: &Value) -> Result<Value, String> {
54    subject_through(v, "IsArray")
55}
56
57/// [`is_array_subject`] for an operation that begins with `IsArray` but reports
58/// itself by its own name (`Object.prototype.toString`).
59pub fn require_live(v: &Value, op: &str) -> Result<(), String> {
60    subject_through(v, op).map(|_| ())
61}
62
63fn subject_through(v: &Value, op: &str) -> Result<Value, String> {
64    let mut cur = v.clone();
65    while let Some((target, _)) = parts(&cur) {
66        if revoked(&cur) {
67            return Err(revoked_err(op));
68        }
69        cur = target;
70    }
71    Ok(cur)
72}
73
74/// V8's message for an operation attempted on a revoked proxy.
75fn revoked_err(op: &str) -> String {
76    host::type_error(&format!(
77        "Cannot perform '{op}' on a proxy that has been revoked"
78    ))
79}
80
81/// Resolve trap `name` on `v`'s handler.
82///
83/// `Ok(None)` means "not a proxy, or no such trap" — the caller runs its
84/// ordinary path (against the target, for the no-trap case). A revoked proxy
85/// and a non-callable trap both throw here, before any target work happens.
86/// Whether this proxy's handler installs `name` as a callable trap.
87///
88/// Distinguishes "the trap answered, and this is its answer" from "there is no
89/// trap, so the read forwarded to the target" — the two are indistinguishable
90/// in the returned value, and `ToPrimitive` has to tell them apart: a `get`
91/// trap that hands back a non-callable `toString` refuses the conversion, while
92/// a trapless proxy over a `Map` brands as its target does.
93pub fn has_trap(v: &Value, name: &str) -> bool {
94    matches!(trap(v, name), Ok(Some(_)))
95}
96
97fn trap(v: &Value, name: &str) -> Result<Option<(Value, Value, Value)>, String> {
98    let Some((target, handler)) = parts(v) else {
99        return Ok(None);
100    };
101    if revoked(v) {
102        return Err(revoked_err(name));
103    }
104    let t = crate::builtins::get_property(&handler, name)?;
105    if matches!(t, Value::Undef) || with_host(|h| h.is_null(&t)) {
106        return Ok(None);
107    }
108    if !with_host(|h| host::is_callable(h, &t)) {
109        return Err(host::type_error(&format!(
110            "'{}' returned for property '{name}' of object '#<Object>' is not a function",
111            with_host(|h| h.str_of(&t))
112        )));
113    }
114    Ok(Some((t, target, handler)))
115}
116
117/// The target of a proxy whose handler declines the operation (no trap), or
118/// `None` when `v` is not a proxy at all. Errors on a revoked proxy.
119fn no_trap(v: &Value, op: &str) -> Result<Option<Value>, String> {
120    match parts(v) {
121        None => Ok(None),
122        Some((target, _)) if !revoked(v) => Ok(Some(target)),
123        Some(_) => Err(revoked_err(op)),
124    }
125}
126
127/// An internal property key as the JS value a trap receives: the SYMBOL for a
128/// symbol-keyed property (`@@sym:7`, `@@iterator`), a string otherwise. A trap
129/// that inspects its key argument must see what the script wrote.
130pub fn key_value(k: &str) -> Value {
131    with_host(|h| {
132        if let Some(s) = h.symbol_of_key(k) {
133            return s;
134        }
135        match k.strip_prefix("@@") {
136            Some(name) if host::WELL_KNOWN_SYMBOLS.contains(&name) => h.well_known_symbol(name),
137            _ => h.new_str(k),
138        }
139    })
140}
141
142fn call(t: &Value, handler: &Value, args: Vec<Value>) -> Result<Value, String> {
143    host::invoke(t, args, Some(handler.clone()))
144}
145
146// ── the thirteen traps ───────────────────────────────────────────────────────
147
148/// `[[Get]]`. `Ok(None)` → not a proxy; the caller proceeds normally.
149// ── trap invariants (10.5) ──────────────────────────────────────────────────
150//
151// A proxy may lie about most things, but not about a property the TARGET has
152// pinned. None of these checks existed: a trap could report a different value
153// for a non-configurable non-writable property, hide one from `in` or
154// `ownKeys`, claim a frozen object was extensible, or report a prototype an
155// unextensible target does not have. Every one is what a membrane or a
156// hardened-JS shim relies on to know a frozen thing stays frozen.
157fn invariant(msg: &str) -> String {
158    host::type_error(msg)
159}
160
161/// V8's side-effect-free rendering of a value inside an invariant message.
162fn shown(v: &Value) -> String {
163    crate::builtins::no_side_effects_string_pub(v)
164}
165
166/// A Property Descriptor record (6.2.6): each field present or absent.
167#[derive(Default)]
168struct Desc {
169    value: Option<Value>,
170    writable: Option<bool>,
171    get: Option<Value>,
172    set: Option<Value>,
173    enumerable: Option<bool>,
174    configurable: Option<bool>,
175}
176
177impl Desc {
178    fn is_accessor(&self) -> bool {
179        self.get.is_some() || self.set.is_some()
180    }
181    fn is_data(&self) -> bool {
182        self.value.is_some() || self.writable.is_some()
183    }
184    fn is_generic(&self) -> bool {
185        !self.is_accessor() && !self.is_data()
186    }
187    fn is_empty(&self) -> bool {
188        self.is_generic() && self.enumerable.is_none() && self.configurable.is_none()
189    }
190
191    /// `ToPropertyDescriptor(obj)` (6.2.6.5): each field read only when the
192    /// object HAS it, in the spec's order, with V8's wording for each refusal.
193    fn from_object(obj: &Value) -> Result<Desc, String> {
194        if !with_host(|h| {
195            matches!(obj, Value::Obj(_)) && !h.is_null(obj) && !host::is_primitive(h, obj)
196        }) {
197            return Err(host::type_error(&format!(
198                "Property description must be an object: {}",
199                shown(obj)
200            )));
201        }
202        let field = |k: &str| -> Result<Option<Value>, String> {
203            if crate::builtins::has_property(obj, k)? {
204                crate::builtins::get_property(obj, k).map(Some)
205            } else {
206                Ok(None)
207            }
208        };
209        let truthy = |v: Value| with_host(|h| h.truthy(&v));
210        let mut d = Desc {
211            enumerable: field("enumerable")?.map(truthy),
212            configurable: field("configurable")?.map(truthy),
213            value: field("value")?,
214            writable: field("writable")?.map(truthy),
215            ..Desc::default()
216        };
217        for (k, slot, what) in [("get", &mut d.get, "Getter"), ("set", &mut d.set, "Setter")] {
218            if let Some(f) = field(k)? {
219                if !matches!(f, Value::Undef) && !with_host(|h| host::is_callable(h, &f)) {
220                    return Err(host::type_error(&format!(
221                        "{what} must be a function: {}",
222                        shown(&f)
223                    )));
224                }
225                *slot = Some(f);
226            }
227        }
228        if d.is_accessor() && d.is_data() {
229            return Err(host::type_error(&format!(
230                "Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, {}",
231                shown(obj)
232            )));
233        }
234        Ok(d)
235    }
236
237    /// `CompletePropertyDescriptor` (6.2.6.6).
238    fn complete(mut self) -> Desc {
239        if self.is_generic() || self.is_data() {
240            self.value.get_or_insert(Value::Undef);
241            self.writable.get_or_insert(false);
242        } else {
243            self.get.get_or_insert(Value::Undef);
244            self.set.get_or_insert(Value::Undef);
245        }
246        self.enumerable.get_or_insert(false);
247        self.configurable.get_or_insert(false);
248        self
249    }
250
251    /// `FromPropertyDescriptor` (6.2.6.4): an object with the present fields,
252    /// in the spec's order.
253    fn to_object(&self) -> Value {
254        let mut m = indexmap::IndexMap::new();
255        if let Some(v) = &self.value {
256            m.insert("value".to_string(), v.clone());
257        }
258        if let Some(w) = self.writable {
259            m.insert("writable".to_string(), Value::Bool(w));
260        }
261        if let Some(g) = &self.get {
262            m.insert("get".to_string(), g.clone());
263        }
264        if let Some(s) = &self.set {
265            m.insert("set".to_string(), s.clone());
266        }
267        if let Some(e) = self.enumerable {
268            m.insert("enumerable".to_string(), Value::Bool(e));
269        }
270        if let Some(c) = self.configurable {
271            m.insert("configurable".to_string(), Value::Bool(c));
272        }
273        with_host(|h| h.new_object(m))
274    }
275}
276
277/// `target.[[GetOwnProperty]](key)` as a record, `None` when absent. A proxy
278/// target answers through its own traps.
279fn target_desc(target: &Value, key: &str) -> Result<Option<Desc>, String> {
280    let d = crate::builtins::own_descriptor_pub(target, key_value(key))?;
281    if matches!(d, Value::Undef) {
282        return Ok(None);
283    }
284    Desc::from_object(&d).map(Some)
285}
286
287/// `IsExtensible(target)`, through the target's own trap when it is a proxy.
288fn target_extensible(target: &Value) -> Result<bool, String> {
289    match is_extensible(target)? {
290        Some(b) => Ok(b),
291        None => Ok(with_host(|h| h.is_extensible(target))),
292    }
293}
294
295/// `IsCompatiblePropertyDescriptor(extensible, desc, current)` (10.1.6.2):
296/// `ValidateAndApplyPropertyDescriptor` with no object to apply it to.
297fn is_compatible(extensible: bool, desc: &Desc, current: Option<&Desc>) -> bool {
298    let Some(current) = current else {
299        return extensible;
300    };
301    if desc.is_empty() || current.configurable != Some(false) {
302        return true;
303    }
304    if desc.configurable == Some(true) {
305        return false;
306    }
307    if desc.enumerable.is_some() && desc.enumerable != current.enumerable {
308        return false;
309    }
310    if !desc.is_generic() && desc.is_accessor() != current.is_accessor() {
311        return false;
312    }
313    let differs = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
314        (Some(x), Some(y)) => !crate::builtins::same_value(x, y),
315        (Some(x), None) => !matches!(x, Value::Undef),
316        _ => false,
317    };
318    if current.is_accessor() {
319        return !differs(&desc.get, &current.get) && !differs(&desc.set, &current.set);
320    }
321    if current.writable == Some(false) {
322        return desc.writable != Some(true) && !differs(&desc.value, &current.value);
323    }
324    true
325}
326
327pub fn get(v: &Value, key: &str, receiver: &Value) -> Result<Option<Value>, String> {
328    if let Some((t, target, handler)) = trap(v, "get")? {
329        let k = key_value(key);
330        let got = call(&t, &handler, vec![target.clone(), k, receiver.clone()])?;
331        // 10.5.8 step 9: a non-configurable property pins the answer — a
332        // read-only data property to its value, an accessor with no getter to
333        // `undefined`.
334        if let Some(d) = target_desc(&target, key)?.filter(|d| d.configurable == Some(false)) {
335            if d.is_data() && d.writable == Some(false) {
336                let val = d.value.clone().unwrap_or(Value::Undef);
337                if !crate::builtins::same_value(&got, &val) {
338                    return Err(invariant(&format!(
339                        "'get' on proxy: property '{key}' is a read-only and non-configurable data property on the proxy target but the proxy did not return its actual value (expected '{}' but got '{}')",
340                        shown(&val),
341                        shown(&got)
342                    )));
343                }
344            }
345            if d.is_accessor()
346                && matches!(d.get, Some(Value::Undef) | None)
347                && !matches!(got, Value::Undef)
348            {
349                return Err(invariant(&format!(
350                    "'get' on proxy: property '{key}' is a non-configurable accessor property on the proxy target and does not have a getter function, but the trap did not return 'undefined' (got '{}')",
351                    shown(&got)
352                )));
353            }
354        }
355        return Ok(Some(got));
356    }
357    match no_trap(v, "get")? {
358        Some(target) => crate::builtins::get_property_recv(&target, key, receiver).map(Some),
359        None => Ok(None),
360    }
361}
362
363/// `[[Set]]`. `Ok(true)` means the write was handled here.
364pub fn set(v: &Value, key: &str, val: &Value, receiver: &Value) -> Result<bool, String> {
365    if let Some((t, target, handler)) = trap(v, "set")? {
366        let k = key_value(key);
367        let r = call(
368            &t,
369            &handler,
370            vec![target.clone(), k, val.clone(), receiver.clone()],
371        )?;
372        // A FALSISH return means the trap refused the write. That is silent in
373        // sloppy code and a TypeError in strict — the same split an ordinary
374        // refused write has, and `Reflect.set` reports it as `false` either way.
375        // The return value was discarded, so a refusing trap looked like a
376        // successful write.
377        if !with_host(|h| h.truthy(&r)) {
378            return Ok(false);
379        }
380        // 10.5.9 step 10: reporting success for a write the target pins is a
381        // lie — a read-only data property holding another value, or an
382        // accessor with no setter.
383        if let Some(d) = target_desc(&target, key)?.filter(|d| d.configurable == Some(false)) {
384            if d.is_data()
385                && d.writable == Some(false)
386                && !crate::builtins::same_value(val, d.value.as_ref().unwrap_or(&Value::Undef))
387            {
388                return Err(invariant(&format!(
389                    "'set' on proxy: trap returned truish for property '{key}' which exists in the proxy target as a non-configurable and non-writable data property with a different value"
390                )));
391            }
392            if d.is_accessor() && matches!(d.set, Some(Value::Undef) | None) {
393                return Err(invariant(&format!(
394                    "'set' on proxy: trap returned truish for property '{key}' which exists in the proxy target as a non-configurable and non-writable accessor property without a setter"
395                )));
396            }
397        }
398        return Ok(true);
399    }
400    match no_trap(v, "set")? {
401        Some(target) => {
402            if receiver_observes_set(v, &target, key, receiver) {
403                return define_on_proxy_receiver(v, key, val);
404            }
405            crate::builtins::set_property_pub(&target, key, val.clone())?;
406            Ok(true)
407        }
408        None => Ok(false),
409    }
410}
411
412/// Whether a trapless `[[Set]]` has to run `OrdinarySet` (10.1.9.2) against the
413/// target with THIS proxy as the receiver, rather than forwarding the write.
414///
415/// The forward is observationally identical unless the handler traps one of
416/// the two receiver operations that `OrdinarySet` performs on a data property:
417/// `[[GetOwnProperty]]` (step 3.c) and `[[DefineOwnProperty]]` (3.d.iv / 3.e).
418/// A logging or validating handler that installs only those still sees every
419/// `p.k = v`; forwarding skipped both traps. Only the plain case takes the
420/// receiver route: a data property the target can accept, on an ordinary
421/// target. An accessor or a read-only slot keeps the ordinary forward.
422fn receiver_observes_set(v: &Value, target: &Value, key: &str, receiver: &Value) -> bool {
423    with_host(|h| h.strict_eq(receiver, v))
424        && (has_trap(v, "getOwnPropertyDescriptor") || has_trap(v, "defineProperty"))
425        && parts(target).is_none()
426        && with_host(|h| {
427            host::lookup_accessor(h, target, key).is_none() && h.can_write_prop(target, key)
428        })
429}
430
431/// 10.1.9.2 steps 3.c–3.e with the proxy `v` as the receiver: read its own
432/// descriptor through the `getOwnPropertyDescriptor` trap, then DEFINE through
433/// the `defineProperty` trap — `{ value }` alone over an existing writable data
434/// property, a full enumerable/writable/configurable data descriptor for a new
435/// one. A refused define is a TypeError in strict code, named for the trap that
436/// refused (V8's message), and a silent `false` in sloppy code.
437fn define_on_proxy_receiver(v: &Value, key: &str, val: &Value) -> Result<bool, String> {
438    let existing = get_own_descriptor(v, key)?.unwrap_or(Value::Undef);
439    let mut desc = indexmap::IndexMap::new();
440    desc.insert("value".to_string(), val.clone());
441    if !matches!(existing, Value::Undef) {
442        let field = |n: &str| crate::builtins::get_property(&existing, n);
443        let is_accessor = with_host(|h| {
444            host::lookup_chain(h, &existing, "get").is_some()
445                || host::lookup_chain(h, &existing, "set").is_some()
446        });
447        let writable = field("writable")?;
448        if is_accessor || !with_host(|h| h.truthy(&writable)) {
449            return Ok(false);
450        }
451    } else {
452        for flag in ["writable", "enumerable", "configurable"] {
453            desc.insert(flag.to_string(), Value::Bool(true));
454        }
455    }
456    let desc = with_host(|h| h.new_object(desc));
457    if define_property(v, key, &desc)? {
458        return Ok(true);
459    }
460    if with_host(|h| h.current_strict()) {
461        return Err(host::type_error(&format!(
462            "'defineProperty' on proxy: trap returned falsish for property '{key}'"
463        )));
464    }
465    Ok(false)
466}
467
468/// `[[HasProperty]]` (`key in proxy`).
469pub fn has(v: &Value, key: &str) -> Result<Option<bool>, String> {
470    if let Some((t, target, handler)) = trap(v, "has")? {
471        let k = key_value(key);
472        let r = call(&t, &handler, vec![target.clone(), k])?;
473        let reported = with_host(|h| h.truthy(&r));
474        // 10.5.7 step 9: a non-configurable property, or any property of a
475        // non-extensible target, cannot be hidden from `in`.
476        if !reported {
477            if let Some(d) = target_desc(&target, key)? {
478                if d.configurable == Some(false) {
479                    return Err(invariant(&format!(
480                        "'has' on proxy: trap returned falsish for property '{key}' which exists in the proxy target as non-configurable"
481                    )));
482                }
483                if !target_extensible(&target)? {
484                    return Err(invariant(&format!(
485                        "'has' on proxy: trap returned falsish for property '{key}' but the proxy target is not extensible"
486                    )));
487                }
488            }
489        }
490        return Ok(Some(reported));
491    }
492    match no_trap(v, "has")? {
493        Some(target) => crate::builtins::has_property(&target, key).map(Some),
494        None => Ok(None),
495    }
496}
497
498/// `[[Delete]]`.
499pub fn delete(v: &Value, key: &str) -> Result<Option<bool>, String> {
500    if let Some((t, target, handler)) = trap(v, "deleteProperty")? {
501        let k = key_value(key);
502        let r = call(&t, &handler, vec![target.clone(), k])?;
503        let reported = with_host(|h| h.truthy(&r));
504        // 10.5.10 steps 10-13: a non-configurable property, or any property of
505        // a non-extensible target, cannot be reported as deleted.
506        if reported {
507            if let Some(d) = target_desc(&target, key)? {
508                if d.configurable == Some(false) {
509                    return Err(invariant(&format!(
510                        "'deleteProperty' on proxy: trap returned truish for property '{key}' which is non-configurable in the proxy target"
511                    )));
512                }
513                if !target_extensible(&target)? {
514                    return Err(invariant(&format!(
515                        "'deleteProperty' on proxy: trap returned truish for property '{key}' but the proxy target is non-extensible"
516                    )));
517                }
518            }
519        }
520        return Ok(Some(reported));
521    }
522    match no_trap(v, "deleteProperty")? {
523        Some(target) => crate::builtins::delete_property(&target, key).map(Some),
524        None => Ok(None),
525    }
526}
527
528/// `[[OwnPropertyKeys]]`, as INTERNAL key strings (so a symbol key comes back as
529/// `@@sym:<id>` — the form the rest of the runtime indexes by).
530pub fn own_keys(v: &Value) -> Result<Option<Vec<String>>, String> {
531    if let Some((t, target, handler)) = trap(v, "ownKeys")? {
532        let r = call(&t, &handler, vec![target.clone()])?;
533        // `CreateListFromArrayLike(result, « String, Symbol »)`: an array-like
534        // read by `length` and index, whose every element is a property key.
535        if !with_host(|h| {
536            matches!(r, Value::Obj(_)) && !h.is_null(&r) && !host::is_primitive(h, &r)
537        }) {
538            return Err(host::type_error(
539                "CreateListFromArrayLike called on non-object",
540            ));
541        }
542        let len = crate::builtins::length_of_array_like(&r)?;
543        let mut out = Vec::with_capacity(len);
544        for i in 0..len {
545            let k = crate::builtins::get_property(&r, &i.to_string())?;
546            let is_key = with_host(|h| {
547                h.as_str(&k).is_some() || matches!(h.get(&k), Some(JsObj::Symbol { .. }))
548            });
549            if !is_key {
550                return Err(host::type_error(&format!(
551                    "{} is not a valid property name",
552                    shown(&k)
553                )));
554            }
555            out.push(host::to_property_key(&k)?);
556        }
557        // The list must contain no duplicates …
558        let mut seen: Vec<&String> = Vec::with_capacity(out.len());
559        for k in &out {
560            if seen.contains(&k) {
561                return Err(invariant(
562                    "'ownKeys' on proxy: trap returned duplicate entries",
563                ));
564            }
565            seen.push(k);
566        }
567        // … must include every non-configurable own key of the target …
568        let target_keys = with_host(|h| {
569            let mut ks = h.own_key_names(&target, false);
570            ks.extend(
571                h.own_symbol_keys(&target)
572                    .iter()
573                    .map(|sym| h.property_key(sym))
574                    .collect::<Vec<_>>(),
575            );
576            ks
577        });
578        for k in &target_keys {
579            let pinned =
580                crate::builtins::own_prop_facts(&target, k).is_some_and(|(_, _, conf, _)| !conf);
581            if pinned && !out.contains(k) {
582                return Err(invariant(&format!(
583                    "'ownKeys' on proxy: trap result did not include '{k}'"
584                )));
585            }
586        }
587        // … and, for a NON-EXTENSIBLE target, must be exactly its own keys.
588        if !with_host(|h| h.is_extensible(&target)) {
589            for k in &target_keys {
590                if !out.contains(k) {
591                    return Err(invariant(&format!(
592                        "'ownKeys' on proxy: trap result did not include '{k}'"
593                    )));
594                }
595            }
596            for k in &out {
597                if !target_keys.contains(k) {
598                    return Err(invariant(
599                        "'ownKeys' on proxy: trap returned extra keys but proxy target is non-extensible",
600                    ));
601                }
602            }
603        }
604        return Ok(Some(out));
605    }
606    match no_trap(v, "ownKeys")? {
607        Some(target) => {
608            let mut keys = with_host(|h| h.own_key_names(&target, false));
609            keys.extend(with_host(|h| {
610                h.own_symbol_keys(&target)
611                    .iter()
612                    .map(|s| h.property_key(s))
613                    .collect::<Vec<_>>()
614            }));
615            Ok(Some(keys))
616        }
617        None => Ok(None),
618    }
619}
620
621/// `[[GetOwnProperty]]` — the descriptor object (or `undefined`).
622pub fn get_own_descriptor(v: &Value, key: &str) -> Result<Option<Value>, String> {
623    if let Some((t, target, handler)) = trap(v, "getOwnPropertyDescriptor")? {
624        let k = key_value(key);
625        let d = call(&t, &handler, vec![target.clone(), k])?;
626        return checked_own_descriptor(&target, key, &d).map(Some);
627    }
628    match no_trap(v, "getOwnPropertyDescriptor")? {
629        Some(target) => {
630            let k = key_value(key);
631            crate::builtins::own_descriptor_pub(&target, k).map(Some)
632        }
633        None => Ok(None),
634    }
635}
636
637/// 10.5.5 steps 8-17: validate what a `getOwnPropertyDescriptor` trap
638/// returned against the target, and hand back the COMPLETED descriptor the
639/// operation yields — not the trap's own object.
640fn checked_own_descriptor(target: &Value, key: &str, d: &Value) -> Result<Value, String> {
641    let is_object =
642        with_host(|h| matches!(d, Value::Obj(_)) && !h.is_null(d) && !host::is_primitive(h, d));
643    if !is_object && !matches!(d, Value::Undef) {
644        return Err(invariant(&format!(
645            "'getOwnPropertyDescriptor' on proxy: trap returned neither object nor undefined for property '{key}'"
646        )));
647    }
648    let target_d = target_desc(target, key)?;
649    if !is_object {
650        if let Some(td) = &target_d {
651            if td.configurable == Some(false) {
652                return Err(invariant(&format!(
653                    "'getOwnPropertyDescriptor' on proxy: trap returned undefined for property '{key}' which is non-configurable in the proxy target"
654                )));
655            }
656            if !target_extensible(target)? {
657                return Err(invariant(&format!(
658                    "'getOwnPropertyDescriptor' on proxy: trap returned undefined for property '{key}' which exists in the non-extensible proxy target"
659                )));
660            }
661        }
662        return Ok(Value::Undef);
663    }
664    let extensible = target_extensible(target)?;
665    let result = Desc::from_object(d)?.complete();
666    if !is_compatible(extensible, &result, target_d.as_ref()) {
667        return Err(invariant(&format!(
668            "'getOwnPropertyDescriptor' on proxy: trap returned descriptor for property '{key}' that is incompatible with the existing property in the proxy target"
669        )));
670    }
671    if result.configurable == Some(false) {
672        match &target_d {
673            Some(td) if td.configurable == Some(false) => {
674                if result.writable == Some(false) && td.writable == Some(true) {
675                    return Err(invariant(&format!(
676                        "'getOwnPropertyDescriptor' on proxy: trap reported non-configurable and non-writable for property '{key}' which is non-configurable, writable in the proxy target"
677                    )));
678                }
679            }
680            _ => {
681                return Err(invariant(&format!(
682                    "'getOwnPropertyDescriptor' on proxy: trap reported non-configurability for property '{key}' which is either non-existent or configurable in the proxy target"
683                )));
684            }
685        }
686    }
687    Ok(result.to_object())
688}
689
690/// `[[DefineOwnProperty]]`. The trap receives the descriptor normalized by
691/// `ToPropertyDescriptor` → `FromPropertyDescriptor`, not the caller's object.
692pub fn define_property(v: &Value, key: &str, desc: &Value) -> Result<bool, String> {
693    if let Some((t, target, handler)) = trap(v, "defineProperty")? {
694        let k = key_value(key);
695        let d = Desc::from_object(desc)?;
696        let r = call(&t, &handler, vec![target.clone(), k, d.to_object()])?;
697        // A FALSISH return means the trap refused. Unlike `set` and
698        // `deleteProperty`, this one throws from `Object.defineProperty` in
699        // SLOPPY code too — only `Reflect.defineProperty` reports it as
700        // `false`. The return value was discarded, so a refusing trap looked
701        // like a successful define.
702        if !with_host(|h| h.truthy(&r)) {
703            return Ok(false);
704        }
705        // 10.5.6 steps 10-16: the target must be able to hold what the trap
706        // claims to have defined.
707        let target_d = target_desc(&target, key)?;
708        let extensible = target_extensible(&target)?;
709        let setting_config_false = d.configurable == Some(false);
710        let non_configurable = || {
711            invariant(&format!(
712                "'defineProperty' on proxy: trap returned truish for defining non-configurable property '{key}' which is either non-existent or configurable in the proxy target"
713            ))
714        };
715        match &target_d {
716            None => {
717                if !extensible {
718                    return Err(invariant(&format!(
719                        "'defineProperty' on proxy: trap returned truish for adding property '{key}' to the non-extensible proxy target"
720                    )));
721                }
722                if setting_config_false {
723                    return Err(non_configurable());
724                }
725            }
726            Some(td) => {
727                if !is_compatible(extensible, &d, Some(td)) {
728                    return Err(invariant(&format!(
729                        "'defineProperty' on proxy: trap returned truish for adding property '{key}'  that is incompatible with the existing property in the proxy target"
730                    )));
731                }
732                if setting_config_false && td.configurable == Some(true) {
733                    return Err(non_configurable());
734                }
735                if td.is_data()
736                    && td.configurable == Some(false)
737                    && td.writable == Some(true)
738                    && d.writable == Some(false)
739                {
740                    return Err(invariant(&format!(
741                        "'defineProperty' on proxy: trap returned truish for defining non-configurable property '{key}' which cannot be non-writable, unless there exists a corresponding non-configurable, non-writable own property of the target object."
742                    )));
743                }
744            }
745        }
746        return Ok(true);
747    }
748    match no_trap(v, "defineProperty")? {
749        Some(target) => {
750            let k = key_value(key);
751            crate::builtins::define_property_pub(&target, k, desc.clone())?;
752            Ok(true)
753        }
754        None => Ok(false),
755    }
756}
757
758/// `[[GetPrototypeOf]]`.
759pub fn get_prototype_of(v: &Value) -> Result<Option<Value>, String> {
760    if let Some((t, target, handler)) = trap(v, "getPrototypeOf")? {
761        let reported = call(&t, &handler, vec![target.clone()])?;
762        // A non-extensible target's prototype is fixed, so it must be reported
763        // as it is.
764        if !with_host(|h| h.is_extensible(&target)) {
765            let actual = crate::builtins::prototype_of(&target);
766            if !with_host(|h| h.strict_eq(&reported, &actual)) {
767                return Err(invariant(
768                    "'getPrototypeOf' on proxy: proxy target is non-extensible but the trap did not return its actual prototype",
769                ));
770            }
771        }
772        return Ok(Some(reported));
773    }
774    match no_trap(v, "getPrototypeOf")? {
775        Some(target) => Ok(Some(crate::builtins::prototype_of(&target))),
776        None => Ok(None),
777    }
778}
779
780/// `[[SetPrototypeOf]]`.
781///
782/// The trap's answer is the result (10.5.2): `false` is a refusal, which
783/// `Object.setPrototypeOf` turns into a TypeError and `Reflect.setPrototypeOf`
784/// reports. A non-extensible target's prototype cannot be changed, so `true`
785/// is checked against the prototype it really has.
786pub fn set_prototype_of(v: &Value, proto: &Value) -> Result<bool, String> {
787    if let Some((t, target, handler)) = trap(v, "setPrototypeOf")? {
788        let r = call(&t, &handler, vec![target.clone(), proto.clone()])?;
789        if !with_host(|h| h.truthy(&r)) {
790            return Ok(false);
791        }
792        if !target_extensible(&target)? {
793            let actual = match get_prototype_of(&target)? {
794                Some(p) => p,
795                None => crate::builtins::prototype_of(&target),
796            };
797            if !crate::builtins::same_value(proto, &actual) {
798                return Err(invariant(
799                    "'setPrototypeOf' on proxy: trap returned truish for setting a new prototype on the non-extensible proxy target",
800                ));
801            }
802        }
803        return Ok(true);
804    }
805    match no_trap(v, "setPrototypeOf")? {
806        // `target.[[SetPrototypeOf]]` (10.5.2 step 7): an ordinary object
807        // refuses a change when it is non-extensible and agrees to a no-op,
808        // and refuses a cycle.
809        Some(target) => {
810            if !target_extensible(&target)? {
811                let actual = match get_prototype_of(&target)? {
812                    Some(p) => p,
813                    None => crate::builtins::prototype_of(&target),
814                };
815                return Ok(crate::builtins::same_value(proto, &actual));
816            }
817            if crate::builtins::would_cycle_pub(&target, proto) {
818                return Ok(false);
819            }
820            with_host(|h| h.set_proto(&target, proto.clone()));
821            Ok(true)
822        }
823        None => Ok(false),
824    }
825}
826
827/// `[[IsExtensible]]`.
828pub fn is_extensible(v: &Value) -> Result<Option<bool>, String> {
829    if let Some((t, target, handler)) = trap(v, "isExtensible")? {
830        // Extensibility cannot be misreported: the answer must match the
831        // target's, so a frozen target cannot be passed off as open.
832        let reported = call(&t, &handler, vec![target.clone()])?;
833        let reported = with_host(|h| h.truthy(&reported));
834        let actual = target_extensible(&target)?;
835        if reported != actual {
836            return Err(invariant(&format!(
837                "'isExtensible' on proxy: trap result does not reflect extensibility of proxy target (which is '{actual}')"
838            )));
839        }
840        return Ok(Some(reported));
841    }
842    match no_trap(v, "isExtensible")? {
843        Some(target) => Ok(Some(with_host(|h| h.is_extensible(&target)))),
844        None => Ok(None),
845    }
846}
847
848/// `[[PreventExtensions]]`.
849///
850/// `Ok(None)` → not a proxy. Otherwise the operation's boolean result
851/// (10.5.4): a trap's `false` is a refusal — a TypeError from
852/// `Object.preventExtensions`, `false` from `Reflect.preventExtensions` — and
853/// its `true` must leave the target really non-extensible.
854pub fn prevent_extensions(v: &Value) -> Result<Option<bool>, String> {
855    if let Some((t, target, handler)) = trap(v, "preventExtensions")? {
856        let r = call(&t, &handler, vec![target.clone()])?;
857        let reported = with_host(|h| h.truthy(&r));
858        if reported && target_extensible(&target)? {
859            return Err(invariant(
860                "'preventExtensions' on proxy: trap returned truish but the proxy target is extensible",
861            ));
862        }
863        return Ok(Some(reported));
864    }
865    match no_trap(v, "preventExtensions")? {
866        Some(target) => match prevent_extensions(&target)? {
867            Some(b) => Ok(Some(b)),
868            None => {
869                with_host(|h| h.prevent_extensions(&target));
870                Ok(Some(true))
871            }
872        },
873        None => Ok(None),
874    }
875}
876
877/// V8's TypeError for an `Object.preventExtensions`/`freeze`/`seal` whose
878/// proxy trap refused.
879pub fn prevent_extensions_refused() -> String {
880    host::type_error("'preventExtensions' on proxy: trap returned falsish")
881}
882
883/// `[[Call]]`.
884pub fn apply(v: &Value, args: Vec<Value>, this: Option<Value>) -> Result<Option<Value>, String> {
885    if let Some((t, target, handler)) = trap(v, "apply")? {
886        let this_arg = this.unwrap_or(Value::Undef);
887        let list = with_host(|h| h.new_array(args));
888        return call(&t, &handler, vec![target, this_arg, list]).map(Some);
889    }
890    match no_trap(v, "apply")? {
891        Some(target) => host::invoke(&target, args, this).map(Some),
892        None => Ok(None),
893    }
894}
895
896/// `[[Construct]]`.
897pub fn construct(v: &Value, args: Vec<Value>, new_target: &Value) -> Result<Option<Value>, String> {
898    if let Some((t, target, handler)) = trap(v, "construct")? {
899        let list = with_host(|h| h.new_array(args));
900        let made = call(&t, &handler, vec![target, list, new_target.clone()])?;
901        // 10.5.13 step 10: `new` always yields an object.
902        if !with_host(|h| {
903            matches!(made, Value::Obj(_)) && !h.is_null(&made) && !host::is_primitive(h, &made)
904        }) {
905            return Err(invariant(&format!(
906                "'construct' on proxy: trap returned non-object ('{}')",
907                shown(&made)
908            )));
909        }
910        return Ok(Some(made));
911    }
912    match no_trap(v, "construct")? {
913        Some(target) => {
914            // 10.1.13 OrdinaryCreateFromConstructor reads `newTarget.prototype`
915            // with `[[Get]]` — through this proxy's `get` trap when it is the
916            // new.target — and the object it builds inherits from the answer.
917            let proto = if parts(new_target).is_some() {
918                Some(crate::builtins::get_property(new_target, "prototype")?)
919            } else {
920                None
921            };
922            let made = host::construct_nt(&target, args, new_target.clone())?;
923            if let Some(p) = proto {
924                let plain = matches!(p, Value::Obj(_))
925                    && with_host(|h| !h.is_null(&p) && !host::is_primitive(h, &p));
926                let fresh = matches!(with_host(|h| h.get(&made).cloned()), Some(JsObj::Object(_)));
927                if plain && fresh {
928                    with_host(|h| h.set_proto(&made, p));
929                }
930            }
931            Ok(Some(made))
932        }
933        None => Ok(None),
934    }
935}
936
937// ── enumeration built on the traps ───────────────────────────────────────────
938
939/// The own keys of a proxy that are ENUMERABLE string keys — `Object.keys`,
940/// `for-in`'s own half, object spread and `JSON.stringify` all need this shape.
941/// 10.5.11 defines it as `ownKeys` filtered by each key's `[[GetOwnProperty]]`,
942/// so both traps really do run, in that order.
943pub fn own_enum_string_keys(v: &Value) -> Result<Vec<String>, String> {
944    let Some(keys) = own_keys(v)? else {
945        return Ok(Vec::new());
946    };
947    let mut out = Vec::new();
948    for k in keys {
949        if host::is_symbol_key(&k) {
950            continue;
951        }
952        let Some(d) = get_own_descriptor(v, &k)? else {
953            continue;
954        };
955        let enumerable = with_host(|h| match h.get(&d) {
956            Some(JsObj::Object(p)) => p.get("enumerable").map(|e| h.truthy(e)).unwrap_or(false),
957            _ => false,
958        });
959        if enumerable {
960            out.push(k);
961        }
962    }
963    Ok(out)
964}
965
966/// Is `key` an own ENUMERABLE property of this proxy right now? One
967/// `getOwnPropertyDescriptor` trap call, which is what `for-in` runs per key at
968/// the moment it visits it (14.7.5.10) — `own_enum_string_keys` answers the same
969/// question for every key at once, which is the wrong shape when the body
970/// between two visits can delete a key or flip its enumerability.
971pub fn own_enumerable(v: &Value, key: &str) -> Result<bool, String> {
972    let Some(d) = get_own_descriptor(v, key)? else {
973        return Ok(false);
974    };
975    Ok(with_host(|h| match h.get(&d) {
976        Some(JsObj::Object(p)) => p.get("enumerable").map(|e| h.truthy(e)).unwrap_or(false),
977        _ => false,
978    }))
979}
980
981/// `(key, value)` for every own enumerable string key — spread / `Object.assign`
982/// / `Object.entries`. Each of those (7.3.25 `CopyDataProperties`, 20.1.2.1
983/// `Object.assign`, 7.3.23 `EnumerableOwnProperties` in key+value mode) visits
984/// one key at a time: its `getOwnPropertyDescriptor` trap, then — if
985/// enumerable — its `get` trap, before the next key's descriptor is asked for.
986pub fn own_enum_entries(v: &Value) -> Result<Vec<(String, Value)>, String> {
987    let Some(keys) = own_keys(v)? else {
988        return Ok(Vec::new());
989    };
990    let mut out = Vec::with_capacity(keys.len());
991    for k in keys {
992        if host::is_symbol_key(&k) || !own_enumerable(v, &k)? {
993            continue;
994        }
995        let val = get(v, &k, v)?.unwrap_or(Value::Undef);
996        out.push((k, val));
997    }
998    Ok(out)
999}
1000
1001/// Whether the proxy chain bottoms out in an Array — the shape `IsArray` and
1002/// `Array.prototype[Symbol.iterator]` both key off.
1003fn wraps_array(v: &Value) -> bool {
1004    match ultimate_target(v) {
1005        Some(t) => with_host(|h| matches!(h.get(&t), Some(JsObj::Array(_)))),
1006        None => false,
1007    }
1008}
1009
1010/// `GetIterator(proxy, sync)` → the iterator object. `Ok(None)` → not a proxy.
1011///
1012/// Three cases, in the order `GetIterator` reaches them:
1013/// a user `Symbol.iterator` read THROUGH the `get` trap, called with the proxy
1014/// as `this`; an array target still holding the default, whose
1015/// `Array.prototype[Symbol.iterator]` is a live array iterator over the PROXY —
1016/// each step re-reads `length` and then `Get(O, i)` through the traps
1017/// (23.1.5.1), never `has`; and anything else (Map/Set/string/generator
1018/// target), which iterates as the target does.
1019pub fn get_iterator(v: &Value) -> Result<Option<Value>, String> {
1020    if parts(v).is_none() {
1021        return Ok(None);
1022    }
1023    let array_backed = wraps_array(v);
1024    let iter_fn = get(v, "@@iterator", v)?.unwrap_or(Value::Undef);
1025    // node-js models `Array.prototype[Symbol.iterator]` as a thunk BOUND to the
1026    // array it was read off, where the real method is generic over `this`. Read
1027    // through a proxy, that thunk would walk the TARGET and ignore every answer
1028    // the `get` trap gave — so an array-backed proxy still holding the default
1029    // gets the generic iterator over the proxy itself. A user-installed iterator
1030    // is an ordinary function value and is called.
1031    let default_array_iter =
1032        array_backed && with_host(|h| matches!(h.get(&iter_fn), Some(JsObj::BoundMethod { .. })));
1033    if !default_array_iter && with_host(|h| host::is_callable(h, &iter_fn)) {
1034        return host::call_iterator_method(&iter_fn, v).map(Some);
1035    }
1036    if array_backed {
1037        return Ok(Some(crate::builtins::array_iterator(
1038            v,
1039            host::ArrayIterKind::Values,
1040        )));
1041    }
1042    let target = no_trap(v, "get")?.expect("checked it is a proxy");
1043    let items = host::iter_all(&target)?;
1044    Ok(Some(with_host(|h| {
1045        h.alloc(JsObj::Iter {
1046            items,
1047            idx: 0,
1048            array: None,
1049            brand: None,
1050        })
1051    })))
1052}
1053
1054/// `[...proxy]` and the other consumers that drain: [`get_iterator`], stepped
1055/// to the end. `Ok(None)` → not a proxy.
1056pub fn iterate(v: &Value) -> Result<Option<Vec<Value>>, String> {
1057    let Some(iterator) = get_iterator(v)? else {
1058        return Ok(None);
1059    };
1060    if with_host(|h| matches!(h.get(&iterator), Some(JsObj::Iter { .. }))) {
1061        return host::iter_all(&iterator).map(Some);
1062    }
1063    host::drain_iterator(&iterator).map(Some)
1064}
1065
1066/// `[...proxy]` / `for (… of proxy)`. `Ok(None)` → not a proxy.
1067/// `Get(O, "length")` once, then `Get(O, i)` for each index below it, all
1068/// through the traps.
1069fn length_walk(v: &Value) -> Result<Vec<Value>, String> {
1070    let len_v = get(v, "length", v)?.unwrap_or(Value::Undef);
1071    let len = with_host(|h| h.to_number(&len_v));
1072    let len = if len.is_finite() && len > 0.0 {
1073        len as usize
1074    } else {
1075        0
1076    };
1077    let mut out = Vec::with_capacity(len);
1078    for i in 0..len {
1079        out.push(get(v, &i.to_string(), v)?.unwrap_or(Value::Undef));
1080    }
1081    Ok(out)
1082}
1083
1084/// The plain value `JSON.stringify` serializes a proxy as. `SerializeJSONArray`
1085/// and `SerializeJSONObject` both read every member through `[[Get]]`, so the
1086/// snapshot is taken through the traps rather than off the target.
1087pub fn json_snapshot(v: &Value) -> Result<Value, String> {
1088    // `SerializeJSONArray` (25.5.2.6) is `LengthOfArrayLike` then `Get` per
1089    // index — never `Symbol.iterator`, which a user may have replaced.
1090    if wraps_array(v) {
1091        let items = length_walk(v)?;
1092        return Ok(with_host(|h| h.new_array(items)));
1093    }
1094    // `SerializeJSONObject` takes `EnumerableOwnProperties(value, key)` — every
1095    // descriptor first — and only then `Get`s each key while serializing.
1096    let mut entries = Vec::new();
1097    for k in own_enum_string_keys(v)? {
1098        let val = get(v, &k, v)?.unwrap_or(Value::Undef);
1099        entries.push((k, val));
1100    }
1101    Ok(with_host(|h| {
1102        let mut m = indexmap::IndexMap::new();
1103        for (k, val) in entries {
1104            m.insert(k, val);
1105        }
1106        h.new_object(m)
1107    }))
1108}
1109
1110// ── construction ─────────────────────────────────────────────────────────────
1111
1112/// `new Proxy(target, handler)` (10.5.14 `ProxyCreate`).
1113pub fn create(args: &[Value]) -> Result<Value, String> {
1114    let target = args.first().cloned().unwrap_or(Value::Undef);
1115    let handler = args.get(1).cloned().unwrap_or(Value::Undef);
1116    let ok = |v: &Value| {
1117        with_host(|h| matches!(v, Value::Obj(_)) && !h.is_null(v) && !host::is_primitive(h, v))
1118    };
1119    if !ok(&target) || !ok(&handler) {
1120        return Err(host::type_error(
1121            "Cannot create proxy with a non-object as target or handler",
1122        ));
1123    }
1124    Ok(with_host(|h| {
1125        h.alloc(JsObj::Proxy {
1126            target,
1127            handler,
1128            revoked: false,
1129        })
1130    }))
1131}
1132
1133/// `Proxy.revocable(target, handler)` → `{ proxy, revoke }`. The revoker is a
1134/// builtin thunk keyed by the proxy's heap index, so calling it twice is the
1135/// no-op the spec asks for rather than a second teardown.
1136pub fn revocable(args: &[Value]) -> Result<Value, String> {
1137    let proxy = create(args)?;
1138    let idx = match proxy {
1139        Value::Obj(i) => i,
1140        _ => unreachable!("create returns a heap object"),
1141    };
1142    let revoke = with_host(|h| h.alloc(JsObj::Builtin(format!("@@prevoke:{idx}"))));
1143    Ok(with_host(|h| {
1144        let mut m = indexmap::IndexMap::new();
1145        m.insert("proxy".to_string(), proxy);
1146        m.insert("revoke".to_string(), revoke);
1147        h.new_object(m)
1148    }))
1149}
1150
1151/// Run a `@@prevoke:<idx>` thunk: mark the proxy dead so every trap throws.
1152///
1153/// The target handle is KEPT rather than nulled as 10.5.15 step 5 words it,
1154/// because `typeof` is fixed at creation by whether the target was callable and
1155/// V8 still answers `'function'` for a revoked proxy of a function. Nothing can
1156/// read the target through the proxy anymore — `revoked` is checked before any
1157/// trap or fallback runs.
1158pub fn revoke(idx: u32) -> Value {
1159    with_host(|h| {
1160        if let Some(JsObj::Proxy { revoked, .. }) = h.get_mut(&Value::Obj(idx)) {
1161            *revoked = true;
1162        }
1163    });
1164    Value::Undef
1165}