Skip to main content

quickjs_jit_stdlib/llrt/llrt_url/
url_class.rs

1// Vendored from LLRT d9fd873e793c (modules/llrt_url/src/url_class.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::uninlined_format_args)]
6
7use std::{cell::RefCell, rc::Rc};
8
9use rquickjs::{
10    atom::PredefinedAtom, class::Trace, function::Opt, Class, Coerced, Ctx, Exception, FromJs,
11    IntoJs, Null, Object, Result, Value,
12};
13use url::{quirks, Url};
14
15use super::url_search_params::URLSearchParams;
16
17/// Represents a JavaScript
18/// [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) as defined
19/// by the [WHATWG URL standard](https://url.spec.whatwg.org/).
20#[derive(Clone, Trace, rquickjs::JsLifetime)]
21#[rquickjs::class]
22pub struct URL<'js> {
23    #[qjs(skip_trace)]
24    url: Rc<RefCell<Url>>,
25    search_params: Class<'js, URLSearchParams>,
26}
27
28#[rquickjs::methods(rename_all = "camelCase")]
29impl<'js> URL<'js> {
30    #[qjs(constructor)]
31    pub fn new(ctx: Ctx<'js>, input: Value<'js>, base: Opt<Value<'js>>) -> Result<Self> {
32        // USVString conversion per WHATWG URL spec: lone UTF-16 surrogates
33        // must be replaced with U+FFFD (not rejected) before the basic URL
34        // parser runs (WPT `url-origin.any.js` passes URLs containing lone
35        // surrogates and expects them to parse).
36        let input: Result<String> = if input.is_string() {
37            crate::utils::bytes::get_lossy_string(input.clone())
38        } else {
39            Coerced::<String>::from_js(&ctx, input.clone()).map(|c| c.0)
40        };
41        if let Some(base) = base.into_inner() {
42            if let Some(base) = base.as_string() {
43                if let Ok(base) = base.to_string() {
44                    let base_url: Url = base
45                        .parse()
46                        .map_err(|_| Exception::throw_type(&ctx, "Invalid base URL"))?;
47                    // Work around a url-crate normalization that loses the
48                    // host when a file:// URL's path starts with a Windows
49                    // drive letter (WPT url-constructor.any.js file-URL-
50                    // with-host base cases). Extract the host manually
51                    // from the original source string and preserve it.
52                    let base_url = super::preserve_file_url_host(&base, base_url);
53                    if let Ok(input) = input {
54                        let mut joined = base_url
55                            .join(input.as_str())
56                            .map_err(|_| Exception::throw_type(&ctx, "Invalid URL"))?;
57                        super::restore_file_url_host(&base_url, &mut joined);
58                        return Self::from_url(ctx, joined);
59                    }
60                    return Self::from_str(ctx, &base);
61                }
62            }
63        }
64        if let Ok(input) = input {
65            Self::from_str(ctx, input.as_str())
66        } else {
67            Err(Exception::throw_message(&ctx, "Invalid URL"))
68        }
69    }
70
71    #[qjs(get)]
72    pub fn hash(&self) -> String {
73        quirks::hash(&self.url.borrow()).to_string()
74    }
75
76    #[qjs(set, rename = "hash")]
77    pub fn set_hash(&mut self, hash: String) -> String {
78        self.before_mutation();
79        quirks::set_hash(&mut self.url.borrow_mut(), &hash);
80        hash
81    }
82
83    #[qjs(get)]
84    pub fn host(&self) -> String {
85        quirks::host(&self.url.borrow()).to_string()
86    }
87
88    #[qjs(set, rename = "host")]
89    pub fn set_host(&mut self, host: Coerced<String>) -> String {
90        self.before_mutation();
91        let _ = quirks::set_host(&mut self.url.borrow_mut(), &host);
92        host.0
93    }
94
95    #[qjs(get)]
96    pub fn hostname(&self) -> String {
97        quirks::hostname(&self.url.borrow()).to_string()
98    }
99
100    #[qjs(set, rename = "hostname")]
101    pub fn set_hostname(&mut self, hostname: Coerced<String>) -> String {
102        self.before_mutation();
103        let _ = quirks::set_hostname(&mut self.url.borrow_mut(), hostname.as_str());
104        super::strip_path_sentinel(&mut self.url.borrow_mut());
105        hostname.0
106    }
107
108    #[qjs(get)]
109    pub fn href(&self) -> String {
110        quirks::href(&self.url.borrow()).to_string()
111    }
112
113    #[qjs(set, rename = "href")]
114    pub fn set_href(&mut self, href: String) -> String {
115        self.before_mutation();
116        let _ = quirks::set_href(&mut self.url.borrow_mut(), &href);
117        href
118    }
119
120    #[qjs(get)]
121    pub fn origin(&self) -> String {
122        let url = self.url.borrow();
123        // Per WHATWG URL spec §6.2, origin of a blob URL is computed by parsing
124        // the path as a URL. If the result's scheme is HTTP(S), return that
125        // URL's origin; otherwise, return an opaque (null) origin. The `url`
126        // crate returns the nested URL's origin even for non-HTTP schemes,
127        // breaking WPT `url-origin.any.js` on cases like `blob:ftp://...` and
128        // `blob:blob:https://...`.
129        if url.scheme() == "blob" {
130            return match url::Url::parse(url.path()) {
131                Ok(inner) if matches!(inner.scheme(), "http" | "https") => quirks::origin(&inner),
132                _ => "null".into(),
133            };
134        }
135        quirks::origin(&url)
136    }
137
138    #[qjs(get)]
139    pub fn password(&self) -> String {
140        quirks::password(&self.url.borrow()).to_string()
141    }
142
143    #[qjs(set, rename = "password")]
144    pub fn set_password(&mut self, password: Coerced<String>) -> String {
145        self.before_mutation();
146        let _ = quirks::set_password(&mut self.url.borrow_mut(), &password);
147        password.0
148    }
149
150    #[qjs(get)]
151    pub fn pathname(&self) -> String {
152        quirks::pathname(&self.url.borrow()).to_string()
153    }
154
155    #[qjs(set, rename = "pathname")]
156    pub fn set_pathname(&mut self, pathname: Coerced<String>) -> String {
157        self.before_mutation();
158        quirks::set_pathname(&mut self.url.borrow_mut(), pathname.as_str());
159        // Per WHATWG URL spec, a non-special URL with an empty host can have
160        // its path erased (WPT `url-setters.any.js` "Non-special URLs with
161        // an empty host can have their paths erased"). The `url` crate
162        // forces a single `/` after the authority; strip it when the caller
163        // set an empty pathname on such a URL.
164        if pathname.0.is_empty() {
165            super::erase_empty_host_path(&mut self.url.borrow_mut());
166        }
167        pathname.0
168    }
169
170    #[qjs(get)]
171    pub fn port(&self) -> String {
172        quirks::port(&self.url.borrow()).to_string()
173    }
174
175    #[qjs(set, rename = "port")]
176    pub fn set_port(&mut self, ctx: Ctx<'js>, port: Value<'js>) -> Value<'js> {
177        if port.is_null()
178            || port.is_undefined()
179            || (port.is_int() && unsafe { port.as_int().unwrap_unchecked() } < 0)
180        {
181            return port;
182        }
183        if let Ok(port_string) = Coerced::<String>::from_js(&ctx, port.clone()) {
184            self.before_mutation();
185            // Per WHATWG URL spec, the port-state parser strips tab/LF/CR
186            // before reading. An empty STRIPPED value (but non-empty original)
187            // makes port parsing fail, which per spec means no-op (keep
188            // existing port). An empty ORIGINAL value, however, clears the
189            // port.
190            if port_string.is_empty() {
191                let _ = quirks::set_port(&mut self.url.borrow_mut(), "");
192            } else {
193                let stripped: String = port_string
194                    .chars()
195                    .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
196                    .collect();
197                if !stripped.is_empty() {
198                    let _ = quirks::set_port(&mut self.url.borrow_mut(), &stripped);
199                }
200                // stripped is empty → parse failure per spec → no-op
201            }
202        }
203        port
204    }
205
206    #[qjs(get)]
207    pub fn protocol(&self) -> String {
208        quirks::protocol(&self.url.borrow()).to_string()
209    }
210
211    #[qjs(set, rename = "protocol")]
212    pub fn set_protocol(&mut self, protocol: Coerced<String>) -> String {
213        self.before_mutation();
214        let _ = quirks::set_protocol(&mut self.url.borrow_mut(), &protocol);
215        protocol.0
216    }
217
218    #[qjs(get)]
219    pub fn search(&self) -> String {
220        quirks::search(&self.url.borrow()).to_string()
221    }
222
223    #[qjs(set, rename = "search")]
224    pub fn set_search(&mut self, search: Coerced<String>) -> String {
225        self.before_mutation();
226        quirks::set_search(&mut self.url.borrow_mut(), &search);
227        search.0
228    }
229
230    #[qjs(get)]
231    pub fn search_params(&self) -> &Value<'js> {
232        self.search_params.as_value()
233    }
234
235    #[qjs(prop, rename = PredefinedAtom::SymbolToStringTag, configurable)]
236    pub fn to_string_tag() -> &'static str {
237        stringify!(URL)
238    }
239
240    #[qjs(get)]
241    pub fn username(&self) -> String {
242        quirks::username(&self.url.borrow()).to_string()
243    }
244
245    #[qjs(set, rename = "username")]
246    pub fn set_username(&mut self, username: Coerced<String>) -> String {
247        self.before_mutation();
248        let _ = quirks::set_username(&mut self.url.borrow_mut(), &username);
249        username.0
250    }
251
252    #[qjs(static)]
253    pub fn can_parse(ctx: Ctx<'js>, input: Value<'js>, base: Opt<Value<'js>>) -> bool {
254        Self::new(ctx, input, base).is_ok()
255    }
256
257    #[qjs(static)]
258    pub fn parse(ctx: Ctx<'js>, input: Value<'js>, base: Opt<Value<'js>>) -> Result<Value<'js>> {
259        Self::new(ctx.clone(), input, base)
260            .map_or_else(|_| Null.into_js(&ctx), |instance| instance.into_js(&ctx))
261    }
262
263    #[qjs(rename = PredefinedAtom::ToJSON)]
264    pub fn to_json(&self) -> String {
265        self.to_string()
266    }
267
268    pub fn to_string(&self) -> String {
269        self.href()
270    }
271}
272
273impl<'js> URL<'js> {
274    pub fn from_str(ctx: Ctx<'js>, input: &str) -> Result<Self> {
275        let mut url: Url = input
276            .parse()
277            .map_err(|_| Exception::throw_type(&ctx, "Invalid URL"))?;
278        super::normalize_windows_drive_letter(&mut url);
279        super::convert_trailing_space(&mut url);
280        Self::build(ctx, url)
281    }
282
283    pub fn from_url(ctx: Ctx<'js>, mut url: Url) -> Result<Self> {
284        super::normalize_windows_drive_letter(&mut url);
285        super::convert_trailing_space(&mut url);
286        Self::build(ctx, url)
287    }
288
289    /// Validate that a string parses as a URL without constructing a JS
290    /// instance. Used by callers (e.g. `llrt_fetch`) that just need to know
291    /// whether a user-supplied string is a valid URL.
292    pub fn is_valid(input: &str) -> bool {
293        input.parse::<Url>().is_ok()
294    }
295
296    fn build(ctx: Ctx<'js>, url: Url) -> Result<Self> {
297        let shared = Rc::new(RefCell::new(url));
298        let search_params = Class::instance(ctx, URLSearchParams::from_url(&shared))?;
299        Ok(Self {
300            url: shared,
301            search_params,
302        })
303    }
304
305    fn before_mutation(&mut self) {
306        super::convert_trailing_space(&mut self.url.borrow_mut());
307    }
308
309    pub(crate) fn inner_url(&self) -> std::cell::Ref<'_, Url> {
310        self.url.borrow()
311    }
312}
313
314pub fn url_to_http_options<'js>(ctx: Ctx<'js>, url: Class<'js, URL<'js>>) -> Result<Object<'js>> {
315    let obj = Object::new(ctx)?;
316    let url = url.borrow();
317
318    let port = url.port();
319    let username = url.username();
320    let search = url.search();
321    let hash = url.inner_url().fragment().unwrap_or("").to_string();
322
323    obj.set("protocol", url.protocol())?;
324    obj.set("hostname", url.hostname())?;
325
326    if !hash.is_empty() {
327        obj.set("hash", hash)?;
328    }
329
330    let pathname = url.pathname();
331    let path = [pathname.as_str(), search.as_str()].concat();
332    if !search.is_empty() {
333        obj.set("search", search)?;
334    }
335    obj.set("pathname", pathname)?;
336    obj.set("path", path)?;
337    obj.set("href", url.href())?;
338
339    if !username.is_empty() {
340        obj.set("auth", [username, url.password()].join(":"))?;
341    }
342
343    if !port.is_empty() {
344        obj.set("port", port)?;
345    }
346
347    Ok(obj)
348}