1use super::*;
3
4pub(crate) fn navigator_get_high_entropy_values(
10 it: &mut Interp,
11 this: Value,
12 a: &[Value],
13) -> Result<Value, Value> {
14 let hints: alloc::vec::Vec<String> = this_items(&arg(a, 0)).iter().map(|v| v.to_js_string()).collect();
15 let result = Obj::plain();
16 {
17 let mut r = result.borrow_mut();
18 if let Value::Object(ua) = &this {
19 for key in ["brands", "mobile", "platform"] {
20 if let Some(v) = ua.borrow().props.get(key).cloned() {
21 r.props.insert(key.into(), v);
22 }
23 }
24 }
25 for hint in &hints {
26 match hint.as_str() {
27 "architecture" => {
28 r.props.insert("architecture".into(), Value::str("arm"));
29 }
30 "bitness" => {
31 r.props.insert("bitness".into(), Value::str("64"));
32 }
33 "model" => {
34 r.props.insert("model".into(), Value::str(""));
35 }
36 "platformVersion" => {
37 r.props.insert("platformVersion".into(), Value::str("1.0"));
38 }
39 "uaFullVersion" | "fullVersionList" => {
40 if let Value::Object(ua) = &this {
41 if let Some(v) = ua.borrow().props.get("brands").cloned() {
42 r.props.insert(hint.clone().into(), v);
43 }
44 }
45 }
46 _ => {}
47 }
48 }
49 }
50 Ok(resolved_promise(it, Value::Object(result)))
51}
52pub(crate) fn navigator_storage_estimate(it: &mut Interp, _this: Value, _a: &[Value]) -> Result<Value, Value> {
56 let result = Obj::plain();
57 {
58 let mut r = result.borrow_mut();
59 r.props.insert("usage".into(), Value::Number(0.0));
60 r.props.insert("quota".into(), Value::Number(1024.0 * 1024.0 * 1024.0));
61 }
62 Ok(resolved_promise(it, Value::Object(result)))
63}
64pub(crate) fn navigator_storage_persist(it: &mut Interp, _this: Value, _a: &[Value]) -> Result<Value, Value> {
68 Ok(resolved_promise(it, Value::Bool(true)))
69}
70
71
72pub(crate) fn split_http_url(url: &str) -> Option<(bool, String, String)> {
75 let (is_https, rest) = if let Some(r) = url.strip_prefix("https://") {
76 (true, r)
77 } else if let Some(r) = url.strip_prefix("http://") {
78 (false, r)
79 } else {
80 return None;
81 };
82 let (host, path) = match rest.split_once('/') {
83 Some((h, p)) => (h.to_string(), format!("/{}", p)),
84 None => (rest.to_string(), String::from("/")),
85 };
86 if host.is_empty() {
87 return None;
88 }
89 Some((is_https, host, path))
90}
91
92pub(crate) fn data_url_body(url: &str) -> Option<String> {
94 let rest = url.strip_prefix("data:")?;
95 let (meta, body) = rest.split_once(',')?;
96 let bytes = if meta.to_ascii_lowercase().ends_with(";base64") {
99 super::base64_to_bytes(body)
100 } else {
101 let b = body.as_bytes();
102 let mut out = Vec::with_capacity(b.len());
103 let mut i = 0;
104 while i < b.len() {
105 if b[i] == b'%' && i + 2 < b.len() {
106 let h = core::str::from_utf8(&b[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok());
107 if let Some(v) = h {
108 out.push(v);
109 i += 3;
110 continue;
111 }
112 }
113 out.push(b[i]);
114 i += 1;
115 }
116 out
117 };
118 Some(String::from_utf8_lossy(&bytes).into_owned())
119}
120
121pub(crate) fn http_status_text(status: u16) -> &'static str {
128 match status {
129 200 => "OK",
130 201 => "Created",
131 202 => "Accepted",
132 204 => "No Content",
133 301 => "Moved Permanently",
134 302 => "Found",
135 304 => "Not Modified",
136 400 => "Bad Request",
137 401 => "Unauthorized",
138 403 => "Forbidden",
139 404 => "Not Found",
140 405 => "Method Not Allowed",
141 408 => "Request Timeout",
142 409 => "Conflict",
143 410 => "Gone",
144 429 => "Too Many Requests",
145 500 => "Internal Server Error",
146 501 => "Not Implemented",
147 502 => "Bad Gateway",
148 503 => "Service Unavailable",
149 504 => "Gateway Timeout",
150 _ => "",
151 }
152}
153pub(crate) fn make_response(status: u16, body: String) -> Value {
154 make_response_with_url(status, body, String::new())
155}
156pub(crate) fn response_init_status(init: &Value, default: u16) -> u16 {
158 match init {
159 Value::Object(o) => o
160 .borrow()
161 .props
162 .get("status")
163 .map(|v| v.to_number() as u16)
164 .unwrap_or(default),
165 _ => default,
166 }
167}
168pub(crate) fn response_ctor(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
170 let stream = match arg(a, 0) {
172 Value::Object(o) if o.borrow().props.contains_key("_chunks") && o.borrow().props.contains_key("getReader") => Some(o),
173 _ => None,
174 };
175 let body = match arg(a, 0) {
176 Value::Undefined => String::new(),
177 _ if stream.is_some() => String::new(),
178 v => v.to_js_string(),
179 };
180 let init = arg(a, 1);
181 let status = response_init_status(&init, 200);
182 let headers_init = match &init {
183 Value::Object(o) => o.borrow().props.get("headers").cloned().unwrap_or(Value::Undefined),
184 _ => Value::Undefined,
185 };
186 let resp = make_response(status, body);
187 if let Value::Object(r) = &resp {
188 let mut r = r.borrow_mut();
189 r.props.insert("headers".into(), make_headers(headers_init));
190 if let Some(s) = stream {
191 r.props.insert("body".into(), Value::Object(s.clone()));
192 r.props.insert("_body_stream".into(), Value::Object(s));
193 }
194 }
195 Ok(resp)
196}
197
198fn response_stream(this: &Value) -> Option<crate::os_lib::ecma::value::ObjRef> {
200 match this {
201 Value::Object(o) => match o.borrow().props.get("_body_stream") {
202 Some(Value::Object(s)) => Some(s.clone()),
203 _ => None,
204 },
205 _ => None,
206 }
207}
208pub(crate) fn response_json_static(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
211 let body = json_stringify(it, Value::Undefined, &[arg(a, 0)])?.to_js_string();
212 let status = response_init_status(&arg(a, 1), 200);
213 let resp = make_response(status, body);
214 if let Value::Object(r) = &resp {
215 let headers = make_headers(Value::Undefined);
216 if let Value::Object(h) = &headers {
217 h.borrow_mut()
218 .props
219 .insert("content-type".into(), Value::str("application/json"));
220 }
221 r.borrow_mut().props.insert("headers".into(), headers);
222 }
223 Ok(resp)
224}
225pub(crate) fn response_error_static(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
228 let resp = make_response(0, String::new());
229 if let Value::Object(r) = &resp {
230 let mut b = r.borrow_mut();
231 b.props.insert("type".into(), Value::str("error"));
232 b.props.insert("ok".into(), Value::Bool(false));
233 }
234 Ok(resp)
235}
236pub(crate) fn response_redirect_static(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
239 let url = arg(a, 0).to_js_string();
240 let status = match arg(a, 1) {
241 Value::Undefined => 302,
242 v => v.to_number() as u16,
243 };
244 let resp = make_response(status, String::new());
245 if let Value::Object(r) = &resp {
246 let headers = make_headers(Value::Undefined);
247 if let Value::Object(h) = &headers {
248 h.borrow_mut().props.insert("location".into(), Value::str(url));
249 }
250 r.borrow_mut().props.insert("headers".into(), headers);
251 }
252 Ok(resp)
253}
254
255pub(crate) fn make_response_with_url(status: u16, body: String, url: String) -> Value {
260 let resp = Obj::plain();
261 {
262 let mut r = resp.borrow_mut();
263 r.props
264 .insert("status".into(), Value::Number(status as f64));
265 r.props
266 .insert("ok".into(), Value::Bool((200..300).contains(&status)));
267 r.props
268 .insert("statusText".into(), Value::str(http_status_text(status)));
269 r.props.insert("url".into(), Value::str(url));
270 r.props.insert("type".into(), Value::str("basic"));
274 r.props.insert("redirected".into(), Value::Bool(false));
275 r.props.insert("headers".into(), make_headers(Value::Undefined));
280 r.props.insert("body".into(), make_readable_stream_from_string(&body));
281 r.props.insert("_body".into(), Value::str(body));
282 r.props.insert("text".into(), nv("text", response_text));
283 r.props.insert("json".into(), nv("json", response_json));
284 r.props.insert("blob".into(), nv("blob", response_blob));
287 r.props
290 .insert("arrayBuffer".into(), nv("arrayBuffer", response_array_buffer));
291 r.props.insert("clone".into(), nv("clone", response_clone));
295 }
296 Value::Object(resp)
297}
298
299pub(crate) fn response_clone(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
304 if let Value::Object(o) = &this {
305 let (status, body, url) = {
306 let b = o.borrow();
307 (
308 b.props.get("status").map(|v| v.to_number() as u16).unwrap_or(200),
309 b.props.get("_body").map(|v| v.to_js_string()).unwrap_or_default(),
310 b.props.get("url").map(|v| v.to_js_string()).unwrap_or_default(),
311 )
312 };
313 let clone = make_response_with_url(status, body, url);
314 let bytes: Vec<u8> = response_body_bytes(&this).iter().map(|&b| b as u8).collect();
318 let stream = super::streams::make_readable_stream_from_bytes(it, &bytes);
319 if let Value::Object(c) = &clone {
320 let src = o.borrow();
321 let mut dst = c.borrow_mut();
322 for key in ["statusText", "ok", "type", "redirected", "headers", "_body_latin1"] {
323 if let Some(v) = src.props.get(key) {
324 dst.props.insert(key.into(), v.clone());
325 }
326 }
327 dst.props.insert("body".into(), stream);
328 }
329 return Ok(clone);
330 }
331 Ok(this)
332}
333
334pub(crate) fn response_body_string(this: &Value) -> String {
336 if let Value::Object(o) = this {
337 if let Some(v) = o.borrow().props.get("_body") {
338 return v.to_js_string();
339 }
340 }
341 String::new()
342}
343
344pub(crate) fn response_text(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
346 if let Some(st) = response_stream(&this) {
347 return Ok(super::streams::read_stream_body(it, &st, "text"));
348 }
349 let body = response_body_string(&this);
350 Ok(resolved_promise(it, Value::str(body)))
351}
352
353pub(crate) fn response_json(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
355 if let Some(st) = response_stream(&this) {
356 return Ok(super::streams::read_stream_body(it, &st, "json"));
357 }
358 let body = response_body_string(&this);
359 let parsed = json_parse(it, Value::Undefined, &[Value::str(body)])?;
360 Ok(resolved_promise(it, parsed))
361}
362
363pub(crate) fn attach_raw_body(resp: &Value, bytes: &[u8]) {
368 let Value::Object(o) = resp else { return };
369 let same = o.borrow().props.get("_body").is_some_and(|v| v.to_js_string().as_bytes() == bytes);
370 if !same {
371 let latin1: String = bytes.iter().map(|&b| b as char).collect();
372 o.borrow_mut().props.insert("_body_latin1".into(), Value::str(latin1));
373 }
374}
375
376fn response_body_bytes(this: &Value) -> alloc::vec::Vec<f64> {
378 if let Value::Object(o) = this {
379 if let Some(v) = o.borrow().props.get("_body_latin1") {
380 return v.to_js_string().chars().map(|c| (c as u32 & 0xff) as f64).collect();
381 }
382 }
383 response_body_string(this).as_bytes().iter().map(|b| *b as f64).collect()
384}
385
386pub(crate) fn response_blob(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
388 if let Some(st) = response_stream(&this) {
389 return Ok(super::streams::read_stream_body(it, &st, "blob"));
390 }
391 let bytes = response_body_bytes(&this);
392 let blob = make_blob(bytes, String::new());
393 Ok(resolved_promise(it, blob))
394}
395
396pub(crate) fn response_array_buffer(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
399 if let Some(st) = response_stream(&this) {
400 return Ok(super::streams::read_stream_body(it, &st, "arrayBuffer"));
401 }
402 let bytes = response_body_bytes(&this);
403 let buf = make_arraybuffer_with_bytes(bytes);
404 Ok(resolved_promise(it, buf))
405}
406
407pub(crate) fn location_to_string(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
409 if let Value::Object(o) = &this {
410 if let Some(v) = o.borrow().props.get("href") {
411 return Ok(v.clone());
412 }
413 }
414 Ok(Value::str(""))
415}
416
417pub(crate) fn queue_location_nav(this: &Value, url: &str, mode: &str) {
421 crate::warn!("[JSNAV] location {} {:?}", mode, url.chars().take(120).collect::<String>());
422 if let Value::Object(o) = this {
423 let mut b = o.borrow_mut();
424 b.props
425 .insert(String::from("_pending_location").into(), Value::str(url));
426 b.props
427 .insert(String::from("_pending_location_mode").into(), Value::str(mode));
428 }
429}
430
431pub(crate) fn location_assign(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
433 let url = a.first().map(|v| v.to_js_string()).unwrap_or_default();
434 if !url.is_empty() {
435 queue_location_nav(&this, &url, "assign");
436 }
437 Ok(Value::Undefined)
438}
439
440pub(crate) fn location_replace(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
442 let url = a.first().map(|v| v.to_js_string()).unwrap_or_default();
443 if !url.is_empty() {
444 queue_location_nav(&this, &url, "replace");
445 }
446 Ok(Value::Undefined)
447}
448
449pub(crate) fn location_reload(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
451 let cur = if let Value::Object(o) = &this {
453 o.borrow()
454 .props
455 .get("href")
456 .map(|v| v.to_js_string())
457 .unwrap_or_default()
458 } else {
459 String::new()
460 };
461 queue_location_nav(&this, &cur, "reload");
462 Ok(Value::Undefined)
463}
464
465pub(crate) fn location_components(url: &str) -> Vec<(&'static str, String)> {
468 let (protocol, after) = if let Some(a) = url.strip_prefix("https://") {
469 ("https:", a)
470 } else if let Some(a) = url.strip_prefix("http://") {
471 ("http:", a)
472 } else {
473 ("", url)
474 };
475 let (hostport, pathpart) = match after.find(['/', '?', '#']) {
478 Some(i) => {
479 let (h, rest) = after.split_at(i);
480 let p = if rest.starts_with('/') { String::from(rest) } else { format!("/{}", rest) };
481 (String::from(h), p)
482 }
483 None => (String::from(after), String::from("/")),
484 };
485 let (userinfo, hostport) = match hostport.split_once('@') {
492 Some((ui, hp)) => (String::from(ui), String::from(hp)),
493 None => (String::new(), hostport),
494 };
495 let (username, password) = match userinfo.split_once(':') {
496 Some((u, p)) => (String::from(u), String::from(p)),
497 None => (userinfo.clone(), String::new()),
498 };
499 let (before_hash, hash) = match pathpart.split_once('#') {
500 Some((b, h)) => (String::from(b), format!("#{}", h)),
501 None => (pathpart.clone(), String::new()),
502 };
503 let (pathname, search) = match before_hash.split_once('?') {
504 Some((p, q)) => (String::from(p), format!("?{}", q)),
505 None => (before_hash.clone(), String::new()),
506 };
507 let (hostname, port) = match hostport.split_once(':') {
508 Some((h, p)) => (String::from(h), String::from(p)),
509 None => (hostport.clone(), String::new()),
510 };
511 let origin = if protocol.is_empty() {
512 String::new()
513 } else {
514 format!("{}//{}", protocol, hostport)
515 };
516 let href = if protocol.is_empty() {
518 String::from(url)
519 } else {
520 let auth = if url.contains('@') && !userinfo.is_empty() { format!("{}@{}", userinfo, hostport) } else { hostport.clone() };
521 format!("{}//{}{}{}{}", protocol, auth, pathname, search, hash)
522 };
523 alloc::vec![
524 ("href", href),
525 ("protocol", String::from(protocol)),
526 ("username", username),
527 ("password", password),
528 ("host", hostport),
529 ("hostname", hostname),
530 ("port", port),
531 ("origin", origin),
532 ("pathname", pathname),
533 ("search", search),
534 ("hash", hash),
535 ]
536}
537
538pub fn location_href(global: &Rc<RefCell<Scope>>) -> Option<String> {
540 let loc = match global.borrow().vars.get("location") {
541 Some(Value::Object(o)) => o.clone(),
542 _ => return None,
543 };
544 let href = loc
545 .borrow()
546 .props
547 .get("href")
548 .map(|v| v.to_js_string())
549 .unwrap_or_default();
550 if href.is_empty() {
551 None
552 } else {
553 Some(href)
554 }
555}
556
557pub fn location_hostname(global: &Rc<RefCell<Scope>>) -> Option<String> {
560 let loc = match global.borrow().vars.get("location") {
561 Some(Value::Object(o)) => o.clone(),
562 _ => return None,
563 };
564 let hostname = loc.borrow().props.get("hostname").map(|v| v.to_js_string());
565 hostname
566}
567
568pub fn format_last_modified() -> String {
572 let (y, mo, d, hh, mm, ss, ..) = decompose_ms(epoch_ms_now());
573 alloc::format!("{mo:02}/{d:02}/{y:04} {hh:02}:{mm:02}:{ss:02}")
574}
575
576pub(crate) fn history_change_state(
579 it: &mut Interp,
580 this: &Value,
581 a: &[Value],
582 push: bool,
583) -> Result<Value, Value> {
584 let new_state = arg(a, 0);
585 let url_arg = arg(a, 2);
586
587 if let Value::Object(o) = this {
588 if push {
589 let cur_url = location_href(&it.global).unwrap_or_default();
591 let cur_state = o.borrow().props.get("state").cloned().unwrap_or(Value::Null);
592 let stack_val = o.borrow().props.get("_spa_back_stack").cloned();
593 let stack = match stack_val {
594 Some(Value::Object(arr)) => arr,
595 _ => Obj::array(alloc::vec![]),
596 };
597 let entry = Obj::plain();
598 {
599 let mut eb = entry.borrow_mut();
600 eb.props.insert("url".into(), Value::str(cur_url));
601 eb.props.insert("state".into(), cur_state);
602 }
603 if let ObjKind::Array(items) = &mut stack.borrow_mut().kind {
604 items.push(Value::Object(entry));
605 }
606 o.borrow_mut().props.insert("_spa_back_stack".into(), Value::Object(stack));
607 o.borrow_mut().props.shift_remove("_spa_fwd_stack");
609 }
610
611 if !matches!(url_arg, Value::Undefined | Value::Null) {
612 let url = url_arg.to_js_string();
613 if !url.is_empty() {
614 let base = location_href(&it.global).unwrap_or_default();
615 let resolved = resolve_url(&base, &url);
616 update_location(&it.global, &resolved);
617 it.base_url = resolved;
618 }
619 }
620
621 let mut b = o.borrow_mut();
622 b.props.insert("state".into(), new_state);
623 if push {
624 let len = match b.props.get("length") {
625 Some(Value::Number(n)) => *n,
626 _ => 1.0,
627 };
628 b.props.insert("length".into(), Value::Number(len + 1.0));
629 }
630 } else {
631 if !matches!(url_arg, Value::Undefined | Value::Null) {
632 let url = url_arg.to_js_string();
633 if !url.is_empty() {
634 let base = location_href(&it.global).unwrap_or_default();
635 let resolved = resolve_url(&base, &url);
636 update_location(&it.global, &resolved);
637 it.base_url = resolved;
638 }
639 }
640 }
641 Ok(Value::Undefined)
642}
643
644pub(crate) fn history_push_state(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
645 history_change_state(it, &this, a, true)
646}
647
648pub(crate) fn history_replace_state(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
649 history_change_state(it, &this, a, false)
650}
651
652pub(crate) fn set_pending_nav(global: &Rc<RefCell<Scope>>, delta: i64) {
657 if delta == 0 {
658 return;
659 }
660 if let Some(Value::Object(h)) = global.borrow().vars.get("history") {
661 let cur = match h.borrow().props.get("_pending_nav") {
662 Some(Value::Number(n)) => *n as i64,
663 _ => 0,
664 };
665 h.borrow_mut()
666 .props
667 .insert("_pending_nav".into(), Value::Number((cur + delta) as f64));
668 }
669}
670
671pub(crate) fn history_back(it: &mut Interp, _this: Value, _a: &[Value]) -> Result<Value, Value> {
672 set_pending_nav(&it.global, -1);
673 Ok(Value::Undefined)
674}
675
676pub(crate) fn history_forward(it: &mut Interp, _this: Value, _a: &[Value]) -> Result<Value, Value> {
677 set_pending_nav(&it.global, 1);
678 Ok(Value::Undefined)
679}
680
681pub(crate) fn history_go(it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
682 let n = arg(a, 0).to_number();
684 if n.is_finite() {
685 set_pending_nav(&it.global, n as i64);
686 }
687 Ok(Value::Undefined)
688}
689