1use super::*;
4
5pub(crate) static LOCAL_STORAGE: spin::Mutex<alloc::collections::BTreeMap<String, String>> =
8 spin::Mutex::new(alloc::collections::BTreeMap::new());
9pub(crate) static SESSION_STORAGE: spin::Mutex<alloc::collections::BTreeMap<String, String>> =
10 spin::Mutex::new(alloc::collections::BTreeMap::new());
11pub(crate) static LS_LOADED: core::sync::atomic::AtomicBool =
12 core::sync::atomic::AtomicBool::new(false);
13pub(crate) static COOKIES: spin::Mutex<crate::os_lib::cookie::CookieJar> =
18 spin::Mutex::new(crate::os_lib::cookie::CookieJar::new());
19
20pub(crate) const LS_FILENAME: &str = "__localStorage__";
21
22pub(crate) use crate::os_lib::web_storage::{ls_deserialize, ls_serialize};
23
24pub(crate) fn ls_ensure_loaded() {
26 if LS_LOADED.load(core::sync::atomic::Ordering::Relaxed) {
27 return;
28 }
29 LS_LOADED.store(true, core::sync::atomic::Ordering::Relaxed);
30 if !crate::os_lib::platform::fs_is_mounted() {
31 return;
32 }
33 match crate::os_lib::platform::fs_read_file_checked(LS_FILENAME) {
34 Ok(Some(data)) => {
35 *LOCAL_STORAGE.lock() = ls_deserialize(&data);
36 }
37 Ok(None) => {}
38 Err(e) => {
39 crate::warn!("[SYS] localStorage read_file failed: {}", e);
40 }
41 }
42}
43
44pub(crate) fn ls_flush() {
46 if !crate::os_lib::platform::fs_is_mounted() {
47 return;
48 }
49 let data = ls_serialize(&LOCAL_STORAGE.lock());
50 let _fs_guard = crate::os_lib::platform::fs_lock();
60 let fs = crate::os_lib::platform::fs_get();
61 if data.is_empty() {
68 if let Err(e) = fs.delete_file(LS_FILENAME) {
69 if !e.contains("not found") {
71 crate::warn!("[JS] localStorage: failed to remove empty store: {}", e);
72 }
73 }
74 } else if let Err(e) = fs.save_file(LS_FILENAME, &data, "system") {
75 crate::error!("[JS] localStorage: failed to persist ({} bytes): {}", data.len(), e);
76 }
77}
78
79pub fn cookie_string() -> String {
81 COOKIES.lock().cookie_string()
82}
83
84pub fn cookie_set(s: &str) {
86 COOKIES.lock().apply_cookie(s);
87}
88
89pub(crate) fn cookie_store_get(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
93 let name = arg(a, 0).to_js_string();
94 let value = COOKIES.lock().get(&name).map(|c| c.value.clone());
95 let result = match value {
96 Some(v) => {
97 let o = Obj::plain();
98 o.borrow_mut().props.insert("name".into(), Value::str(&name));
99 o.borrow_mut().props.insert("value".into(), Value::str(v));
100 Value::Object(o)
101 }
102 None => Value::Null,
103 };
104 Ok(resolved_promise(it, result))
105}
106pub(crate) fn cookie_store_get_all(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
108 let filter = if a.is_empty() { None } else { Some(arg(a, 0).to_js_string()) };
109 let items: Vec<Value> = COOKIES
110 .lock()
111 .all()
112 .filter(|c| filter.as_ref().is_none_or(|f| *f == c.name))
113 .map(|c| {
114 let o = Obj::plain();
115 o.borrow_mut().props.insert("name".into(), Value::str(&c.name));
116 o.borrow_mut().props.insert("value".into(), Value::str(&c.value));
117 Value::Object(o)
118 })
119 .collect();
120 Ok(resolved_promise(it, Value::Object(Obj::array(items))))
121}
122pub(crate) fn cookie_store_set(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
125 let first = arg(a, 0);
126 let (name, value) = if let Value::Object(_) = &first {
127 (
128 obj_prop(&first, "name").map(|v| v.to_js_string()).unwrap_or_default(),
129 obj_prop(&first, "value").map(|v| v.to_js_string()).unwrap_or_default(),
130 )
131 } else {
132 (first.to_js_string(), arg(a, 1).to_js_string())
133 };
134 if !name.is_empty() {
135 COOKIES.lock().insert(&name, &value);
136 }
137 Ok(resolved_promise(it, Value::Undefined))
138}
139pub(crate) fn cookie_store_delete(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
141 let name = arg(a, 0).to_js_string();
142 COOKIES.lock().delete(&name);
143 Ok(resolved_promise(it, Value::Undefined))
144}
145
146pub(crate) fn storage_map(tag: &str) -> &'static spin::Mutex<alloc::collections::BTreeMap<String, String>> {
147 if tag == "storage:session" {
148 &SESSION_STORAGE
149 } else {
150 &LOCAL_STORAGE
151 }
152}
153pub(crate) fn storage_tag_for(id: usize) -> &'static str {
155 if id == STORAGE_SESSION {
156 "storage:session"
157 } else {
158 "storage:local"
159 }
160}
161pub(crate) fn storage_entries(tag: &str) -> Vec<(String, String)> {
164 if tag != "storage:session" {
165 ls_ensure_loaded();
166 }
167 storage_map(tag).lock().iter().map(|(k, v)| (k.clone(), v.clone())).collect()
168}
169pub(crate) fn dataset_entries(dom: &super::super::dom_bridge::DomBridge, idx: usize) -> Vec<(String, String)> {
174 dom.attr_names(idx)
175 .into_iter()
176 .filter_map(|n| {
177 crate::os_lib::dom_dataset::data_attr_to_camel(&n).map(|camel| {
178 let val = dom.get_attr(idx, &n).unwrap_or_default();
179 (camel, val)
180 })
181 })
182 .collect()
183}
184pub(crate) fn data_attr_to_camel(name: &str) -> String {
186 let full = if name.starts_with("data-") {
187 name.to_string()
188 } else {
189 alloc::format!("data-{}", name)
190 };
191 crate::os_lib::dom_dataset::data_attr_to_camel(&full).unwrap_or_else(|| name.to_string())
192}
193pub(crate) fn this_storage_tag(this: &Value) -> Option<&'static str> {
194 if let Value::Object(o) = this {
195 if let ObjKind::HostRef(h) = &o.borrow().kind {
196 if h.class == HOST_STORAGE {
197 return Some(storage_tag_for(h.id));
198 }
199 }
200 }
201 None
202}
203pub(crate) fn storage_get_item(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
204 if let Some(tag) = this_storage_tag(&this) {
205 if tag != "storage:session" {
206 ls_ensure_loaded();
207 }
208 let k = arg(a, 0).to_js_string();
209 return Ok(match storage_map(tag).lock().get(&k) {
210 Some(v) => Value::str(v.clone()),
211 None => Value::Null,
212 });
213 }
214 Ok(Value::Null)
215}
216pub(crate) fn storage_set_item(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
217 if let Some(tag) = this_storage_tag(&this) {
218 if tag != "storage:session" {
219 ls_ensure_loaded();
220 }
221 storage_map(tag)
222 .lock()
223 .insert(arg(a, 0).to_js_string(), arg(a, 1).to_js_string());
224 if tag != "storage:session" {
225 ls_flush();
226 }
227 }
228 Ok(Value::Undefined)
229}
230pub(crate) fn storage_remove_item(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
231 if let Some(tag) = this_storage_tag(&this) {
232 if tag != "storage:session" {
233 ls_ensure_loaded();
234 }
235 storage_map(tag).lock().remove(&arg(a, 0).to_js_string());
236 if tag != "storage:session" {
237 ls_flush();
238 }
239 }
240 Ok(Value::Undefined)
241}
242pub(crate) fn storage_clear(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
243 if let Some(tag) = this_storage_tag(&this) {
244 storage_map(tag).lock().clear();
245 if tag != "storage:session" {
246 ls_flush();
247 }
248 }
249 Ok(Value::Undefined)
250}
251pub(crate) fn storage_key(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
252 if let Some(tag) = this_storage_tag(&this) {
253 if tag != "storage:session" {
254 ls_ensure_loaded();
255 }
256 let i = arg(a, 0).to_number() as usize;
257 return Ok(match storage_map(tag).lock().keys().nth(i) {
258 Some(k) => Value::str(k.clone()),
259 None => Value::Null,
260 });
261 }
262 Ok(Value::Null)
263}
264
265pub fn storage_method_fn(key: &str) -> Option<(&'static str, NativeFn)> {
266 match key {
267 "getItem" => Some(("getItem", storage_get_item)),
268 "setItem" => Some(("setItem", storage_set_item)),
269 "removeItem" => Some(("removeItem", storage_remove_item)),
270 "clear" => Some(("clear", storage_clear)),
271 "key" => Some(("key", storage_key)),
272 _ => None,
273 }
274}
275
276pub fn storage_get_prop(tag: &str, key: &str) -> Value {
278 if tag != "storage:session" {
279 ls_ensure_loaded();
280 }
281 if let Some((n, f)) = storage_method_fn(key) {
282 return nv(n, f);
283 }
284 match key {
285 "length" => Value::Number(storage_map(tag).lock().len() as f64),
286 _ => match storage_map(tag).lock().get(key) {
287 Some(v) => Value::str(v.clone()),
288 None => Value::Undefined,
289 },
290 }
291}
292pub fn storage_remove_prop(tag: &str, key: &str) {
297 if tag != "storage:session" {
298 ls_ensure_loaded();
299 }
300 storage_map(tag).lock().remove(key);
301 if tag != "storage:session" {
302 ls_flush();
303 }
304}
305pub fn storage_set_prop(tag: &str, key: &str, val: &Value) {
306 if key != "length" {
307 if tag != "storage:session" {
308 ls_ensure_loaded();
309 }
310 storage_map(tag)
311 .lock()
312 .insert(String::from(key), val.to_js_string());
313 if tag != "storage:session" {
314 ls_flush();
315 }
316 }
317}
318
319pub(crate) fn parse_query(q: &str) -> Vec<(String, String)> {
323 let q = q.strip_prefix('?').unwrap_or(q);
324 q.split('&')
325 .filter(|s| !s.is_empty())
326 .map(|pair| match pair.split_once('=') {
327 Some((k, v)) => (percent_decode(k, true), percent_decode(v, true)),
328 None => (percent_decode(pair, true), String::new()),
329 })
330 .collect()
331}
332pub(crate) fn form_url_encode(s: &str) -> String {
334 let mut out = String::new();
335 for b in s.as_bytes() {
336 match *b {
337 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
338 out.push(*b as char);
339 }
340 b' ' => out.push('+'),
341 _ => out.push_str(&alloc::format!("%{:02X}", b)),
342 }
343 }
344 out
345}
346pub(crate) fn build_query(pairs: &[(String, String)]) -> String {
347 let parts: Vec<String> = pairs
348 .iter()
349 .map(|(k, v)| format!("{}={}", form_url_encode(k), form_url_encode(v)))
350 .collect();
351 parts.join("&")
352}
353pub fn usp_entry_count(this: &Value) -> usize {
358 parse_query(&usp_query(this)).len()
359}
360pub(crate) fn usp_size_getter(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
361 Ok(Value::Number(usp_entry_count(&this) as f64))
362}
363pub(crate) fn usp_query(this: &Value) -> String {
364 if let Value::Object(o) = this {
365 return o
366 .borrow()
367 .props
368 .get("_query")
369 .map(|v| v.to_js_string())
370 .unwrap_or_default();
371 }
372 String::new()
373}
374pub(crate) fn usp_set_query(this: &Value, q: &str) {
375 if let Value::Object(o) = this {
376 let parent = {
377 let mut b = o.borrow_mut();
378 b.props.insert(String::from("_query").into(), Value::str(q));
379 b.props.get("_parent_url").cloned()
380 };
381 if let Some(Value::Object(po)) = parent {
382 let search_val = if q.is_empty() {
383 String::new()
384 } else {
385 alloc::format!("?{}", q)
386 };
387 let href = po.borrow().props.get("_href").map(|v| v.to_js_string());
388 let mut b = po.borrow_mut();
389 if let Some(mut u) = href.and_then(|h| super::url_parser::parse(&h, None)) {
391 u.query = if q.is_empty() { None } else { Some(String::from(q)) };
392 b.props.insert(String::from("_href").into(), Value::str(super::url_parser::serialize(&u, false)));
393 }
394 b.props.insert(String::from("search").into(), Value::str(search_val));
395 }
396 }
397}
398pub(crate) fn usp_get(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
399 let k = arg(a, 0).to_js_string();
400 let pairs = parse_query(&usp_query(&this));
401 Ok(pairs
402 .iter()
403 .find(|(pk, _)| *pk == k)
404 .map(|(_, v)| Value::str(v.clone()))
405 .unwrap_or(Value::Null))
406}
407pub(crate) fn usp_get_all(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
408 let k = arg(a, 0).to_js_string();
409 let items: Vec<Value> = parse_query(&usp_query(&this))
410 .into_iter()
411 .filter(|(pk, _)| *pk == k)
412 .map(|(_, v)| Value::str(v))
413 .collect();
414 Ok(Value::Object(Obj::array(items)))
415}
416pub(crate) fn usp_has(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
421 let k = arg(a, 0).to_js_string();
422 let entries = parse_query(&usp_query(&this));
423 let found = if matches!(arg(a, 1), Value::Undefined) {
424 entries.iter().any(|(pk, _)| *pk == k)
425 } else {
426 let v = arg(a, 1).to_js_string();
427 entries.iter().any(|(pk, pv)| *pk == k && *pv == v)
428 };
429 Ok(Value::Bool(found))
430}
431pub(crate) fn usp_append(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
432 let mut pairs = parse_query(&usp_query(&this));
433 pairs.push((arg(a, 0).to_js_string(), arg(a, 1).to_js_string()));
434 usp_set_query(&this, &build_query(&pairs));
435 Ok(Value::Undefined)
436}
437pub(crate) fn usp_set(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
438 let k = arg(a, 0).to_js_string();
439 let mut pairs: Vec<(String, String)> = parse_query(&usp_query(&this))
440 .into_iter()
441 .filter(|(pk, _)| *pk != k)
442 .collect();
443 pairs.push((k, arg(a, 1).to_js_string()));
444 usp_set_query(&this, &build_query(&pairs));
445 Ok(Value::Undefined)
446}
447pub(crate) fn usp_delete(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
451 let k = arg(a, 0).to_js_string();
452 let value_filter = if matches!(arg(a, 1), Value::Undefined) {
453 None
454 } else {
455 Some(arg(a, 1).to_js_string())
456 };
457 let pairs: Vec<(String, String)> = parse_query(&usp_query(&this))
458 .into_iter()
459 .filter(|(pk, pv)| match &value_filter {
460 Some(v) => !(*pk == k && pv == v),
461 None => *pk != k,
462 })
463 .collect();
464 usp_set_query(&this, &build_query(&pairs));
465 Ok(Value::Undefined)
466}
467pub(crate) fn usp_to_string(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
468 Ok(Value::str(usp_query(&this)))
469}
470pub(crate) fn usp_sort(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
473 let mut pairs = parse_query(&usp_query(&this));
474 pairs.sort_by(|a, b| a.0.cmp(&b.0));
475 usp_set_query(&this, &build_query(&pairs));
476 Ok(Value::Undefined)
477}
478pub(crate) fn usp_iterator(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
481 let items: Vec<Value> = parse_query(&usp_query(&this))
482 .into_iter()
483 .map(|(k, v)| Value::Object(Obj::array(alloc::vec![Value::str(k), Value::str(v)])))
484 .collect();
485 Ok(Value::Object(make_iterator(items)))
486}
487pub(crate) fn url_search_params_ctor(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
497 let init = arg(a, 0);
498 let q = match &init {
499 Value::Undefined | Value::Null => String::new(),
500 Value::Object(o) => {
501 let is_array = matches!(&o.borrow().kind, ObjKind::Array(_));
502 if is_array {
503 let pairs: alloc::vec::Vec<(String, String)> = this_items(&init)
504 .iter()
505 .filter_map(|item| {
506 let inner = this_items(item);
507 if inner.len() >= 2 {
508 Some((inner[0].to_js_string(), inner[1].to_js_string()))
509 } else {
510 None
511 }
512 })
513 .collect();
514 build_query(&pairs)
515 } else if let Some(existing) = o.borrow().props.get("_query") {
516 existing.to_js_string()
518 } else {
519 let pairs: alloc::vec::Vec<(String, String)> = o
520 .borrow()
521 .props
522 .iter()
523 .map(|(k, v)| (k.to_string(), v.to_js_string()))
524 .collect();
525 build_query(&pairs)
526 }
527 }
528 other => other.to_js_string(),
529 };
530 let o = Obj::plain();
531 {
532 let mut b = o.borrow_mut();
533 b.props
534 .insert("_query".into(), Value::str(build_query(&parse_query(&q))));
535 b.props.insert("_is_usp".into(), Value::Bool(true));
537 b.insert_accessor(
538 String::from("size"),
539 crate::os_lib::ecma::value::Accessor {
540 get: Some(nv("get size", usp_size_getter)),
541 set: None,
542 },
543 );
544 b.props.insert("sort".into(), nv("sort", usp_sort));
546 b.props.insert("get".into(), nv("get", usp_get));
547 b.props.insert("getAll".into(), nv("getAll", usp_get_all));
548 b.props.insert("has".into(), nv("has", usp_has));
549 b.props.insert("append".into(), nv("append", usp_append));
550 b.props.insert("set".into(), nv("set", usp_set));
551 b.props.insert("delete".into(), nv("delete", usp_delete));
552 b.props.insert("entries".into(), nv("entries", fd_entries));
556 b.props.insert("keys".into(), nv("keys", fd_keys));
557 b.props.insert("values".into(), nv("values", fd_values));
558 b.props.insert("forEach".into(), nv("forEach", fd_for_each));
559 b.props.insert(
565 "Symbol(Symbol.iterator)".into(),
566 nv("[Symbol.iterator]", usp_iterator),
567 );
568 b.props
569 .insert("toString".into(), nv("toString", usp_to_string));
570 }
571 Ok(Value::Object(o))
572}
573
574pub(crate) fn fd_entries(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
578 let items: Vec<Value> = parse_query(&usp_query(&this))
579 .into_iter()
580 .map(|(k, v)| Value::Object(Obj::array(alloc::vec![Value::str(k), Value::str(v)])))
581 .collect();
582 Ok(Value::Object(Obj::array(items)))
583}
584pub(crate) fn fd_keys(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
585 let items: Vec<Value> = parse_query(&usp_query(&this))
586 .into_iter()
587 .map(|(k, _)| Value::str(k))
588 .collect();
589 Ok(Value::Object(Obj::array(items)))
590}
591pub(crate) fn fd_values(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
592 let items: Vec<Value> = parse_query(&usp_query(&this))
593 .into_iter()
594 .map(|(_, v)| Value::str(v))
595 .collect();
596 Ok(Value::Object(Obj::array(items)))
597}
598pub(crate) fn fd_for_each(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
599 let cb = arg(a, 0);
600 if matches!(cb, Value::Object(_)) {
601 for (k, v) in parse_query(&usp_query(&this)) {
602 it.call_value(
603 &cb,
604 Value::Undefined,
605 &[Value::str(v), Value::str(k), this.clone()],
606 )?;
607 }
608 }
609 Ok(Value::Undefined)
610}
611
612pub(crate) fn collect_form_data(it: &Interp, form_idx: usize) -> Vec<(String, String)> {
618 let dom = it.dom().borrow();
619 let mut out: Vec<(String, String)> = Vec::new();
620 let mut stack: Vec<usize> = alloc::vec![0usize];
628 let mut order: Vec<usize> = Vec::new();
629 while let Some(i) = stack.pop() {
630 order.push(i);
631 if let Some(n) = dom.nodes.get(i) {
632 for &c in n.children.iter().rev() {
634 stack.push(c);
635 }
636 }
637 }
638 for &i in order.iter() {
639 let n = match dom.nodes.get(i) {
640 Some(n) => n,
641 None => continue,
642 };
643 if n.is_text || i == form_idx {
644 continue;
645 }
646 let tag = n.tag.as_str();
647 if tag != "input" && tag != "select" && tag != "textarea" {
648 continue;
649 }
650 if dom.associated_form(i) != Some(form_idx) {
651 continue;
652 }
653 if dom.is_disabled(i) {
658 continue;
659 }
660 let name = dom.get_attr(i, "name").unwrap_or_default();
661 if name.is_empty() {
662 continue;
663 }
664 match tag {
665 "input" => {
666 let ty = dom.get_attr(i, "type").unwrap_or_default().to_lowercase();
667 match ty.as_str() {
668 "submit" | "button" | "reset" | "image" | "file" => { }
669 "checkbox" | "radio" => {
670 if dom.has_attr(i, "checked") {
671 let v = dom
672 .get_attr(i, "value")
673 .filter(|s| !s.is_empty())
674 .unwrap_or_else(|| String::from("on"));
675 out.push((name, v));
676 }
677 }
678 _ => {
679 out.push((name, dom.get_attr(i, "value").unwrap_or_default()));
680 }
681 }
682 }
683 "textarea" => {
684 let v = dom
685 .get_attr(i, "value")
686 .unwrap_or_else(|| n.initial_text.clone());
687 out.push((name, v));
688 }
689 "select" => {
690 if dom.has_attr(i, "multiple") {
700 for c in dom.select_options(i) {
701 if dom.has_attr(c, "selected") {
702 let v = dom.get_attr(c, "value").unwrap_or_else(|| {
703 dom.nodes.get(c).map(|cn| cn.initial_text.clone()).unwrap_or_default()
704 });
705 out.push((name.clone(), v));
706 }
707 }
708 }
709 else if let Some(v) = dom.get_attr(i, "value").filter(|s| !s.is_empty()) {
711 out.push((name, v));
712 } else {
713 let opts = dom.select_options(i);
725 let chosen = opts
726 .iter()
727 .find(|&&o| dom.has_attr(o, "selected"))
728 .or_else(|| opts.first());
729 if let Some(&oi) = chosen {
730 let v = dom.get_attr(oi, "value").unwrap_or_else(|| {
731 dom.nodes
732 .get(oi)
733 .map(|cn| cn.initial_text.clone())
734 .unwrap_or_default()
735 });
736 out.push((name, v));
737 }
738 }
739 }
740 _ => {}
741 }
742 }
743 out
744}
745
746pub(crate) fn form_data_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
747 let pairs = match this_dom_idx(&arg(a, 0)) {
749 Some(form_idx) => collect_form_data(it, form_idx),
750 None => Vec::new(),
751 };
752 let o = Obj::plain();
753 {
754 let mut b = o.borrow_mut();
755 b.props
756 .insert("_query".into(), Value::str(build_query(&pairs)));
757 b.props.insert("get".into(), nv("get", usp_get));
758 b.props.insert("getAll".into(), nv("getAll", usp_get_all));
759 b.props.insert("has".into(), nv("has", usp_has));
760 b.props.insert("append".into(), nv("append", usp_append));
761 b.props.insert("set".into(), nv("set", usp_set));
762 b.props.insert("delete".into(), nv("delete", usp_delete));
763 b.props.insert("entries".into(), nv("entries", fd_entries));
764 b.props.insert("keys".into(), nv("keys", fd_keys));
765 b.props.insert("values".into(), nv("values", fd_values));
766 b.props.insert("forEach".into(), nv("forEach", fd_for_each));
767 b.props.insert(
770 "Symbol(Symbol.iterator)".into(),
771 nv("[Symbol.iterator]", usp_iterator),
772 );
773 b.props
774 .insert("toString".into(), nv("toString", usp_to_string));
775 }
776 Ok(Value::Object(o))
777}
778
779use super::url_parser::{self, Url};
781
782fn url_arg_string(v: &Value) -> String {
784 if let Value::Object(o) = v {
785 if let Some(h) = o.borrow().props.get("_href") {
786 return h.to_js_string();
787 }
788 }
789 v.to_js_string()
790}
791fn url_parse_args(a: &[Value]) -> Option<Url> {
792 let raw = url_arg_string(&arg(a, 0));
793 let base = match arg(a, 1) {
794 Value::Undefined => None,
795 v => Some(url_arg_string(&v)),
796 };
797 url_parser::parse(&raw, base.as_deref())
798}
799pub(crate) fn url_can_parse(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
801 Ok(Value::Bool(url_parse_args(a).is_some()))
802}
803pub(crate) fn url_parse(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
805 match url_parse_args(a) {
806 Some(u) => url_build(it, &u),
807 None => Ok(Value::Null),
808 }
809}
810pub(crate) fn has_url_scheme(s: &str) -> bool {
811 if !s.contains(':') {
812 return false;
813 }
814 let mut chars = s.chars().take_while(|&c| c != ':');
815 match chars.next() {
816 Some(c) if c.is_ascii_alphabetic() => {}
817 _ => return false,
818 }
819 chars.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
820}
821pub(crate) fn url_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
822 if a.is_empty() {
823 return Err(it.type_error("Failed to construct 'URL': 1 argument required, but only 0 present."));
824 }
825 match url_parse_args(a) {
826 Some(u) => url_build(it, &u),
827 None => Err(it.type_error("Failed to construct 'URL': Invalid URL")),
828 }
829}
830
831fn url_current(this: &Value) -> Option<Url> {
833 if let Value::Object(o) = this {
834 let href = o.borrow().props.get("_href").map(|v| v.to_js_string())?;
835 let u = url_parser::parse(&href, None)?;
836 return Some(u);
837 }
838 None
839}
840fn url_store(this: &Value, u: &Url) {
841 if let Value::Object(o) = this {
842 let host = u.host.clone().unwrap_or_default();
843 let hostport = match u.port {
844 Some(p) => alloc::format!("{}:{}", host, p),
845 None => host.clone(),
846 };
847 let mut b = o.borrow_mut();
848 let mut put = |k: &str, v: String| {
849 b.props.insert(String::from(k).into(), Value::str(v));
850 };
851 put("_href", url_parser::serialize(u, false));
852 put("protocol", alloc::format!("{}:", u.scheme));
853 put("username", u.username.clone());
854 put("password", u.password.clone());
855 put("host", hostport);
856 put("hostname", host);
857 put("port", u.port.map(|p| alloc::format!("{}", p)).unwrap_or_default());
858 put("pathname", url_parser::path_string(u));
859 put("search", match &u.query {
860 Some(q) if !q.is_empty() => alloc::format!("?{}", q),
861 _ => String::new(),
862 });
863 put("hash", match &u.fragment {
864 Some(f) if !f.is_empty() => alloc::format!("#{}", f),
865 _ => String::new(),
866 });
867 put("origin", url_parser::origin(u));
868 }
869}
870fn url_sync_search_params(it: &mut Interp, this: &Value, u: &Url) -> Result<(), Value> {
872 let fresh = url_search_params_ctor(it, Value::Undefined, &[Value::str(u.query.clone().unwrap_or_default())])?;
873 let q = usp_query(&fresh);
874 if let Value::Object(o) = this {
875 let sp = o.borrow().props.get("searchParams").cloned();
876 if let Some(Value::Object(spo)) = sp {
877 spo.borrow_mut().props.insert(String::from("_query").into(), Value::str(q));
878 }
879 }
880 Ok(())
881}
882fn url_set_named(it: &mut Interp, this: &Value, name: &str, v: &str) -> Result<Value, Value> {
883 if let Some(mut u) = url_current(this) {
884 url_parser::apply_setter(&mut u, name, v);
885 url_store(this, &u);
886 if name == "search" {
887 url_sync_search_params(it, this, &u)?;
888 }
889 }
890 Ok(Value::Undefined)
891}
892macro_rules! url_accessors {
893 ($(($get:ident, $set:ident, $name:expr)),*) => {$(
894 pub(crate) fn $get(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
895 Ok(url_prop_or_empty(&this, $name))
896 }
897 pub(crate) fn $set(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
898 url_set_named(it, &this, $name, &arg(a, 0).to_js_string())
899 }
900 )*};
901}
902url_accessors!(
903 (url_get_protocol, url_set_protocol, "protocol"),
904 (url_get_username, url_set_username, "username"),
905 (url_get_password, url_set_password, "password"),
906 (url_get_host, url_set_host, "host"),
907 (url_get_hostname, url_set_hostname, "hostname"),
908 (url_get_port, url_set_port, "port"),
909 (url_get_pathname, url_set_pathname, "pathname"),
910 (url_get_search, url_set_search, "search"),
911 (url_get_hash, url_set_hash, "hash")
912);
913pub(crate) fn url_get_origin(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
914 Ok(url_prop_or_empty(&this, "origin"))
915}
916fn url_prop_or_empty(this: &Value, key: &str) -> Value {
917 if let Value::Object(o) = this {
918 if let Some(v) = o.borrow().props.get(key) {
919 return v.clone();
920 }
921 }
922 Value::str("")
923}
924pub(crate) fn url_set_href(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
926 match url_parser::parse(&arg(a, 0).to_js_string(), None) {
927 Some(u) => {
928 url_store(&this, &u);
929 url_sync_search_params(it, &this, &u)?;
930 Ok(Value::Undefined)
931 }
932 None => Err(it.type_error("Invalid URL")),
933 }
934}
935pub(crate) fn url_to_string(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
937 Ok(Value::str(match url_current(&this) {
938 Some(u) => url_parser::serialize(&u, false),
939 None => String::new(),
940 }))
941}
942fn url_build(it: &mut Interp, u: &Url) -> Result<Value, Value> {
943 let sp = url_search_params_ctor(it, Value::Undefined, &[Value::str(u.query.clone().unwrap_or_default())])?;
944 let o = Obj::plain();
945 if let Value::Object(sp_obj) = &sp {
946 sp_obj.borrow_mut().props.insert(String::from("_parent_url").into(), Value::Object(o.clone()));
947 }
948 {
949 let mut b = o.borrow_mut();
950 b.props.insert("searchParams".into(), sp);
951 b.props.insert("toString".into(), nv("toString", url_to_string));
952 b.props.insert("toJSON".into(), nv("toJSON", url_to_string));
953 let acc = |g: Value, s: Option<Value>| crate::os_lib::ecma::value::Accessor { get: Some(g), set: s };
954 b.insert_accessor(String::from("href"), acc(nv("href", url_to_string), Some(nv("href", url_set_href))));
955 b.insert_accessor(String::from("origin"), acc(nv("origin", url_get_origin), None));
956 for (key, g, s) in [
957 ("protocol", url_get_protocol as NativeFn, url_set_protocol as NativeFn),
958 ("username", url_get_username, url_set_username),
959 ("password", url_get_password, url_set_password),
960 ("host", url_get_host, url_set_host),
961 ("hostname", url_get_hostname, url_set_hostname),
962 ("port", url_get_port, url_set_port),
963 ("pathname", url_get_pathname, url_set_pathname),
964 ("search", url_get_search, url_set_search),
965 ("hash", url_get_hash, url_set_hash),
966 ] {
967 b.insert_accessor(String::from(key), acc(nv(key, g), Some(nv(key, s))));
968 }
969 }
970 let v = Value::Object(o);
971 url_store(&v, u);
972 Ok(v)
973}
974
975pub(crate) fn url_pattern_ctor(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
978 let arg0 = arg(a, 0);
979 let mut pattern_pathname = String::from("*");
980 let mut pattern_hostname = String::from("*");
981 let mut pattern_protocol = String::from("*");
982
983 match &arg0 {
984 Value::Object(o) => {
985 let b = o.borrow();
986 if let Some(p) = b.props.get("pathname") {
987 pattern_pathname = p.to_js_string();
988 }
989 if let Some(h) = b.props.get("hostname") {
990 pattern_hostname = h.to_js_string();
991 }
992 if let Some(pr) = b.props.get("protocol") {
993 pattern_protocol = pr.to_js_string();
994 }
995 }
996 _ => {
997 let pat_str = arg0.to_js_string();
998 if !pat_str.is_empty() {
999 if pat_str.contains("://") {
1000 let href = pat_str;
1001 if let Some((proto, rest)) = href.split_once("://") {
1002 pattern_protocol = proto.to_string();
1003 match rest.split_once('/') {
1004 Some((host, path)) => {
1005 pattern_hostname = host.to_string();
1006 pattern_pathname = alloc::format!("/{}", path);
1007 }
1008 None => {
1009 pattern_hostname = rest.to_string();
1010 pattern_pathname = String::from("/");
1011 }
1012 }
1013 }
1014 } else {
1015 pattern_pathname = pat_str;
1016 }
1017 }
1018 }
1019 }
1020
1021 let o = Obj::plain();
1022 {
1023 let mut b = o.borrow_mut();
1024 b.props.insert("pathname".into(), Value::str(pattern_pathname));
1025 b.props.insert("hostname".into(), Value::str(pattern_hostname));
1026 b.props.insert("protocol".into(), Value::str(pattern_protocol));
1027 b.props.insert("test".into(), nv("test", url_pattern_test));
1028 b.props.insert("exec".into(), nv("exec", url_pattern_exec));
1029 }
1030 Ok(Value::Object(o))
1031}
1032
1033fn match_pathname_pattern(pattern: &str, target: &str) -> Option<Vec<(String, String)>> {
1043 if pattern == "*" || pattern.is_empty() {
1044 return Some(Vec::new());
1045 }
1046 if pattern == target {
1047 return Some(Vec::new());
1048 }
1049 if pattern.contains('*') && !pattern.contains(':') {
1050 let parts: Vec<&str> = pattern.split('*').collect();
1051 if parts.len() == 2 && target.starts_with(parts[0]) && target.ends_with(parts[1]) {
1052 return Some(Vec::new());
1053 }
1054 return None;
1055 }
1056 let pat_segs: Vec<&str> = pattern.split('/').collect();
1057 let tgt_segs: Vec<&str> = target.split('/').collect();
1058 if pat_segs.len() != tgt_segs.len() {
1059 return None;
1060 }
1061 let mut groups = Vec::new();
1062 for (p, t) in pat_segs.iter().zip(tgt_segs.iter()) {
1063 if let Some(name) = p.strip_prefix(':') {
1064 groups.push((name.to_string(), t.to_string()));
1065 } else if *p == "*" {
1066 } else if p != t {
1068 return None;
1069 }
1070 }
1071 Some(groups)
1072}
1073
1074fn match_pattern_part(pattern: &str, target: &str) -> bool {
1075 if pattern == "*" || pattern.is_empty() {
1076 return true;
1077 }
1078 if pattern == target {
1079 return true;
1080 }
1081 if pattern.starts_with(':') || pattern == "*" {
1082 return true;
1083 }
1084 if pattern.contains('*') {
1085 let parts: Vec<&str> = pattern.split('*').collect();
1086 if parts.len() == 2 {
1087 return target.starts_with(parts[0]) && target.ends_with(parts[1]);
1088 }
1089 }
1090 false
1091}
1092
1093pub(crate) fn url_pattern_test(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1094 let res = url_pattern_exec(it, this, a)?;
1095 Ok(Value::Bool(!matches!(res, Value::Null)))
1096}
1097
1098pub(crate) fn url_pattern_exec(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1099 let input = arg(a, 0);
1100 let (pat_pathname, pat_hostname, pat_protocol) = match &this {
1101 Value::Object(o) => {
1102 let b = o.borrow();
1103 (
1104 b.props.get("pathname").map(|v| v.to_js_string()).unwrap_or_else(|| "*".into()),
1105 b.props.get("hostname").map(|v| v.to_js_string()).unwrap_or_else(|| "*".into()),
1106 b.props.get("protocol").map(|v| v.to_js_string()).unwrap_or_else(|| "*".into()),
1107 )
1108 }
1109 _ => return Ok(Value::Null),
1110 };
1111
1112 let mut target_pathname = String::new();
1113 let mut target_hostname = String::new();
1114 let mut target_protocol = String::new();
1115
1116 match &input {
1117 Value::Object(o) => {
1118 let b = o.borrow();
1119 target_pathname = b.props.get("pathname").map(|v| v.to_js_string()).unwrap_or_default();
1120 target_hostname = b.props.get("hostname").map(|v| v.to_js_string()).unwrap_or_default();
1121 target_protocol = b.props.get("protocol").map(|v| v.to_js_string()).unwrap_or_default();
1122 }
1123 _ => {
1124 let url_str = input.to_js_string();
1125 if url_str.contains("://") {
1126 if let Some((proto, rest)) = url_str.split_once("://") {
1127 target_protocol = proto.to_string();
1128 match rest.split_once('/') {
1129 Some((host, path)) => {
1130 target_hostname = host.to_string();
1131 target_pathname = alloc::format!("/{}", path);
1132 }
1133 None => {
1134 target_hostname = rest.to_string();
1135 target_pathname = String::from("/");
1136 }
1137 }
1138 }
1139 } else {
1140 target_pathname = url_str;
1141 }
1142 }
1143 }
1144
1145 let path_match = match_pathname_pattern(&pat_pathname, &target_pathname);
1146 let match_host = match_pattern_part(&pat_hostname, &target_hostname);
1147 let match_proto = match_pattern_part(&pat_protocol, &target_protocol);
1148
1149 if let (Some(groups), true, true) = (path_match, match_host, match_proto) {
1150 let result_obj = Obj::plain();
1151 {
1152 let mut b = result_obj.borrow_mut();
1153 let pathname_obj = Obj::plain();
1154 {
1155 let mut pb = pathname_obj.borrow_mut();
1156 pb.props.insert("input".into(), Value::str(target_pathname));
1157 let groups_obj = Obj::plain();
1158 {
1159 let mut gb = groups_obj.borrow_mut();
1160 for (name, value) in &groups {
1161 gb.props.insert(name.clone().into(), Value::str(value.clone()));
1162 }
1163 }
1164 pb.props.insert("groups".into(), Value::Object(groups_obj));
1165 }
1166 b.props.insert("pathname".into(), Value::Object(pathname_obj));
1167 }
1168 Ok(Value::Object(result_obj))
1169 } else {
1170 Ok(Value::Null)
1171 }
1172}
1173