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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
//! Node `url` module: the WHATWG `URL` class (global + `require('url').URL`) and
//! the legacy `url.parse`. A `URL` instance stores its components as data
//! properties (so `u.hostname` reads directly) plus a `@@native = "URL"` tag for
//! `toString`. Assigning one of those components goes through [`refresh`], which
//! rewrites the DERIVED fields (`href`, `host`, `origin`) so the object cannot
//! disagree with itself; the `searchParams` it carries holds an `@@ownerUrl`
//! back-reference so its own mutations rewrite the query in the other direction.
//!
//! They remain OWN properties of the instance, where node has them as accessors
//! on `URL.prototype` — so `Object.keys(url)` lists twelve names here and none
//! in node.

use super::arg_str;
use crate::host::{with_host, JsObj};
use fusevm::Value;
use indexmap::IndexMap;

pub const MODULE_METHODS: &[&str] = &[
    "parse",
    "format",
    "fileURLToPath",
    "fileURLToPathBuffer",
    "pathToFileURL",
    "domainToASCII",
    "domainToUnicode",
    "urlToHttpOptions",
    "resolve",
    "resolveObject",
];

/// Parsed URL components.
/// The component names a `URL` exposes as writable ACCESSORS on its prototype.
///
/// Assigning one has to rewrite the DERIVED fields — `href`, `host` and
/// `origin` — which are stored alongside rather than computed on read. Without
/// that, `u.pathname = '/p'` read back as `/p` while `u.href` still showed the
/// old path, so the object disagreed with itself.
///
/// `host` and `href` are here too, and both need more than a write: `host`
/// carries the port, and assigning `href` REPLACES the whole URL. Neither was
/// settable, so `u.href = 'http://x/y'` stored a string that every other
/// property then contradicted.
pub const COMPONENTS: &[&str] = &[
    "protocol", "username", "password", "host", "hostname", "port", "pathname", "search", "hash",
    "href",
];

/// Whether `name` is a `URL` component whose assignment must refresh the
/// derived fields.
pub fn is_component(name: &str) -> bool {
    COMPONENTS.contains(&name)
}

/// Recompute `href`, `host` and `origin` from the component properties now on
/// `url`, and normalise the two components that carry a leading delimiter.
///
/// `sync_params` rewrites the attached `searchParams` from the new query. It is
/// false when the caller IS that `searchParams` object pushing its own edit
/// back, which would otherwise recurse.
fn recompute(url: &Value, sync_params: bool) {
    let read = |k: &str| {
        with_host(|h| match h.get(url) {
            Some(JsObj::Object(p)) => p.get(k).map(|v| h.str_of(v)).unwrap_or_default(),
            _ => String::new(),
        })
    };
    let mut protocol = read("@@protocol");
    if !protocol.is_empty() && !protocol.ends_with(':') {
        protocol.push(':');
    }
    // A search or hash assigned without its delimiter gains one; assigning the
    // empty string clears it, as the WHATWG setters do.
    let delimited = |s: String, lead: char| {
        if s.is_empty() || s.starts_with(lead) {
            s
        } else {
            format!("{lead}{s}")
        }
    };
    let parts = Parts {
        protocol,
        username: read("@@username"),
        password: read("@@password"),
        hostname: read("@@hostname"),
        port: read("@@port"),
        pathname: read("@@pathname"),
        search: delimited(read("@@search"), '?'),
        hash: delimited(read("@@hash"), '#'),
    };
    let (href, host, origin) = (parts.href(), parts.host(), parts.origin());
    let search = parts.search.clone();
    if sync_params {
        // The attached `searchParams` is updated IN PLACE: node hands out one
        // object per URL for the life of the URL, so `u.searchParams` before and
        // after `u.search = …` is the same object.
        let query = search.strip_prefix('?').unwrap_or(&search).to_string();
        let params = with_host(|h| match h.get(url) {
            Some(JsObj::Object(p)) => p.get("@@searchParams").cloned(),
            _ => None,
        });
        if let Some(params) = params {
            write_pairs(&params, &parse_query(&query));
        }
    }
    with_host(|h| {
        let vals = [
            ("@@href", h.new_str(href)),
            ("@@host", h.new_str(host)),
            ("@@origin", h.new_str(origin)),
            ("@@protocol", h.new_str(parts.protocol.clone())),
            ("@@search", h.new_str(search)),
            ("@@hash", h.new_str(parts.hash.clone())),
        ];
        if let Some(JsObj::Object(p)) = h.get_mut(url) {
            for (k, v) in vals {
                p.insert(k.to_string(), v);
            }
        }
    });
}

/// Refresh a `URL` after one of its components was assigned.
pub fn refresh(url: &Value) {
    recompute(url, true);
}

/// Split the `host` just assigned to `url` into the `hostname` and `port` it
/// actually carries.
///
/// `host` is DERIVED from those two on every refresh, so writing it as one
/// string was undone immediately: `u.host = 'b:99'` left the URL pointing at
/// the old host entirely.
pub fn split_host(url: &Value) {
    let host = with_host(|h| match h.get(url) {
        Some(JsObj::Object(p)) => p.get("@@host").map(|v| h.str_of(v)).unwrap_or_default(),
        _ => String::new(),
    });
    // An IPv6 literal keeps its brackets; the port is whatever follows the LAST
    // colon outside them.
    let split = match host.rfind(']') {
        Some(i) => host[i..].find(':').map(|j| i + j),
        None => host.rfind(':'),
    };
    let (hostname, port) = match split {
        Some(i) => (host[..i].to_string(), host[i + 1..].to_string()),
        None => (host.clone(), String::new()),
    };
    with_host(|h| {
        let (hn, pt) = (h.new_str(hostname), h.new_str(port));
        if let Some(JsObj::Object(p)) = h.get_mut(url) {
            p.insert("@@hostname".into(), hn);
            p.insert("@@port".into(), pt);
        }
    });
    refresh(url);
}

/// Re-parse `url` from the `href` just assigned to it.
///
/// `href` is not a component: it is the WHOLE URL, so setting it replaces every
/// other field. Treating it as one more stored string left `u.host` and
/// `u.pathname` reporting the old URL's values while `u.href` showed the new
/// one. An unparseable value is ignored, which is what node does — its `href`
/// setter throws only for a value no parser can accept, and this parser is the
/// one deciding that.
pub fn reparse(url: &Value) {
    let href = with_host(|h| match h.get(url) {
        Some(JsObj::Object(p)) => p.get("@@href").map(|v| h.str_of(v)).unwrap_or_default(),
        _ => String::new(),
    });
    let Some(parts) = parse_absolute(&href) else {
        return;
    };
    let fresh = build(&parts);
    let props = with_host(|h| match h.get(&fresh) {
        Some(JsObj::Object(p)) => p.clone(),
        _ => IndexMap::new(),
    });
    with_host(|h| {
        if let Some(JsObj::Object(p)) = h.get_mut(url) {
            for (k, v) in props {
                p.insert(k, v);
            }
        }
    });
}

struct Parts {
    protocol: String,
    username: String,
    password: String,
    hostname: String,
    port: String,
    pathname: String,
    search: String,
    hash: String,
}

impl Parts {
    fn host(&self) -> String {
        if self.port.is_empty() {
            self.hostname.clone()
        } else {
            format!("{}:{}", self.hostname, self.port)
        }
    }
    fn origin(&self) -> String {
        // Only a special scheme with a network host has a tuple origin; every
        // other URL (`foo://h/`, `redis://h:1/`, `file:///x`) is opaque: `null`.
        let scheme = self.protocol.strip_suffix(':').unwrap_or(&self.protocol);
        if self.hostname.is_empty() || special_port(scheme).is_none() {
            "null".into()
        } else {
            format!("{}//{}", self.protocol, self.host())
        }
    }
    fn href(&self) -> String {
        let auth = if self.username.is_empty() {
            String::new()
        } else if self.password.is_empty() {
            format!("{}@", self.username)
        } else {
            format!("{}:{}@", self.username, self.password)
        };
        format!(
            "{}//{auth}{}{}{}{}",
            self.protocol,
            self.host(),
            self.pathname,
            self.search,
            self.hash
        )
    }
}

/// Whether `scheme` is one of the WHATWG "special" schemes, whose parsing
/// normalizes backslashes and drops a default port.
fn special_port(scheme: &str) -> Option<&'static str> {
    match scheme {
        "http" | "ws" => Some("80"),
        "https" | "wss" => Some("443"),
        "ftp" => Some("21"),
        _ => None,
    }
}

/// Parse an absolute URL. Returns `None` if there is no `scheme://`.
fn parse_absolute(input: &str) -> Option<Parts> {
    // The URL parser REMOVES every tab and newline from the input before doing
    // anything else, rather than treating them as content. They were surviving
    // into the components and then being percent-encoded.
    let stripped: String;
    let input = if input.contains(['\t', '\n', '\r']) {
        stripped = input.replace(['\t', '\n', '\r'], "");
        stripped.as_str()
    } else {
        input
    };
    let (scheme, rest) = input.split_once("://")?;
    // For a special scheme a backslash is a path separator, not a character —
    // in the AUTHORITY too, where it terminates the userinfo. It is NOT one in
    // the query or fragment, where node keeps it literal, so the rewrite stops
    // at whichever of `?`/`#` comes first.
    let backslashed: String;
    let rest = if special_port(&scheme.to_ascii_lowercase()).is_some() && rest.contains('\\') {
        let cut = rest.find(['?', '#']).unwrap_or(rest.len());
        backslashed = format!("{}{}", rest[..cut].replace('\\', "/"), &rest[cut..]);
        backslashed.as_str()
    } else {
        rest
    };
    if scheme.is_empty()
        || !scheme
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
    {
        return None;
    }
    // A special scheme ignores any further slashes before the authority
    // ("special authority ignore slashes state"): `http:///a` is `http://a/`.
    let rest = if special_port(&scheme.to_ascii_lowercase()).is_some() {
        rest.trim_start_matches('/')
    } else {
        rest
    };
    // authority is up to the first '/', '?' or '#'.
    let auth_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let authority = &rest[..auth_end];
    let mut tail = &rest[auth_end..];

    let (userinfo, hostport) = match authority.rsplit_once('@') {
        Some((u, h)) => (u, h),
        None => ("", authority),
    };
    let (username, password) = match userinfo.split_once(':') {
        Some((u, p)) => (u.to_string(), p.to_string()),
        None => (userinfo.to_string(), String::new()),
    };
    // An IPv6 literal carries colons of its own: the port separator is the
    // first colon AFTER its closing bracket, and nothing else may sit there.
    let (hostname, port) = if hostport.starts_with('[') {
        let close = hostport.find(']')?;
        match &hostport[close + 1..] {
            "" => (&hostport[..=close], ""),
            p => (&hostport[..=close], p.strip_prefix(':')?),
        }
    } else {
        hostport.split_once(':').unwrap_or((hostport, ""))
    };
    let lower_scheme = scheme.to_ascii_lowercase();
    let special = special_port(&lower_scheme).is_some();
    // The host parser: a special scheme's host is a domain (percent-decoded,
    // mapped to ASCII, and checked for forbidden code points), an IPv4 address
    // in any of its number forms, or a bracketed IPv6 address, each serialized
    // canonically — `http://0x7f.1/` is `http://127.0.0.1/`, and `http://a b/`
    // is no URL at all. Any other scheme's host is opaque and only checked.
    let hostname = if special {
        if hostname.is_empty() {
            return None;
        }
        url::Host::parse(hostname).ok()?.to_string()
    } else if hostname.is_empty() {
        String::new()
    } else {
        url::Host::parse_opaque(hostname).ok()?.to_string()
    };
    // A port is digits only and at most 65535, serialized without leading
    // zeros; an empty port after the colon is the same as none.
    let port = if port.is_empty() {
        String::new()
    } else if port.bytes().all(|b| b.is_ascii_digit()) {
        port.trim_start_matches('0').parse::<u16>().map_or_else(
            |_| {
                if port.bytes().all(|b| b == b'0') {
                    Some("0".to_string())
                } else {
                    None
                }
            },
            |n| Some(n.to_string()),
        )?
    } else {
        return None;
    };

    let hash = match tail.find('#') {
        Some(i) => {
            let h = tail[i..].to_string();
            tail = &tail[..i];
            h
        }
        None => String::new(),
    };
    let search = match tail.find('?') {
        Some(i) => {
            let s = tail[i..].to_string();
            tail = &tail[..i];
            s
        }
        None => String::new(),
    };
    // A scheme is case-insensitive and reported lower-case.
    let scheme = scheme.to_ascii_lowercase();
    let default_port = special_port(&scheme);
    let pathname = if tail.is_empty() {
        "/".to_string()
    } else {
        normalize_path(tail)
    };
    // The scheme's default port is not part of the serialization.
    let port = if default_port == Some(port.as_str()) {
        String::new()
    } else {
        port
    };

    Some(Parts {
        protocol: format!("{scheme}:"),
        username,
        password,
        hostname,
        port,
        pathname,
        search,
        hash,
    })
}

/// Collapse `.` and `..` segments in an absolute-ish URL path, per the WHATWG
/// URL path-state machine: `.` drops, `..` pops the previous segment (never past
/// the root), and a trailing `.`/`..` leaves a trailing slash
/// (`/a/b/../../../c` → `/c`, `/a/b/..` → `/a/`).
fn normalize_path(path: &str) -> String {
    if !path.contains('.') {
        return path.to_string();
    }
    let rooted = path.starts_with('/');
    let mut out: Vec<&str> = Vec::new();
    let mut trailing_slash = false;
    for seg in path.split('/') {
        match seg {
            "." => trailing_slash = true,
            ".." => {
                out.pop();
                trailing_slash = true;
            }
            _ => {
                out.push(seg);
                trailing_slash = false;
            }
        }
    }
    // `split` on a rooted path yields a leading "" that rebuilds the root slash;
    // a `..` may have popped it, so restore it.
    if rooted && out.first() != Some(&"") {
        out.insert(0, "");
    }
    let mut joined = out.join("/");
    if trailing_slash && !joined.ends_with('/') {
        joined.push('/');
    }
    if joined.is_empty() {
        joined.push('/');
    }
    joined
}

/// `new URL(input[, base])`.
pub fn construct(args: &[Value]) -> Result<Value, String> {
    // Both arguments go through ToString, so an object's own `toString` is
    // what gets parsed (`new URL('x', { toString() { return 'http://a/' } })`).
    let to_str = |v: &Value| {
        crate::host::to_string_value(v).map(|s| crate::host::with_host(|h| h.str_of(&s)))
    };
    let input = match args.first() {
        Some(v) => to_str(v)?,
        None => "undefined".to_string(),
    };
    // An explicit `undefined` base is no base at all.
    let base = match args.get(1) {
        Some(Value::Undef) | None => None,
        Some(v) => Some(to_str(v)?),
    };
    let parts = parse_absolute(&input)
        .or_else(|| {
            // A base makes a relative input absolute (path replacement only).
            if let Some(base) = &base {
                parse_absolute(base).map(|mut b| {
                    // Split the RELATIVE reference's own query/fragment off first;
                    // they replace the base's, they do not append to its path.
                    let mut rest = input.as_str();
                    let hash = match rest.find('#') {
                        Some(i) => {
                            let h = rest[i..].to_string();
                            rest = &rest[..i];
                            h
                        }
                        None => String::new(),
                    };
                    let search = match rest.find('?') {
                        Some(i) => {
                            let q = rest[i..].to_string();
                            rest = &rest[..i];
                            q
                        }
                        None => String::new(),
                    };
                    // A rooted reference replaces the path; anything else resolves
                    // against the base's DIRECTORY (everything up to its last `/`).
                    let merged = if rest.starts_with('/') {
                        rest.to_string()
                    } else if rest.is_empty() {
                        b.pathname.clone()
                    } else {
                        let dir = match b.pathname.rfind('/') {
                            Some(i) => &b.pathname[..=i],
                            None => "/",
                        };
                        format!("{dir}{rest}")
                    };
                    b.pathname = normalize_path(&merged);
                    b.search = search;
                    b.hash = hash;
                    b
                })
            } else {
                None
            }
        })
        // Node's message is the bare `Invalid URL` and it carries
        // `code === 'ERR_INVALID_URL'`; the input is exposed as `err.input`, not
        // appended to the text. `url_legacy::invalid_url` was already emitting
        // the current form — this site was the one still hardcoding an older one.
        // node also hangs the input (and the base, when one was passed) off the
        // error as `err.input` / `err.base`.
        .ok_or_else(|| {
            let mut fields = vec![("input", input.as_str())];
            if let Some(b) = &base {
                fields.push(("base", b.as_str()));
            }
            crate::host::plain_coded_error_with(
                "TypeError",
                "ERR_INVALID_URL",
                "Invalid URL",
                &fields,
            )
        })?;
    Ok(build(&parts))
}

/// Percent-encode `s` for one URL component, per the WHATWG percent-encode sets.
///
/// None of this was happening: `new URL('https://a.b/a b?c=d e').href` came back
/// with the spaces intact, which is not a valid URL and does not round-trip.
///
/// The sets below were derived by feeding every ASCII character through node
/// v26.8.1 in each position rather than transcribed, since the spec's sets and
/// what a parser actually emits differ around the component delimiters. Every
/// C0 control, `%7F`, and every non-ASCII byte is encoded in all four; a byte
/// already part of a valid `%XX` escape is left alone so re-parsing a URL does
/// not double-encode it.
fn percent_encode(s: &str, extra: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        // An existing escape passes through untouched.
        if b == b'%' && i + 2 < bytes.len() + 1 {
            let hex = bytes.get(i + 1..i + 3);
            if hex.is_some_and(|h| h.iter().all(|c| c.is_ascii_hexdigit())) {
                out.push('%');
                out.push(bytes[i + 1] as char);
                out.push(bytes[i + 2] as char);
                i += 3;
                continue;
            }
        }
        if b < 0x20 || b == 0x7f || b >= 0x80 || extra.as_bytes().contains(&b) {
            out.push_str(&format!("%{b:02X}"));
        } else {
            out.push(b as char);
        }
        i += 1;
    }
    out
}

/// The four component encode sets, as measured against node.
const PATH_SET: &str = " \"<>^`{}";
const QUERY_SET: &str = " \"'<>";
const FRAGMENT_SET: &str = " \"<>`";
const USERINFO_SET: &str = " \";<=>@[]^`{|}";

fn build(p: &Parts) -> Value {
    // Percent-encode each component once, here, so `href()` and every
    // individual property report the same normalized text. The host arrives
    // already canonical from the host parser in `parse_absolute`; lower-casing
    // it again here also folded a non-special scheme's opaque host, which
    // node keeps as written (`foo://Host/`).
    let p = &Parts {
        protocol: p.protocol.clone(),
        username: percent_encode(&p.username, USERINFO_SET),
        password: percent_encode(&p.password, USERINFO_SET),
        hostname: p.hostname.clone(),
        port: p.port.clone(),
        pathname: percent_encode(&p.pathname, PATH_SET),
        search: percent_encode(&p.search, QUERY_SET),
        hash: percent_encode(&p.hash, FRAGMENT_SET),
    };
    // Build the `URLSearchParams` BEFORE the allocating `with_host` below (never
    // nest `with_host`); it is stored as the `searchParams` data property so
    // `url.searchParams.get(...)` reads it directly. It is LIVE, not a snapshot:
    // it gets an `@@ownerUrl` back-reference below so that mutating it rewrites
    // this URL's `search` and `href`.
    let query = p.search.strip_prefix('?').unwrap_or(&p.search);
    let search_params = make_search_params(&parse_query(query));
    with_host(|h| {
        let mut m = IndexMap::new();
        m.insert("@@native".into(), h.new_str("URL"));
        m.insert("@@href".into(), h.new_str(p.href()));
        m.insert("@@origin".into(), h.new_str(p.origin()));
        m.insert("@@protocol".into(), h.new_str(p.protocol.clone()));
        m.insert("@@username".into(), h.new_str(p.username.clone()));
        m.insert("@@password".into(), h.new_str(p.password.clone()));
        m.insert("@@host".into(), h.new_str(p.host()));
        m.insert("@@hostname".into(), h.new_str(p.hostname.clone()));
        m.insert("@@port".into(), h.new_str(p.port.clone()));
        m.insert("@@pathname".into(), h.new_str(p.pathname.clone()));
        m.insert("@@search".into(), h.new_str(p.search.clone()));
        m.insert("@@searchParams".into(), search_params.clone());
        m.insert("@@hash".into(), h.new_str(p.hash.clone()));
        let obj = h.new_object(m);
        // Hidden, and set after the URL exists so the two can point at each other.
        if let Some(JsObj::Object(sp)) = h.get_mut(&search_params) {
            sp.insert("@@ownerUrl".into(), obj.clone());
        }
        obj
    })
}

/// Statics on the `URL` CLASS — distinct from [`MODULE_METHODS`], which are the
/// legacy `require('url')` functions.
///
/// `createObjectURL`/`revokeObjectURL` are absent because `Blob` is not
/// implemented; they would have nothing to register.
pub const STATIC_METHODS: &[&str] = &["canParse", "parse"];

/// `URL.canParse(input[, base])` / `URL.parse(input[, base])`.
///
/// Both are the non-throwing form of the constructor: `canParse` reports
/// whether parsing succeeds, `parse` returns the `URL` or `null`. Neither
/// existed, so `URL.canParse` was a TypeError rather than a boolean.
pub fn static_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
    let parsed = construct(args);
    Some(match method {
        "canParse" => Ok(Value::Bool(parsed.is_ok())),
        "parse" => Ok(parsed.unwrap_or_else(|_| with_host(|h| h.null()))),
        _ => return None,
    })
}

pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
    Some(match method {
        "parse" => legacy_parse(args).map(|u| super::url_legacy::to_js(&u)),
        "format" => super::url_legacy::format_value(&args.first().cloned().unwrap_or(Value::Undef)),
        // `url.fileURLToPath(url)` — a `file:` URL/string → a filesystem path
        // (percent-decoded). POSIX best-effort: any authority (host) is accepted
        // but not re-prefixed; Windows drive/UNC rewriting is not modeled.
        "fileURLToPath" => file_url_to_path(args).map(|s| with_host(|h| h.new_str(s))),
        // Same, but returns the path as a `Buffer`.
        "fileURLToPathBuffer" => {
            file_url_to_path(args).map(|s| super::buffer::from_bytes(s.as_bytes()))
        }
        // `url.pathToFileURL(path)` → a `URL` instance with a `file:` href.
        "pathToFileURL" => Ok(path_to_file_url(&arg_str(args, 0))),
        // `url.domainToASCII` / `url.domainToUnicode` — delegate to the punycode
        // codec; an ASCII-only domain passes through unchanged, an invalid domain
        // yields "" (matching Node, which never throws here).
        "domainToASCII" => Ok(punycode_domain(args, true)),
        "domainToUnicode" => Ok(punycode_domain(args, false)),
        // `url.urlToHttpOptions(URL)` → an options object for http/https.request.
        "urlToHttpOptions" => Ok(url_to_http_options(
            &args.first().cloned().unwrap_or(Value::Undef),
        )),
        // Legacy `url.resolve(from, to)` — `urlParse(from, false, true)
        // .resolve(to)`: both sides parsed with `slashesDenoteHost`, resolved by
        // the `Url.prototype.resolveObject` port, then formatted.
        "resolve" => legacy_resolve_object(args)
            .map(|u| with_host(|h| h.new_str(u.href.unwrap_or_default()))),
        // Legacy `url.resolveObject(from, to)` — the same resolution, returned
        // as the parsed object. An empty `from` hands `to` back untouched.
        "resolveObject" => {
            if !args.first().is_some_and(|v| with_host(|h| h.truthy(v))) {
                return Some(Ok(args.get(1).cloned().unwrap_or(Value::Undef)));
            }
            legacy_resolve_object(args).map(|u| super::url_legacy::to_js(&u))
        }
        _ => return None,
    })
}

/// Legacy `url.parse(urlString[, parseQueryString[, slashesDenoteHost]])`.
/// Emits the one-shot `DEP0169` deprecation warning, exactly as Node's
/// `urlParse` does, then delegates to the `Url.prototype.parse` port.
fn legacy_parse(args: &[Value]) -> Result<super::url_legacy::Url, String> {
    emit_url_parse_deprecation();
    let input = arg_str(args, 0);
    let truthy = |i: usize| {
        args.get(i)
            .map(|v| with_host(|h| h.truthy(v)))
            .unwrap_or(false)
    };
    super::url_legacy::parse(&input, truthy(1), truthy(2))
}

/// `urlParse`'s one-time `DEP0169`, shared by `parse`, `resolve` and
/// `resolveObject` — all three go through `urlParse` in node.
fn emit_url_parse_deprecation() {
    super::process::emit_deprecation_warning(
        "DEP0169",
        "`url.parse()` behavior is not standardized and prone to errors that \
         have security implications. Use the WHATWG URL API instead. CVEs are \
         not issued for `url.parse()` vulnerabilities.",
    );
}

/// `urlParse(args[0], false, true).resolveObject(args[1])`, emitting the
/// one-shot `DEP0169` that `urlParse` raises.
fn legacy_resolve_object(args: &[Value]) -> Result<super::url_legacy::Url, String> {
    emit_url_parse_deprecation();
    let source = super::url_legacy::parse(&arg_str(args, 0), false, true)?;
    let relative = super::url_legacy::parse(&arg_str(args, 1), false, true)?;
    Ok(super::url_legacy::resolve_object(&source, relative))
}

/// `URL` instance methods (component reads are plain data properties).
pub fn instance_call(recv: &Value, method: &str, _args: &[Value]) -> Result<Value, String> {
    match method {
        "toString" | "toJSON" => Ok(with_host(|h| match h.get(recv) {
            Some(JsObj::Object(p)) => p.get("@@href").cloned().unwrap_or(Value::Undef),
            _ => Value::Undef,
        })),
        _ => Err(crate::host::type_error(&format!(
            "url.{method} is not a function"
        ))),
    }
}

// ── file:/legacy URL helpers ─────────────────────────────────────────────────

/// The `href` string of a value: for a native `URL` its stored `href`, else the
/// value coerced to a string (so both `URL` objects and strings are accepted).
fn url_href(v: &Value) -> String {
    with_host(|h| match h.get(v) {
        Some(JsObj::Object(p)) => match p.get("@@native").map(|x| h.str_of(x)).as_deref() {
            Some("URL") => p.get("@@href").map(|x| h.str_of(x)).unwrap_or_default(),
            _ => h.str_of(v),
        },
        _ => h.str_of(v),
    })
}

/// `fileURLToPath` core: `file://[host]/path` → decoded `/path`.
fn file_url_to_path(args: &[Value]) -> Result<String, String> {
    let v = args.first().cloned().unwrap_or(Value::Undef);
    let href = url_href(&v);
    let rest = href.strip_prefix("file://").ok_or_else(|| {
        crate::host::plain_coded_error(
            "TypeError",
            "ERR_INVALID_URL_SCHEME",
            "The URL must be of scheme file",
        )
    })?;
    // The authority runs up to the first '/'; the remainder is the path.
    let path = match rest.find('/') {
        Some(0) => rest,
        Some(i) => &rest[i..],
        None => "/",
    };
    Ok(percent_decode(path))
}

/// `pathToFileURL(path)` → a `URL` instance whose href is `file://` + the
/// percent-encoded (path-set) path.
fn path_to_file_url(path: &str) -> Value {
    let enc = encode_path_component(path);
    let pathname = if enc.starts_with('/') {
        enc
    } else {
        format!("/{enc}")
    };
    let parts = Parts {
        protocol: "file:".into(),
        username: String::new(),
        password: String::new(),
        hostname: String::new(),
        port: String::new(),
        pathname,
        search: String::new(),
        hash: String::new(),
    };
    build(&parts)
}

/// `domainToASCII` (`ascii = true`) / `domainToUnicode` — via the punycode codec.
fn punycode_domain(args: &[Value], ascii: bool) -> Value {
    let method = if ascii { "toASCII" } else { "toUnicode" };
    match super::punycode::call(method, args) {
        Some(Ok(v)) => v,
        _ => with_host(|h| h.new_str("")),
    }
}

/// `urlToHttpOptions(URL)` → `{ protocol, hostname, hash, search, pathname, path,
/// href[, port][, auth] }`, mirroring Node's field set and IPv6 bracket-stripping.
fn url_to_http_options(v: &Value) -> Value {
    let get = |key: &str| -> String {
        with_host(|h| match h.get(v) {
            Some(JsObj::Object(p)) => p.get(key).map(|x| h.str_of(x)).unwrap_or_default(),
            _ => String::new(),
        })
    };
    let protocol = get("@@protocol");
    let mut hostname = get("@@hostname");
    if hostname.starts_with('[') && hostname.ends_with(']') && hostname.len() >= 2 {
        hostname = hostname[1..hostname.len() - 1].to_string();
    }
    let hash = get("@@hash");
    let search = get("@@search");
    let pathname = get("@@pathname");
    let href = get("@@href");
    let port = get("@@port");
    let username = get("@@username");
    let password = get("@@password");
    let path = format!("{pathname}{search}");
    let auth = if username.is_empty() && password.is_empty() {
        None
    } else {
        Some(format!(
            "{}:{}",
            percent_decode(&username),
            percent_decode(&password)
        ))
    };
    let port_num = if port.is_empty() {
        None
    } else {
        port.parse::<f64>().ok()
    };
    with_host(|h| {
        let mut m = IndexMap::new();
        m.insert("protocol".into(), h.new_str(protocol));
        m.insert("hostname".into(), h.new_str(hostname));
        m.insert("hash".into(), h.new_str(hash));
        m.insert("search".into(), h.new_str(search));
        m.insert("pathname".into(), h.new_str(pathname));
        m.insert("path".into(), h.new_str(path));
        m.insert("href".into(), h.new_str(href));
        if let Some(n) = port_num {
            m.insert("port".into(), Value::Float(n));
        }
        if let Some(a) = auth {
            m.insert("auth".into(), h.new_str(a));
        }
        h.new_object(m)
    })
}

/// Percent-decode a URL component (`%XX` → byte, then UTF-8 lossy). Unlike the
/// form decoder this leaves `+` literal (a file path may legitimately contain it).
pub(crate) fn percent_decode(s: &str) -> String {
    let b = s.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' && i + 2 < b.len() {
            if let (Some(hi), Some(lo)) = (hex_val(b[i + 1]), hex_val(b[i + 2])) {
                out.push((hi << 4) | lo);
                i += 3;
                continue;
            }
        }
        out.push(b[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Percent-encode a path for a `file:` URL: keep the unreserved + sub-delim set
/// and `/ : @`, encode everything else (space, `# ? %` `< > "` etc.).
fn encode_path_component(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for &b in s.as_bytes() {
        let keep = b.is_ascii_alphanumeric()
            || matches!(
                b,
                b'/' | b'-'
                    | b'.'
                    | b'_'
                    | b'~'
                    | b'!'
                    | b'$'
                    | b'&'
                    | b'\''
                    | b'('
                    | b')'
                    | b'*'
                    | b'+'
                    | b','
                    | b';'
                    | b'='
                    | b':'
                    | b'@'
            );
        if keep {
            out.push(b as char);
        } else {
            out.push('%');
            out.push(hex_upper(b >> 4));
            out.push(hex_upper(b & 0x0f));
        }
    }
    out
}

// ── URLSearchParams ──────────────────────────────────────────────────────────
//
// A `URLSearchParams` is a plain object tagged `@@native = "URLSearchParams"`
// whose ordered `[key, value]` pairs live in a hidden `@@pairs` array (each entry
// a 2-element `[key, value]` array of strings). All string coercion happens up
// front; methods mutate a plain `Vec<(String, String)>` and write it back.

/// Method names dispatched through `search_params_call` (for `instance_has_method`
/// wiring in `stdlib::mod`; `@@iterator` makes `[...params]` / `for..of` work).
pub const SEARCH_PARAMS_METHODS: &[&str] = &[
    "get",
    "getAll",
    "has",
    "set",
    "append",
    "delete",
    "keys",
    "values",
    "entries",
    "forEach",
    "toString",
    "sort",
    "@@iterator",
];

/// Build a `URLSearchParams` native object from ordered key/value pairs.
fn make_search_params(pairs: &[(String, String)]) -> Value {
    with_host(|h| {
        let items: Vec<Value> = pairs
            .iter()
            .map(|(k, v)| {
                let kv = vec![h.new_str(k.clone()), h.new_str(v.clone())];
                h.new_array(kv)
            })
            .collect();
        let arr = h.new_array(items);
        let mut m = IndexMap::new();
        m.insert("@@native".into(), h.new_str("URLSearchParams"));
        m.insert("@@pairs".into(), arr);
        // `size` is a prototype getter in the spec; kept in sync as a hidden own
        // property here, so it reads back without appearing in `Object.keys` or
        // `console.log`. `set_pairs` maintains it.
        m.insert("size".into(), Value::Float(pairs.len() as f64));
        let obj = h.new_object(m);
        h.hide_prop(&obj, "size");
        obj
    })
}

/// Serialize ordered pairs back into an `application/x-www-form-urlencoded`
/// query string — the inverse of [`parse_query`].
fn encode_query(pairs: &[(String, String)]) -> String {
    pairs
        .iter()
        .map(|(k, v)| format!("{}={}", form_encode(k), form_encode(v)))
        .collect::<Vec<_>>()
        .join("&")
}

/// Read the ordered `(key, value)` pairs out of a `URLSearchParams`.
fn pairs_of(recv: &Value) -> Vec<(String, String)> {
    with_host(|h| {
        let items: Vec<Value> = match h.get(recv) {
            Some(JsObj::Object(p)) => match p.get("@@pairs").and_then(|a| h.get(a)) {
                Some(JsObj::Array(items)) => items.clone(),
                _ => Vec::new(),
            },
            _ => Vec::new(),
        };
        items
            .iter()
            .map(|it| match h.get(it) {
                Some(JsObj::Array(kv)) => {
                    let kv = kv.clone();
                    let k = kv.first().map(|x| h.str_of(x)).unwrap_or_default();
                    let v = kv.get(1).map(|x| h.str_of(x)).unwrap_or_default();
                    (k, v)
                }
                _ => (h.str_of(it), String::new()),
            })
            .collect()
    })
}

/// Overwrite a `URLSearchParams`' backing `@@pairs` array, and push the new
/// query back to the `URL` that owns it if there is one.
///
/// A `URLSearchParams` reached through `url.searchParams` is LIVE in both
/// directions: `u.searchParams.set('b', '2')` has to rewrite `u.search` and
/// `u.href`. It was previously a detached snapshot, so the edit went nowhere.
fn set_pairs(recv: &Value, pairs: &[(String, String)]) {
    write_pairs(recv, pairs);
    let owner = with_host(|h| match h.get(recv) {
        Some(JsObj::Object(p)) => p.get("@@ownerUrl").cloned(),
        _ => None,
    });
    if let Some(owner) = owner {
        let query = encode_query(pairs);
        with_host(|h| {
            let s = h.new_str(if query.is_empty() {
                String::new()
            } else {
                format!("?{query}")
            });
            if let Some(JsObj::Object(p)) = h.get_mut(&owner) {
                p.insert("@@search".into(), s);
            }
        });
        recompute(&owner, false);
    }
}

/// Write `pairs` into a `URLSearchParams` without notifying an owning `URL`.
fn write_pairs(recv: &Value, pairs: &[(String, String)]) {
    with_host(|h| {
        let items: Vec<Value> = pairs
            .iter()
            .map(|(k, v)| {
                let kv = vec![h.new_str(k.clone()), h.new_str(v.clone())];
                h.new_array(kv)
            })
            .collect();
        let arr = h.new_array(items);
        let n = Value::Float(pairs.len() as f64);
        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
            p.insert("@@pairs".into(), arr);
            p.insert("size".into(), n);
        }
        h.hide_prop(recv, "size");
    });
}

/// `new URLSearchParams([init])` — from a query string, an object, an iterable of
/// `[key, value]` pairs, another `URLSearchParams`, or empty.
pub fn construct_search_params(args: &[Value]) -> Result<Value, String> {
    let pairs = match args.first() {
        None => Vec::new(),
        Some(v) if matches!(v, Value::Undef) || with_host(|h| h.is_null(v)) => Vec::new(),
        Some(v) => pairs_from_init(v),
    };
    Ok(make_search_params(&pairs))
}

fn pairs_from_init(v: &Value) -> Vec<(String, String)> {
    // Copy of another URLSearchParams.
    if super::native_tag(v).as_deref() == Some("URLSearchParams") {
        return pairs_of(v);
    }
    // Query string (a leading `?` is stripped, matching the URL/WHATWG parser).
    if let Some(s) = with_host(|h| h.as_str(v)) {
        return parse_query(s.strip_prefix('?').unwrap_or(&s));
    }
    with_host(|h| match h.get(v) {
        // Iterable of `[key, value]` pairs.
        Some(JsObj::Array(items)) => {
            let items = items.clone();
            items
                .iter()
                .map(|it| match h.get(it) {
                    Some(JsObj::Array(kv)) => {
                        let kv = kv.clone();
                        let k = kv.first().map(|x| h.str_of(x)).unwrap_or_default();
                        let val = kv.get(1).map(|x| h.str_of(x)).unwrap_or_default();
                        (k, val)
                    }
                    _ => (h.str_of(it), String::new()),
                })
                .collect()
        }
        // Plain object: own enumerable entries (hidden `@@` keys excluded).
        Some(JsObj::Object(p)) => {
            let entries: Vec<(String, Value)> = p
                .iter()
                .filter(|(k, _)| !k.starts_with("@@"))
                .map(|(k, val)| (k.clone(), val.clone()))
                .collect();
            entries
                .into_iter()
                .map(|(k, val)| (k, h.str_of(&val)))
                .collect()
        }
        _ => Vec::new(),
    })
}

/// `URLSearchParams` instance methods.
pub fn search_params_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
    match method {
        "get" => {
            let name = arg_str(args, 0);
            match pairs_of(recv).into_iter().find(|(k, _)| *k == name) {
                Some((_, v)) => Ok(with_host(|h| h.new_str(v))),
                None => Ok(with_host(|h| h.null())),
            }
        }
        "getAll" => {
            let name = arg_str(args, 0);
            let vals: Vec<String> = pairs_of(recv)
                .into_iter()
                .filter(|(k, _)| *k == name)
                .map(|(_, v)| v)
                .collect();
            Ok(with_host(|h| {
                let items = vals.into_iter().map(|v| h.new_str(v)).collect();
                h.new_array(items)
            }))
        }
        "has" => {
            let name = arg_str(args, 0);
            let pairs = pairs_of(recv);
            let found = if args.len() > 1 {
                let val = arg_str(args, 1);
                pairs.iter().any(|(k, v)| *k == name && *v == val)
            } else {
                pairs.iter().any(|(k, _)| *k == name)
            };
            Ok(Value::Bool(found))
        }
        "append" => {
            let mut pairs = pairs_of(recv);
            pairs.push((arg_str(args, 0), arg_str(args, 1)));
            set_pairs(recv, &pairs);
            Ok(Value::Undef)
        }
        "set" => {
            let name = arg_str(args, 0);
            let val = arg_str(args, 1);
            let mut pairs = pairs_of(recv);
            // Set the first pair named `name` to `val`, remove any others; append
            // if none existed (WHATWG `set`).
            let mut seen = false;
            pairs.retain_mut(|(k, v)| {
                if *k == name {
                    if seen {
                        false
                    } else {
                        *v = val.clone();
                        seen = true;
                        true
                    }
                } else {
                    true
                }
            });
            if !seen {
                pairs.push((name, val));
            }
            set_pairs(recv, &pairs);
            Ok(Value::Undef)
        }
        "delete" => {
            let name = arg_str(args, 0);
            let mut pairs = pairs_of(recv);
            if args.len() > 1 {
                let val = arg_str(args, 1);
                pairs.retain(|(k, v)| !(*k == name && *v == val));
            } else {
                pairs.retain(|(k, _)| *k != name);
            }
            set_pairs(recv, &pairs);
            Ok(Value::Undef)
        }
        "sort" => {
            let mut pairs = pairs_of(recv);
            // Stable sort by key, comparing UTF-16 code units (WHATWG `sort`).
            pairs.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
            set_pairs(recv, &pairs);
            Ok(Value::Undef)
        }
        "toString" => {
            let s = encode_query(&pairs_of(recv));
            Ok(with_host(|h| h.new_str(s)))
        }
        "keys" => {
            let pairs = pairs_of(recv);
            Ok(with_host(|h| {
                let items = pairs.into_iter().map(|(k, _)| h.new_str(k)).collect();
                h.alloc(JsObj::Iter {
                    items,
                    idx: 0,
                    array: None,
                })
            }))
        }
        "values" => {
            let pairs = pairs_of(recv);
            Ok(with_host(|h| {
                let items = pairs.into_iter().map(|(_, v)| h.new_str(v)).collect();
                h.alloc(JsObj::Iter {
                    items,
                    idx: 0,
                    array: None,
                })
            }))
        }
        "entries" | "@@iterator" => {
            let pairs = pairs_of(recv);
            Ok(with_host(|h| {
                let items = pairs
                    .into_iter()
                    .map(|(k, v)| {
                        let kv = vec![h.new_str(k), h.new_str(v)];
                        h.new_array(kv)
                    })
                    .collect();
                h.alloc(JsObj::Iter {
                    items,
                    idx: 0,
                    array: None,
                })
            }))
        }
        "forEach" => {
            let cb = args.first().cloned().unwrap_or(Value::Undef);
            let this_arg = args.get(1).cloned();
            // Materialize pairs (releasing the host borrow) before re-entrant invoke.
            for (k, v) in pairs_of(recv) {
                let (value, name) = with_host(|h| (h.new_str(v), h.new_str(k)));
                crate::host::invoke(&cb, vec![value, name, recv.clone()], this_arg.clone())?;
            }
            Ok(Value::Undef)
        }
        _ => Err(crate::host::type_error(&format!(
            "urlSearchParams.{method} is not a function"
        ))),
    }
}

/// Parse an `application/x-www-form-urlencoded` string into ordered pairs.
fn parse_query(q: &str) -> Vec<(String, String)> {
    q.split('&')
        .filter(|s| !s.is_empty())
        .map(|seg| match seg.split_once('=') {
            Some((k, v)) => (form_decode(k), form_decode(v)),
            None => (form_decode(seg), String::new()),
        })
        .collect()
}

/// Decode one `application/x-www-form-urlencoded` component (`+` → space,
/// `%XX` → byte, then UTF-8 lossy).
fn form_decode(s: &str) -> String {
    let b = s.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        match b[i] {
            b'+' => {
                out.push(b' ');
                i += 1;
            }
            b'%' if i + 2 < b.len() => match (hex_val(b[i + 1]), hex_val(b[i + 2])) {
                (Some(hi), Some(lo)) => {
                    out.push((hi << 4) | lo);
                    i += 3;
                }
                _ => {
                    out.push(b'%');
                    i += 1;
                }
            },
            c => {
                out.push(c);
                i += 1;
            }
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Encode one `application/x-www-form-urlencoded` component: space → `+`, the
/// unreserved set `A-Za-z0-9 * - . _` verbatim, every other byte percent-encoded.
fn form_encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for &b in s.as_bytes() {
        match b {
            b' ' => out.push('+'),
            b'*' | b'-' | b'.' | b'_' => out.push(b as char),
            _ if b.is_ascii_alphanumeric() => out.push(b as char),
            _ => {
                out.push('%');
                out.push(hex_upper(b >> 4));
                out.push(hex_upper(b & 0x0f));
            }
        }
    }
    out
}

fn hex_val(c: u8) -> Option<u8> {
    match c {
        b'0'..=b'9' => Some(c - b'0'),
        b'a'..=b'f' => Some(c - b'a' + 10),
        b'A'..=b'F' => Some(c - b'A' + 10),
        _ => None,
    }
}

fn hex_upper(n: u8) -> char {
    char::from_digit(n as u32, 16).unwrap().to_ascii_uppercase()
}