node-js 0.1.13

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
//! `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)
}

/// 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)
}

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()])?;
        // A non-configurable non-writable data property must be reported as it
        // is on the target.
        if let Some((val, writable, configurable, is_accessor)) =
            crate::builtins::own_prop_facts(&target, key)
        {
            if !configurable && !is_accessor && !writable && !with_host(|h| h.strict_eq(&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"
                )));
            }
        }
        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);
        }
        // Reporting success for a write the target pins is a lie.
        if let Some((cur, writable, configurable, is_accessor)) =
            crate::builtins::own_prop_facts(&target, key)
        {
            if !configurable && !is_accessor && !writable && !with_host(|h| h.strict_eq(val, &cur))
            {
                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"
                )));
            }
        }
        return Ok(true);
    }
    match no_trap(v, "set")? {
        Some(target) => {
            crate::builtins::set_property_pub(&target, key, val.clone())?;
            Ok(true)
        }
        None => 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));
        // A non-configurable property, or any property of a non-extensible
        // target, cannot be hidden from `in`.
        if !reported {
            if let Some((_, _, configurable, _)) = crate::builtins::own_prop_facts(&target, key) {
                if !configurable || !with_host(|h| h.is_extensible(&target)) {
                    return Err(invariant(&format!(
                        "'has' on proxy: trap returned falsish for property '{key}' which exists in the proxy target as non-configurable"
                    )));
                }
            }
        }
        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));
        // A non-configurable property cannot be reported as deleted.
        if reported {
            if let Some((_, _, configurable, _)) = crate::builtins::own_prop_facts(&target, key) {
                if !configurable {
                    return Err(invariant(&format!(
                        "'deleteProperty' on proxy: trap returned truish for property '{key}' which is non-configurable in the proxy target"
                    )));
                }
            }
        }
        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()])?;
        let items = with_host(|h| h.iter_vec(&r))?;
        let mut out = Vec::with_capacity(items.len());
        for k in items {
            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(&format!(
                    "'ownKeys' on proxy: trap returned duplicate entries for property '{k}'"
                )));
            }
            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])?;
        // A non-configurable property cannot be reported as absent.
        if matches!(d, Value::Undef) {
            if let Some((_, _, configurable, _)) = crate::builtins::own_prop_facts(&target, key) {
                if !configurable {
                    return Err(invariant(&format!(
                        "'getOwnPropertyDescriptor' on proxy: trap returned undefined for property '{key}' which is non-configurable in the proxy target"
                    )));
                }
            }
        }
        return Ok(Some(d));
    }
    match no_trap(v, "getOwnPropertyDescriptor")? {
        Some(target) => {
            let k = key_value(key);
            crate::builtins::own_descriptor_pub(&target, k).map(Some)
        }
        None => Ok(None),
    }
}

/// `[[DefineOwnProperty]]`.
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 r = call(&t, &handler, vec![target.clone(), k, desc.clone()])?;
        // 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);
        }
        // A new property cannot be added to a non-extensible target.
        if crate::builtins::own_prop_facts(&target, key).is_none()
            && !with_host(|h| h.is_extensible(&target))
        {
            return Err(invariant(&format!(
                "'defineProperty' on proxy: trap returned truish for adding property '{key}' to the non-extensible proxy target"
            )));
        }
        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]]`.
pub fn set_prototype_of(v: &Value, proto: &Value) -> Result<bool, String> {
    if let Some((t, target, handler)) = trap(v, "setPrototypeOf")? {
        call(&t, &handler, vec![target, proto.clone()])?;
        return Ok(true);
    }
    match no_trap(v, "setPrototypeOf")? {
        Some(target) => {
            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));
        if reported != with_host(|h| h.is_extensible(&target)) {
            return Err(invariant(
                "'isExtensible' on proxy: trap result does not reflect extensibility of proxy target",
            ));
        }
        return Ok(Some(reported));
    }
    match no_trap(v, "isExtensible")? {
        Some(target) => Ok(Some(with_host(|h| h.is_extensible(&target)))),
        None => Ok(None),
    }
}

/// `[[PreventExtensions]]`.
pub fn prevent_extensions(v: &Value) -> Result<bool, String> {
    if let Some((t, target, handler)) = trap(v, "preventExtensions")? {
        call(&t, &handler, vec![target])?;
        return Ok(true);
    }
    match no_trap(v, "preventExtensions")? {
        Some(target) => {
            with_host(|h| h.prevent_extensions(&target));
            Ok(true)
        }
        None => Ok(false),
    }
}

/// `[[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));
        return call(&t, &handler, vec![target, list, new_target.clone()]).map(Some);
    }
    match no_trap(v, "construct")? {
        Some(target) => host::construct_nt(&target, args, new_target.clone()).map(Some),
        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` / `JSON.stringify`. Each value is read through the `get`
/// trap, as the spec's `CreateDataPropertyOrThrow(…, Get(from, key))` requires.
pub fn own_enum_entries(v: &Value) -> Result<Vec<(String, Value)>, String> {
    let keys = own_enum_string_keys(v)?;
    let mut out = Vec::with_capacity(keys.len());
    for k in keys {
        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,
    }
}

/// `[...proxy]` / `for (… of proxy)`. `Ok(None)` → not a proxy.
///
/// Three cases, in the order `GetIterator` reaches them:
/// a user `Symbol.iterator` read THROUGH the `get` trap; an array target, whose
/// `Array.prototype[Symbol.iterator]` observably does `Get(O, "length")` then
/// `Get(O, i)` (so a `get` trap that lies about either is honored); and anything
/// else (Map/Set/string/generator target), which iterates as the target does.
pub fn iterate(v: &Value) -> Result<Option<Vec<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
    // falls through to the length-driven walk, which is what the generic method
    // observably does. A user-installed iterator is an ordinary function value
    // and keeps the fast path.
    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)) {
        let iterator = host::invoke(&iter_fn, Vec::new(), Some(v.clone()))?;
        return host::drain_iterator(&iterator).map(Some);
    }
    if array_backed {
        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));
        }
        return Ok(Some(out));
    }
    let target = no_trap(v, "get")?.expect("checked it is a proxy");
    host::iter_all(&target).map(Some)
}

/// 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> {
    if wraps_array(v) {
        let items = iterate(v)?.unwrap_or_default();
        return Ok(with_host(|h| h.new_array(items)));
    }
    let entries = own_enum_entries(v)?;
    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
}