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
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
//! Node `assert` module. Failing assertions throw an `AssertionError` (returned
//! as an `Err`, which the host surfaces as a thrown JS exception).

use crate::host::{
    call_method, invoke, is_callable, promise_of, reject_promise_val, resolve_promise_val,
    subscribe_native, take_exc_or_error, with_host, JsObj, PromiseState,
};
use fusevm::Value;

pub const METHODS: &[&str] = &[
    "ok",
    "equal",
    "notEqual",
    "strictEqual",
    "notStrictEqual",
    "deepEqual",
    "notDeepEqual",
    "deepStrictEqual",
    "notDeepStrictEqual",
    "throws",
    "doesNotThrow",
    "fail",
    "match",
    "doesNotMatch",
    "ifError",
    "partialDeepStrictEqual",
    "rejects",
    "doesNotReject",
];

pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
    let a = || args.first().cloned().unwrap_or(Value::Undef);
    let b = || args.get(1).cloned().unwrap_or(Value::Undef);
    Some(match method {
        "ok" => assert_ok(args),
        "equal" => check(loose_eq(&a(), &b()), args, 2, "==", &a(), &b()),
        "notEqual" => check(!loose_eq(&a(), &b()), args, 2, "!=", &a(), &b()),
        "strictEqual" => check(strict(&a(), &b()), args, 2, "===", &a(), &b()),
        "notStrictEqual" => check(!strict(&a(), &b()), args, 2, "!==", &a(), &b()),
        "deepEqual" => check(
            deep_equal(&a(), &b(), false),
            args,
            2,
            "deepEqual",
            &a(),
            &b(),
        ),
        "notDeepEqual" => check(
            !deep_equal(&a(), &b(), false),
            args,
            2,
            "notDeepEqual",
            &a(),
            &b(),
        ),
        "deepStrictEqual" => check(
            deep_equal(&a(), &b(), true),
            args,
            2,
            "deepStrictEqual",
            &a(),
            &b(),
        ),
        "notDeepStrictEqual" => check(
            !deep_equal(&a(), &b(), true),
            args,
            2,
            "notDeepStrictEqual",
            &a(),
            &b(),
        ),
        "throws" => throws(args, true),
        "doesNotThrow" => throws(args, false),
        // `fail` carries no operands: `actual`/`expected` are own properties
        // holding `undefined`, and `operator` is the literal `"fail"`.
        "fail" => Err(throw_assertion(
            &message(args, 0).unwrap_or_else(|| "Failed".to_string()),
            message(args, 0).is_none(),
            "fail",
            Value::Undef,
            Value::Undef,
        )),
        "match" => assert_match(args, true),
        "doesNotMatch" => assert_match(args, false),
        "ifError" => if_error(&a()),
        "partialDeepStrictEqual" => partial(&a(), &b(), args),
        "rejects" => Ok(rejects_impl(&a(), true)),
        "doesNotReject" => Ok(rejects_impl(&a(), false)),
        _ => return None,
    })
}

/// The strict-mode variants (`assert.strict.equal` === `assert.strictEqual`).
/// Maps the loose method names onto their strict counterparts, then delegates.
pub fn strict_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
    let mapped = match method {
        "equal" => "strictEqual",
        "notEqual" => "notStrictEqual",
        "deepEqual" => "deepStrictEqual",
        "notDeepEqual" => "notDeepStrictEqual",
        other => other,
    };
    call(mapped, args)
}

/// `assert.match(string, regexp)` / `assert.doesNotMatch(...)`. `regexp` must be
/// a `RegExp`; matching runs through the JS `RegExp.prototype.test`.
fn assert_match(args: &[Value], want_match: bool) -> Result<Value, String> {
    let s = args.first().cloned().unwrap_or(Value::Undef);
    let re = args.get(1).cloned().unwrap_or(Value::Undef);
    if !with_host(|h| matches!(h.get(&re), Some(JsObj::RegExp(_)))) {
        // Node names the instance, not a type, and appends the received value.
        return Err(crate::host::coded_error(
            "TypeError",
            "ERR_INVALID_ARG_TYPE",
            &format!(
                "The \"regexp\" argument must be an instance of RegExp. Received {}",
                crate::stdlib::received_desc(&re)
            ),
        ));
    }
    let matched = call_method(&re, "test", vec![s.clone()])?;
    let matched = with_host(|h| h.truthy(&matched));
    if matched == want_match {
        return Ok(Value::Undef);
    }
    if let Some(m) = message(args, 2) {
        return Err(assertion_error(&m));
    }
    let (sre, sstr) = with_host(|h| (h.inspect(&re), h.str_of(&s)));
    let verb = if want_match {
        "The input did not match the regular expression"
    } else {
        "The input was expected to not match the regular expression"
    };
    Err(assertion_error(&format!("{verb} {sre}. Input: '{sstr}'")))
}

/// `assert.ifError(value)` — throws unless `value` is `null`/`undefined`.
fn if_error(v: &Value) -> Result<Value, String> {
    if with_host(|h| h.is_nullish(v)) {
        return Ok(Value::Undef);
    }
    let desc = with_host(|h| match h.get(v) {
        Some(JsObj::Object(p)) => p
            .get("message")
            .map(|m| h.str_of(m))
            .unwrap_or_else(|| h.inspect(v)),
        _ => h.inspect(v),
    });
    Err(assertion_error(&format!(
        "ifError got unwanted exception: {desc}"
    )))
}

/// `assert.partialDeepStrictEqual(actual, expected)` — passes when every leaf of
/// `expected` strict-deep-matches the corresponding part of `actual` (extra
/// props/elements in `actual` are ignored).
fn partial(actual: &Value, expected: &Value, args: &[Value]) -> Result<Value, String> {
    if partial_deep(actual, expected) {
        return Ok(Value::Undef);
    }
    if let Some(m) = message(args, 2) {
        return Err(assertion_error(&m));
    }
    let (sa, sb) = with_host(|h| (h.inspect(actual), h.inspect(expected)));
    Err(assertion_error(&format!(
        "Expected values to be strictly deep-equal (partial):\n{sb} should be a subset of {sa}"
    )))
}

fn partial_deep(actual: &Value, expected: &Value) -> bool {
    let ekind = with_host(|h| h.get(expected).map(kind));
    match ekind {
        Some(Kind::Object) => {
            if !matches!(with_host(|h| h.get(actual).map(kind)), Some(Kind::Object)) {
                return false;
            }
            let (ea, ee) = with_host(|h| (object_of(h, actual), object_of(h, expected)));
            ee.iter().all(|(k, ve)| {
                ea.iter()
                    .find(|(k2, _)| k2 == k)
                    .is_some_and(|(_, va)| partial_deep(va, ve))
            })
        }
        Some(Kind::Array) => {
            if !matches!(with_host(|h| h.get(actual).map(kind)), Some(Kind::Array)) {
                return false;
            }
            let (ia, ie) = with_host(|h| (array_of(h, actual), array_of(h, expected)));
            ie.len() <= ia.len() && ie.iter().zip(ia.iter()).all(|(e, a)| partial_deep(a, e))
        }
        _ => strict(actual, expected),
    }
}

/// `assert.rejects(fn|promise)` / `assert.doesNotReject(...)` — returns a Promise
/// that fulfills when the operand settles the expected way, else rejects with an
/// `AssertionError`.
fn rejects_impl(input: &Value, want_reject: bool) -> Value {
    let result = with_host(|h| h.new_promise());
    let rid = with_host(|h| h.promise_id(&result).unwrap());
    // Reduce the operand to a promise: call it if it is a function.
    let operand = if with_host(|h| is_callable(h, input)) {
        match invoke(input, Vec::new(), None) {
            Ok(v) => promise_of(&v),
            Err(e) => {
                let ev = take_exc_or_error(&e);
                let p = with_host(|h| h.new_promise());
                let pid = with_host(|h| h.promise_id(&p).unwrap());
                reject_promise_val(pid, ev);
                p
            }
        }
    } else {
        promise_of(input)
    };
    let Some(oid) = with_host(|h| h.promise_id(&operand)) else {
        // Not thenable: treat as an immediate non-rejection.
        settle_rejects(rid, false, want_reject);
        return result;
    };
    subscribe_native(
        oid,
        Box::new(move |state, _val| {
            settle_rejects(rid, state == PromiseState::Rejected, want_reject);
            Ok(())
        }),
    );
    result
}

/// `new assert.AssertionError(options)` — a real `Error`-prototype-linked object
/// carrying `name`/`message`/`code`/`actual`/`expected`/`operator`. Parent wires
/// this to `construct("AssertionError")` and `constant("assert","AssertionError")`.
pub fn construct_assertion_error(args: &[Value]) -> Value {
    let opts = args.first().cloned().unwrap_or(Value::Undef);
    let (message, actual, expected, operator) = with_host(|h| match h.get(&opts) {
        Some(JsObj::Object(p)) => (
            p.get("message").map(|v| h.str_of(v)),
            p.get("actual").cloned(),
            p.get("expected").cloned(),
            p.get("operator").map(|v| h.str_of(v)),
        ),
        _ => (None, None, None, None),
    });
    let generated = message.is_none();
    let msg = message.unwrap_or_else(|| {
        let (sa, se) = with_host(|h| {
            (
                actual.as_ref().map(|v| h.inspect(v)).unwrap_or_default(),
                expected.as_ref().map(|v| h.inspect(v)).unwrap_or_default(),
            )
        });
        let op = operator.clone().unwrap_or_else(|| "==".to_string());
        format!("{sa} {op} {se}")
    });
    assertion_error_object(
        &msg,
        generated,
        operator.as_deref(),
        actual.unwrap_or(Value::Undef),
        expected.unwrap_or(Value::Undef),
    )
}

/// Node's `diff` field. Every failure form measured on node v26.7.0 — `ok`,
/// `equal`, `strictEqual`, `notStrictEqual`, `deepEqual`, `deepStrictEqual`,
/// `match`, `throws`, `fail` — reports the same `"simple"`; it names the diff
/// MODE the error was built under, not a rendered diff.
const DIFF_MODE: &str = "simple";

/// Build the `AssertionError` object a failing assertion throws.
///
/// The own-property set is what a test runner reads, and node-js carried only
/// `code`/`message`/`stack`: `err.actual`, `err.expected`, `err.operator` and
/// `err.generatedMessage` were all `undefined`, so every framework that reports
/// "expected X, got Y" from a caught `AssertionError` had nothing to report.
/// Measured on node v26.7.0, `Object.keys(err)` is
/// `["generatedMessage","code","actual","expected","operator","diff"]` — in that
/// order — while `name`, `message` and `stack` are own but NOT enumerable.
fn assertion_error_object(
    msg: &str,
    generated: bool,
    operator: Option<&str>,
    actual: Value,
    expected: Value,
) -> Value {
    let stack = format!("AssertionError [ERR_ASSERTION]: {msg}\n    at <anonymous>");
    let op_val = match operator {
        Some(o) => with_host(|h| h.new_str(o)),
        None => Value::Undef,
    };
    let name_v = with_host(|h| h.new_str("AssertionError"));
    let msg_v = with_host(|h| h.new_str(msg));
    let code_v = with_host(|h| h.new_str("ERR_ASSERTION"));
    let stack_v = with_host(|h| h.new_str(stack));
    let diff_v = with_host(|h| h.new_str(DIFF_MODE));
    let mut props: indexmap::IndexMap<String, Value> = indexmap::IndexMap::new();
    // Enumerable, in node's order, first.
    props.insert("generatedMessage".into(), Value::Bool(generated));
    props.insert("code".into(), code_v);
    props.insert("actual".into(), actual);
    props.insert("expected".into(), expected);
    props.insert("operator".into(), op_val);
    props.insert("diff".into(), diff_v);
    props.insert("name".into(), name_v);
    props.insert("message".into(), msg_v);
    props.insert("stack".into(), stack_v);
    let obj = with_host(|h| h.new_object(props));
    with_host(|h| {
        for k in ["name", "message", "stack"] {
            h.hide_prop(&obj, k);
        }
        h.ensure_error_protos();
        // The `AssertionError` prototype, not `Error`'s: `e.constructor.name`
        // is what a test runner branches on, and linking straight to `Error`
        // reported `Error` there while `e.name` still said `AssertionError`.
        if let Some(p) = crate::host::error_proto_of(h, "AssertionError") {
            h.set_proto(&obj, p);
        }
    });
    obj
}

/// Raise a failing assertion as a REAL `AssertionError` object.
///
/// The internal `Name [CODE]: message` string is still what propagates (it is
/// what an uncaught failure prints), but the live thrown VALUE is parked in
/// `host.exc` so a `catch` receives the object with its full property set rather
/// than one synthesized from the message alone.
fn throw_assertion(
    msg: &str,
    generated: bool,
    operator: &str,
    actual: Value,
    expected: Value,
) -> String {
    let err = assertion_error_object(msg, generated, Some(operator), actual, expected);
    with_host(|h| h.exc = Some(err));
    assertion_error(msg)
}

fn settle_rejects(rid: u32, rejected: bool, want_reject: bool) {
    if rejected == want_reject {
        resolve_promise_val(rid, Value::Undef);
    } else {
        let msg = if want_reject {
            "AssertionError [ERR_ASSERTION]: Missing expected rejection."
        } else {
            "AssertionError [ERR_ASSERTION]: Got unwanted rejection."
        };
        let ev = with_host(|h| crate::builtins::synth_error(h, msg));
        reject_promise_val(rid, ev);
    }
}

/// `assert(value[, message])` — throws unless `value` is truthy.
pub fn assert_ok(args: &[Value]) -> Result<Value, String> {
    let v = args.first().cloned().unwrap_or(Value::Undef);
    if with_host(|h| h.truthy(&v)) {
        return Ok(Value::Undef);
    }
    let custom = message(args, 1);
    let msg = custom.clone().unwrap_or_else(||
        // Node's heading ends with a colon and is followed by an echo of
        // the failing source line, which needs the call site's text.
        "The expression evaluated to a falsy value:".to_string());
    // `ok` reports the operand as `actual` against a literal `true`, under the
    // `==` operator (measured on node v26.7.0: `assert.ok(0)` gives
    // `actual: 0`, `expected: true`, `operator: '=='`).
    Err(throw_assertion(
        &msg,
        custom.is_none(),
        "==",
        v,
        Value::Bool(true),
    ))
}

fn check(
    pass: bool,
    args: &[Value],
    msg_idx: usize,
    op: &str,
    a: &Value,
    b: &Value,
) -> Result<Value, String> {
    if pass {
        return Ok(Value::Undef);
    }
    let custom = message(args, msg_idx);
    // `strictEqual`, `deepStrictEqual` and `partialDeepStrictEqual` are Node's
    // `kMethodsWithCustomMessageDiff`: they render a structural `+ actual -
    // expected` diff of the two operands, and they keep rendering it when a
    // custom message is supplied (the custom text replaces the heading only).
    // Every other comparison writes a fixed sentence.
    let diff_operator = match op {
        "===" => Some("strictEqual"),
        "deepStrictEqual" => Some("deepStrictEqual"),
        "partialDeepStrictEqual" => Some("partialDeepStrictEqual"),
        _ => None,
    };
    if let Some(diff_op) = diff_operator {
        let msg = super::assert_diff::create_err_diff(a, b, diff_op, custom.as_deref());
        let operator = if op == "===" { "strictEqual" } else { op };
        return Err(throw_assertion(
            &msg,
            custom.is_none(),
            operator,
            a.clone(),
            b.clone(),
        ));
    }
    // The remaining messages echo one or both operands, and do so with assert's
    // OWN inspect settings (expanded and sorted), not `console.log`'s: node
    // reports `notDeepStrictEqual({a:1},{a:1})` as `{\n  a: 1\n}`, one property
    // per line, where the default rendering is `{ a: 1 }`.
    let (sa, sb) = (
        super::assert_diff::inspect_operand(a),
        super::assert_diff::inspect_operand(b),
    );
    // Each comparison has its OWN generated-message shape in Node; `{a} {op} {b}`
    // is only right for the two loose forms. `strictEqual(1, 2)` produced
    // `1 strictEqual 2` here, which is not a sentence any Node emits — the
    // operator name was being substituted where Node writes a whole heading.
    let msg = match op {
        "==" | "!=" => format!("{sa} {op} {sb}"),
        "===" => format!("Expected values to be strictly equal:\n\n{sa} !== {sb}\n"),
        "!==" => format!("Expected \"actual\" to be strictly unequal to: {sa}"),
        "deepEqual" => format!(
            "Expected values to be loosely deep-equal:\n\n{sa}\n\nshould loosely \
             deep-equal\n\n{sb}"
        ),
        "notDeepEqual" => {
            format!("Expected \"actual\" not to be loosely deep-equal to:\n\n{sa}")
        }
        // The `+ actual - expected` structural DIFF Node renders between two
        // non-primitive operands is not reproduced (it needs a line-oriented
        // differ over `util.inspect` output); the primitive form, which is the
        // whole message when neither side is an object, is exact.
        "deepStrictEqual" => {
            format!("Expected values to be strictly deep-equal:\n\n{sa} !== {sb}\n")
        }
        "notDeepStrictEqual" => {
            format!("Expected \"actual\" not to be strictly deep-equal to:\n\n{sa}\n")
        }
        _ => format!("{sa} {op} {sb}"),
    };
    // Node names the METHOD for the strict/deep forms and the OPERATOR for the
    // two loose ones: `strictEqual` reports `operator: 'strictEqual'` while
    // `equal` reports `'=='`. A custom message replaces the generated text but
    // keeps every other field, and flips `generatedMessage` to false.
    let operator = match op {
        "===" => "strictEqual",
        "!==" => "notStrictEqual",
        other => other,
    };
    Err(throw_assertion(
        &custom.clone().unwrap_or(msg),
        custom.is_none(),
        operator,
        a.clone(),
        b.clone(),
    ))
}

fn throws(args: &[Value], want_throw: bool) -> Result<Value, String> {
    let f = args.first().cloned().unwrap_or(Value::Undef);
    // The thrown value becomes `err.actual` on a `doesNotThrow` failure, so it
    // has to be captured rather than discarded with `.is_err()`.
    let caught = match invoke(&f, Vec::new(), None) {
        Ok(_) => None,
        Err(e) => Some(crate::host::take_exc_or_error(&e)),
    };
    let threw = caught.is_some();
    match (threw, want_throw) {
        (true, true) | (false, false) => Ok(Value::Undef),
        // `generatedMessage` is FALSE for both, which is what node reports even
        // though it wrote the sentence itself (v26.7.0, `assert.throws(()=>{})`).
        (false, true) => Err(throw_assertion(
            "Missing expected exception.",
            false,
            "throws",
            Value::Undef,
            Value::Undef,
        )),
        (true, false) => Err(throw_assertion(
            "Got unwanted exception.",
            false,
            "doesNotThrow",
            caught.unwrap_or(Value::Undef),
            Value::Undef,
        )),
    }
}

fn message(args: &[Value], idx: usize) -> Option<String> {
    match args.get(idx) {
        Some(Value::Undef) | None => None,
        Some(v) => Some(with_host(|h| h.str_of(v))),
    }
}

/// An `AssertionError` as an internal error string.
///
/// `Name [CODE]: message` is the shared encoding `synth_error` parses back into
/// `.name`/`.code`/`.message`, so the prefix must be built by the one
/// constructor rather than written out here — spelling it inline is what let
/// this site keep a form the parser did not recognize.
fn assertion_error(msg: &str) -> String {
    crate::host::coded_error("AssertionError", "ERR_ASSERTION", msg)
}

/// `assert.strictEqual` compares with `Object.is`, not `===`.
///
/// That is the whole difference for two values: `NaN` equals itself, and `+0`
/// does not equal `-0`. Using `===` had both backwards — `strictEqual(NaN, NaN)`
/// failed and `strictEqual(0, -0)` passed.
fn strict(a: &Value, b: &Value) -> bool {
    crate::builtins::same_value(a, b)
}

fn loose_eq(a: &Value, b: &Value) -> bool {
    if strict(a, b) {
        return true;
    }
    with_host(|h| {
        let (na, nb) = (h.to_number(a), h.to_number(b));
        if !na.is_nan() && !nb.is_nan() && (na == nb) {
            return true;
        }
        h.str_of(a) == h.str_of(b)
    })
}

/// Structural equality. `strict` compares leaves with `===`, otherwise `==`.
pub fn deep_equal(a: &Value, b: &Value, strict_mode: bool) -> bool {
    deep_equal_seen(a, b, strict_mode, &mut Vec::new())
}

/// `deep_equal` carrying the pairs currently being compared.
///
/// Without it a self-referential structure recursed until the stack overflowed
/// and the process aborted — `const x = {}; x.self = x;` compared against
/// another of the same shape, which is exactly what a test asserting on a
/// linked structure does. A pair already on the stack is treated as equal: if
/// anything else about the two differs, some other comparison finds it.
fn deep_equal_seen(
    a: &Value,
    b: &Value,
    strict_mode: bool,
    seen: &mut Vec<(Value, Value)>,
) -> bool {
    if seen.iter().any(|(x, y)| x == a && y == b) {
        return true;
    }
    // `deepStrictEqual` requires the two to share a [[Prototype]]. That single
    // check is what separates `Object.create(null)` from `{}`, an instance of
    // one class from an instance of another, and a `Uint8Array` from an
    // `Int8Array` — none of which were being distinguished.
    if strict_mode {
        let both_objects = with_host(|h| h.get(a).is_some() && h.get(b).is_some());
        if both_objects
            && with_host(|h| {
                // A null-prototype object is tracked separately rather than by
                // `proto_of` returning None — which a plain object does too, its
                // `Object.prototype` being implicit. Comparing only `proto_of`
                // therefore called `Object.create(null)` and `{}` alike.
                h.proto_of(a) != h.proto_of(b) || h.has_null_proto(a) != h.has_null_proto(b)
            })
        {
            return false;
        }
    }
    let kinds = with_host(|h| {
        let av = h.get(a).map(kind);
        let bv = h.get(b).map(kind);
        (av, bv)
    });
    seen.push((a.clone(), b.clone()));
    let result = deep_equal_body(a, b, strict_mode, seen, kinds);
    seen.pop();
    result
}

fn deep_equal_body(
    a: &Value,
    b: &Value,
    strict_mode: bool,
    seen: &mut Vec<(Value, Value)>,
    kinds: (Option<Kind>, Option<Kind>),
) -> bool {
    match kinds {
        (Some(Kind::Array), Some(Kind::Array)) => {
            let (ia, ib) = with_host(|h| (array_of(h, a), array_of(h, b)));
            ia.len() == ib.len()
                && ia
                    .iter()
                    .zip(ib.iter())
                    .all(|(x, y)| deep_equal_seen(x, y, strict_mode, seen))
        }
        (Some(Kind::Object), Some(Kind::Object)) => {
            let (ea, eb) = with_host(|h| (object_of(h, a), object_of(h, b)));
            if ea.len() != eb.len() {
                return false;
            }
            let props_match = ea.iter().all(|(k, va)| {
                eb.iter()
                    .find(|(k2, _)| k2 == k)
                    .is_some_and(|(_, vb)| deep_equal_seen(va, vb, strict_mode, seen))
            });
            if !props_match {
                return false;
            }
            // The brands whose whole state lives in INTERNAL slots — a Date's
            // `@@ms`, a typed array's `@@buffer`/`byteOffset`, an Error's name
            // and message — are objects with no enumerable own properties at
            // all. Comparing only the public ones therefore reported every pair
            // of them as deep-equal: `deepStrictEqual(new Date(0), new Date(1))`
            // PASSED, as did two Buffers with different bytes. Slots are
            // compared here rather than folded into `object_of` because they are
            // not properties — they must not affect the key COUNT above, which
            // node takes over enumerable keys only.
            let (ia, ib) = with_host(|h| (internals_of(h, a), internals_of(h, b)));
            if ia.len() != ib.len() {
                return false;
            }
            ia.iter().all(|(k, va)| {
                ib.iter()
                    .find(|(k2, _)| k2 == k)
                    .is_some_and(|(_, vb)| deep_equal_seen(va, vb, strict_mode, seen))
            })
        }
        // A Map compares by ENTRIES and a Set by MEMBERS, both order-insensitively
        // (`new Set([1, 2])` deep-equals `new Set([2, 1])`), so each entry on the
        // left is matched against an as-yet-unclaimed entry on the right rather
        // than against the one at its own index.
        (Some(Kind::Map), Some(Kind::Map)) => {
            let (ea, eb) = with_host(|h| (map_entries_of(h, a), map_entries_of(h, b)));
            unordered_match(&ea, &eb, seen, |(ka, va), (kb, vb), seen| {
                deep_equal_seen(ka, kb, strict_mode, seen)
                    && deep_equal_seen(va, vb, strict_mode, seen)
            })
        }
        (Some(Kind::Set), Some(Kind::Set)) => {
            let (ea, eb) = with_host(|h| (set_members_of(h, a), set_members_of(h, b)));
            unordered_match(&ea, &eb, seen, |x, y, seen| {
                deep_equal_seen(x, y, strict_mode, seen)
            })
        }
        // Two distinct RegExp objects are deep-equal when their pattern and flags
        // are; `same_value` would call every one of them unequal.
        (Some(Kind::RegExp), Some(Kind::RegExp)) => {
            with_host(|h| regexp_key(h, a) == regexp_key(h, b))
        }
        // Everything else — strings, symbols, bigints, functions, and any two
        // values of DIFFERENT kinds — is compared as a leaf. This arm used to be
        // unreachable for heap values because `kind` called them all `Object`,
        // and `object_of` then reported each as having zero properties, so any
        // two of them matched: `deepStrictEqual('abc', 'abd')` passed silently.
        _ => {
            if strict_mode {
                strict(a, b)
            } else {
                loose_eq(a, b)
            }
        }
    }
}

/// Whether every element of `ea` can be paired off with a DISTINCT element of
/// `eb` under `eq`. Greedy matching is enough here because the relation is an
/// equivalence: anything that matches a claimed element would have matched
/// whatever claimed it.
fn unordered_match<T>(
    ea: &[T],
    eb: &[T],
    seen: &mut Vec<(Value, Value)>,
    eq: impl Fn(&T, &T, &mut Vec<(Value, Value)>) -> bool,
) -> bool {
    if ea.len() != eb.len() {
        return false;
    }
    let mut claimed = vec![false; eb.len()];
    'outer: for x in ea {
        for (i, y) in eb.iter().enumerate() {
            if !claimed[i] && eq(x, y, seen) {
                claimed[i] = true;
                continue 'outer;
            }
        }
        return false;
    }
    true
}

enum Kind {
    Array,
    Object,
    Map,
    Set,
    RegExp,
    /// A leaf: compared with `===`, never structurally.
    Other,
}
fn kind(o: &JsObj) -> Kind {
    match o {
        JsObj::Array(_) => Kind::Array,
        JsObj::Object(_) => Kind::Object,
        // A WEAK collection exposes no entries, so there is nothing to compare
        // structurally; node treats two of them as equal only by identity.
        JsObj::Map { weak: false, .. } => Kind::Map,
        JsObj::Set { weak: false, .. } => Kind::Set,
        JsObj::RegExp(_) => Kind::RegExp,
        _ => Kind::Other,
    }
}
/// A Map's entries as `(key, value)` pairs, in insertion order.
fn map_entries_of(h: &crate::host::JsHost, v: &Value) -> Vec<(Value, Value)> {
    match h.get(v) {
        Some(JsObj::Map { entries, .. }) => entries.values().cloned().collect(),
        _ => Vec::new(),
    }
}
/// A Set's members, in insertion order.
fn set_members_of(h: &crate::host::JsHost, v: &Value) -> Vec<Value> {
    match h.get(v) {
        Some(JsObj::Set { entries, .. }) => entries.values().cloned().collect(),
        _ => Vec::new(),
    }
}
/// The identity of a regular expression for comparison: its pattern and flags.
fn regexp_key(h: &crate::host::JsHost, v: &Value) -> Option<(String, String)> {
    match h.get(v) {
        Some(JsObj::RegExp(r)) => Some((r.source.clone(), r.flags.clone())),
        _ => None,
    }
}
/// An object's INTERNAL slots — the `@@`-prefixed keys that carry brand state
/// (`@@ms`, `@@buffer`, `@@kind`) and are deliberately absent from `object_of`.
/// Private class fields (`#`-prefixed) stay excluded: node's `deepStrictEqual`
/// compares own ENUMERABLE properties, and a private field is neither.
fn internals_of(h: &crate::host::JsHost, v: &Value) -> Vec<(String, Value)> {
    match h.get(v) {
        Some(JsObj::Object(p)) => p
            .iter()
            .filter(|(k, _)| k.starts_with("@@"))
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect(),
        _ => Vec::new(),
    }
}
fn array_of(h: &crate::host::JsHost, v: &Value) -> Vec<Value> {
    match h.get(v) {
        Some(JsObj::Array(items)) => items.clone(),
        _ => Vec::new(),
    }
}
fn object_of(h: &crate::host::JsHost, v: &Value) -> Vec<(String, Value)> {
    match h.get(v) {
        Some(JsObj::Object(p)) => p
            .iter()
            .filter(|(k, _)| !k.starts_with("@@") && !k.starts_with('#'))
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect(),
        _ => Vec::new(),
    }
}