Skip to main content

quickjs_jit_stdlib/llrt/llrt_url/
lib.rs

1// Vendored from LLRT d9fd873e793c (modules/llrt_url/src/lib.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5#![allow(clippy::inherent_to_string)]
6pub mod url_class;
7pub mod url_search_params;
8
9use std::{path::PathBuf, str::FromStr};
10
11use crate::utils::{
12    module::{export_default, ModuleInfo},
13    primordials::{BasePrimordials, Primordial},
14    result::ResultExt,
15};
16use rquickjs::{
17    function::{Constructor, Func},
18    module::{Declarations, Exports, ModuleDef},
19    prelude::Opt,
20    Class, Coerced, Ctx, Exception, Result, Value,
21};
22use url::{quirks, Url};
23
24use self::url_class::{url_to_http_options, URL};
25use self::url_search_params::URLSearchParams;
26
27/// Returns whether the given scheme is a [special scheme](https://url.spec.whatwg.org/#special-scheme).
28pub fn is_special_scheme(scheme: &str) -> bool {
29    matches!(scheme, "http" | "https" | "ftp" | "ws" | "wss" | "file")
30}
31
32pub fn domain_to_unicode(domain: &str) -> String {
33    quirks::domain_to_unicode(domain)
34}
35
36pub fn domain_to_ascii(domain: &str) -> String {
37    quirks::domain_to_ascii(domain)
38}
39
40//options are ignored, no windows support yet
41pub fn path_to_file_url<'js>(ctx: Ctx<'js>, path: String, _: Opt<Value>) -> Result<URL<'js>> {
42    let url = Url::from_file_path(&path)
43        .map_err(|_| Exception::throw_type(&ctx, &["Path is not absolute: ", &path].concat()))?;
44
45    URL::from_url(ctx, url)
46}
47
48//options are ignored, no windows support yet
49pub fn file_url_to_path<'js>(ctx: Ctx<'js>, url: Value<'js>) -> Result<String> {
50    let url_string = if let Ok(url) = Class::<URL>::from_value(&url) {
51        url.borrow().to_string()
52    } else {
53        url.get::<Coerced<String>>()?.to_string()
54    };
55
56    let path = url_string.trim_start_matches("file://");
57
58    Ok(PathBuf::from_str(path)
59        .or_throw(&ctx)?
60        .to_string_lossy()
61        .to_string())
62}
63
64pub fn url_format<'js>(url: Class<'js, URL<'js>>, options: Opt<Value<'js>>) -> Result<String> {
65    let url = url.borrow();
66    let mut string = url.protocol();
67    string.push_str("//");
68
69    let mut include_fragment = true;
70    let mut unicode_encode = false;
71    let mut include_auth = true;
72    let mut include_search = true;
73
74    // Parse options if provided
75    if let Some(options) = options.into_inner() {
76        if let Some(options) = options.as_object() {
77            if let Ok(value) = options.get("unicode") {
78                unicode_encode = value;
79            }
80            if let Ok(value) = options.get("auth") {
81                include_auth = value;
82            }
83            if let Ok(value) = options.get("fragment") {
84                include_fragment = value;
85            }
86            if let Ok(value) = options.get("search") {
87                include_search = value
88            }
89        }
90    }
91
92    if include_auth {
93        let username = url.username();
94        let password = url.password();
95        if !username.is_empty() {
96            string.push_str(&username);
97            if !password.is_empty() {
98                string.push(':');
99                string.push_str(&password);
100            }
101            string.push('@');
102        }
103    }
104
105    if unicode_encode {
106        string.push_str(&domain_to_unicode(&url.host()));
107    } else {
108        string.push_str(&url.host());
109    }
110
111    string.push_str(&url.pathname());
112
113    if include_search {
114        string.push_str(&url.search());
115    }
116
117    if include_fragment {
118        string.push_str(&url.hash());
119    }
120
121    Ok(string)
122}
123
124/// Encode trailing space as `%20` in opaque paths before a setter runs.
125///
126/// Used by [`URLSearchParams`] which mutates the shared [`Url`] directly.
127pub fn convert_trailing_space(url: &mut Url) {
128    if is_special_scheme(url.scheme()) {
129        return;
130    }
131
132    let path = url.path();
133    let has_remaining = url.fragment().is_some() || url.query().is_some();
134
135    #[allow(clippy::manual_strip)]
136    if path.ends_with(' ') && has_remaining {
137        let new_path = [&path[..path.len() - 1], "%20"].concat();
138        url.set_path(&new_path);
139    }
140}
141
142/// Per WHATWG URL spec §4.5.3 ("URL serializer"), the `/.` path sentinel is
143/// only inserted when a URL has no host AND its path starts with `//`. The
144/// `url` crate inserts the sentinel during parsing and can leave it in the
145/// serialization even after a host is set, breaking WPT `url-setters`
146/// subtests like `<non-spec:/.//p>.hostname = 'h'`.
147///
148/// This strips the sentinel whenever the URL has a non-empty host and the
149/// path begins with `/./`.
150/// Per WHATWG URL spec §4.2, a file URL path segment matching `[A-Za-z]|`
151/// followed by `/`, `\`, `?`, `#`, or end-of-path is a Windows drive letter.
152/// Parsers normalize the `|` to `:`. The `url` crate doesn't perform this
153/// rewrite itself, so we do it after parsing (WPT `url-constructor.any.js`
154/// "Parsing: <file:///w|/m>").
155/// When a `file://HOST/C:/...` string is parsed, the `url` crate drops
156/// HOST (normalizing to `file:///C:/...`). Per WHATWG URL spec the host
157/// must be preserved when non-empty (drive-letter state only applies when
158/// host is null). Extract the host from the original source string and
159/// re-set it on the parsed URL so downstream `join()` sees the host.
160pub fn preserve_file_url_host(source: &str, mut url: Url) -> Url {
161    if url.scheme() != "file" {
162        return url;
163    }
164    if url.host_str().is_some_and(|h| !h.is_empty()) {
165        return url;
166    }
167    // Look for `file://HOST/...` in the original string.
168    let Some(rest) = source.strip_prefix("file://") else {
169        return url;
170    };
171    let Some((host, _)) = rest.split_once('/') else {
172        return url;
173    };
174    if host.is_empty() {
175        return url;
176    }
177    let _ = url.set_host(Some(host));
178    url
179}
180
181/// When resolving a relative URL against a file:// base whose first path
182/// segment is a Windows drive letter (e.g. `file://h/C:/a/b`), the url crate
183/// loses the host during `join`. Per WHATWG URL spec the host must be
184/// preserved (WPT `url-constructor.any.js` "<file://h/C:/a/b>" base).
185/// Patch the joined URL by restoring the base's host.
186pub fn restore_file_url_host(base: &Url, joined: &mut Url) {
187    if base.scheme() != "file" || joined.scheme() != "file" {
188        return;
189    }
190    // Only when base had a host and joined has none / empty.
191    let Some(base_host) = base.host_str() else {
192        return;
193    };
194    if base_host.is_empty() {
195        return;
196    }
197    if joined.host_str().is_some_and(|h| !h.is_empty()) {
198        return;
199    }
200    // Only when base's first path segment is a Windows drive letter — that's
201    // the code path that the url crate mishandles.
202    let base_path = base.path();
203    let is_drive_letter_first_seg = base_path
204        .as_bytes()
205        .get(1)
206        .is_some_and(|b| b.is_ascii_alphabetic())
207        && base_path.as_bytes().get(2) == Some(&b':')
208        && matches!(base_path.as_bytes().get(3), Some(&b'/') | None);
209    if !is_drive_letter_first_seg {
210        return;
211    }
212    let _ = joined.set_host(Some(base_host));
213}
214
215pub fn normalize_windows_drive_letter(url: &mut Url) {
216    if url.scheme() != "file" {
217        return;
218    }
219    let path = url.path();
220    let bytes = path.as_bytes();
221    // Expect path like "/<letter>|/..." — 4+ bytes, leading slash, letter,
222    // pipe, trailing slash.
223    if bytes.len() < 4
224        || bytes[0] != b'/'
225        || !bytes[1].is_ascii_alphabetic()
226        || bytes[2] != b'|'
227        || bytes[3] != b'/'
228    {
229        return;
230    }
231    let new_path = ["/", &path[1..2], ":", &path[3..]].concat();
232    url.set_path(&new_path);
233}
234
235/// Per WHATWG URL spec, a non-special URL with an empty host can have its
236/// path erased (WPT `url-setters.any.js`). The `url` crate keeps a trailing
237/// `/` after the authority; reparse the serialization with it stripped when
238/// the caller has explicitly set an empty pathname on such a URL.
239pub fn erase_empty_host_path(url: &mut Url) {
240    if is_special_scheme(url.scheme()) {
241        return;
242    }
243    if url.path() != "/" {
244        return;
245    }
246    let serialized = url.as_str();
247    // Serialized form must be `<scheme>://` + `/` to qualify. (`scheme:/`,
248    // without authority, isn't eligible — the extra `/` is not a sentinel
249    // but a real path character.)
250    let Some(scheme_end) = serialized.find("://") else {
251        return;
252    };
253    let authority_and_path = &serialized[scheme_end + 3..];
254    // After "://": optional userinfo + host + port, then the path. If the
255    // path is just "/" and everything before is empty, the full
256    // authority_and_path is "/".
257    if authority_and_path != "/" {
258        return;
259    }
260    // Strip the trailing `/`.
261    let stripped = &serialized[..serialized.len() - 1];
262    if let Ok(reparsed) = Url::parse(stripped) {
263        *url = reparsed;
264    }
265}
266
267pub fn strip_path_sentinel(url: &mut Url) {
268    if is_special_scheme(url.scheme()) {
269        return;
270    }
271    // Path starting with `//` is what triggers the `/.` sentinel in the url
272    // crate's serialization — but the sentinel is only spec-correct when
273    // there's no authority. If the URL has `://` and its serialization still
274    // contains `/./` at the path boundary, reparse with it stripped.
275    if !url.path().starts_with("//") {
276        return;
277    }
278    let serialized = url.as_str();
279    // Authority is present iff serialization contains "://".
280    let Some(auth_start) = serialized.find("://") else {
281        return;
282    };
283    let after_auth = auth_start + 3;
284    // Look for next `/` that starts the path region.
285    let Some(path_start_rel) = serialized[after_auth..].find('/') else {
286        return;
287    };
288    let path_idx = after_auth + path_start_rel;
289    if serialized[path_idx..].starts_with("/./") {
290        let stripped = [&serialized[..path_idx], &serialized[path_idx + 2..]].concat();
291        if let Ok(reparsed) = Url::parse(&stripped) {
292            *url = reparsed;
293        }
294    }
295}
296
297pub fn init(ctx: &Ctx<'_>) -> Result<()> {
298    let globals = ctx.globals();
299
300    Class::<URLSearchParams>::define(&globals)?;
301    Class::<URL>::define(&globals)?;
302
303    Ok(())
304}
305
306pub struct UrlModule;
307
308impl ModuleDef for UrlModule {
309    fn declare(declare: &Declarations) -> Result<()> {
310        declare.declare(stringify!(URL))?;
311        declare.declare(stringify!(URLSearchParams))?;
312        declare.declare("urlToHttpOptions")?;
313        declare.declare("domainToUnicode")?;
314        declare.declare("domainToASCII")?;
315        declare.declare("fileURLToPath")?;
316        declare.declare("pathToFileURL")?;
317        declare.declare("format")?;
318        declare.declare("default")?;
319        Ok(())
320    }
321
322    fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
323        let globals = ctx.globals();
324        BasePrimordials::init(ctx)?;
325        let url: Constructor = globals.get(stringify!(URL))?;
326        let url_search_params: Constructor = globals.get(stringify!(URLSearchParams))?;
327
328        export_default(ctx, exports, |default| {
329            default.set(stringify!(URL), url)?;
330            default.set(stringify!(URLSearchParams), url_search_params)?;
331            default.set("urlToHttpOptions", Func::from(url_to_http_options))?;
332            default.set(
333                "domainToUnicode",
334                Func::from(|domain: String| domain_to_unicode(&domain)),
335            )?;
336            default.set(
337                "domainToASCII",
338                Func::from(|domain: String| domain_to_ascii(&domain)),
339            )?;
340            default.set("fileURLToPath", Func::from(file_url_to_path))?;
341            default.set("pathToFileURL", Func::from(path_to_file_url))?;
342            default.set("format", Func::from(url_format))?;
343            Ok(())
344        })?;
345
346        Ok(())
347    }
348}
349
350impl From<UrlModule> for ModuleInfo<UrlModule> {
351    fn from(val: UrlModule) -> Self {
352        ModuleInfo {
353            name: "url",
354            module: val,
355        }
356    }
357}