node-js 0.1.15

JavaScript as a fusevm frontend: a lexer/parser and compiler to fusevm::Chunk on a JsHost object heap, with no bespoke VM or JIT
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
//! `Proxy` — the ECMAScript exotic object (10.5) whose essential internal
//! methods are redirected to a handler's traps.
//!
//! A Proxy is not a shape node-js could fake with a property map: every one of
//! its internal methods has to be diverted, so it is its own heap variant
//! (`JsObj::Proxy`) and this module is the single place the diversion happens.
//! The funnels the rest of the runtime already routes through —
//! `builtins::get_property` / `set_property` / `has_property` /
//! `delete_property` / `object_keys`, `host::invoke` / `construct_nt` — each
//! call into here first; when the handler has no trap for the operation, the
//! `no_trap` fallback re-runs the SAME funnel against the target, which is what
//! makes `new Proxy(t, {})` observationally indistinguishable from `t`.
//!
//! Not implemented, deliberately, and recorded in BUGS.md rather than faked: the
//! spec's trap-result *invariant* checks (10.5.x steps that throw when a trap
//! contradicts a non-configurable/non-extensible target property). node-js
//! reports the trap's answer as given. Every trap itself is real.

use crate::host::{self, with_host, JsObj};
use fusevm::Value;

/// `(target, handler)` when `v` is a Proxy — revoked or not.
pub fn parts(v: &Value) -> Option<(Value, Value)> {
    with_host(|h| match h.get(v) {
        Some(JsObj::Proxy {
            target, handler, ..
        }) => Some((target.clone(), handler.clone())),
        _ => None,
    })
}

/// Whether `v` is a Proxy whose `[[ProxyHandler]]` is still live.
fn revoked(v: &Value) -> bool {
    with_host(|h| matches!(h.get(v), Some(JsObj::Proxy { revoked, .. }) if *revoked))
}

/// The proxy chain's ultimate non-proxy target — what `Array.isArray`,
/// `Object.prototype.toString` and `typeof` classify by (10.5.x defer those to
/// `[[ProxyTarget]]`, and a proxy of a proxy defers again).
pub fn ultimate_target(v: &Value) -> Option<Value> {
    let mut cur = parts(v)?.0;
    for _ in 0..100 {
        match parts(&cur) {
            Some((t, _)) => cur = t,
            None => return Some(cur),
        }
    }
    Some(cur)
}

/// The object `IsArray` (7.2.2) decides on: `v`, or the end of its proxy chain.
/// Every proxy passed on the way must still be live.
pub fn is_array_subject(v: &Value) -> Result<Value, String> {
    subject_through(v, "IsArray")
}

/// [`is_array_subject`] for an operation that begins with `IsArray` but reports
/// itself by its own name (`Object.prototype.toString`).
pub fn require_live(v: &Value, op: &str) -> Result<(), String> {
    subject_through(v, op).map(|_| ())
}

fn subject_through(v: &Value, op: &str) -> Result<Value, String> {
    let mut cur = v.clone();
    while let Some((target, _)) = parts(&cur) {
        if revoked(&cur) {
            return Err(revoked_err(op));
        }
        cur = target;
    }
    Ok(cur)
}

/// V8's message for an operation attempted on a revoked proxy.
fn revoked_err(op: &str) -> String {
    host::type_error(&format!(
        "Cannot perform '{op}' on a proxy that has been revoked"
    ))
}

/// Resolve trap `name` on `v`'s handler.
///
/// `Ok(None)` means "not a proxy, or no such trap" — the caller runs its
/// ordinary path (against the target, for the no-trap case). A revoked proxy
/// and a non-callable trap both throw here, before any target work happens.
/// Whether this proxy's handler installs `name` as a callable trap.
///
/// Distinguishes "the trap answered, and this is its answer" from "there is no
/// trap, so the read forwarded to the target" — the two are indistinguishable
/// in the returned value, and `ToPrimitive` has to tell them apart: a `get`
/// trap that hands back a non-callable `toString` refuses the conversion, while
/// a trapless proxy over a `Map` brands as its target does.
pub fn has_trap(v: &Value, name: &str) -> bool {
    matches!(trap(v, name), Ok(Some(_)))
}

fn trap(v: &Value, name: &str) -> Result<Option<(Value, Value, Value)>, String> {
    let Some((target, handler)) = parts(v) else {
        return Ok(None);
    };
    if revoked(v) {
        return Err(revoked_err(name));
    }
    let t = crate::builtins::get_property(&handler, name)?;
    if matches!(t, Value::Undef) || with_host(|h| h.is_null(&t)) {
        return Ok(None);
    }
    if !with_host(|h| host::is_callable(h, &t)) {
        return Err(host::type_error(&format!(
            "'{}' returned for property '{name}' of object '#<Object>' is not a function",
            with_host(|h| h.str_of(&t))
        )));
    }
    Ok(Some((t, target, handler)))
}

/// The target of a proxy whose handler declines the operation (no trap), or
/// `None` when `v` is not a proxy at all. Errors on a revoked proxy.
fn no_trap(v: &Value, op: &str) -> Result<Option<Value>, String> {
    match parts(v) {
        None => Ok(None),
        Some((target, _)) if !revoked(v) => Ok(Some(target)),
        Some(_) => Err(revoked_err(op)),
    }
}

/// An internal property key as the JS value a trap receives: the SYMBOL for a
/// symbol-keyed property (`@@sym:7`, `@@iterator`), a string otherwise. A trap
/// that inspects its key argument must see what the script wrote.
pub fn key_value(k: &str) -> Value {
    with_host(|h| {
        if let Some(s) = h.symbol_of_key(k) {
            return s;
        }
        match k.strip_prefix("@@") {
            Some(name) if host::WELL_KNOWN_SYMBOLS.contains(&name) => h.well_known_symbol(name),
            _ => h.new_str(k),
        }
    })
}

fn call(t: &Value, handler: &Value, args: Vec<Value>) -> Result<Value, String> {
    host::invoke(t, args, Some(handler.clone()))
}

// ── the thirteen traps ───────────────────────────────────────────────────────

/// `[[Get]]`. `Ok(None)` → not a proxy; the caller proceeds normally.
// ── trap invariants (10.5) ──────────────────────────────────────────────────
//
// A proxy may lie about most things, but not about a property the TARGET has
// pinned. None of these checks existed: a trap could report a different value
// for a non-configurable non-writable property, hide one from `in` or
// `ownKeys`, claim a frozen object was extensible, or report a prototype an
// unextensible target does not have. Every one is what a membrane or a
// hardened-JS shim relies on to know a frozen thing stays frozen.
fn invariant(msg: &str) -> String {
    host::type_error(msg)
}

/// V8's side-effect-free rendering of a value inside an invariant message.
fn shown(v: &Value) -> String {
    crate::builtins::no_side_effects_string_pub(v)
}

/// A Property Descriptor record (6.2.6): each field present or absent.
#[derive(Default)]
struct Desc {
    value: Option<Value>,
    writable: Option<bool>,
    get: Option<Value>,
    set: Option<Value>,
    enumerable: Option<bool>,
    configurable: Option<bool>,
}

impl Desc {
    fn is_accessor(&self) -> bool {
        self.get.is_some() || self.set.is_some()
    }
    fn is_data(&self) -> bool {
        self.value.is_some() || self.writable.is_some()
    }
    fn is_generic(&self) -> bool {
        !self.is_accessor() && !self.is_data()
    }
    fn is_empty(&self) -> bool {
        self.is_generic() && self.enumerable.is_none() && self.configurable.is_none()
    }

    /// `ToPropertyDescriptor(obj)` (6.2.6.5): each field read only when the
    /// object HAS it, in the spec's order, with V8's wording for each refusal.
    fn from_object(obj: &Value) -> Result<Desc, String> {
        if !with_host(|h| {
            matches!(obj, Value::Obj(_)) && !h.is_null(obj) && !host::is_primitive(h, obj)
        }) {
            return Err(host::type_error(&format!(
                "Property description must be an object: {}",
                shown(obj)
            )));
        }
        let field = |k: &str| -> Result<Option<Value>, String> {
            if crate::builtins::has_property(obj, k)? {
                crate::builtins::get_property(obj, k).map(Some)
            } else {
                Ok(None)
            }
        };
        let truthy = |v: Value| with_host(|h| h.truthy(&v));
        let mut d = Desc {
            enumerable: field("enumerable")?.map(truthy),
            configurable: field("configurable")?.map(truthy),
            value: field("value")?,
            writable: field("writable")?.map(truthy),
            ..Desc::default()
        };
        for (k, slot, what) in [("get", &mut d.get, "Getter"), ("set", &mut d.set, "Setter")] {
            if let Some(f) = field(k)? {
                if !matches!(f, Value::Undef) && !with_host(|h| host::is_callable(h, &f)) {
                    return Err(host::type_error(&format!(
                        "{what} must be a function: {}",
                        shown(&f)
                    )));
                }
                *slot = Some(f);
            }
        }
        if d.is_accessor() && d.is_data() {
            return Err(host::type_error(&format!(
                "Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, {}",
                shown(obj)
            )));
        }
        Ok(d)
    }

    /// `CompletePropertyDescriptor` (6.2.6.6).
    fn complete(mut self) -> Desc {
        if self.is_generic() || self.is_data() {
            self.value.get_or_insert(Value::Undef);
            self.writable.get_or_insert(false);
        } else {
            self.get.get_or_insert(Value::Undef);
            self.set.get_or_insert(Value::Undef);
        }
        self.enumerable.get_or_insert(false);
        self.configurable.get_or_insert(false);
        self
    }

    /// `FromPropertyDescriptor` (6.2.6.4): an object with the present fields,
    /// in the spec's order.
    fn to_object(&self) -> Value {
        let mut m = indexmap::IndexMap::new();
        if let Some(v) = &self.value {
            m.insert("value".to_string(), v.clone());
        }
        if let Some(w) = self.writable {
            m.insert("writable".to_string(), Value::Bool(w));
        }
        if let Some(g) = &self.get {
            m.insert("get".to_string(), g.clone());
        }
        if let Some(s) = &self.set {
            m.insert("set".to_string(), s.clone());
        }
        if let Some(e) = self.enumerable {
            m.insert("enumerable".to_string(), Value::Bool(e));
        }
        if let Some(c) = self.configurable {
            m.insert("configurable".to_string(), Value::Bool(c));
        }
        with_host(|h| h.new_object(m))
    }
}

/// `target.[[GetOwnProperty]](key)` as a record, `None` when absent. A proxy
/// target answers through its own traps.
fn target_desc(target: &Value, key: &str) -> Result<Option<Desc>, String> {
    let d = crate::builtins::own_descriptor_pub(target, key_value(key))?;
    if matches!(d, Value::Undef) {
        return Ok(None);
    }
    Desc::from_object(&d).map(Some)
}

/// `IsExtensible(target)`, through the target's own trap when it is a proxy.
fn target_extensible(target: &Value) -> Result<bool, String> {
    match is_extensible(target)? {
        Some(b) => Ok(b),
        None => Ok(with_host(|h| h.is_extensible(target))),
    }
}

/// `IsCompatiblePropertyDescriptor(extensible, desc, current)` (10.1.6.2):
/// `ValidateAndApplyPropertyDescriptor` with no object to apply it to.
fn is_compatible(extensible: bool, desc: &Desc, current: Option<&Desc>) -> bool {
    let Some(current) = current else {
        return extensible;
    };
    if desc.is_empty() || current.configurable != Some(false) {
        return true;
    }
    if desc.configurable == Some(true) {
        return false;
    }
    if desc.enumerable.is_some() && desc.enumerable != current.enumerable {
        return false;
    }
    if !desc.is_generic() && desc.is_accessor() != current.is_accessor() {
        return false;
    }
    let differs = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
        (Some(x), Some(y)) => !crate::builtins::same_value(x, y),
        (Some(x), None) => !matches!(x, Value::Undef),
        _ => false,
    };
    if current.is_accessor() {
        return !differs(&desc.get, &current.get) && !differs(&desc.set, &current.set);
    }
    if current.writable == Some(false) {
        return desc.writable != Some(true) && !differs(&desc.value, &current.value);
    }
    true
}

pub fn get(v: &Value, key: &str, receiver: &Value) -> Result<Option<Value>, String> {
    if let Some((t, target, handler)) = trap(v, "get")? {
        let k = key_value(key);
        let got = call(&t, &handler, vec![target.clone(), k, receiver.clone()])?;
        // 10.5.8 step 9: a non-configurable property pins the answer — a
        // read-only data property to its value, an accessor with no getter to
        // `undefined`.
        if let Some(d) = target_desc(&target, key)?.filter(|d| d.configurable == Some(false)) {
            if d.is_data() && d.writable == Some(false) {
                let val = d.value.clone().unwrap_or(Value::Undef);
                if !crate::builtins::same_value(&got, &val) {
                    return Err(invariant(&format!(
                        "'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 '{}')",
                        shown(&val),
                        shown(&got)
                    )));
                }
            }
            if d.is_accessor()
                && matches!(d.get, Some(Value::Undef) | None)
                && !matches!(got, Value::Undef)
            {
                return Err(invariant(&format!(
                    "'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 '{}')",
                    shown(&got)
                )));
            }
        }
        return Ok(Some(got));
    }
    match no_trap(v, "get")? {
        Some(target) => crate::builtins::get_property_recv(&target, key, receiver).map(Some),
        None => Ok(None),
    }
}

/// `[[Set]]`. `Ok(true)` means the write was handled here.
pub fn set(v: &Value, key: &str, val: &Value, receiver: &Value) -> Result<bool, String> {
    if let Some((t, target, handler)) = trap(v, "set")? {
        let k = key_value(key);
        let r = call(
            &t,
            &handler,
            vec![target.clone(), k, val.clone(), receiver.clone()],
        )?;
        // A FALSISH return means the trap refused the write. That is silent in
        // sloppy code and a TypeError in strict — the same split an ordinary
        // refused write has, and `Reflect.set` reports it as `false` either way.
        // The return value was discarded, so a refusing trap looked like a
        // successful write.
        if !with_host(|h| h.truthy(&r)) {
            return Ok(false);
        }
        // 10.5.9 step 10: reporting success for a write the target pins is a
        // lie — a read-only data property holding another value, or an
        // accessor with no setter.
        if let Some(d) = target_desc(&target, key)?.filter(|d| d.configurable == Some(false)) {
            if d.is_data()
                && d.writable == Some(false)
                && !crate::builtins::same_value(val, d.value.as_ref().unwrap_or(&Value::Undef))
            {
                return Err(invariant(&format!(
                    "'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"
                )));
            }
            if d.is_accessor() && matches!(d.set, Some(Value::Undef) | None) {
                return Err(invariant(&format!(
                    "'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"
                )));
            }
        }
        return Ok(true);
    }
    match no_trap(v, "set")? {
        Some(target) => {
            if receiver_observes_set(v, &target, key, receiver) {
                return define_on_proxy_receiver(v, key, val);
            }
            crate::builtins::set_property_pub(&target, key, val.clone())?;
            Ok(true)
        }
        None => Ok(false),
    }
}

/// Whether a trapless `[[Set]]` has to run `OrdinarySet` (10.1.9.2) against the
/// target with THIS proxy as the receiver, rather than forwarding the write.
///
/// The forward is observationally identical unless the handler traps one of
/// the two receiver operations that `OrdinarySet` performs on a data property:
/// `[[GetOwnProperty]]` (step 3.c) and `[[DefineOwnProperty]]` (3.d.iv / 3.e).
/// A logging or validating handler that installs only those still sees every
/// `p.k = v`; forwarding skipped both traps. Only the plain case takes the
/// receiver route: a data property the target can accept, on an ordinary
/// target. An accessor or a read-only slot keeps the ordinary forward.
fn receiver_observes_set(v: &Value, target: &Value, key: &str, receiver: &Value) -> bool {
    with_host(|h| h.strict_eq(receiver, v))
        && (has_trap(v, "getOwnPropertyDescriptor") || has_trap(v, "defineProperty"))
        && parts(target).is_none()
        && with_host(|h| {
            host::lookup_accessor(h, target, key).is_none() && h.can_write_prop(target, key)
        })
}

/// 10.1.9.2 steps 3.c–3.e with the proxy `v` as the receiver: read its own
/// descriptor through the `getOwnPropertyDescriptor` trap, then DEFINE through
/// the `defineProperty` trap — `{ value }` alone over an existing writable data
/// property, a full enumerable/writable/configurable data descriptor for a new
/// one. A refused define is a TypeError in strict code, named for the trap that
/// refused (V8's message), and a silent `false` in sloppy code.
fn define_on_proxy_receiver(v: &Value, key: &str, val: &Value) -> Result<bool, String> {
    let existing = get_own_descriptor(v, key)?.unwrap_or(Value::Undef);
    let mut desc = indexmap::IndexMap::new();
    desc.insert("value".to_string(), val.clone());
    if !matches!(existing, Value::Undef) {
        let field = |n: &str| crate::builtins::get_property(&existing, n);
        let is_accessor = with_host(|h| {
            host::lookup_chain(h, &existing, "get").is_some()
                || host::lookup_chain(h, &existing, "set").is_some()
        });
        let writable = field("writable")?;
        if is_accessor || !with_host(|h| h.truthy(&writable)) {
            return Ok(false);
        }
    } else {
        for flag in ["writable", "enumerable", "configurable"] {
            desc.insert(flag.to_string(), Value::Bool(true));
        }
    }
    let desc = with_host(|h| h.new_object(desc));
    if define_property(v, key, &desc)? {
        return Ok(true);
    }
    if with_host(|h| h.current_strict()) {
        return Err(host::type_error(&format!(
            "'defineProperty' on proxy: trap returned falsish for property '{key}'"
        )));
    }
    Ok(false)
}

/// `[[HasProperty]]` (`key in proxy`).
pub fn has(v: &Value, key: &str) -> Result<Option<bool>, String> {
    if let Some((t, target, handler)) = trap(v, "has")? {
        let k = key_value(key);
        let r = call(&t, &handler, vec![target.clone(), k])?;
        let reported = with_host(|h| h.truthy(&r));
        // 10.5.7 step 9: a non-configurable property, or any property of a
        // non-extensible target, cannot be hidden from `in`.
        if !reported {
            if let Some(d) = target_desc(&target, key)? {
                if d.configurable == Some(false) {
                    return Err(invariant(&format!(
                        "'has' on proxy: trap returned falsish for property '{key}' which exists in the proxy target as non-configurable"
                    )));
                }
                if !target_extensible(&target)? {
                    return Err(invariant(&format!(
                        "'has' on proxy: trap returned falsish for property '{key}' but the proxy target is not extensible"
                    )));
                }
            }
        }
        return Ok(Some(reported));
    }
    match no_trap(v, "has")? {
        Some(target) => crate::builtins::has_property(&target, key).map(Some),
        None => Ok(None),
    }
}

/// `[[Delete]]`.
pub fn delete(v: &Value, key: &str) -> Result<Option<bool>, String> {
    if let Some((t, target, handler)) = trap(v, "deleteProperty")? {
        let k = key_value(key);
        let r = call(&t, &handler, vec![target.clone(), k])?;
        let reported = with_host(|h| h.truthy(&r));
        // 10.5.10 steps 10-13: a non-configurable property, or any property of
        // a non-extensible target, cannot be reported as deleted.
        if reported {
            if let Some(d) = target_desc(&target, key)? {
                if d.configurable == Some(false) {
                    return Err(invariant(&format!(
                        "'deleteProperty' on proxy: trap returned truish for property '{key}' which is non-configurable in the proxy target"
                    )));
                }
                if !target_extensible(&target)? {
                    return Err(invariant(&format!(
                        "'deleteProperty' on proxy: trap returned truish for property '{key}' but the proxy target is non-extensible"
                    )));
                }
            }
        }
        return Ok(Some(reported));
    }
    match no_trap(v, "deleteProperty")? {
        Some(target) => crate::builtins::delete_property(&target, key).map(Some),
        None => Ok(None),
    }
}

/// `[[OwnPropertyKeys]]`, as INTERNAL key strings (so a symbol key comes back as
/// `@@sym:<id>` — the form the rest of the runtime indexes by).
pub fn own_keys(v: &Value) -> Result<Option<Vec<String>>, String> {
    if let Some((t, target, handler)) = trap(v, "ownKeys")? {
        let r = call(&t, &handler, vec![target.clone()])?;
        // `CreateListFromArrayLike(result, « String, Symbol »)`: an array-like
        // read by `length` and index, whose every element is a property key.
        if !with_host(|h| {
            matches!(r, Value::Obj(_)) && !h.is_null(&r) && !host::is_primitive(h, &r)
        }) {
            return Err(host::type_error(
                "CreateListFromArrayLike called on non-object",
            ));
        }
        let len = crate::builtins::length_of_array_like(&r)?;
        let mut out = Vec::with_capacity(len);
        for i in 0..len {
            let k = crate::builtins::get_property(&r, &i.to_string())?;
            let is_key = with_host(|h| {
                h.as_str(&k).is_some() || matches!(h.get(&k), Some(JsObj::Symbol { .. }))
            });
            if !is_key {
                return Err(host::type_error(&format!(
                    "{} is not a valid property name",
                    shown(&k)
                )));
            }
            out.push(host::to_property_key(&k)?);
        }
        // The list must contain no duplicates …
        let mut seen: Vec<&String> = Vec::with_capacity(out.len());
        for k in &out {
            if seen.contains(&k) {
                return Err(invariant(
                    "'ownKeys' on proxy: trap returned duplicate entries",
                ));
            }
            seen.push(k);
        }
        // … must include every non-configurable own key of the target …
        let target_keys = with_host(|h| {
            let mut ks = h.own_key_names(&target, false);
            ks.extend(
                h.own_symbol_keys(&target)
                    .iter()
                    .map(|sym| h.property_key(sym))
                    .collect::<Vec<_>>(),
            );
            ks
        });
        for k in &target_keys {
            let pinned =
                crate::builtins::own_prop_facts(&target, k).is_some_and(|(_, _, conf, _)| !conf);
            if pinned && !out.contains(k) {
                return Err(invariant(&format!(
                    "'ownKeys' on proxy: trap result did not include '{k}'"
                )));
            }
        }
        // … and, for a NON-EXTENSIBLE target, must be exactly its own keys.
        if !with_host(|h| h.is_extensible(&target)) {
            for k in &target_keys {
                if !out.contains(k) {
                    return Err(invariant(&format!(
                        "'ownKeys' on proxy: trap result did not include '{k}'"
                    )));
                }
            }
            for k in &out {
                if !target_keys.contains(k) {
                    return Err(invariant(
                        "'ownKeys' on proxy: trap returned extra keys but proxy target is non-extensible",
                    ));
                }
            }
        }
        return Ok(Some(out));
    }
    match no_trap(v, "ownKeys")? {
        Some(target) => {
            let mut keys = with_host(|h| h.own_key_names(&target, false));
            keys.extend(with_host(|h| {
                h.own_symbol_keys(&target)
                    .iter()
                    .map(|s| h.property_key(s))
                    .collect::<Vec<_>>()
            }));
            Ok(Some(keys))
        }
        None => Ok(None),
    }
}

/// `[[GetOwnProperty]]` — the descriptor object (or `undefined`).
pub fn get_own_descriptor(v: &Value, key: &str) -> Result<Option<Value>, String> {
    if let Some((t, target, handler)) = trap(v, "getOwnPropertyDescriptor")? {
        let k = key_value(key);
        let d = call(&t, &handler, vec![target.clone(), k])?;
        return checked_own_descriptor(&target, key, &d).map(Some);
    }
    match no_trap(v, "getOwnPropertyDescriptor")? {
        Some(target) => {
            let k = key_value(key);
            crate::builtins::own_descriptor_pub(&target, k).map(Some)
        }
        None => Ok(None),
    }
}

/// 10.5.5 steps 8-17: validate what a `getOwnPropertyDescriptor` trap
/// returned against the target, and hand back the COMPLETED descriptor the
/// operation yields — not the trap's own object.
fn checked_own_descriptor(target: &Value, key: &str, d: &Value) -> Result<Value, String> {
    let is_object =
        with_host(|h| matches!(d, Value::Obj(_)) && !h.is_null(d) && !host::is_primitive(h, d));
    if !is_object && !matches!(d, Value::Undef) {
        return Err(invariant(&format!(
            "'getOwnPropertyDescriptor' on proxy: trap returned neither object nor undefined for property '{key}'"
        )));
    }
    let target_d = target_desc(target, key)?;
    if !is_object {
        if let Some(td) = &target_d {
            if td.configurable == Some(false) {
                return Err(invariant(&format!(
                    "'getOwnPropertyDescriptor' on proxy: trap returned undefined for property '{key}' which is non-configurable in the proxy target"
                )));
            }
            if !target_extensible(target)? {
                return Err(invariant(&format!(
                    "'getOwnPropertyDescriptor' on proxy: trap returned undefined for property '{key}' which exists in the non-extensible proxy target"
                )));
            }
        }
        return Ok(Value::Undef);
    }
    let extensible = target_extensible(target)?;
    let result = Desc::from_object(d)?.complete();
    if !is_compatible(extensible, &result, target_d.as_ref()) {
        return Err(invariant(&format!(
            "'getOwnPropertyDescriptor' on proxy: trap returned descriptor for property '{key}' that is incompatible with the existing property in the proxy target"
        )));
    }
    if result.configurable == Some(false) {
        match &target_d {
            Some(td) if td.configurable == Some(false) => {
                if result.writable == Some(false) && td.writable == Some(true) {
                    return Err(invariant(&format!(
                        "'getOwnPropertyDescriptor' on proxy: trap reported non-configurable and non-writable for property '{key}' which is non-configurable, writable in the proxy target"
                    )));
                }
            }
            _ => {
                return Err(invariant(&format!(
                    "'getOwnPropertyDescriptor' on proxy: trap reported non-configurability for property '{key}' which is either non-existent or configurable in the proxy target"
                )));
            }
        }
    }
    Ok(result.to_object())
}

/// `[[DefineOwnProperty]]`. The trap receives the descriptor normalized by
/// `ToPropertyDescriptor` → `FromPropertyDescriptor`, not the caller's object.
pub fn define_property(v: &Value, key: &str, desc: &Value) -> Result<bool, String> {
    if let Some((t, target, handler)) = trap(v, "defineProperty")? {
        let k = key_value(key);
        let d = Desc::from_object(desc)?;
        let r = call(&t, &handler, vec![target.clone(), k, d.to_object()])?;
        // A FALSISH return means the trap refused. Unlike `set` and
        // `deleteProperty`, this one throws from `Object.defineProperty` in
        // SLOPPY code too — only `Reflect.defineProperty` reports it as
        // `false`. The return value was discarded, so a refusing trap looked
        // like a successful define.
        if !with_host(|h| h.truthy(&r)) {
            return Ok(false);
        }
        // 10.5.6 steps 10-16: the target must be able to hold what the trap
        // claims to have defined.
        let target_d = target_desc(&target, key)?;
        let extensible = target_extensible(&target)?;
        let setting_config_false = d.configurable == Some(false);
        let non_configurable = || {
            invariant(&format!(
                "'defineProperty' on proxy: trap returned truish for defining non-configurable property '{key}' which is either non-existent or configurable in the proxy target"
            ))
        };
        match &target_d {
            None => {
                if !extensible {
                    return Err(invariant(&format!(
                        "'defineProperty' on proxy: trap returned truish for adding property '{key}' to the non-extensible proxy target"
                    )));
                }
                if setting_config_false {
                    return Err(non_configurable());
                }
            }
            Some(td) => {
                if !is_compatible(extensible, &d, Some(td)) {
                    return Err(invariant(&format!(
                        "'defineProperty' on proxy: trap returned truish for adding property '{key}'  that is incompatible with the existing property in the proxy target"
                    )));
                }
                if setting_config_false && td.configurable == Some(true) {
                    return Err(non_configurable());
                }
                if td.is_data()
                    && td.configurable == Some(false)
                    && td.writable == Some(true)
                    && d.writable == Some(false)
                {
                    return Err(invariant(&format!(
                        "'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."
                    )));
                }
            }
        }
        return Ok(true);
    }
    match no_trap(v, "defineProperty")? {
        Some(target) => {
            let k = key_value(key);
            crate::builtins::define_property_pub(&target, k, desc.clone())?;
            Ok(true)
        }
        None => Ok(false),
    }
}

/// `[[GetPrototypeOf]]`.
pub fn get_prototype_of(v: &Value) -> Result<Option<Value>, String> {
    if let Some((t, target, handler)) = trap(v, "getPrototypeOf")? {
        let reported = call(&t, &handler, vec![target.clone()])?;
        // A non-extensible target's prototype is fixed, so it must be reported
        // as it is.
        if !with_host(|h| h.is_extensible(&target)) {
            let actual = crate::builtins::prototype_of(&target);
            if !with_host(|h| h.strict_eq(&reported, &actual)) {
                return Err(invariant(
                    "'getPrototypeOf' on proxy: proxy target is non-extensible but the trap did not return its actual prototype",
                ));
            }
        }
        return Ok(Some(reported));
    }
    match no_trap(v, "getPrototypeOf")? {
        Some(target) => Ok(Some(crate::builtins::prototype_of(&target))),
        None => Ok(None),
    }
}

/// `[[SetPrototypeOf]]`.
///
/// The trap's answer is the result (10.5.2): `false` is a refusal, which
/// `Object.setPrototypeOf` turns into a TypeError and `Reflect.setPrototypeOf`
/// reports. A non-extensible target's prototype cannot be changed, so `true`
/// is checked against the prototype it really has.
pub fn set_prototype_of(v: &Value, proto: &Value) -> Result<bool, String> {
    if let Some((t, target, handler)) = trap(v, "setPrototypeOf")? {
        let r = call(&t, &handler, vec![target.clone(), proto.clone()])?;
        if !with_host(|h| h.truthy(&r)) {
            return Ok(false);
        }
        if !target_extensible(&target)? {
            let actual = match get_prototype_of(&target)? {
                Some(p) => p,
                None => crate::builtins::prototype_of(&target),
            };
            if !crate::builtins::same_value(proto, &actual) {
                return Err(invariant(
                    "'setPrototypeOf' on proxy: trap returned truish for setting a new prototype on the non-extensible proxy target",
                ));
            }
        }
        return Ok(true);
    }
    match no_trap(v, "setPrototypeOf")? {
        // `target.[[SetPrototypeOf]]` (10.5.2 step 7): an ordinary object
        // refuses a change when it is non-extensible and agrees to a no-op,
        // and refuses a cycle.
        Some(target) => {
            if !target_extensible(&target)? {
                let actual = match get_prototype_of(&target)? {
                    Some(p) => p,
                    None => crate::builtins::prototype_of(&target),
                };
                return Ok(crate::builtins::same_value(proto, &actual));
            }
            if crate::builtins::would_cycle_pub(&target, proto) {
                return Ok(false);
            }
            with_host(|h| h.set_proto(&target, proto.clone()));
            Ok(true)
        }
        None => Ok(false),
    }
}

/// `[[IsExtensible]]`.
pub fn is_extensible(v: &Value) -> Result<Option<bool>, String> {
    if let Some((t, target, handler)) = trap(v, "isExtensible")? {
        // Extensibility cannot be misreported: the answer must match the
        // target's, so a frozen target cannot be passed off as open.
        let reported = call(&t, &handler, vec![target.clone()])?;
        let reported = with_host(|h| h.truthy(&reported));
        let actual = target_extensible(&target)?;
        if reported != actual {
            return Err(invariant(&format!(
                "'isExtensible' on proxy: trap result does not reflect extensibility of proxy target (which is '{actual}')"
            )));
        }
        return Ok(Some(reported));
    }
    match no_trap(v, "isExtensible")? {
        Some(target) => Ok(Some(with_host(|h| h.is_extensible(&target)))),
        None => Ok(None),
    }
}

/// `[[PreventExtensions]]`.
///
/// `Ok(None)` → not a proxy. Otherwise the operation's boolean result
/// (10.5.4): a trap's `false` is a refusal — a TypeError from
/// `Object.preventExtensions`, `false` from `Reflect.preventExtensions` — and
/// its `true` must leave the target really non-extensible.
pub fn prevent_extensions(v: &Value) -> Result<Option<bool>, String> {
    if let Some((t, target, handler)) = trap(v, "preventExtensions")? {
        let r = call(&t, &handler, vec![target.clone()])?;
        let reported = with_host(|h| h.truthy(&r));
        if reported && target_extensible(&target)? {
            return Err(invariant(
                "'preventExtensions' on proxy: trap returned truish but the proxy target is extensible",
            ));
        }
        return Ok(Some(reported));
    }
    match no_trap(v, "preventExtensions")? {
        Some(target) => match prevent_extensions(&target)? {
            Some(b) => Ok(Some(b)),
            None => {
                with_host(|h| h.prevent_extensions(&target));
                Ok(Some(true))
            }
        },
        None => Ok(None),
    }
}

/// V8's TypeError for an `Object.preventExtensions`/`freeze`/`seal` whose
/// proxy trap refused.
pub fn prevent_extensions_refused() -> String {
    host::type_error("'preventExtensions' on proxy: trap returned falsish")
}

/// `[[Call]]`.
pub fn apply(v: &Value, args: Vec<Value>, this: Option<Value>) -> Result<Option<Value>, String> {
    if let Some((t, target, handler)) = trap(v, "apply")? {
        let this_arg = this.unwrap_or(Value::Undef);
        let list = with_host(|h| h.new_array(args));
        return call(&t, &handler, vec![target, this_arg, list]).map(Some);
    }
    match no_trap(v, "apply")? {
        Some(target) => host::invoke(&target, args, this).map(Some),
        None => Ok(None),
    }
}

/// `[[Construct]]`.
pub fn construct(v: &Value, args: Vec<Value>, new_target: &Value) -> Result<Option<Value>, String> {
    if let Some((t, target, handler)) = trap(v, "construct")? {
        let list = with_host(|h| h.new_array(args));
        let made = call(&t, &handler, vec![target, list, new_target.clone()])?;
        // 10.5.13 step 10: `new` always yields an object.
        if !with_host(|h| {
            matches!(made, Value::Obj(_)) && !h.is_null(&made) && !host::is_primitive(h, &made)
        }) {
            return Err(invariant(&format!(
                "'construct' on proxy: trap returned non-object ('{}')",
                shown(&made)
            )));
        }
        return Ok(Some(made));
    }
    match no_trap(v, "construct")? {
        Some(target) => {
            // 10.1.13 OrdinaryCreateFromConstructor reads `newTarget.prototype`
            // with `[[Get]]` — through this proxy's `get` trap when it is the
            // new.target — and the object it builds inherits from the answer.
            let proto = if parts(new_target).is_some() {
                Some(crate::builtins::get_property(new_target, "prototype")?)
            } else {
                None
            };
            let made = host::construct_nt(&target, args, new_target.clone())?;
            if let Some(p) = proto {
                let plain = matches!(p, Value::Obj(_))
                    && with_host(|h| !h.is_null(&p) && !host::is_primitive(h, &p));
                let fresh = matches!(with_host(|h| h.get(&made).cloned()), Some(JsObj::Object(_)));
                if plain && fresh {
                    with_host(|h| h.set_proto(&made, p));
                }
            }
            Ok(Some(made))
        }
        None => Ok(None),
    }
}

// ── enumeration built on the traps ───────────────────────────────────────────

/// The own keys of a proxy that are ENUMERABLE string keys — `Object.keys`,
/// `for-in`'s own half, object spread and `JSON.stringify` all need this shape.
/// 10.5.11 defines it as `ownKeys` filtered by each key's `[[GetOwnProperty]]`,
/// so both traps really do run, in that order.
pub fn own_enum_string_keys(v: &Value) -> Result<Vec<String>, String> {
    let Some(keys) = own_keys(v)? else {
        return Ok(Vec::new());
    };
    let mut out = Vec::new();
    for k in keys {
        if host::is_symbol_key(&k) {
            continue;
        }
        let Some(d) = get_own_descriptor(v, &k)? else {
            continue;
        };
        let enumerable = with_host(|h| match h.get(&d) {
            Some(JsObj::Object(p)) => p.get("enumerable").map(|e| h.truthy(e)).unwrap_or(false),
            _ => false,
        });
        if enumerable {
            out.push(k);
        }
    }
    Ok(out)
}

/// Is `key` an own ENUMERABLE property of this proxy right now? One
/// `getOwnPropertyDescriptor` trap call, which is what `for-in` runs per key at
/// the moment it visits it (14.7.5.10) — `own_enum_string_keys` answers the same
/// question for every key at once, which is the wrong shape when the body
/// between two visits can delete a key or flip its enumerability.
pub fn own_enumerable(v: &Value, key: &str) -> Result<bool, String> {
    let Some(d) = get_own_descriptor(v, key)? else {
        return Ok(false);
    };
    Ok(with_host(|h| match h.get(&d) {
        Some(JsObj::Object(p)) => p.get("enumerable").map(|e| h.truthy(e)).unwrap_or(false),
        _ => false,
    }))
}

/// `(key, value)` for every own enumerable string key — spread / `Object.assign`
/// / `Object.entries`. Each of those (7.3.25 `CopyDataProperties`, 20.1.2.1
/// `Object.assign`, 7.3.23 `EnumerableOwnProperties` in key+value mode) visits
/// one key at a time: its `getOwnPropertyDescriptor` trap, then — if
/// enumerable — its `get` trap, before the next key's descriptor is asked for.
pub fn own_enum_entries(v: &Value) -> Result<Vec<(String, Value)>, String> {
    let Some(keys) = own_keys(v)? else {
        return Ok(Vec::new());
    };
    let mut out = Vec::with_capacity(keys.len());
    for k in keys {
        if host::is_symbol_key(&k) || !own_enumerable(v, &k)? {
            continue;
        }
        let val = get(v, &k, v)?.unwrap_or(Value::Undef);
        out.push((k, val));
    }
    Ok(out)
}

/// Whether the proxy chain bottoms out in an Array — the shape `IsArray` and
/// `Array.prototype[Symbol.iterator]` both key off.
fn wraps_array(v: &Value) -> bool {
    match ultimate_target(v) {
        Some(t) => with_host(|h| matches!(h.get(&t), Some(JsObj::Array(_)))),
        None => false,
    }
}

/// `GetIterator(proxy, sync)` → the iterator object. `Ok(None)` → not a proxy.
///
/// Three cases, in the order `GetIterator` reaches them:
/// a user `Symbol.iterator` read THROUGH the `get` trap, called with the proxy
/// as `this`; an array target still holding the default, whose
/// `Array.prototype[Symbol.iterator]` is a live array iterator over the PROXY —
/// each step re-reads `length` and then `Get(O, i)` through the traps
/// (23.1.5.1), never `has`; and anything else (Map/Set/string/generator
/// target), which iterates as the target does.
pub fn get_iterator(v: &Value) -> Result<Option<Value>, String> {
    if parts(v).is_none() {
        return Ok(None);
    }
    let array_backed = wraps_array(v);
    let iter_fn = get(v, "@@iterator", v)?.unwrap_or(Value::Undef);
    // node-js models `Array.prototype[Symbol.iterator]` as a thunk BOUND to the
    // array it was read off, where the real method is generic over `this`. Read
    // through a proxy, that thunk would walk the TARGET and ignore every answer
    // the `get` trap gave — so an array-backed proxy still holding the default
    // gets the generic iterator over the proxy itself. A user-installed iterator
    // is an ordinary function value and is called.
    let default_array_iter =
        array_backed && with_host(|h| matches!(h.get(&iter_fn), Some(JsObj::BoundMethod { .. })));
    if !default_array_iter && with_host(|h| host::is_callable(h, &iter_fn)) {
        return host::call_iterator_method(&iter_fn, v).map(Some);
    }
    if array_backed {
        return Ok(Some(crate::builtins::array_iterator(
            v,
            host::ArrayIterKind::Values,
        )));
    }
    let target = no_trap(v, "get")?.expect("checked it is a proxy");
    let items = host::iter_all(&target)?;
    Ok(Some(with_host(|h| {
        h.alloc(JsObj::Iter {
            items,
            idx: 0,
            array: None,
            brand: None,
        })
    })))
}

/// `[...proxy]` and the other consumers that drain: [`get_iterator`], stepped
/// to the end. `Ok(None)` → not a proxy.
pub fn iterate(v: &Value) -> Result<Option<Vec<Value>>, String> {
    let Some(iterator) = get_iterator(v)? else {
        return Ok(None);
    };
    if with_host(|h| matches!(h.get(&iterator), Some(JsObj::Iter { .. }))) {
        return host::iter_all(&iterator).map(Some);
    }
    host::drain_iterator(&iterator).map(Some)
}

/// `[...proxy]` / `for (… of proxy)`. `Ok(None)` → not a proxy.
/// `Get(O, "length")` once, then `Get(O, i)` for each index below it, all
/// through the traps.
fn length_walk(v: &Value) -> Result<Vec<Value>, String> {
    let len_v = get(v, "length", v)?.unwrap_or(Value::Undef);
    let len = with_host(|h| h.to_number(&len_v));
    let len = if len.is_finite() && len > 0.0 {
        len as usize
    } else {
        0
    };
    let mut out = Vec::with_capacity(len);
    for i in 0..len {
        out.push(get(v, &i.to_string(), v)?.unwrap_or(Value::Undef));
    }
    Ok(out)
}

/// The plain value `JSON.stringify` serializes a proxy as. `SerializeJSONArray`
/// and `SerializeJSONObject` both read every member through `[[Get]]`, so the
/// snapshot is taken through the traps rather than off the target.
pub fn json_snapshot(v: &Value) -> Result<Value, String> {
    // `SerializeJSONArray` (25.5.2.6) is `LengthOfArrayLike` then `Get` per
    // index — never `Symbol.iterator`, which a user may have replaced.
    if wraps_array(v) {
        let items = length_walk(v)?;
        return Ok(with_host(|h| h.new_array(items)));
    }
    // `SerializeJSONObject` takes `EnumerableOwnProperties(value, key)` — every
    // descriptor first — and only then `Get`s each key while serializing.
    let mut entries = Vec::new();
    for k in own_enum_string_keys(v)? {
        let val = get(v, &k, v)?.unwrap_or(Value::Undef);
        entries.push((k, val));
    }
    Ok(with_host(|h| {
        let mut m = indexmap::IndexMap::new();
        for (k, val) in entries {
            m.insert(k, val);
        }
        h.new_object(m)
    }))
}

// ── construction ─────────────────────────────────────────────────────────────

/// `new Proxy(target, handler)` (10.5.14 `ProxyCreate`).
pub fn create(args: &[Value]) -> Result<Value, String> {
    let target = args.first().cloned().unwrap_or(Value::Undef);
    let handler = args.get(1).cloned().unwrap_or(Value::Undef);
    let ok = |v: &Value| {
        with_host(|h| matches!(v, Value::Obj(_)) && !h.is_null(v) && !host::is_primitive(h, v))
    };
    if !ok(&target) || !ok(&handler) {
        return Err(host::type_error(
            "Cannot create proxy with a non-object as target or handler",
        ));
    }
    Ok(with_host(|h| {
        h.alloc(JsObj::Proxy {
            target,
            handler,
            revoked: false,
        })
    }))
}

/// `Proxy.revocable(target, handler)` → `{ proxy, revoke }`. The revoker is a
/// builtin thunk keyed by the proxy's heap index, so calling it twice is the
/// no-op the spec asks for rather than a second teardown.
pub fn revocable(args: &[Value]) -> Result<Value, String> {
    let proxy = create(args)?;
    let idx = match proxy {
        Value::Obj(i) => i,
        _ => unreachable!("create returns a heap object"),
    };
    let revoke = with_host(|h| h.alloc(JsObj::Builtin(format!("@@prevoke:{idx}"))));
    Ok(with_host(|h| {
        let mut m = indexmap::IndexMap::new();
        m.insert("proxy".to_string(), proxy);
        m.insert("revoke".to_string(), revoke);
        h.new_object(m)
    }))
}

/// Run a `@@prevoke:<idx>` thunk: mark the proxy dead so every trap throws.
///
/// The target handle is KEPT rather than nulled as 10.5.15 step 5 words it,
/// because `typeof` is fixed at creation by whether the target was callable and
/// V8 still answers `'function'` for a revoked proxy of a function. Nothing can
/// read the target through the proxy anymore — `revoked` is checked before any
/// trap or fallback runs.
pub fn revoke(idx: u32) -> Value {
    with_host(|h| {
        if let Some(JsObj::Proxy { revoked, .. }) = h.get_mut(&Value::Obj(idx)) {
            *revoked = true;
        }
    });
    Value::Undef
}