Skip to main content

nodejs/stdlib/
url.rs

1//! Node `url` module: the WHATWG `URL` class (global + `require('url').URL`) and
2//! the legacy `url.parse`. Parsing and the component setters are the URL
3//! Standard's, through the `url` crate (its basic URL parser and `quirks`
4//! setters). A `URL` instance keeps each component in a hidden `@@<name>` slot
5//! read by the accessors on `URL.prototype`; a setter rewrites every slot from
6//! the re-serialized URL ([`set_component`]), and the `searchParams` it carries
7//! holds an `@@ownerUrl` back-reference so its own mutations rewrite the query
8//! in the other direction.
9
10use super::arg_str;
11use crate::host::{with_host, JsObj};
12use fusevm::Value;
13use indexmap::IndexMap;
14
15pub const MODULE_METHODS: &[&str] = &[
16    "parse",
17    "format",
18    "fileURLToPath",
19    "fileURLToPathBuffer",
20    "pathToFileURL",
21    "domainToASCII",
22    "domainToUnicode",
23    "urlToHttpOptions",
24    "resolve",
25    "resolveObject",
26];
27
28/// Parsed URL components.
29/// The component names a `URL` exposes as writable ACCESSORS on its prototype.
30///
31/// Assigning one has to rewrite the DERIVED fields — `href`, `host` and
32/// `origin` — which are stored alongside rather than computed on read. Without
33/// that, `u.pathname = '/p'` read back as `/p` while `u.href` still showed the
34/// old path, so the object disagreed with itself.
35///
36/// `host` and `href` are here too, and both need more than a write: `host`
37/// carries the port, and assigning `href` REPLACES the whole URL. Neither was
38/// settable, so `u.href = 'http://x/y'` stored a string that every other
39/// property then contradicted.
40pub const COMPONENTS: &[&str] = &[
41    "protocol", "username", "password", "host", "hostname", "port", "pathname", "search", "hash",
42    "href",
43];
44
45/// `url.protocol = 'file'` on a special non-file URL, which the WHATWG
46/// protocol setter allows unless the URL has credentials or a port (the scheme
47/// state with a state override, steps 2.1.1-2.1.3). The `url` crate refuses
48/// every such change (it rejects a `file` scheme on any URL with an authority),
49/// so this applies it: the scheme is replaced, the rest kept, and the result
50/// re-parsed. The re-parse is what refuses credentials and a port (a file URL
51/// can carry neither), and it re-runs file-host parsing, which turns a
52/// `localhost` host into the empty one where the setter keeps it (BUGS.md).
53fn special_to_file(u: &url::Url, value: &str) -> Option<url::Url> {
54    // The scheme state's buffer: ASCII alphanumerics, `+`, `-` and `.`, ended
55    // by `:` or the end of input (anything else refuses the assignment).
56    let end = value
57        .find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')))
58        .unwrap_or(value.len());
59    let (scheme, rest) = value.split_at(end);
60    if !(rest.is_empty() || rest.starts_with(':')) {
61        return None;
62    }
63    let special = ["http", "https", "ws", "wss", "ftp"];
64    if !scheme.eq_ignore_ascii_case("file") || !special.contains(&u.scheme()) {
65        return None;
66    }
67    let href = u.as_str();
68    url::Url::parse(&format!("file{}", &href[u.scheme().len()..])).ok()
69}
70
71/// Whether `name` is a `URL` component whose assignment must refresh the
72/// derived fields.
73pub fn is_component(name: &str) -> bool {
74    COMPONENTS.contains(&name)
75}
76
77/// The components a URL's parse produced, as the getters report them.
78fn parts_of(u: &url::Url) -> Parts {
79    let delimited = |lead: char, s: Option<&str>| match s {
80        Some(s) if !s.is_empty() => format!("{lead}{s}"),
81        _ => String::new(),
82    };
83    Parts {
84        protocol: format!("{}:", u.scheme()),
85        username: u.username().to_string(),
86        password: u.password().unwrap_or("").to_string(),
87        hostname: u.host_str().unwrap_or("").to_string(),
88        port: u.port().map(|p| p.to_string()).unwrap_or_default(),
89        pathname: u.path().to_string(),
90        search: delimited('?', u.query()),
91        hash: delimited('#', u.fragment()),
92        authority: u.has_authority(),
93        href: Some(u.as_str().to_string()),
94    }
95}
96
97/// Assign one `URL` component through the URL Standard's setter for it — the
98/// state-override parse `url::quirks` implements — and rewrite every stored
99/// field from the result. A value the setter rejects leaves the URL as it was
100/// (`u.port = 'abc'`), as in node; only `href` throws, since it reparses the
101/// whole URL.
102pub fn set_component(url_obj: &Value, key: &str, v: &Value) -> Result<(), String> {
103    let value = crate::host::to_string_value(v).map(|s| with_host(|h| h.str_of(&s)))?;
104    let href = read_slot(url_obj, "@@href");
105    let Ok(mut u) = url::Url::parse(&href) else {
106        return Ok(());
107    };
108    use url::quirks;
109    match key {
110        "href" => {
111            u = url::Url::parse(&value).map_err(|_| {
112                crate::host::plain_coded_error_with(
113                    "TypeError",
114                    "ERR_INVALID_URL",
115                    "Invalid URL",
116                    &[("input", value.as_str())],
117                )
118            })?;
119        }
120        "protocol" => {
121            if quirks::set_protocol(&mut u, &value).is_err() {
122                if let Some(file) = special_to_file(&u, &value) {
123                    u = file;
124                }
125            }
126        }
127        "username" => {
128            let _ = quirks::set_username(&mut u, &value);
129        }
130        "password" => {
131            let _ = quirks::set_password(&mut u, &value);
132        }
133        "host" => {
134            let _ = quirks::set_host(&mut u, &value);
135        }
136        "hostname" => {
137            let _ = quirks::set_hostname(&mut u, &value);
138        }
139        "port" => {
140            let _ = quirks::set_port(&mut u, &value);
141        }
142        "pathname" => quirks::set_pathname(&mut u, &value),
143        "search" => quirks::set_search(&mut u, &value),
144        "hash" => quirks::set_hash(&mut u, &value),
145        _ => return Ok(()),
146    }
147    store_parts(url_obj, &parts_of(&u), true);
148    Ok(())
149}
150
151fn read_slot(obj: &Value, key: &str) -> String {
152    with_host(|h| match h.get(obj) {
153        Some(JsObj::Object(p)) => p.get(key).map(|v| h.str_of(v)).unwrap_or_default(),
154        _ => String::new(),
155    })
156}
157
158/// Write every component of `p` into the URL's hidden slots. `sync_params`
159/// rewrites the attached `URLSearchParams` IN PLACE (one object per URL for its
160/// life); it is false when that object is the one pushing its own edit back.
161fn store_parts(url_obj: &Value, p: &Parts, sync_params: bool) {
162    if sync_params {
163        let query = p.search.strip_prefix('?').unwrap_or(&p.search).to_string();
164        let params = with_host(|h| match h.get(url_obj) {
165            Some(JsObj::Object(o)) => o.get("@@searchParams").cloned(),
166            _ => None,
167        });
168        if let Some(params) = params {
169            write_pairs(&params, &parse_query(&query));
170        }
171    }
172    with_host(|h| {
173        let vals = [
174            ("@@href", h.new_str(p.href())),
175            ("@@origin", h.new_str(p.origin())),
176            ("@@protocol", h.new_str(p.protocol.clone())),
177            ("@@username", h.new_str(p.username.clone())),
178            ("@@password", h.new_str(p.password.clone())),
179            ("@@host", h.new_str(p.host())),
180            ("@@hostname", h.new_str(p.hostname.clone())),
181            ("@@port", h.new_str(p.port.clone())),
182            ("@@pathname", h.new_str(p.pathname.clone())),
183            ("@@search", h.new_str(p.search.clone())),
184            ("@@hash", h.new_str(p.hash.clone())),
185            (
186                "@@authority",
187                h.new_str(if p.authority { "true" } else { "false" }),
188            ),
189        ];
190        if let Some(JsObj::Object(o)) = h.get_mut(url_obj) {
191            for (k, v) in vals {
192                o.insert(k.to_string(), v);
193            }
194        }
195    });
196}
197
198struct Parts {
199    protocol: String,
200    username: String,
201    password: String,
202    hostname: String,
203    port: String,
204    pathname: String,
205    search: String,
206    hash: String,
207    /// Whether the URL has an authority (`//`): an opaque-path URL such as
208    /// `mailto:a@b` has none and serializes without the slashes.
209    authority: bool,
210    /// The parser's own serialization, when the parts came from it; setters
211    /// re-serialize from the components instead.
212    href: Option<String>,
213}
214
215impl Parts {
216    fn host(&self) -> String {
217        if self.port.is_empty() {
218            self.hostname.clone()
219        } else {
220            format!("{}:{}", self.hostname, self.port)
221        }
222    }
223    fn origin(&self) -> String {
224        // A `blob:` URL's origin is that of the URL in its path, when that one
225        // is http(s) (URL Standard, "origin" for scheme `blob`).
226        if self.protocol == "blob:" {
227            return match url::Url::parse(&self.pathname) {
228                Ok(inner) if matches!(inner.scheme(), "http" | "https") => {
229                    inner.origin().ascii_serialization()
230                }
231                _ => "null".into(),
232            };
233        }
234        // Only a special scheme with a network host has a tuple origin; every
235        // other URL (`foo://h/`, `redis://h:1/`, `file:///x`) is opaque: `null`.
236        let scheme = self.protocol.strip_suffix(':').unwrap_or(&self.protocol);
237        if self.hostname.is_empty() || special_port(scheme).is_none() {
238            "null".into()
239        } else {
240            format!("{}//{}", self.protocol, self.host())
241        }
242    }
243    fn href(&self) -> String {
244        if let Some(h) = &self.href {
245            return h.clone();
246        }
247        if !self.authority && self.hostname.is_empty() {
248            // The URL Standard's serializer: no host, so no `//`; a path that
249            // would then read as one gets the `/.` prefix.
250            let dot = if self.pathname.starts_with("//") {
251                "/."
252            } else {
253                ""
254            };
255            return format!(
256                "{}{dot}{}{}{}",
257                self.protocol, self.pathname, self.search, self.hash
258            );
259        }
260        let auth = if self.username.is_empty() {
261            String::new()
262        } else if self.password.is_empty() {
263            format!("{}@", self.username)
264        } else {
265            format!("{}:{}@", self.username, self.password)
266        };
267        format!(
268            "{}//{auth}{}{}{}{}",
269            self.protocol,
270            self.host(),
271            self.pathname,
272            self.search,
273            self.hash
274        )
275    }
276}
277
278/// Whether `scheme` is one of the WHATWG "special" schemes, whose parsing
279/// normalizes backslashes and drops a default port.
280fn special_port(scheme: &str) -> Option<&'static str> {
281    match scheme {
282        "http" | "ws" => Some("80"),
283        "https" | "wss" => Some("443"),
284        "ftp" => Some("21"),
285        _ => None,
286    }
287}
288
289/// The WHATWG URL parser (`url` crate, an implementation of the URL Standard's
290/// basic URL parser) over `input`, resolved against `base` when one is given.
291///
292/// Replaces a hand-rolled split on `://` that knew nothing of opaque paths
293/// (`mailto:a@b`, `data:…`, `x:` were all `Invalid URL`), scheme-relative input
294/// (`//h/p` was appended to the base's path), a base's query surviving a
295/// fragment-only reference, or a same-scheme `http:foo` reference.
296fn parse_whatwg(input: &str, base: Option<&str>) -> Option<Parts> {
297    let base = match base {
298        Some(b) => Some(url::Url::parse(b).ok()?),
299        None => None,
300    };
301    let u = url::Url::options()
302        .base_url(base.as_ref())
303        .parse(input)
304        .ok()?;
305    Some(parts_of(&u))
306}
307
308/// `new URL(input[, base])`.
309pub fn construct(args: &[Value]) -> Result<Value, String> {
310    // Both arguments go through ToString, so an object's own `toString` is
311    // what gets parsed (`new URL('x', { toString() { return 'http://a/' } })`).
312    let to_str = |v: &Value| {
313        crate::host::to_string_value(v).map(|s| crate::host::with_host(|h| h.str_of(&s)))
314    };
315    let input = match args.first() {
316        Some(v) => to_str(v)?,
317        None => "undefined".to_string(),
318    };
319    // An explicit `undefined` base is no base at all.
320    let base = match args.get(1) {
321        Some(Value::Undef) | None => None,
322        Some(v) => Some(to_str(v)?),
323    };
324    let parts = parse_whatwg(&input, base.as_deref())
325        // Node's message is the bare `Invalid URL` and it carries
326        // `code === 'ERR_INVALID_URL'`; the input is exposed as `err.input`, not
327        // appended to the text. `url_legacy::invalid_url` was already emitting
328        // the current form — this site was the one still hardcoding an older one.
329        // node also hangs the input (and the base, when one was passed) off the
330        // error as `err.input` / `err.base`.
331        .ok_or_else(|| {
332            let mut fields = vec![("input", input.as_str())];
333            if let Some(b) = &base {
334                fields.push(("base", b.as_str()));
335            }
336            crate::host::plain_coded_error_with(
337                "TypeError",
338                "ERR_INVALID_URL",
339                "Invalid URL",
340                &fields,
341            )
342        })?;
343    Ok(build(&parts))
344}
345
346/// Percent-encode `s` for one URL component, per the WHATWG percent-encode sets.
347///
348/// None of this was happening: `new URL('https://a.b/a b?c=d e').href` came back
349/// with the spaces intact, which is not a valid URL and does not round-trip.
350///
351/// The sets below were derived by feeding every ASCII character through node
352/// v26.8.1 in each position rather than transcribed, since the spec's sets and
353/// what a parser actually emits differ around the component delimiters. Every
354/// C0 control, `%7F`, and every non-ASCII byte is encoded in all four; a byte
355/// already part of a valid `%XX` escape is left alone so re-parsing a URL does
356/// not double-encode it.
357fn percent_encode(s: &str, extra: &str) -> String {
358    let bytes = s.as_bytes();
359    let mut out = String::with_capacity(s.len());
360    let mut i = 0;
361    while i < bytes.len() {
362        let b = bytes[i];
363        // An existing escape passes through untouched.
364        if b == b'%' && i + 2 < bytes.len() + 1 {
365            let hex = bytes.get(i + 1..i + 3);
366            if hex.is_some_and(|h| h.iter().all(|c| c.is_ascii_hexdigit())) {
367                out.push('%');
368                out.push(bytes[i + 1] as char);
369                out.push(bytes[i + 2] as char);
370                i += 3;
371                continue;
372            }
373        }
374        if b < 0x20 || b == 0x7f || b >= 0x80 || extra.as_bytes().contains(&b) {
375            out.push_str(&format!("%{b:02X}"));
376        } else {
377            out.push(b as char);
378        }
379        i += 1;
380    }
381    out
382}
383
384/// The four component encode sets, as measured against node.
385const PATH_SET: &str = " \"<>^`{}";
386const QUERY_SET: &str = " \"'<>";
387const FRAGMENT_SET: &str = " \"<>`";
388const USERINFO_SET: &str = " \";<=>@[]^`{|}";
389
390fn build(p: &Parts) -> Value {
391    // Percent-encode each component once, here, so `href()` and every
392    // individual property report the same normalized text. The host arrives
393    // already canonical from the host parser in `parse_absolute`; lower-casing
394    // it again here also folded a non-special scheme's opaque host, which
395    // node keeps as written (`foo://Host/`).
396    let p = &Parts {
397        protocol: p.protocol.clone(),
398        username: percent_encode(&p.username, USERINFO_SET),
399        password: percent_encode(&p.password, USERINFO_SET),
400        hostname: p.hostname.clone(),
401        port: p.port.clone(),
402        pathname: percent_encode(&p.pathname, PATH_SET),
403        search: percent_encode(&p.search, QUERY_SET),
404        hash: percent_encode(&p.hash, FRAGMENT_SET),
405        authority: p.authority,
406        href: p.href.clone(),
407    };
408    // Build the `URLSearchParams` BEFORE the allocating `with_host` below (never
409    // nest `with_host`); it is stored as the `searchParams` data property so
410    // `url.searchParams.get(...)` reads it directly. It is LIVE, not a snapshot:
411    // it gets an `@@ownerUrl` back-reference below so that mutating it rewrites
412    // this URL's `search` and `href`.
413    let query = p.search.strip_prefix('?').unwrap_or(&p.search);
414    let search_params = make_search_params(&parse_query(query));
415    with_host(|h| {
416        let mut m = IndexMap::new();
417        m.insert("@@native".into(), h.new_str("URL"));
418        m.insert("@@href".into(), h.new_str(p.href()));
419        m.insert("@@origin".into(), h.new_str(p.origin()));
420        m.insert("@@protocol".into(), h.new_str(p.protocol.clone()));
421        m.insert("@@username".into(), h.new_str(p.username.clone()));
422        m.insert("@@password".into(), h.new_str(p.password.clone()));
423        m.insert("@@host".into(), h.new_str(p.host()));
424        m.insert("@@hostname".into(), h.new_str(p.hostname.clone()));
425        m.insert("@@port".into(), h.new_str(p.port.clone()));
426        m.insert("@@pathname".into(), h.new_str(p.pathname.clone()));
427        m.insert("@@search".into(), h.new_str(p.search.clone()));
428        m.insert("@@searchParams".into(), search_params.clone());
429        m.insert("@@hash".into(), h.new_str(p.hash.clone()));
430        m.insert(
431            "@@authority".into(),
432            h.new_str(if p.authority { "true" } else { "false" }),
433        );
434        let obj = h.new_object(m);
435        // Hidden, and set after the URL exists so the two can point at each other.
436        if let Some(JsObj::Object(sp)) = h.get_mut(&search_params) {
437            sp.insert("@@ownerUrl".into(), obj.clone());
438        }
439        obj
440    })
441}
442
443/// Statics on the `URL` CLASS — distinct from [`MODULE_METHODS`], which are the
444/// legacy `require('url')` functions.
445///
446/// `createObjectURL`/`revokeObjectURL` are absent because `Blob` is not
447/// implemented; they would have nothing to register.
448pub const STATIC_METHODS: &[&str] = &["canParse", "parse"];
449
450/// `URL.canParse(input[, base])` / `URL.parse(input[, base])`.
451///
452/// Both are the non-throwing form of the constructor: `canParse` reports
453/// whether parsing succeeds, `parse` returns the `URL` or `null`. Neither
454/// existed, so `URL.canParse` was a TypeError rather than a boolean.
455pub fn static_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
456    let parsed = construct(args);
457    Some(match method {
458        "canParse" => Ok(Value::Bool(parsed.is_ok())),
459        "parse" => Ok(parsed.unwrap_or_else(|_| with_host(|h| h.null()))),
460        _ => return None,
461    })
462}
463
464pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
465    Some(match method {
466        "parse" => legacy_parse(args).map(|u| super::url_legacy::to_js(&u)),
467        "format" => super::url_legacy::format_value(
468            &args.first().cloned().unwrap_or(Value::Undef),
469            &args.get(1).cloned().unwrap_or(Value::Undef),
470        ),
471        // `url.fileURLToPath(url)` — a `file:` URL/string → a filesystem path
472        // (percent-decoded). POSIX best-effort: any authority (host) is accepted
473        // but not re-prefixed; Windows drive/UNC rewriting is not modeled.
474        "fileURLToPath" => file_url_to_path(args).map(|s| with_host(|h| h.new_str(s))),
475        // Same, but returns the path as a `Buffer`.
476        "fileURLToPathBuffer" => {
477            file_url_to_path(args).map(|s| super::buffer::from_bytes(s.as_bytes()))
478        }
479        // `url.pathToFileURL(path)` → a `URL` instance with a `file:` href.
480        "pathToFileURL" => Ok(path_to_file_url(&arg_str(args, 0))),
481        // `url.domainToASCII` / `url.domainToUnicode` — delegate to the punycode
482        // codec; an ASCII-only domain passes through unchanged, an invalid domain
483        // yields "" (matching Node, which never throws here).
484        "domainToASCII" => Ok(punycode_domain(args, true)),
485        "domainToUnicode" => Ok(punycode_domain(args, false)),
486        // `url.urlToHttpOptions(URL)` → an options object for http/https.request.
487        "urlToHttpOptions" => Ok(url_to_http_options(
488            &args.first().cloned().unwrap_or(Value::Undef),
489        )),
490        // Legacy `url.resolve(from, to)` — `urlParse(from, false, true)
491        // .resolve(to)`: both sides parsed with `slashesDenoteHost`, resolved by
492        // the `Url.prototype.resolveObject` port, then formatted.
493        "resolve" => legacy_resolve_object(args)
494            .map(|u| with_host(|h| h.new_str(u.href.unwrap_or_default()))),
495        // Legacy `url.resolveObject(from, to)` — the same resolution, returned
496        // as the parsed object. An empty `from` hands `to` back untouched.
497        "resolveObject" => {
498            if !args.first().is_some_and(|v| with_host(|h| h.truthy(v))) {
499                return Some(Ok(args.get(1).cloned().unwrap_or(Value::Undef)));
500            }
501            legacy_resolve_object(args).map(|u| super::url_legacy::to_js(&u))
502        }
503        _ => return None,
504    })
505}
506
507/// Legacy `url.parse(urlString[, parseQueryString[, slashesDenoteHost]])`.
508/// Emits the one-shot `DEP0169` deprecation warning, exactly as Node's
509/// `urlParse` does, then delegates to the `Url.prototype.parse` port.
510fn legacy_parse(args: &[Value]) -> Result<super::url_legacy::Url, String> {
511    emit_url_parse_deprecation();
512    let input = arg_str(args, 0);
513    let truthy = |i: usize| {
514        args.get(i)
515            .map(|v| with_host(|h| h.truthy(v)))
516            .unwrap_or(false)
517    };
518    super::url_legacy::parse(&input, truthy(1), truthy(2))
519}
520
521/// `urlParse`'s one-time `DEP0169`, shared by `parse`, `resolve` and
522/// `resolveObject` — all three go through `urlParse` in node.
523fn emit_url_parse_deprecation() {
524    super::process::emit_deprecation_warning(
525        "DEP0169",
526        "`url.parse()` behavior is not standardized and prone to errors that \
527         have security implications. Use the WHATWG URL API instead. CVEs are \
528         not issued for `url.parse()` vulnerabilities.",
529    );
530}
531
532/// `urlParse(args[0], false, true).resolveObject(args[1])`, emitting the
533/// one-shot `DEP0169` that `urlParse` raises.
534fn legacy_resolve_object(args: &[Value]) -> Result<super::url_legacy::Url, String> {
535    emit_url_parse_deprecation();
536    let source = super::url_legacy::parse(&arg_str(args, 0), false, true)?;
537    let relative = super::url_legacy::parse(&arg_str(args, 1), false, true)?;
538    Ok(super::url_legacy::resolve_object(&source, relative))
539}
540
541/// `URL` instance methods (component reads are plain data properties).
542pub fn instance_call(recv: &Value, method: &str, _args: &[Value]) -> Result<Value, String> {
543    match method {
544        "toString" | "toJSON" => Ok(with_host(|h| match h.get(recv) {
545            Some(JsObj::Object(p)) => p.get("@@href").cloned().unwrap_or(Value::Undef),
546            _ => Value::Undef,
547        })),
548        _ => Err(crate::host::type_error(&format!(
549            "url.{method} is not a function"
550        ))),
551    }
552}
553
554// ── file:/legacy URL helpers ─────────────────────────────────────────────────
555
556/// The `href` string of a value: for a native `URL` its stored `href`, else the
557/// value coerced to a string (so both `URL` objects and strings are accepted).
558fn url_href(v: &Value) -> String {
559    with_host(|h| match h.get(v) {
560        Some(JsObj::Object(p)) => match p.get("@@native").map(|x| h.str_of(x)).as_deref() {
561            Some("URL") => p.get("@@href").map(|x| h.str_of(x)).unwrap_or_default(),
562            _ => h.str_of(v),
563        },
564        _ => h.str_of(v),
565    })
566}
567
568/// `fileURLToPath` core: `file://[host]/path` → decoded `/path`.
569pub(crate) fn file_url_to_path(args: &[Value]) -> Result<String, String> {
570    let v = args.first().cloned().unwrap_or(Value::Undef);
571    let href = url_href(&v);
572    let rest = href.strip_prefix("file://").ok_or_else(|| {
573        crate::host::plain_coded_error(
574            "TypeError",
575            "ERR_INVALID_URL_SCHEME",
576            "The URL must be of scheme file",
577        )
578    })?;
579    // The authority runs up to the first '/'; the remainder is the path.
580    let (host, path) = match rest.find('/') {
581        Some(i) => (&rest[..i], &rest[i..]),
582        None => (rest, "/"),
583    };
584    // `getPathFromURLPosix`: a POSIX file URL names no host (the URL parser
585    // reduces `localhost` to the empty host), and its path may not encode `/`.
586    if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") {
587        return Err(crate::host::plain_coded_error(
588            "TypeError",
589            "ERR_INVALID_FILE_URL_HOST",
590            &format!(
591                "File URL host must be \"localhost\" or empty on {}",
592                super::os::platform()
593            ),
594        ));
595    }
596    if path.to_ascii_lowercase().contains("%2f") {
597        return Err(crate::host::plain_coded_error(
598            "TypeError",
599            "ERR_INVALID_FILE_URL_PATH",
600            "File URL path must not include encoded / characters",
601        ));
602    }
603    Ok(percent_decode(path))
604}
605
606/// `pathToFileURL(path)` → a `URL` instance whose href is `file://` + the
607/// percent-encoded (path-set) path.
608fn path_to_file_url(path: &str) -> Value {
609    let enc = encode_path_component(path);
610    let pathname = if enc.starts_with('/') {
611        enc
612    } else {
613        format!("/{enc}")
614    };
615    let parts = Parts {
616        protocol: "file:".into(),
617        username: String::new(),
618        password: String::new(),
619        hostname: String::new(),
620        port: String::new(),
621        pathname,
622        search: String::new(),
623        hash: String::new(),
624        authority: true,
625        href: None,
626    };
627    build(&parts)
628}
629
630/// `domainToASCII` (`ascii = true`) / `domainToUnicode` — via the punycode codec.
631fn punycode_domain(args: &[Value], ascii: bool) -> Value {
632    let method = if ascii { "toASCII" } else { "toUnicode" };
633    match super::punycode::call(method, args) {
634        Some(Ok(v)) => v,
635        _ => with_host(|h| h.new_str("")),
636    }
637}
638
639/// `urlToHttpOptions(URL)` → `{ protocol, hostname, hash, search, pathname, path,
640/// href[, port][, auth] }`, mirroring Node's field set and IPv6 bracket-stripping.
641fn url_to_http_options(v: &Value) -> Value {
642    let get = |key: &str| -> String {
643        with_host(|h| match h.get(v) {
644            Some(JsObj::Object(p)) => p.get(key).map(|x| h.str_of(x)).unwrap_or_default(),
645            _ => String::new(),
646        })
647    };
648    let protocol = get("@@protocol");
649    let mut hostname = get("@@hostname");
650    if hostname.starts_with('[') && hostname.ends_with(']') && hostname.len() >= 2 {
651        hostname = hostname[1..hostname.len() - 1].to_string();
652    }
653    let hash = get("@@hash");
654    let search = get("@@search");
655    let pathname = get("@@pathname");
656    let href = get("@@href");
657    let port = get("@@port");
658    let username = get("@@username");
659    let password = get("@@password");
660    let path = format!("{pathname}{search}");
661    let auth = if username.is_empty() && password.is_empty() {
662        None
663    } else {
664        Some(format!(
665            "{}:{}",
666            percent_decode(&username),
667            percent_decode(&password)
668        ))
669    };
670    let port_num = if port.is_empty() {
671        None
672    } else {
673        port.parse::<f64>().ok()
674    };
675    with_host(|h| {
676        let mut m = IndexMap::new();
677        m.insert("protocol".into(), h.new_str(protocol));
678        m.insert("hostname".into(), h.new_str(hostname));
679        m.insert("hash".into(), h.new_str(hash));
680        m.insert("search".into(), h.new_str(search));
681        m.insert("pathname".into(), h.new_str(pathname));
682        m.insert("path".into(), h.new_str(path));
683        m.insert("href".into(), h.new_str(href));
684        if let Some(n) = port_num {
685            m.insert("port".into(), Value::Float(n));
686        }
687        if let Some(a) = auth {
688            m.insert("auth".into(), h.new_str(a));
689        }
690        h.new_object(m)
691    })
692}
693
694/// Percent-decode a URL component (`%XX` → byte, then UTF-8 lossy). Unlike the
695/// form decoder this leaves `+` literal (a file path may legitimately contain it).
696pub(crate) fn percent_decode(s: &str) -> String {
697    let b = s.as_bytes();
698    let mut out: Vec<u8> = Vec::with_capacity(b.len());
699    let mut i = 0;
700    while i < b.len() {
701        if b[i] == b'%' && i + 2 < b.len() {
702            if let (Some(hi), Some(lo)) = (hex_val(b[i + 1]), hex_val(b[i + 2])) {
703                out.push((hi << 4) | lo);
704                i += 3;
705                continue;
706            }
707        }
708        out.push(b[i]);
709        i += 1;
710    }
711    String::from_utf8_lossy(&out).into_owned()
712}
713
714/// Percent-encode a path for a `file:` URL: keep the unreserved + sub-delim set
715/// and `/ : @`, encode everything else (space, `# ? %` `< > "` etc.).
716fn encode_path_component(s: &str) -> String {
717    let mut out = String::with_capacity(s.len());
718    for &b in s.as_bytes() {
719        let keep = b.is_ascii_alphanumeric()
720            || matches!(
721                b,
722                b'/' | b'-'
723                    | b'.'
724                    | b'_'
725                    | b'~'
726                    | b'!'
727                    | b'$'
728                    | b'&'
729                    | b'\''
730                    | b'('
731                    | b')'
732                    | b'*'
733                    | b'+'
734                    | b','
735                    | b';'
736                    | b'='
737                    | b':'
738                    | b'@'
739            );
740        if keep {
741            out.push(b as char);
742        } else {
743            out.push('%');
744            out.push(hex_upper(b >> 4));
745            out.push(hex_upper(b & 0x0f));
746        }
747    }
748    out
749}
750
751// ── URLSearchParams ──────────────────────────────────────────────────────────
752//
753// A `URLSearchParams` is a plain object tagged `@@native = "URLSearchParams"`
754// whose ordered `[key, value]` pairs live in a hidden `@@pairs` array (each entry
755// a 2-element `[key, value]` array of strings). All string coercion happens up
756// front; methods mutate a plain `Vec<(String, String)>` and write it back.
757
758/// Method names dispatched through `search_params_call` (for `instance_has_method`
759/// wiring in `stdlib::mod`; `@@iterator` makes `[...params]` / `for..of` work).
760pub const SEARCH_PARAMS_METHODS: &[&str] = &[
761    "get",
762    "getAll",
763    "has",
764    "set",
765    "append",
766    "delete",
767    "keys",
768    "values",
769    "entries",
770    "forEach",
771    "toString",
772    "sort",
773    "@@iterator",
774];
775
776/// Build a `URLSearchParams` native object from ordered key/value pairs.
777fn make_search_params(pairs: &[(String, String)]) -> Value {
778    with_host(|h| {
779        let items: Vec<Value> = pairs
780            .iter()
781            .map(|(k, v)| {
782                let kv = vec![h.new_str(k.clone()), h.new_str(v.clone())];
783                h.new_array(kv)
784            })
785            .collect();
786        let arr = h.new_array(items);
787        let mut m = IndexMap::new();
788        m.insert("@@native".into(), h.new_str("URLSearchParams"));
789        m.insert("@@pairs".into(), arr);
790        // `size` is a prototype getter in the spec; kept in sync as a hidden own
791        // property here, so it reads back without appearing in `Object.keys` or
792        // `console.log`. `set_pairs` maintains it.
793        m.insert("size".into(), Value::Float(pairs.len() as f64));
794        let obj = h.new_object(m);
795        h.hide_prop(&obj, "size");
796        obj
797    })
798}
799
800/// Serialize ordered pairs back into an `application/x-www-form-urlencoded`
801/// query string — the inverse of [`parse_query`].
802fn encode_query(pairs: &[(String, String)]) -> String {
803    pairs
804        .iter()
805        .map(|(k, v)| format!("{}={}", form_encode(k), form_encode(v)))
806        .collect::<Vec<_>>()
807        .join("&")
808}
809
810/// Read the ordered `(key, value)` pairs out of a `URLSearchParams`.
811fn pairs_of(recv: &Value) -> Vec<(String, String)> {
812    with_host(|h| {
813        let items: Vec<Value> = match h.get(recv) {
814            Some(JsObj::Object(p)) => match p.get("@@pairs").and_then(|a| h.get(a)) {
815                Some(JsObj::Array(items)) => items.clone(),
816                _ => Vec::new(),
817            },
818            _ => Vec::new(),
819        };
820        items
821            .iter()
822            .map(|it| match h.get(it) {
823                Some(JsObj::Array(kv)) => {
824                    let kv = kv.clone();
825                    let k = kv.first().map(|x| h.str_of(x)).unwrap_or_default();
826                    let v = kv.get(1).map(|x| h.str_of(x)).unwrap_or_default();
827                    (k, v)
828                }
829                _ => (h.str_of(it), String::new()),
830            })
831            .collect()
832    })
833}
834
835/// Overwrite a `URLSearchParams`' backing `@@pairs` array, and push the new
836/// query back to the `URL` that owns it if there is one.
837///
838/// A `URLSearchParams` reached through `url.searchParams` is LIVE in both
839/// directions: `u.searchParams.set('b', '2')` has to rewrite `u.search` and
840/// `u.href`. It was previously a detached snapshot, so the edit went nowhere.
841fn set_pairs(recv: &Value, pairs: &[(String, String)]) {
842    write_pairs(recv, pairs);
843    let owner = with_host(|h| match h.get(recv) {
844        Some(JsObj::Object(p)) => p.get("@@ownerUrl").cloned(),
845        _ => None,
846    });
847    // URL Standard "update": the owner's query becomes the serialization,
848    // or null when there are no pairs.
849    if let Some(owner) = owner {
850        let query = encode_query(pairs);
851        if let Ok(mut u) = url::Url::parse(&read_slot(&owner, "@@href")) {
852            u.set_query(if query.is_empty() { None } else { Some(&query) });
853            store_parts(&owner, &parts_of(&u), false);
854        }
855    }
856}
857
858/// Write `pairs` into a `URLSearchParams` without notifying an owning `URL`.
859fn write_pairs(recv: &Value, pairs: &[(String, String)]) {
860    with_host(|h| {
861        let items: Vec<Value> = pairs
862            .iter()
863            .map(|(k, v)| {
864                let kv = vec![h.new_str(k.clone()), h.new_str(v.clone())];
865                h.new_array(kv)
866            })
867            .collect();
868        let arr = h.new_array(items);
869        let n = Value::Float(pairs.len() as f64);
870        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
871            p.insert("@@pairs".into(), arr);
872            p.insert("size".into(), n);
873        }
874        h.hide_prop(recv, "size");
875    });
876}
877
878/// `new URLSearchParams([init])` — from a query string, an object, an iterable of
879/// `[key, value]` pairs, another `URLSearchParams`, or empty.
880pub fn construct_search_params(args: &[Value]) -> Result<Value, String> {
881    let pairs = match args.first() {
882        None => Vec::new(),
883        Some(v) if matches!(v, Value::Undef) || with_host(|h| h.is_null(v)) => Vec::new(),
884        Some(v) => pairs_from_init(v),
885    };
886    Ok(make_search_params(&pairs))
887}
888
889fn pairs_from_init(v: &Value) -> Vec<(String, String)> {
890    // Copy of another URLSearchParams.
891    if super::native_tag(v).as_deref() == Some("URLSearchParams") {
892        return pairs_of(v);
893    }
894    // Query string (a leading `?` is stripped, matching the URL/WHATWG parser).
895    if let Some(s) = with_host(|h| h.as_str(v)) {
896        return parse_query(s.strip_prefix('?').unwrap_or(&s));
897    }
898    with_host(|h| match h.get(v) {
899        // Iterable of `[key, value]` pairs.
900        Some(JsObj::Array(items)) => {
901            let items = items.clone();
902            items
903                .iter()
904                .map(|it| match h.get(it) {
905                    Some(JsObj::Array(kv)) => {
906                        let kv = kv.clone();
907                        let k = kv.first().map(|x| h.str_of(x)).unwrap_or_default();
908                        let val = kv.get(1).map(|x| h.str_of(x)).unwrap_or_default();
909                        (k, val)
910                    }
911                    _ => (h.str_of(it), String::new()),
912                })
913                .collect()
914        }
915        // Plain object: own enumerable entries (hidden `@@` keys excluded).
916        Some(JsObj::Object(p)) => {
917            let entries: Vec<(String, Value)> = p
918                .iter()
919                .filter(|(k, _)| !k.starts_with("@@"))
920                .map(|(k, val)| (k.clone(), val.clone()))
921                .collect();
922            entries
923                .into_iter()
924                .map(|(k, val)| (k, h.str_of(&val)))
925                .collect()
926        }
927        _ => Vec::new(),
928    })
929}
930
931/// `URLSearchParams` instance methods.
932pub fn search_params_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
933    match method {
934        "get" => {
935            let name = arg_str(args, 0);
936            match pairs_of(recv).into_iter().find(|(k, _)| *k == name) {
937                Some((_, v)) => Ok(with_host(|h| h.new_str(v))),
938                None => Ok(with_host(|h| h.null())),
939            }
940        }
941        "getAll" => {
942            let name = arg_str(args, 0);
943            let vals: Vec<String> = pairs_of(recv)
944                .into_iter()
945                .filter(|(k, _)| *k == name)
946                .map(|(_, v)| v)
947                .collect();
948            Ok(with_host(|h| {
949                let items = vals.into_iter().map(|v| h.new_str(v)).collect();
950                h.new_array(items)
951            }))
952        }
953        "has" => {
954            let name = arg_str(args, 0);
955            let pairs = pairs_of(recv);
956            let found = if args.len() > 1 {
957                let val = arg_str(args, 1);
958                pairs.iter().any(|(k, v)| *k == name && *v == val)
959            } else {
960                pairs.iter().any(|(k, _)| *k == name)
961            };
962            Ok(Value::Bool(found))
963        }
964        "append" => {
965            let mut pairs = pairs_of(recv);
966            pairs.push((arg_str(args, 0), arg_str(args, 1)));
967            set_pairs(recv, &pairs);
968            Ok(Value::Undef)
969        }
970        "set" => {
971            let name = arg_str(args, 0);
972            let val = arg_str(args, 1);
973            let mut pairs = pairs_of(recv);
974            // Set the first pair named `name` to `val`, remove any others; append
975            // if none existed (WHATWG `set`).
976            let mut seen = false;
977            pairs.retain_mut(|(k, v)| {
978                if *k == name {
979                    if seen {
980                        false
981                    } else {
982                        *v = val.clone();
983                        seen = true;
984                        true
985                    }
986                } else {
987                    true
988                }
989            });
990            if !seen {
991                pairs.push((name, val));
992            }
993            set_pairs(recv, &pairs);
994            Ok(Value::Undef)
995        }
996        "delete" => {
997            let name = arg_str(args, 0);
998            let mut pairs = pairs_of(recv);
999            if args.len() > 1 {
1000                let val = arg_str(args, 1);
1001                pairs.retain(|(k, v)| !(*k == name && *v == val));
1002            } else {
1003                pairs.retain(|(k, _)| *k != name);
1004            }
1005            set_pairs(recv, &pairs);
1006            Ok(Value::Undef)
1007        }
1008        "sort" => {
1009            let mut pairs = pairs_of(recv);
1010            // Stable sort by key, comparing UTF-16 code units (WHATWG `sort`).
1011            pairs.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
1012            set_pairs(recv, &pairs);
1013            Ok(Value::Undef)
1014        }
1015        "toString" => {
1016            let s = encode_query(&pairs_of(recv));
1017            Ok(with_host(|h| h.new_str(s)))
1018        }
1019        "keys" => {
1020            let pairs = pairs_of(recv);
1021            Ok(with_host(|h| {
1022                let items = pairs.into_iter().map(|(k, _)| h.new_str(k)).collect();
1023                h.alloc(JsObj::Iter {
1024                    items,
1025                    idx: 0,
1026                    array: None,
1027                    brand: Some("URLSearchParams Iterator"),
1028                })
1029            }))
1030        }
1031        "values" => {
1032            let pairs = pairs_of(recv);
1033            Ok(with_host(|h| {
1034                let items = pairs.into_iter().map(|(_, v)| h.new_str(v)).collect();
1035                h.alloc(JsObj::Iter {
1036                    items,
1037                    idx: 0,
1038                    array: None,
1039                    brand: Some("URLSearchParams Iterator"),
1040                })
1041            }))
1042        }
1043        "entries" | "@@iterator" => {
1044            let pairs = pairs_of(recv);
1045            Ok(with_host(|h| {
1046                let items = pairs
1047                    .into_iter()
1048                    .map(|(k, v)| {
1049                        let kv = vec![h.new_str(k), h.new_str(v)];
1050                        h.new_array(kv)
1051                    })
1052                    .collect();
1053                h.alloc(JsObj::Iter {
1054                    items,
1055                    idx: 0,
1056                    array: None,
1057                    brand: Some("URLSearchParams Iterator"),
1058                })
1059            }))
1060        }
1061        "forEach" => {
1062            let cb = args.first().cloned().unwrap_or(Value::Undef);
1063            let this_arg = args.get(1).cloned();
1064            // Materialize pairs (releasing the host borrow) before re-entrant invoke.
1065            for (k, v) in pairs_of(recv) {
1066                let (value, name) = with_host(|h| (h.new_str(v), h.new_str(k)));
1067                crate::host::invoke(&cb, vec![value, name, recv.clone()], this_arg.clone())?;
1068            }
1069            Ok(Value::Undef)
1070        }
1071        _ => Err(crate::host::type_error(&format!(
1072            "urlSearchParams.{method} is not a function"
1073        ))),
1074    }
1075}
1076
1077/// Parse an `application/x-www-form-urlencoded` string into ordered pairs.
1078fn parse_query(q: &str) -> Vec<(String, String)> {
1079    q.split('&')
1080        .filter(|s| !s.is_empty())
1081        .map(|seg| match seg.split_once('=') {
1082            Some((k, v)) => (form_decode(k), form_decode(v)),
1083            None => (form_decode(seg), String::new()),
1084        })
1085        .collect()
1086}
1087
1088/// Decode one `application/x-www-form-urlencoded` component (`+` → space,
1089/// `%XX` → byte, then UTF-8 lossy).
1090fn form_decode(s: &str) -> String {
1091    let b = s.as_bytes();
1092    let mut out: Vec<u8> = Vec::with_capacity(b.len());
1093    let mut i = 0;
1094    while i < b.len() {
1095        match b[i] {
1096            b'+' => {
1097                out.push(b' ');
1098                i += 1;
1099            }
1100            b'%' if i + 2 < b.len() => match (hex_val(b[i + 1]), hex_val(b[i + 2])) {
1101                (Some(hi), Some(lo)) => {
1102                    out.push((hi << 4) | lo);
1103                    i += 3;
1104                }
1105                _ => {
1106                    out.push(b'%');
1107                    i += 1;
1108                }
1109            },
1110            c => {
1111                out.push(c);
1112                i += 1;
1113            }
1114        }
1115    }
1116    String::from_utf8_lossy(&out).into_owned()
1117}
1118
1119/// Encode one `application/x-www-form-urlencoded` component: space → `+`, the
1120/// unreserved set `A-Za-z0-9 * - . _` verbatim, every other byte percent-encoded.
1121fn form_encode(s: &str) -> String {
1122    let mut out = String::with_capacity(s.len());
1123    for &b in s.as_bytes() {
1124        match b {
1125            b' ' => out.push('+'),
1126            b'*' | b'-' | b'.' | b'_' => out.push(b as char),
1127            _ if b.is_ascii_alphanumeric() => out.push(b as char),
1128            _ => {
1129                out.push('%');
1130                out.push(hex_upper(b >> 4));
1131                out.push(hex_upper(b & 0x0f));
1132            }
1133        }
1134    }
1135    out
1136}
1137
1138fn hex_val(c: u8) -> Option<u8> {
1139    match c {
1140        b'0'..=b'9' => Some(c - b'0'),
1141        b'a'..=b'f' => Some(c - b'a' + 10),
1142        b'A'..=b'F' => Some(c - b'A' + 10),
1143        _ => None,
1144    }
1145}
1146
1147fn hex_upper(n: u8) -> char {
1148    char::from_digit(n as u32, 16).unwrap().to_ascii_uppercase()
1149}