1use 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
28pub const COMPONENTS: &[&str] = &[
41 "protocol", "username", "password", "host", "hostname", "port", "pathname", "search", "hash",
42 "href",
43];
44
45fn special_to_file(u: &url::Url, value: &str) -> Option<url::Url> {
54 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
71pub fn is_component(name: &str) -> bool {
74 COMPONENTS.contains(&name)
75}
76
77fn 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
97pub 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
158fn 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(¶ms, &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 authority: bool,
210 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 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 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 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
278fn 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
289fn 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
308pub fn construct(args: &[Value]) -> Result<Value, String> {
310 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 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 .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
346fn 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 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
384const PATH_SET: &str = " \"<>^`{}";
386const QUERY_SET: &str = " \"'<>";
387const FRAGMENT_SET: &str = " \"<>`";
388const USERINFO_SET: &str = " \";<=>@[]^`{|}";
389
390fn build(p: &Parts) -> Value {
391 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 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 if let Some(JsObj::Object(sp)) = h.get_mut(&search_params) {
437 sp.insert("@@ownerUrl".into(), obj.clone());
438 }
439 obj
440 })
441}
442
443pub const STATIC_METHODS: &[&str] = &["canParse", "parse"];
449
450pub 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 "fileURLToPath" => file_url_to_path(args).map(|s| with_host(|h| h.new_str(s))),
475 "fileURLToPathBuffer" => {
477 file_url_to_path(args).map(|s| super::buffer::from_bytes(s.as_bytes()))
478 }
479 "pathToFileURL" => Ok(path_to_file_url(&arg_str(args, 0))),
481 "domainToASCII" => Ok(punycode_domain(args, true)),
485 "domainToUnicode" => Ok(punycode_domain(args, false)),
486 "urlToHttpOptions" => Ok(url_to_http_options(
488 &args.first().cloned().unwrap_or(Value::Undef),
489 )),
490 "resolve" => legacy_resolve_object(args)
494 .map(|u| with_host(|h| h.new_str(u.href.unwrap_or_default()))),
495 "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
507fn 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
521fn 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
532fn 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
541pub 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
554fn 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
568pub(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 let (host, path) = match rest.find('/') {
581 Some(i) => (&rest[..i], &rest[i..]),
582 None => (rest, "/"),
583 };
584 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
606fn 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
630fn 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
639fn 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
694pub(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
714fn 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
751pub 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
776fn 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 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
800fn 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
810fn 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
835fn 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 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
858fn 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
878pub 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 if super::native_tag(v).as_deref() == Some("URLSearchParams") {
892 return pairs_of(v);
893 }
894 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 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 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
931pub 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 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 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 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
1077fn 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
1088fn 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
1119fn 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}