web-api-cat 0.7.4

Bindings between boa-cat (JS engine) and the DOM (html-cat tree) plus fetch (net-cat). v0.7.4 ships the `EventTarget` mixin: `addEventListener(type, callback)` queues handlers under a lazy `__listeners__` slot; `removeEventListener` drops them by `Value::PartialEq`; `dispatchEvent(event)` walks the bubble chain via the v0.6.8 `__parent__` backref and invokes each handler through boa-cat 0.7.1's now-public `expression::call_function`. Listener throws are swallowed at the dispatch boundary per DOM spec. Seventh sub-crate of a Servo-replacement webview runtime targeting Tauri.
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
//! `Element`-side native methods: `getAttribute`, `setAttribute`,
//! `hasAttribute`, `querySelector`, plus the v0.6.1 / v0.6.2 / v0.6.3 /
//! v0.6.7 / v0.6.8 structural, class-list, and parent-tracking
//! mutators (`appendChild`, `removeChild`, `insertBefore`,
//! `replaceChild`, `classList.add`, `classList.remove`,
//! `classList.contains`, `classList.toggle`, `remove`).
//!
//! v0.6.8 introduces a hidden `__parent__` slot on every element
//! (`Value::Object(parent_id)` when attached, `Value::Null` when
//! detached) and routes every structural mutator through
//! `set_parent_backref` / `clear_parent_backref` so the slot
//! stays in sync with the actual children-array membership.
//!
//! Element objects are boa-cat [`Object`]s carrying these properties:
//!
//! - `tagName`: lowercased tag name (string).
//! - `id`: id attribute or empty string.
//! - `className`: class attribute or empty string.
//! - `textContent`: concatenated text of all descendant text nodes.
//! - `children`: array of child element objects.
//! - `__attributes`: object mapping attribute name -> value.
//! - `getAttribute`, `setAttribute`, `hasAttribute`,
//!   `querySelector`: native callables.

use std::collections::BTreeMap;

use boa_cat::Value;
use boa_cat::fuel::Fuel;
use boa_cat::heap::Heap;
use boa_cat::outcome::{EvalResult, Outcome};
use boa_cat::value::{Object, ObjectId};

/// `Element.getAttribute(name)` native implementation.
///
/// # Errors
///
/// Never returns `Err`; bad input yields `Value::Null`.
#[allow(clippy::needless_pass_by_value)]
#[allow(clippy::unnecessary_wraps)]
pub fn get_attribute_impl(args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let name = string_arg(&args, 0);
    let outcome = read_attribute(&this, &name, &heap).map_or(Outcome::Normal(Value::Null), |v| {
        Outcome::Normal(Value::String(v))
    });
    Ok((outcome, heap, fuel))
}

/// `Element.hasAttribute(name)` native implementation.
///
/// # Errors
///
/// Never returns `Err`.
#[allow(clippy::needless_pass_by_value)]
#[allow(clippy::unnecessary_wraps)]
pub fn has_attribute_impl(args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let name = string_arg(&args, 0);
    let present = read_attribute(&this, &name, &heap).is_some();
    Ok((Outcome::Normal(Value::Boolean(present)), heap, fuel))
}

/// `Element.setAttribute(name, value)` native implementation.
///
/// # Errors
///
/// Never returns `Err`; missing element / attributes object yields the
/// unchanged heap.
#[allow(clippy::needless_pass_by_value)]
#[allow(clippy::unnecessary_wraps)]
pub fn set_attribute_impl(args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let name = string_arg(&args, 0);
    let value = string_arg(&args, 1);
    let new_heap = write_attribute(&this, &name, &value, heap);
    Ok((Outcome::Normal(Value::Undefined), new_heap, fuel))
}

fn object_id_of(value: &Value) -> Option<ObjectId> {
    match value {
        Value::Object(id) => Some(*id),
        Value::Undefined
        | Value::Null
        | Value::Boolean(_)
        | Value::Number(_)
        | Value::String(_)
        | Value::Function(_)
        | Value::Native(_)
        | Value::Promise(_) => None,
    }
}

fn attributes_id_of(element: &Object) -> Option<ObjectId> {
    match element.get("__attributes") {
        Some(value) => object_id_of(value),
        None => None,
    }
}

fn read_attribute(this: &Value, name: &str, heap: &Heap) -> Option<String> {
    let element_id = object_id_of(this)?;
    let element = heap.object(element_id)?;
    let attrs_id = attributes_id_of(element)?;
    let attrs = heap.object(attrs_id)?;
    match attrs.get(name) {
        Some(Value::String(s)) => Some(s.clone()),
        Some(_) | None => None,
    }
}

fn write_attribute(this: &Value, name: &str, value: &str, heap: Heap) -> Heap {
    let Some(element_id) = object_id_of(this) else {
        return heap;
    };
    let Some(element) = heap.object(element_id).cloned() else {
        return heap;
    };
    let Some(attrs_id) = attributes_id_of(&element) else {
        return heap;
    };
    let Some(attrs) = heap.object(attrs_id).cloned() else {
        return heap;
    };
    let updated_attrs = attrs.with(name.to_owned(), Value::String(value.to_owned()));
    let heap = heap
        .store_object(attrs_id, updated_attrs)
        .unwrap_or_else(|h| h);
    let mirror_key = match name {
        "id" => Some("id"),
        "class" => Some("className"),
        _other => None,
    };
    if let Some(key) = mirror_key {
        let updated_element = element.with(key.to_owned(), Value::String(value.to_owned()));
        heap.store_object(element_id, updated_element)
            .unwrap_or_else(|h| h)
    } else {
        heap
    }
}

fn string_arg(args: &[Value], idx: usize) -> String {
    match args.get(idx) {
        Some(Value::String(s)) => s.clone(),
        Some(other) => format!("{other}"),
        None => String::new(),
    }
}

/// Build an attributes object (`__attributes`) from a list of pairs.
#[must_use]
pub fn build_attributes_object(pairs: &[(String, String)], heap: Heap) -> (Value, Heap) {
    let map: BTreeMap<String, Value> = pairs
        .iter()
        .map(|(k, v)| (k.clone(), Value::String(v.clone())))
        .collect();
    let (id, heap) = heap.alloc_object(Object::from_properties(map));
    (Value::Object(id), heap)
}

/// `Element.querySelector(selector)` -- limited v0 selector subset
/// (`tag`, `.class`, `#id`, `tag.class`, `tag#id`).
///
/// # Errors
///
/// Never returns `Err`; no match yields `Value::Null`.
#[allow(clippy::needless_pass_by_value)]
#[allow(clippy::unnecessary_wraps)]
pub fn query_selector_impl(args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let selector = string_arg(&args, 0);
    let pattern = parse_simple_selector(&selector);
    let outcome =
        find_matching(&this, &pattern, &heap).map_or(Outcome::Normal(Value::Null), Outcome::Normal);
    Ok((outcome, heap, fuel))
}

#[derive(Debug, Clone, Default)]
struct SelectorPattern {
    tag: Option<String>,
    id: Option<String>,
    class: Option<String>,
}

fn parse_simple_selector(source: &str) -> SelectorPattern {
    let trimmed = source.trim();
    parse_selector_recursive(trimmed, 0, SelectorPattern::default())
}

fn parse_selector_recursive(source: &str, start: usize, acc: SelectorPattern) -> SelectorPattern {
    let bytes = source.as_bytes();
    if start >= bytes.len() {
        acc
    } else {
        match bytes.get(start) {
            Some(b'#') => {
                let end = scan_ident(bytes, start + 1);
                let name = source.get(start + 1..end).unwrap_or("").to_owned();
                parse_selector_recursive(
                    source,
                    end,
                    SelectorPattern {
                        id: Some(name),
                        ..acc
                    },
                )
            }
            Some(b'.') => {
                let end = scan_ident(bytes, start + 1);
                let name = source.get(start + 1..end).unwrap_or("").to_owned();
                parse_selector_recursive(
                    source,
                    end,
                    SelectorPattern {
                        class: Some(name),
                        ..acc
                    },
                )
            }
            Some(_) => {
                let end = scan_ident(bytes, start);
                let name = source.get(start..end).unwrap_or("").to_ascii_lowercase();
                if name.is_empty() {
                    acc
                } else {
                    parse_selector_recursive(
                        source,
                        end,
                        SelectorPattern {
                            tag: Some(name),
                            ..acc
                        },
                    )
                }
            }
            None => acc,
        }
    }
}

fn scan_ident(bytes: &[u8], start: usize) -> usize {
    bytes
        .iter()
        .enumerate()
        .skip(start)
        .find(|(_, b)| !is_ident_byte(**b))
        .map_or(bytes.len(), |(i, _)| i)
}

fn is_ident_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'-' || b == b'_'
}

fn find_matching(this: &Value, pattern: &SelectorPattern, heap: &Heap) -> Option<Value> {
    let root_id = object_id_of(this)?;
    walk_descendants(root_id, pattern, heap)
}

fn walk_descendants(node_id: ObjectId, pattern: &SelectorPattern, heap: &Heap) -> Option<Value> {
    let children = element_children(node_id, heap);
    children.iter().find_map(|child_id| {
        if matches_pattern(*child_id, pattern, heap) {
            Some(Value::Object(*child_id))
        } else {
            walk_descendants(*child_id, pattern, heap)
        }
    })
}

fn element_children(node_id: ObjectId, heap: &Heap) -> Vec<ObjectId> {
    let Some(object) = heap.object(node_id) else {
        return Vec::new();
    };
    let Some(children_id) = object.get("children").and_then(object_id_of) else {
        return Vec::new();
    };
    let Some(children) = heap.object(children_id) else {
        return Vec::new();
    };
    let length = array_length(children);
    (0..length)
        .filter_map(|i| children.get(&format!("{i}")).and_then(object_id_of))
        .collect()
}

fn array_length(array: &Object) -> u32 {
    match array.get("length") {
        Some(Value::Number(n)) if n.is_finite() && *n >= 0.0 => {
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            let len = *n as u32;
            len
        }
        Some(_) | None => 0,
    }
}

fn matches_pattern(node_id: ObjectId, pattern: &SelectorPattern, heap: &Heap) -> bool {
    let Some(object) = heap.object(node_id) else {
        return false;
    };
    let tag_ok = pattern
        .tag
        .as_ref()
        .is_none_or(|want| string_property(object, "tagName").eq_ignore_ascii_case(want));
    let id_ok = pattern
        .id
        .as_ref()
        .is_none_or(|want| string_property(object, "id") == *want);
    let class_ok = pattern.class.as_ref().is_none_or(|want| {
        string_property(object, "className")
            .split_ascii_whitespace()
            .any(|c| c == want)
    });
    tag_ok && id_ok && class_ok
}

fn string_property(object: &Object, key: &str) -> String {
    match object.get(key) {
        Some(Value::String(s)) => s.clone(),
        Some(_) | None => String::new(),
    }
}

/// Public helper used by `document.querySelector` to perform the search
/// from the document root.
#[must_use]
pub fn find_first_descendant(root: ObjectId, pattern_source: &str, heap: &Heap) -> Option<Value> {
    let pattern = parse_simple_selector(pattern_source);
    walk_descendants(root, &pattern, heap)
}

/// Public helper for `document.getElementById`.
#[must_use]
pub fn find_by_id(root: ObjectId, id: &str, heap: &Heap) -> Option<Value> {
    let pattern = SelectorPattern {
        id: Some(id.to_owned()),
        ..SelectorPattern::default()
    };
    walk_descendants(root, &pattern, heap)
}

/// `Element.appendChild(child)` (v0.6.1): append `child` to
/// `this.children`, updating `length`.  Returns `child` per spec
/// so the caller can chain.  No-ops when `this` or `child` aren't
/// Object values, or when the children-array slot is missing /
/// non-object.
///
/// Mutation flow: clone the children array Object, write the new
/// numeric-key entry, write `length`, then `store_object` both the
/// children Object and the parent (the parent's `children` slot
/// already points at the same children-array `ObjectId`, so the
/// parent update is implicit -- only the children Object's
/// in-place mutation matters).  `extract_document` walks
/// `children` numerically in the next back-prop pass, so the new
/// child reaches layout / paint automatically.
///
/// # Errors
///
/// Never returns `Err`; bad inputs yield `Value::Undefined`.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn append_child_impl(args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let child = args.first().cloned().unwrap_or(Value::Undefined);
    let outcome_heap = append_child_to_parent(&this, &child, heap);
    Ok((Outcome::Normal(child), outcome_heap, fuel))
}

fn append_child_to_parent(this: &Value, child: &Value, heap: Heap) -> Heap {
    let Some(parent_id) = object_id_of(this) else {
        return heap;
    };
    if let Some((children_id, children_obj)) = children_object_of(this, &heap) {
        let length = array_length(&children_obj);
        let updated_children = children_obj
            .with(format!("{length}"), child.clone())
            .with("length".to_owned(), Value::Number(f64::from(length + 1)));
        let heap = heap
            .store_object(children_id, updated_children)
            .unwrap_or_else(|h| h);
        set_parent_backref(child, parent_id, heap)
    } else {
        heap
    }
}

/// v0.6.8 helper: set `child_value.__parent__` to
/// `Value::Object(parent_id)`.  No-op when `child_value` isn't an
/// Object or its heap slot is missing.  Called by every structural
/// mutator and by `document::build_element` / `document::clone_element`
/// to wire up parent backrefs.
#[must_use]
pub fn set_parent_backref(child_value: &Value, parent_id: ObjectId, heap: Heap) -> Heap {
    let Some(child_id) = object_id_of(child_value) else {
        return heap;
    };
    let Some(child_obj) = heap.object(child_id).cloned() else {
        return heap;
    };
    let updated = child_obj.with("__parent__".to_owned(), Value::Object(parent_id));
    heap.store_object(child_id, updated).unwrap_or_else(|h| h)
}

/// v0.6.8 helper: clear `child_value.__parent__` to `Value::Null`.
/// No-op when `child_value` isn't an Object or its heap slot is
/// missing.  Called when detaching a child from its parent
/// (`removeChild`, `replaceChild`'s old-child slot, `remove`,
/// `innerHTML` setter's discarded old children).
#[must_use]
pub fn clear_parent_backref(child_value: &Value, heap: Heap) -> Heap {
    let Some(child_id) = object_id_of(child_value) else {
        return heap;
    };
    let Some(child_obj) = heap.object(child_id).cloned() else {
        return heap;
    };
    let updated = child_obj.with("__parent__".to_owned(), Value::Null);
    heap.store_object(child_id, updated).unwrap_or_else(|h| h)
}

fn children_object_of(this: &Value, heap: &Heap) -> Option<(ObjectId, Object)> {
    let parent_id = object_id_of(this)?;
    let parent = heap.object(parent_id)?;
    let children_id = parent.get("children").and_then(|v| match v {
        Value::Object(id) => Some(*id),
        Value::Undefined
        | Value::Null
        | Value::Boolean(_)
        | Value::Number(_)
        | Value::String(_)
        | Value::Function(_)
        | Value::Native(_)
        | Value::Promise(_) => None,
    })?;
    let children_obj = heap.object(children_id)?.clone();
    Some((children_id, children_obj))
}

/// `Element.removeChild(child)` (v0.6.2): remove `child` from
/// `this.children` and return it.  Remaining children shift down
/// to fill the freed slot; `length` decrements.  No-ops (and still
/// returns the requested `child`) when `this` or `child` aren't
/// Object values, the children-array slot is missing / non-object,
/// or `child` isn't currently a child of `this` (the DOM spec
/// throws `NotFoundError` here; this scoped impl no-ops to stay
/// inside the always-`Ok` `NativeFn` contract).
///
/// # Errors
///
/// Never returns `Err`; bad inputs no-op.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn remove_child_impl(args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let child = args.first().cloned().unwrap_or(Value::Undefined);
    let outcome_heap = remove_child_from_parent(&this, &child, heap);
    Ok((Outcome::Normal(child), outcome_heap, fuel))
}

fn remove_child_from_parent(this: &Value, child: &Value, heap: Heap) -> Heap {
    let Some((children_id, children_obj)) = children_object_of(this, &heap) else {
        return heap;
    };
    let Some(child_id) = object_id_of(child) else {
        return heap;
    };
    let length = array_length(&children_obj);
    let Some(removal_index) = (0..length)
        .find(|i| children_obj.get(&format!("{i}")).and_then(object_id_of) == Some(child_id))
    else {
        return heap;
    };
    let new_length = length.saturating_sub(1);
    let pairs: BTreeMap<String, Value> = (0..length)
        .filter(|i| *i != removal_index)
        .enumerate()
        .map(|(new_idx, old_idx)| {
            let value = children_obj
                .get(&format!("{old_idx}"))
                .cloned()
                .unwrap_or(Value::Null);
            (format!("{new_idx}"), value)
        })
        .chain(std::iter::once((
            "length".to_owned(),
            Value::Number(f64::from(new_length)),
        )))
        .collect();
    let new_children = Object::from_properties(pairs);
    let heap = heap
        .store_object(children_id, new_children)
        .unwrap_or_else(|h| h);
    clear_parent_backref(child, heap)
}

/// `Element.insertBefore(newNode, referenceNode)` (v0.6.2): insert
/// `newNode` into `this.children` immediately before
/// `referenceNode`, returning `newNode`.  Existing children at and
/// after `referenceNode`'s slot shift up; `length` increments.  If
/// `referenceNode` is `null` / `undefined` / any non-Object value
/// the call falls through to `appendChild`-like end-of-list
/// behaviour (matching the DOM spec's `null` case).  No-ops if
/// `this` isn't an Object, the children-array slot is missing /
/// non-object, or `referenceNode` is a real Object but isn't
/// actually a child of `this` (the DOM spec throws
/// `NotFoundError`; this scoped impl no-ops).
///
/// # Errors
///
/// Never returns `Err`; bad inputs yield `Value::Undefined`.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn insert_before_impl(args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let new_node = args.first().cloned().unwrap_or(Value::Undefined);
    let ref_node = args.get(1).cloned().unwrap_or(Value::Null);
    let outcome_heap = insert_before_into_parent(&this, &new_node, &ref_node, heap);
    Ok((Outcome::Normal(new_node), outcome_heap, fuel))
}

fn insert_before_into_parent(this: &Value, new_node: &Value, ref_node: &Value, heap: Heap) -> Heap {
    let ref_id_opt = object_id_of(ref_node);
    if ref_id_opt.is_none() {
        append_child_to_parent(this, new_node, heap)
    } else {
        let Some(parent_id) = object_id_of(this) else {
            return heap;
        };
        let Some((children_id, children_obj)) = children_object_of(this, &heap) else {
            return heap;
        };
        let Some(ref_id) = ref_id_opt else {
            return heap;
        };
        let length = array_length(&children_obj);
        let Some(insert_index) = (0..length)
            .find(|i| children_obj.get(&format!("{i}")).and_then(object_id_of) == Some(ref_id))
        else {
            return heap;
        };
        let new_length = length + 1;
        let pairs: BTreeMap<String, Value> = (0..new_length)
            .map(|new_idx| {
                let value = match new_idx.cmp(&insert_index) {
                    std::cmp::Ordering::Less => children_obj
                        .get(&format!("{new_idx}"))
                        .cloned()
                        .unwrap_or(Value::Null),
                    std::cmp::Ordering::Equal => new_node.clone(),
                    std::cmp::Ordering::Greater => {
                        let old_idx = new_idx - 1;
                        children_obj
                            .get(&format!("{old_idx}"))
                            .cloned()
                            .unwrap_or(Value::Null)
                    }
                };
                (format!("{new_idx}"), value)
            })
            .chain(std::iter::once((
                "length".to_owned(),
                Value::Number(f64::from(new_length)),
            )))
            .collect();
        let new_children = Object::from_properties(pairs);
        let heap = heap
            .store_object(children_id, new_children)
            .unwrap_or_else(|h| h);
        set_parent_backref(new_node, parent_id, heap)
    }
}

/// `Element.replaceChild(newChild, oldChild)` (v0.6.7): swap
/// `oldChild` for `newChild` in `this.children`.  Length is
/// preserved (one slot in, one slot out); the surrounding
/// children stay at their indexes.  Returns `oldChild` per spec.
/// No-ops (and still returns the requested `oldChild`) when
/// `this` isn't an Object, the children-array slot is missing /
/// non-object, `oldChild` isn't an Object, or `oldChild` isn't
/// currently a child of `this` (the DOM spec throws
/// `NotFoundError`; this scoped impl no-ops).
///
/// # Errors
///
/// Never returns `Err`; bad inputs no-op.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn replace_child_impl(args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let new_child = args.first().cloned().unwrap_or(Value::Undefined);
    let old_child = args.get(1).cloned().unwrap_or(Value::Undefined);
    let outcome_heap = replace_child_in_parent(&this, &new_child, &old_child, heap);
    Ok((Outcome::Normal(old_child), outcome_heap, fuel))
}

fn replace_child_in_parent(this: &Value, new_child: &Value, old_child: &Value, heap: Heap) -> Heap {
    let Some(parent_id) = object_id_of(this) else {
        return heap;
    };
    let Some((children_id, children_obj)) = children_object_of(this, &heap) else {
        return heap;
    };
    let Some(old_id) = object_id_of(old_child) else {
        return heap;
    };
    let length = array_length(&children_obj);
    let Some(replace_index) = (0..length)
        .find(|i| children_obj.get(&format!("{i}")).and_then(object_id_of) == Some(old_id))
    else {
        return heap;
    };
    let updated_children = children_obj.with(format!("{replace_index}"), new_child.clone());
    let heap = heap
        .store_object(children_id, updated_children)
        .unwrap_or_else(|h| h);
    let heap = set_parent_backref(new_child, parent_id, heap);
    clear_parent_backref(old_child, heap)
}

/// `Element.remove()` (v0.6.8): detach `this` from its parent.
/// Reads `this.__parent__`; if it's an Object, calls the same
/// `remove_child_from_parent` helper that backs `removeChild`,
/// which both excises `this` from the parent's children-array
/// Object and clears `this.__parent__`.  No-op when `this` has no
/// parent (already detached, or it's the document root).
///
/// # Errors
///
/// Never returns `Err`.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn remove_impl(_args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let parent_value = parent_value_of(&this, &heap);
    let outcome_heap = match parent_value {
        Value::Object(_) => remove_child_from_parent(&parent_value, &this, heap),
        Value::Undefined
        | Value::Null
        | Value::Boolean(_)
        | Value::Number(_)
        | Value::String(_)
        | Value::Function(_)
        | Value::Native(_)
        | Value::Promise(_) => heap,
    };
    Ok((Outcome::Normal(Value::Undefined), outcome_heap, fuel))
}

fn parent_value_of(this: &Value, heap: &Heap) -> Value {
    object_id_of(this)
        .and_then(|id| heap.object(id))
        .and_then(|obj| obj.get("__parent__").cloned())
        .unwrap_or(Value::Null)
}

/// v0.6.8 getter for `parentElement` / `parentNode` accessors:
/// returns `this.__parent__` (an `Object` value when attached,
/// `Null` when detached or root).  Same implementation for both
/// accessors -- we don't yet distinguish elements from other node
/// types, so `parentElement` and `parentNode` produce identical
/// results.
///
/// # Errors
///
/// Never returns `Err`.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn parent_getter_impl(_args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let parent = parent_value_of(&this, &heap);
    Ok((Outcome::Normal(parent), heap, fuel))
}

/// v0.6.9 getter for `firstElementChild`: `this.children[0]` or
/// `Value::Null` if `this` has no children.
///
/// # Errors
///
/// Never returns `Err`.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn first_element_child_getter_impl(
    _args: Vec<Value>,
    this: Value,
    heap: Heap,
    fuel: Fuel,
) -> EvalResult {
    let value = own_children_view(&this, &heap)
        .filter(|(_, length)| *length > 0)
        .and_then(|(children, _)| children.get("0").cloned())
        .unwrap_or(Value::Null);
    Ok((Outcome::Normal(value), heap, fuel))
}

/// v0.6.9 getter for `lastElementChild`: `this.children[length-1]`
/// or `Value::Null` if `this` has no children.
///
/// # Errors
///
/// Never returns `Err`.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn last_element_child_getter_impl(
    _args: Vec<Value>,
    this: Value,
    heap: Heap,
    fuel: Fuel,
) -> EvalResult {
    let value = own_children_view(&this, &heap)
        .filter(|(_, length)| *length > 0)
        .and_then(|(children, length)| children.get(&format!("{}", length - 1)).cloned())
        .unwrap_or(Value::Null);
    Ok((Outcome::Normal(value), heap, fuel))
}

/// v0.6.9 getter for `previousElementSibling`: looks `this` up by
/// id in its parent's children-array Object, returns the entry at
/// `this_index - 1` if it exists, else `Value::Null`.
///
/// # Errors
///
/// Never returns `Err`.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn previous_element_sibling_getter_impl(
    _args: Vec<Value>,
    this: Value,
    heap: Heap,
    fuel: Fuel,
) -> EvalResult {
    let value = parent_children_view(&this, &heap)
        .filter(|(_, _, this_index)| *this_index > 0)
        .and_then(|(children, _, this_index)| children.get(&format!("{}", this_index - 1)).cloned())
        .unwrap_or(Value::Null);
    Ok((Outcome::Normal(value), heap, fuel))
}

/// v0.6.9 getter for `nextElementSibling`: looks `this` up by id
/// in its parent's children-array Object, returns the entry at
/// `this_index + 1` if it exists, else `Value::Null`.
///
/// # Errors
///
/// Never returns `Err`.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn next_element_sibling_getter_impl(
    _args: Vec<Value>,
    this: Value,
    heap: Heap,
    fuel: Fuel,
) -> EvalResult {
    let value = parent_children_view(&this, &heap)
        .filter(|(_, length, this_index)| this_index + 1 < *length)
        .and_then(|(children, _, this_index)| children.get(&format!("{}", this_index + 1)).cloned())
        .unwrap_or(Value::Null);
    Ok((Outcome::Normal(value), heap, fuel))
}

fn own_children_view<'h>(this: &Value, heap: &'h Heap) -> Option<(&'h Object, u32)> {
    let this_id = object_id_of(this)?;
    let this_obj = heap.object(this_id)?;
    let children_id = this_obj.get("children").and_then(object_id_of)?;
    let children = heap.object(children_id)?;
    let length = array_length(children);
    Some((children, length))
}

fn parent_children_view<'h>(this: &Value, heap: &'h Heap) -> Option<(&'h Object, u32, u32)> {
    let this_id = object_id_of(this)?;
    let this_obj = heap.object(this_id)?;
    let parent_id = this_obj.get("__parent__").and_then(object_id_of)?;
    let parent = heap.object(parent_id)?;
    let children_id = parent.get("children").and_then(object_id_of)?;
    let children = heap.object(children_id)?;
    let length = array_length(children);
    let this_index = (0..length)
        .find(|i| children.get(&format!("{i}")).and_then(object_id_of) == Some(this_id))?;
    Some((children, length, this_index))
}

/// `Element.classList.add(token)` (v0.6.3): if `token` isn't
/// already among the parent element's class tokens, append it and
/// write the rejoined token list back through `setAttribute`-style
/// mirroring (so both `className` and `__attributes.class` stay in
/// sync; `getAttribute('class')` keeps working).  No-ops if `this`
/// isn't a `classList` Object or its `__element__` backref is
/// missing / non-Object.
///
/// # Errors
///
/// Never returns `Err`; bad inputs no-op.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn class_list_add_impl(args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let token = string_arg(&args, 0);
    let new_heap = add_class_token(&this, &token, heap);
    Ok((Outcome::Normal(Value::Undefined), new_heap, fuel))
}

/// `Element.classList.remove(token)` (v0.6.3): drop every
/// occurrence of `token` from the parent element's class list and
/// write the rejoined token list back through `setAttribute`-style
/// mirroring.  No-ops if `this` isn't a `classList` Object.
///
/// # Errors
///
/// Never returns `Err`; bad inputs no-op.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn class_list_remove_impl(args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let token = string_arg(&args, 0);
    let new_heap = remove_class_token(&this, &token, heap);
    Ok((Outcome::Normal(Value::Undefined), new_heap, fuel))
}

/// `Element.classList.contains(token)` (v0.6.3): return `true` iff
/// `token` is among the parent element's whitespace-separated class
/// tokens.  Returns `false` if `this` isn't a `classList` Object.
///
/// # Errors
///
/// Never returns `Err`.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn class_list_contains_impl(
    args: Vec<Value>,
    this: Value,
    heap: Heap,
    fuel: Fuel,
) -> EvalResult {
    let token = string_arg(&args, 0);
    let present = element_of_class_list(&this, &heap)
        .is_some_and(|(_, element)| class_list_tokens(&element).iter().any(|t| t == &token));
    Ok((Outcome::Normal(Value::Boolean(present)), heap, fuel))
}

/// `Element.classList.toggle(token)` (v0.6.3): remove `token` if it
/// was already present, otherwise add it; return the new
/// presence-state (matches MDN: `true` after add, `false` after
/// remove).  No-ops (returning `false`) if `this` isn't a
/// `classList` Object.
///
/// # Errors
///
/// Never returns `Err`.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn class_list_toggle_impl(args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let token = string_arg(&args, 0);
    let (present, new_heap) = toggle_class_token(&this, &token, heap);
    Ok((Outcome::Normal(Value::Boolean(present)), new_heap, fuel))
}

fn element_of_class_list(this: &Value, heap: &Heap) -> Option<(ObjectId, Object)> {
    let list_id = object_id_of(this)?;
    let list = heap.object(list_id)?;
    let element_id = list.get("__element__").and_then(|v| match v {
        Value::Object(id) => Some(*id),
        Value::Undefined
        | Value::Null
        | Value::Boolean(_)
        | Value::Number(_)
        | Value::String(_)
        | Value::Function(_)
        | Value::Native(_)
        | Value::Promise(_) => None,
    })?;
    let element = heap.object(element_id)?.clone();
    Some((element_id, element))
}

fn class_list_tokens(element: &Object) -> Vec<String> {
    match element.get("className") {
        Some(Value::String(s)) => s.split_ascii_whitespace().map(str::to_owned).collect(),
        Some(_) | None => Vec::new(),
    }
}

fn add_class_token(this: &Value, token: &str, heap: Heap) -> Heap {
    let Some((element_id, element)) = element_of_class_list(this, &heap) else {
        return heap;
    };
    let tokens = class_list_tokens(&element);
    let new_tokens: Vec<String> = if tokens.iter().any(|t| t == token) {
        tokens
    } else {
        tokens
            .into_iter()
            .chain(std::iter::once(token.to_owned()))
            .collect()
    };
    let new_class = new_tokens.join(" ");
    let element_value = Value::Object(element_id);
    write_attribute(&element_value, "class", &new_class, heap)
}

fn remove_class_token(this: &Value, token: &str, heap: Heap) -> Heap {
    let Some((element_id, element)) = element_of_class_list(this, &heap) else {
        return heap;
    };
    let tokens = class_list_tokens(&element);
    let new_tokens: Vec<String> = tokens.into_iter().filter(|t| t != token).collect();
    let new_class = new_tokens.join(" ");
    let element_value = Value::Object(element_id);
    write_attribute(&element_value, "class", &new_class, heap)
}

fn toggle_class_token(this: &Value, token: &str, heap: Heap) -> (bool, Heap) {
    let Some((element_id, element)) = element_of_class_list(this, &heap) else {
        return (false, heap);
    };
    let tokens = class_list_tokens(&element);
    let was_present = tokens.iter().any(|t| t == token);
    let new_tokens: Vec<String> = if was_present {
        tokens.into_iter().filter(|t| t != token).collect()
    } else {
        tokens
            .into_iter()
            .chain(std::iter::once(token.to_owned()))
            .collect()
    };
    let new_class = new_tokens.join(" ");
    let element_value = Value::Object(element_id);
    let new_heap = write_attribute(&element_value, "class", &new_class, heap);
    (!was_present, new_heap)
}