1use super::*;
4
5pub fn dom_classlist_item(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
7 if let Some((idx, attr)) = super::dom::this_token_list(&this) {
8 let n = arg(a, 0).to_number();
10 let i = if n.is_finite() { (libm::trunc(n) as i64).rem_euclid(1i64 << 32) as usize } else { 0 };
11 return Ok(match super::dom::token_list_tokens_pub(it, idx, attr).get(i) {
12 Some(c) => Value::str(c.clone()),
13 None => Value::Null,
14 });
15 }
16 Ok(Value::Null)
17}
18pub fn dom_classlist_to_string(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
19 if let Some((idx, attr)) = super::dom::this_token_list(&this) {
20 return Ok(Value::str(
21 it.dom().borrow().get_attr(idx, attr).unwrap_or_default(),
22 ));
23 }
24 Ok(Value::str(""))
25}
26
27pub fn update_location(global: &Rc<RefCell<Scope>>, url: &str) {
29 let loc = match global.borrow().vars.get("location") {
30 Some(Value::Object(o)) => o.clone(),
31 _ => return,
32 };
33 let mut b = loc.borrow_mut();
34 for (k, v) in location_components(url) {
35 b.props.insert(String::from(k).into(), Value::str(v));
36 }
37}
38
39pub(crate) fn normalize_dot_segments(path: &str) -> String {
48 let mut segs: alloc::vec::Vec<&str> = alloc::vec::Vec::new();
49 for seg in path.split('/') {
50 match seg {
51 "" | "." => {}
52 ".." => {
53 segs.pop();
54 }
55 s => segs.push(s),
56 }
57 }
58 alloc::format!("/{}", segs.join("/"))
59}
60
61fn percent_encode_query(q: &str) -> String {
62 if q.bytes().all(|b| (0x21..=0x7E).contains(&b) && !matches!(b, b'"' | b'<' | b'>')) {
63 return String::from(q);
64 }
65 const HEX: &[u8; 16] = b"0123456789ABCDEF";
66 let mut out = String::with_capacity(q.len());
67 for &b in q.as_bytes() {
68 if (0x21..=0x7E).contains(&b) && !matches!(b, b'"' | b'<' | b'>') {
69 out.push(b as char);
70 } else {
71 out.push('%');
72 out.push(HEX[(b >> 4) as usize] as char);
73 out.push(HEX[(b & 0xF) as usize] as char);
74 }
75 }
76 out
77}
78
79fn finish_resolved_url(s: String) -> String {
80 let Some(qpos) = s.find('?') else { return s; };
81 let (prefix, rest) = s.split_at(qpos + 1);
82 let (query, frag) = match rest.find('#') {
83 Some(fpos) => {
84 let (q, f) = rest.split_at(fpos);
85 (q, Some(f))
86 }
87 None => (rest, None),
88 };
89 let enc = percent_encode_query(query);
90 if enc == query {
91 return s;
92 }
93 match frag {
94 Some(f) => alloc::format!("{prefix}{enc}{f}"),
95 None => alloc::format!("{prefix}{enc}"),
96 }
97}
98
99pub fn resolve_url(base: &str, url: &str) -> String {
100 if url.starts_with("http://") || url.starts_with("https://") || url.starts_with("data:") {
101 if url.starts_with("data:") {
102 return String::from(url);
103 }
104 return finish_resolved_url(String::from(url));
105 }
106 if let Some((scheme, _)) = url.split_once(':') {
111 let mut cs = scheme.chars();
112 if cs.next().is_some_and(|c| c.is_ascii_alphabetic())
113 && cs.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
114 && !scheme.contains('/')
115 {
116 return String::from(url);
117 }
118 }
119 if let Some(rest) = url.strip_prefix("//") {
127 let scheme = if base.starts_with("https://") { "https://" } else { "http://" };
128 return finish_resolved_url(alloc::format!("{scheme}{rest}"));
129 }
130 let (scheme, after) = if let Some(a) = base.strip_prefix("https://") {
131 ("https://", a)
132 } else if let Some(a) = base.strip_prefix("http://") {
133 ("http://", a)
134 } else {
135 return String::from(url); };
137 let (host, path) = match after.split_once('/') {
138 Some((h, p)) => (h, p), None => (after, ""),
140 };
141 if let Some(rest) = url.strip_prefix('?') {
148 let base_path = path.split('?').next().unwrap_or("").split('#').next().unwrap_or("");
149 return finish_resolved_url(alloc::format!("{scheme}{host}/{base_path}?{rest}"));
150 }
151 if let Some(rest) = url.strip_prefix('#') {
152 let base_path_and_query = path.split('#').next().unwrap_or("");
153 return finish_resolved_url(alloc::format!("{scheme}{host}/{base_path_and_query}#{rest}"));
154 }
155 let raw_path = if let Some(rooted) = url.strip_prefix('/') {
156 alloc::format!("/{rooted}")
157 } else {
158 let dir = match path.rfind('/') {
160 Some(i) => path.get(..i).unwrap_or(""),
161 None => "",
162 };
163 if dir.is_empty() {
164 alloc::format!("/{url}")
165 } else {
166 alloc::format!("/{dir}/{url}")
167 }
168 };
169 finish_resolved_url(alloc::format!("{scheme}{host}{}", normalize_dot_segments(&raw_path)))
170}
171
172pub(crate) fn do_http_request(
176 base: &str,
177 url: &str,
178 method: &str,
179 body: &str,
180 content_type: &str,
181) -> Result<(u16, String), &'static str> {
182 do_http_request_raw(base, url, method, body.as_bytes(), content_type, &[]).map(|(s, b, _)| (s, b))
183}
184
185pub(crate) fn body_to_bytes(v: &Value) -> Vec<u8> {
190 match v {
191 Value::Undefined | Value::Null => Vec::new(),
192 Value::Str(s) => s.as_bytes().to_vec(),
193 Value::Object(o) => {
194 let (is_binary, ta_bytes) = {
195 let b = o.borrow();
196 let ta = b.props.get("BYTES_PER_ELEMENT").map(|v| v.to_number() as usize).filter(|_| b.props.contains_key("_ta_kind"));
197 let kind = b.props.get("_ta_kind").map(|v| v.to_js_string()).unwrap_or_default();
198 let binary = ta.is_some()
199 || b.props.contains_key("_blob_bytes")
200 || b.props.contains_key("_bytes")
201 || b.props.contains_key("_dv_bytes");
202 (binary, ta.map(|n| (n, kind)))
203 };
204 if !is_binary {
205 if o.borrow().props.contains_key("_query") {
206 return body_to_string(v).into_bytes();
207 }
208 return v.to_js_string().into_bytes();
209 }
210 if let Some((n, kind)) = ta_bytes {
211 if n > 1 {
212 let mut out = Vec::new();
214 if let ObjKind::Array(items) = &o.borrow().kind {
215 for x in items {
216 let f = x.to_number();
217 match (kind.as_str(), n) {
218 ("Float32Array", _) => out.extend_from_slice(&(f as f32).to_le_bytes()),
219 ("Float64Array", _) => out.extend_from_slice(&f.to_le_bytes()),
220 (_, 2) => out.extend_from_slice(&(f as i64 as u16).to_le_bytes()),
221 (_, 4) => out.extend_from_slice(&(f as i64 as u32).to_le_bytes()),
222 _ => out.extend_from_slice(&(f as i64 as u64).to_le_bytes()),
223 }
224 }
225 }
226 return out;
227 }
228 }
229 let mut f = Vec::new();
230 blob_part_bytes(v, &mut f);
231 f.into_iter().map(|x| x as i64 as u8).collect()
232 }
233 other => other.to_js_string().into_bytes(),
234 }
235}
236
237fn request_header_allowed(name: &str, value: &str) -> bool {
239 const FORBIDDEN: &[&str] = &[
240 "host", "content-length", "connection", "accept-encoding", "accept-charset", "cookie", "cookie2",
241 "date", "dnt", "expect", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding",
242 "upgrade", "via", "content-type", "user-agent",
243 ];
244 let n = name.trim();
245 !n.is_empty()
246 && n.bytes().all(|c| c.is_ascii_graphic() && c != b':')
247 && !value.bytes().any(|c| c == b'\r' || c == b'\n')
248 && !FORBIDDEN.iter().any(|f| n.eq_ignore_ascii_case(f))
249 && !n.to_ascii_lowercase().starts_with("proxy-")
250 && !n.to_ascii_lowercase().starts_with("sec-")
251}
252
253pub(crate) fn do_http_request_raw(
255 base: &str,
256 url: &str,
257 method: &str,
258 body: &[u8],
259 content_type: &str,
260 headers: &[(String, String)],
261) -> Result<(u16, String, Vec<u8>), &'static str> {
262 do_http_request_full(base, url, method, body, content_type, headers).map(|(s, b, raw, _)| (s, b, raw))
263}
264
265pub(crate) fn do_http_request_full(
268 base: &str,
269 url: &str,
270 method: &str,
271 body: &[u8],
272 content_type: &str,
273 headers: &[(String, String)],
274) -> Result<(u16, String, Vec<u8>, alloc::collections::BTreeMap<String, String>), &'static str> {
275 let site = crate::os_lib::web_engine::site_hooks::hooks();
279 let shown_full_orig = resolve_url(base, url);
280 let is_sabr = site.fetch_is_special(method, &shown_full_orig);
282
283 let mut effective_url = alloc::string::String::from(url);
284 let mut site_body: Option<Vec<u8>> = None;
285 if is_sabr {
286 let (u, b) = site.fetch_rewrite_request(&effective_url, body);
287 effective_url = u;
288 site_body = b;
289 }
290
291 let shown_full = resolve_url(base, &effective_url);
292 let shown = shown_full.get(..shown_full.len().min(120)).unwrap_or(&shown_full);
293
294 let clean_body: alloc::borrow::Cow<'_, [u8]> = match site_body {
295 Some(b) => alloc::borrow::Cow::Owned(b),
296 None => alloc::borrow::Cow::Borrowed(body),
297 };
298
299 let mut r = do_http_request_full_inner(base, &effective_url, method, &clean_body, content_type, headers);
300
301 if is_sabr {
302 if let Ok((_status, _, ref mut raw, _)) = &mut r {
303 site.fetch_on_response(raw);
304 }
305 }
306
307
308
309 if let Err(e) = &r {
310 crate::warn!("[FETCH] {} {} -> ERR {} req={}B", method, shown, e, clean_body.len());
311 }
312 r
313}
314
315fn do_http_request_full_inner(
316 base: &str,
317 url: &str,
318 method: &str,
319 body: &[u8],
320 content_type: &str,
321 headers: &[(String, String)],
322) -> Result<(u16, String, Vec<u8>, alloc::collections::BTreeMap<String, String>), &'static str> {
323 let resolved = resolve_url(base, url);
324 if resolved.starts_with("data:") {
325 return match data_url_body(&resolved) {
326 Some(b) => {
327 let bytes = b.as_bytes().to_vec();
328 Ok((200, b, bytes, alloc::collections::BTreeMap::new()))
329 }
330 None => Err("malformed data URL"),
331 };
332 }
333 let (is_https, host, path) = match split_http_url(&resolved) {
334 Some(t) => t,
335 None => return Err("only absolute http(s) and data URLs are supported"),
336 };
337 let stack = crate::os_lib::platform::TcpIpStack::new();
338 let mut hdrs: Vec<(String, String)> = headers
340 .iter()
341 .filter(|(k, v)| request_header_allowed(k, v))
342 .cloned()
343 .collect();
344 if let Some((b_https, b_host, b_path)) = split_http_url(base) {
345 let m = method.to_ascii_uppercase();
346 if m != "GET" && m != "HEAD" {
347 hdrs.push((String::from("Origin"), format!("{}://{}", if b_https { "https" } else { "http" }, b_host)));
348 }
349 if let Some(r) = crate::os_lib::web_engine::referrer::referrer_for(b_https, &b_host, &b_path, is_https, &host) {
350 hdrs.push((String::from("Referer"), r));
351 }
352 }
353 if !hdrs.iter().any(|(k, _)| k.eq_ignore_ascii_case("cookie")) {
355 let cookie_str = crate::os_lib::web_apis::builtins::web_forms::cookie_string();
356 if !cookie_str.is_empty() {
357 hdrs.push((String::from("Cookie"), cookie_str));
358 }
359 }
360
361 let is_get = method.eq_ignore_ascii_case("GET");
363 let now_sec = crate::os_lib::platform::unix_time()
364 .unwrap_or_else(|| crate::os_lib::platform::now_ms() / 1000);
365 if is_get {
366 let req_hdr_pairs: Vec<(&str, &str)> = hdrs.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
367 let lookup_res = crate::os_lib::platform::http_cache().lookup_with_headers(&resolved, &req_hdr_pairs, now_sec);
368 match lookup_res {
369 crate::os_lib::platform::CacheLookup::Hit { body: cached_body, status_code } => {
370 let body_str = String::from_utf8_lossy(&cached_body).into_owned();
371 let mut resp_hdrs = alloc::collections::BTreeMap::new();
372 resp_hdrs.insert(String::from("x-atmos-cache"), String::from("HIT"));
373 return Ok((status_code, body_str, cached_body, resp_hdrs));
374 }
375 crate::os_lib::platform::CacheLookup::Revalidate { conditional_headers } => {
376 for (ck, cv) in conditional_headers {
377 if !hdrs.iter().any(|(ex_k, _)| ex_k.eq_ignore_ascii_case(&ck)) {
378 hdrs.push((ck, cv));
379 }
380 }
381 }
382 crate::os_lib::platform::CacheLookup::Miss => {}
383 }
384 }
385
386 let hdr_refs: Vec<(&str, &str)> = hdrs.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
387 let _exempt = crate::os_lib::web_engine::site_hooks::hooks().is_streaming_url(&host, &path)
390 .then(|| crate::os_lib::platform::begin_exempt(&host, &path));
391 match stack.web_request(
392 is_https,
393 &host,
394 &path,
395 method,
396 content_type,
397 body,
398 &hdr_refs,
399 ) {
400 Ok(resp) => {
401 for (k, v) in &resp.headers {
403 if k.eq_ignore_ascii_case("set-cookie") {
404 crate::os_lib::web_apis::builtins::web_forms::cookie_set(v);
405 }
406 }
407
408 if resp.status_code == 304 && is_get {
410 let mut cache = crate::os_lib::platform::http_cache();
411 let hdr_pairs: Vec<(&str, &str)> = resp.headers.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
412 if let Some(cached_body) = cache.handle_304(&resolved, &hdr_pairs, now_sec) {
413 let body_str = String::from_utf8_lossy(&cached_body).into_owned();
414 let mut out_hdrs = resp.headers.clone();
415 out_hdrs.insert(String::from("x-atmos-cache"), String::from("REVALIDATED"));
416 return Ok((200, body_str, cached_body, out_hdrs));
417 }
418 } else if resp.status_code >= 200 && resp.status_code < 300 && is_get {
419 let mut cache = crate::os_lib::platform::http_cache();
420 let hdr_pairs: Vec<(&str, &str)> = resp.headers.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
421 let req_hdr_pairs: Vec<(&str, &str)> = hdrs.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
422 cache.put_with_request_headers(&resolved, resp.status_code, &hdr_pairs, &req_hdr_pairs, &resp.body_bytes, now_sec);
423 }
424
425 if resp.status_code >= 400 {
426 crate::warn!(
427 "[XHR] HTTP {} {} {}: {}",
428 resp.status_code,
429 method,
430 resolved.chars().take(120).collect::<String>(),
431 String::from_utf8_lossy(&resp.body_bytes).chars().take(200).collect::<String>().replace('\n', " ")
432 );
433 }
434 let declared = resp
437 .headers
438 .iter()
439 .find(|(k, _)| k.eq_ignore_ascii_case("content-length"))
440 .and_then(|(_, v)| v.trim().parse::<usize>().ok());
441 if let Some(len) = declared {
442 if resp.body.len() < len {
443 crate::warn!("[XHR] 途中切れ url={} 受信={} Content-Length={}", resolved, resp.body.len(), len);
444 }
445 }
446 Ok((resp.status_code, resp.body, resp.body_bytes, resp.headers))
447 }
448 Err(_) => Err("network error"),
449 }
450}
451
452pub(crate) fn headers_ctor(_it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
459 Ok(make_headers(arg(a, 0)))
460}
461pub(crate) fn make_headers(init: Value) -> Value {
464 let o = Obj::plain();
465 if let Value::Object(io) = &init {
468 let is_headers_like = io.borrow().props.contains_key("_is_headers");
469 let is_array = matches!(&io.borrow().kind, ObjKind::Array(_));
470 if is_array {
471 if let ObjKind::Array(items) = &io.borrow().kind {
472 for pair in items {
473 if let Value::Object(p) = pair {
474 if let ObjKind::Array(kv) = &p.borrow().kind {
475 if kv.len() >= 2 {
476 let k = kv[0].to_js_string().to_lowercase();
477 o.borrow_mut().props.insert(k.into(), Value::str(kv[1].to_js_string()));
478 }
479 }
480 }
481 }
482 }
483 } else {
484 let entries: Vec<(String, Value)> =
485 io.borrow().props.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();
486 for (k, v) in entries {
487 if matches!(&v, Value::Object(f) if f.borrow().is_callable()) {
489 continue;
490 }
491 let key = k.to_lowercase();
492 o.borrow_mut().props.insert(key.into(), Value::str(v.to_js_string()));
493 }
494 let _ = is_headers_like;
495 }
496 }
497 {
498 let mut b = o.borrow_mut();
499 b.props.insert("_is_headers".into(), Value::Bool(true));
500 b.props.insert("get".into(), nv("get", headers_get));
501 b.props.insert("set".into(), nv("set", headers_set));
502 b.props.insert("append".into(), nv("append", headers_append));
503 b.props.insert("has".into(), nv("has", headers_has));
504 b.props.insert("delete".into(), nv("delete", headers_delete));
505 b.props
506 .insert("forEach".into(), nv("forEach", headers_for_each));
507 b.props.insert("entries".into(), nv("entries", headers_entries));
510 b.props.insert("keys".into(), nv("keys", headers_keys));
511 b.props.insert("values".into(), nv("values", headers_values));
512 b.props.insert(
513 "getSetCookie".into(),
514 nv("getSetCookie", headers_get_set_cookie),
515 );
516 b.props.insert(
517 "Symbol(Symbol.iterator)".into(),
518 nv("[Symbol.iterator]", headers_entries),
519 );
520 }
521 Value::Object(o)
522}
523pub(crate) fn headers_key(a: &[Value]) -> String {
524 arg(a, 0).to_js_string().to_lowercase()
525}
526pub(crate) fn headers_get_set_cookie(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
527 if let Value::Object(o) = &this {
528 if let Some(v) = o.borrow().props.get("set-cookie") {
529 if !matches!(v, Value::Object(f) if f.borrow().is_callable()) {
530 let val_str = v.to_js_string();
531 if !val_str.is_empty() {
532 let cookies: Vec<Value> = val_str
533 .split(", ")
534 .map(|s| Value::str(s.to_string()))
535 .collect();
536 return Ok(Value::Object(Obj::array(cookies)));
537 }
538 }
539 }
540 }
541 Ok(Value::Object(Obj::array(Vec::new())))
542}
543pub(crate) fn headers_entries_sorted(this: &Value) -> Vec<(String, String)> {
547 let mut entries: Vec<(String, String)> = match this {
548 Value::Object(o) => o
549 .borrow()
550 .props
551 .iter()
552 .filter(|(k, v)| {
553 k.as_str() != "_is_headers" && !matches!(v, Value::Object(f) if f.borrow().is_callable())
554 })
555 .map(|(k, v)| (k.to_string(), v.to_js_string()))
556 .collect(),
557 _ => Vec::new(),
558 };
559 entries.sort_by(|a, b| a.0.cmp(&b.0));
560 entries
561}
562pub(crate) fn headers_get(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
563 if let Value::Object(o) = &this {
564 if let Some(v) = o.borrow().props.get(&headers_key(a)) {
565 if !matches!(v, Value::Object(f) if f.borrow().is_callable()) {
566 return Ok(v.clone());
567 }
568 }
569 }
570 Ok(Value::Null)
571}
572pub(crate) fn headers_set(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
573 if let Value::Object(o) = &this {
574 o.borrow_mut()
575 .props
576 .insert(headers_key(a).into(), Value::str(arg(a, 1).to_js_string()));
577 }
578 Ok(Value::Undefined)
579}
580pub(crate) fn headers_append(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
583 if let Value::Object(o) = &this {
584 let key = headers_key(a);
585 let v = arg(a, 1).to_js_string();
586 let existing = o.borrow().props.get(&key).map(|v| v.to_js_string());
587 let merged = match existing {
588 Some(e) if !e.is_empty() => alloc::format!("{}, {}", e, v),
589 _ => v,
590 };
591 o.borrow_mut().props.insert(key.into(), Value::str(merged));
592 }
593 Ok(Value::Undefined)
594}
595pub(crate) fn headers_has(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
596 if let Value::Object(o) = &this {
597 let key = headers_key(a);
598 let has = matches!(o.borrow().props.get(&key), Some(v) if !matches!(v, Value::Object(f) if f.borrow().is_callable()));
599 return Ok(Value::Bool(has));
600 }
601 Ok(Value::Bool(false))
602}
603pub(crate) fn headers_delete(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
604 if let Value::Object(o) = &this {
605 o.borrow_mut().props.shift_remove(&headers_key(a));
606 }
607 Ok(Value::Undefined)
608}
609pub(crate) fn headers_for_each(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
610 let cb = arg(a, 0);
611 for (k, v) in headers_entries_sorted(&this) {
612 it.call_value(&cb, Value::Undefined, &[Value::str(v), Value::str(k), this.clone()])?;
613 }
614 Ok(Value::Undefined)
615}
616pub(crate) fn headers_entries(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
619 let items: Vec<Value> = headers_entries_sorted(&this)
620 .into_iter()
621 .map(|(k, v)| Value::Object(Obj::array(alloc::vec![Value::str(k), Value::str(v)])))
622 .collect();
623 Ok(Value::Object(make_iterator(items)))
624}
625pub(crate) fn headers_keys(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
626 let items: Vec<Value> = headers_entries_sorted(&this)
627 .into_iter()
628 .map(|(k, _)| Value::str(k))
629 .collect();
630 Ok(Value::Object(make_iterator(items)))
631}
632pub(crate) fn headers_values(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
633 let items: Vec<Value> = headers_entries_sorted(&this)
634 .into_iter()
635 .map(|(_, v)| Value::str(v))
636 .collect();
637 Ok(Value::Object(make_iterator(items)))
638}
639
640pub(crate) fn headers_list(headers: &Value) -> Vec<(String, String)> {
643 let mut out = Vec::new();
644 if let Value::Object(o) = headers {
645 for (k, val) in o.borrow().props.iter() {
646 if k.starts_with('_') || matches!(val, Value::Object(f) if f.borrow().is_callable()) {
647 continue;
648 }
649 out.push((k.to_string(), val.to_js_string()));
650 }
651 }
652 out
653}
654
655pub(crate) fn headers_content_type(headers: &Value) -> Option<String> {
656 if let Value::Object(o) = headers {
657 for (k, val) in o.borrow().props.iter() {
658 if k.eq_ignore_ascii_case("content-type") {
659 return Some(val.to_js_string());
660 }
661 }
662 }
663 None
664}
665
666pub(crate) fn body_to_string(v: &Value) -> String {
669 if let Value::Object(o) = v {
670 let b = o.borrow();
671 if let Some(q) = b.props.get("_query") {
672 return q.to_js_string();
673 }
674 if let Some(Value::Object(arr)) = b.props.get("_blob_bytes") {
677 if let ObjKind::Array(items) = &arr.borrow().kind {
678 let bytes: alloc::vec::Vec<u8> = items
679 .iter()
680 .map(|x| match x {
681 Value::Number(n) => *n as u8,
682 _ => 0,
683 })
684 .collect();
685 return String::from_utf8_lossy(&bytes).into_owned();
686 }
687 }
688 }
689 v.to_js_string()
690}
691
692pub(crate) fn request_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
697 let input = arg(a, 0);
698 let opts = arg(a, 1);
699 let is_request_like = matches!(&input, Value::Object(o) if o.borrow().props.contains_key("url"));
700 let url = if is_request_like {
701 let u = obj_prop(&input, "url").unwrap_or(Value::Undefined);
702 it.to_string_value(u)?
703 } else {
704 it.to_string_value(input.clone())?
706 };
707 let method = obj_prop(&opts, "method")
708 .or_else(|| if is_request_like { obj_prop(&input, "method") } else { None })
709 .map(|v| v.to_js_string())
710 .unwrap_or_else(|| String::from("GET"));
711 let body = obj_prop(&opts, "body")
714 .or_else(|| if is_request_like { obj_prop(&input, "_body") } else { None })
715 .map(|v| match v {
716 Value::Object(_) | Value::Str(_) => v,
717 Value::Undefined | Value::Null => Value::str(""),
718 other => Value::str(other.to_js_string()),
719 })
720 .unwrap_or_else(|| Value::str(""));
721 let headers_raw = obj_prop(&opts, "headers")
726 .or_else(|| if is_request_like { obj_prop(&input, "headers") } else { None })
727 .unwrap_or(Value::Undefined);
728 let headers = make_headers(headers_raw);
729 let signal = obj_prop(&opts, "signal")
730 .or_else(|| if is_request_like { obj_prop(&input, "signal") } else { None })
731 .unwrap_or(Value::Undefined);
732 let req = Obj::plain();
733 {
734 let mut r = req.borrow_mut();
735 r.props.insert("url".into(), Value::str(url.clone()));
736 r.props.insert("method".into(), Value::str(method.clone()));
737 r.props.insert("_req_url".into(), Value::str(url));
741 r.props.insert("_req_method".into(), Value::str(method));
742 r.props.insert("_body".into(), body);
743 r.props.insert("headers".into(), headers);
744 r.props.insert("signal".into(), signal);
745 }
746 Ok(Value::Object(req))
747}
748
749pub(crate) fn navigator_send_beacon(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
756 let url = arg(a, 0).to_js_string();
757 let data = arg(a, 1);
758 let resolved = resolve_url(&it.base_url, &url);
764 if resolved.starts_with("data:") {
765 return Ok(Value::Bool(true));
766 }
767 let body = if matches!(data, Value::Undefined) { String::new() } else { body_to_string(&data) };
768 let content_type = match &data {
769 Value::Object(o) => o
770 .borrow()
771 .props
772 .get("type")
773 .map(|v| v.to_js_string())
774 .filter(|t| !t.is_empty())
775 .unwrap_or_else(|| String::from("text/plain;charset=UTF-8")),
776 _ => String::from("text/plain;charset=UTF-8"),
777 };
778 BEACON_QUEUE.lock().push_back((resolved, body, content_type));
779 if !BEACON_WORKER.swap(true, core::sync::atomic::Ordering::AcqRel) {
780 let pid = crate::os_lib::platform::spawn_shared(
781 beacon_thread,
782 crate::os_lib::platform::Priority::Low,
783 "beacon",
784 );
785 if pid == 0 {
786 BEACON_WORKER.store(false, core::sync::atomic::Ordering::Release);
788 }
789 }
790 Ok(Value::Bool(true))
791}
792
793static BEACON_QUEUE: spin::Mutex<alloc::collections::VecDeque<(String, String, String)>> =
795 spin::Mutex::new(alloc::collections::VecDeque::new());
796static BEACON_WORKER: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
798
799fn beacon_thread() {
801 loop {
802 let job = BEACON_QUEUE.lock().pop_front();
803 match job {
804 Some((url, body, content_type)) => {
805 match do_http_request("", &url, "POST", &body, &content_type) {
806 Ok((status, _)) => crate::debug!("[BEACON] sent status={} url={}", status, url),
807 Err(e) => crate::warn!("[BEACON] 送信失敗 url={} err={}", url, e),
808 }
809 crate::os_lib::platform::yield_now();
810 }
811 None => {
812 BEACON_WORKER.store(false, core::sync::atomic::Ordering::Release);
813 if BEACON_QUEUE.lock().is_empty()
815 || BEACON_WORKER.swap(true, core::sync::atomic::Ordering::AcqRel)
816 {
817 return;
818 }
819 }
820 }
821 }
822}
823
824pub(crate) fn make_geolocation_error() -> Value {
828 let o = Obj::plain();
829 let mut b = o.borrow_mut();
830 b.props.insert("code".into(), Value::Number(1.0));
831 b.props.insert(
832 "message".into(),
833 Value::str("Geolocation is not supported in this environment"),
834 );
835 b.props.insert("PERMISSION_DENIED".into(), Value::Number(1.0));
836 b.props.insert("POSITION_UNAVAILABLE".into(), Value::Number(2.0));
837 b.props.insert("TIMEOUT".into(), Value::Number(3.0));
838 drop(b);
839 Value::Object(o)
840}
841pub(crate) fn geolocation_get_current_position(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
846 if let Some(err_cb) = callable_or_none(arg(a, 1)) {
847 it.call_listener(
848 &err_cb,
849 Value::Undefined,
850 &[make_geolocation_error()],
851 "geolocation error callback",
852 );
853 }
854 Ok(Value::Undefined)
855}
856pub(crate) fn geolocation_watch_position(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
860 geolocation_get_current_position(it, this, a)?;
861 Ok(Value::Number(TIMER_ID.fetch_add(1, Ordering::Relaxed) as f64))
862}
863pub(crate) fn geolocation_clear_watch(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
865 Ok(Value::Undefined)
866}
867pub(crate) fn permissions_query(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
871 let name = obj_prop(&arg(a, 0), "name").map(|v| v.to_js_string()).unwrap_or_default();
872 let state = match name.as_str() {
873 "geolocation" | "camera" | "microphone" => "denied",
874 "notifications" => "granted",
875 _ => "prompt",
876 };
877 let status = Obj::plain();
878 {
879 let mut b = status.borrow_mut();
880 b.props.insert("state".into(), Value::str(state));
881 b.props.insert("name".into(), Value::str(name));
882 b.props.insert("onchange".into(), Value::Null);
883 }
884 Ok(resolved_promise(it, Value::Object(status)))
885}
886
887pub(crate) fn wake_lock_request(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
891 let ty = arg(a, 0).to_js_string();
892 let ty = if ty.is_empty() { String::from("screen") } else { ty };
893 let sentinel = Obj::plain();
894 {
895 let mut b = sentinel.borrow_mut();
896 b.props.insert("released".into(), Value::Bool(false));
897 b.props.insert("type".into(), Value::str(ty));
898 b.props
899 .insert("release".into(), nv("WakeLockSentinel.release", wake_lock_sentinel_release));
900 }
901 Ok(resolved_promise(it, Value::Object(sentinel)))
902}
903pub(crate) fn wake_lock_sentinel_release(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
905 if let Value::Object(o) = &this {
906 o.borrow_mut().props.insert("released".into(), Value::Bool(true));
907 }
908 Ok(resolved_promise(it, Value::Undefined))
909}
910
911pub(crate) fn navigator_can_share(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
915 Ok(Value::Bool(false))
916}
917pub(crate) fn navigator_share(it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
921 let err = Obj::plain();
922 {
923 let mut b = err.borrow_mut();
924 b.props.insert("name".into(), Value::str("AbortError"));
925 b.props.insert(
926 "message".into(),
927 Value::str("Share was cancelled: no share target available in this environment"),
928 );
929 }
930 Ok(rejected_promise(it, Value::Object(err)))
931}
932
933pub(crate) fn eye_dropper_ctor(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
936 let o = Obj::plain();
937 o.borrow_mut().props.insert("open".into(), nv("EyeDropper.open", eye_dropper_open));
938 Ok(Value::Object(o))
939}
940pub(crate) fn eye_dropper_open(it: &mut Interp, _this: Value, _a: &[Value]) -> Result<Value, Value> {
944 let err = Obj::plain();
945 {
946 let mut b = err.borrow_mut();
947 b.props.insert("name".into(), Value::str("AbortError"));
948 b.props.insert(
949 "message".into(),
950 Value::str("The color picker was cancelled: no picker UI available in this environment"),
951 );
952 }
953 Ok(rejected_promise(it, Value::Object(err)))
954}
955
956pub(crate) fn navigator_vibrate(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
960 Ok(Value::Bool(true))
961}
962
963pub(crate) fn navigator_locks_request(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
972 let cb = if matches!(arg(a, 2), Value::Object(o) if o.borrow().is_callable()) {
973 arg(a, 2)
974 } else {
975 arg(a, 1)
976 };
977 let name = arg(a, 0).to_js_string();
978 let lock = Obj::plain();
979 {
980 let mut b = lock.borrow_mut();
981 b.props.insert("name".into(), Value::str(name));
982 b.props.insert("mode".into(), Value::str("exclusive"));
983 }
984 let result = it.call_value(&cb, Value::Undefined, &[Value::Object(lock)])?;
985 Ok(resolved_promise(it, result))
986}
987pub(crate) fn navigator_locks_query(it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
990 let o = Obj::plain();
991 {
992 let mut b = o.borrow_mut();
993 b.props.insert("held".into(), Value::Object(Obj::array(alloc::vec![])));
994 b.props.insert("pending".into(), Value::Object(Obj::array(alloc::vec![])));
995 }
996 Ok(resolved_promise(it, Value::Object(o)))
997}
998pub(crate) fn navigator_get_battery(it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
999 let battery = Obj::plain();
1000 {
1001 let mut b = battery.borrow_mut();
1002 b.props.insert("charging".into(), Value::Bool(true));
1003 b.props.insert("chargingTime".into(), Value::Number(0.0));
1004 b.props.insert("dischargingTime".into(), Value::Number(f64::INFINITY));
1005 b.props.insert("level".into(), Value::Number(1.0));
1006 b.props
1007 .insert("addEventListener".into(), nv("addEventListener", dom_noop));
1008 b.props
1009 .insert("removeEventListener".into(), nv("removeEventListener", dom_noop));
1010 }
1011 Ok(resolved_promise(it, Value::Object(battery)))
1012}
1013
1014pub(crate) fn fetch(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1017 let first = arg(a, 0);
1018 let is_request_like = matches!(&first, Value::Object(o) if o.borrow().props.contains_key("url") || o.borrow().props.contains_key("_req_url"));
1022 let url = if let Some(u) = obj_prop(&first, "_req_url") {
1023 u.to_js_string()
1024 } else if is_request_like {
1025 let u = obj_prop(&first, "url").unwrap_or(Value::Undefined);
1026 it.to_string_value(u)?
1027 } else {
1028 it.to_string_value(first.clone())?
1029 };
1030 let opts = arg(a, 1);
1031 let method = obj_prop(&opts, "method")
1032 .or_else(|| if is_request_like { obj_prop(&first, "_req_method").or_else(|| obj_prop(&first, "method")) } else { None })
1033 .map(|v| v.to_js_string())
1034 .unwrap_or_else(|| String::from("GET"));
1035 let body = obj_prop(&opts, "body")
1036 .or_else(|| if is_request_like { obj_prop(&first, "_body") } else { None })
1037 .map(|v| body_to_bytes(&v))
1038 .unwrap_or_default();
1039 let headers = obj_prop(&opts, "headers")
1040 .or_else(|| if is_request_like { obj_prop(&first, "headers") } else { None })
1041 .unwrap_or(Value::Undefined);
1042 let content_type =
1043 headers_content_type(&headers).unwrap_or_else(|| String::from("text/plain;charset=UTF-8"));
1044 let signal_opt = obj_prop(&opts, "signal")
1051 .or_else(|| if is_request_like { obj_prop(&first, "signal") } else { None });
1052 if let Some(signal) = signal_opt {
1053 let already_aborted = matches!(&signal, Value::Object(o) if matches!(o.borrow().props.get("aborted"), Some(Value::Bool(true))));
1054 if already_aborted {
1055 let reason = match &signal {
1056 Value::Object(o) => o.borrow().props.get("reason").cloned().unwrap_or(Value::Undefined),
1057 _ => Value::Undefined,
1058 };
1059 return Ok(rejected_promise(it, reason));
1060 }
1061 }
1062 let base = it.base_url.clone();
1063 let resolved_url = resolve_url(&base, &url);
1064 let req_headers = headers_list(&headers);
1065 if split_http_url(&resolved_url).is_some() {
1069 let state = super::promise::new_pending();
1070 let promise = Value::Object(Obj::promise(state));
1071 let marker = Obj::plain();
1072 {
1073 let mut m = marker.borrow_mut();
1074 m.props.insert("_is_fetch".into(), Value::Bool(true));
1075 m.props.insert("_fetch_promise".into(), promise.clone());
1076 m.props.insert("_fetch_url".into(), Value::str(resolved_url.clone()));
1077 }
1078 let id = XHR_ID_GEN.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
1079 let req = XhrRequestData {
1080 id,
1081 base: base.clone(),
1082 url: url.clone(),
1083 method: method.clone(),
1084 body: body.clone(),
1085 content_type: content_type.clone(),
1086 headers: req_headers.clone(),
1087 group: crate::os_lib::platform::current_mem_group(),
1088 host: String::new(),
1089 runtime: it.runtime_id,
1090 };
1091 if start_async_request(req).is_ok() {
1092 it.pending_xhrs().borrow_mut().insert(id, Value::Object(marker));
1093 return Ok(promise);
1094 }
1095 }
1096 match do_http_request_raw(&base, &url, &method, &body, &content_type, &req_headers) {
1097 Ok((status, body, bytes)) => {
1098 let resp = make_response_with_url(status, body, resolved_url);
1099 attach_raw_body(&resp, &bytes);
1100 let stream = super::streams::make_readable_stream_from_bytes(it, &bytes);
1102 if let Value::Object(r) = &resp {
1103 r.borrow_mut().props.insert("body".into(), stream);
1104 }
1105 Ok(resolved_promise(it, resp))
1106 }
1107 Err(msg) => Ok(rejected_promise(it, it.error(format!("fetch: {}", msg)))),
1108 }
1109}
1110
1111pub(crate) fn xhr_ctor(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
1114 let o = Obj::plain();
1115 {
1116 let mut b = o.borrow_mut();
1117 b.props.insert("UNSENT".into(), Value::Number(0.0));
1118 b.props.insert("OPENED".into(), Value::Number(1.0));
1119 b.props.insert("HEADERS_RECEIVED".into(), Value::Number(2.0));
1120 b.props.insert("LOADING".into(), Value::Number(3.0));
1121 b.props.insert("DONE".into(), Value::Number(4.0));
1122 b.props.insert("readyState".into(), Value::Number(0.0));
1123 b.props.insert("status".into(), Value::Number(0.0));
1124 b.props.insert("statusText".into(), Value::str(""));
1125 b.props.insert("responseText".into(), Value::str(""));
1126 b.props.insert("response".into(), Value::str(""));
1127 b.props.insert("open".into(), nv("open", xhr_open));
1128 b.props.insert("send".into(), nv("send", xhr_send));
1129 b.props.insert(
1130 "setRequestHeader".into(),
1131 nv("setRequestHeader", xhr_set_request_header),
1132 );
1133 b.props.insert("abort".into(), nv("abort", xhr_abort));
1134 b.props.insert(
1135 "getAllResponseHeaders".into(),
1136 nv("getAllResponseHeaders", xhr_get_all_response_headers),
1137 );
1138 b.props.insert(
1139 "getResponseHeader".into(),
1140 nv("getResponseHeader", xhr_get_response_header),
1141 );
1142 b.props.insert(
1143 "addEventListener".into(),
1144 nv("addEventListener", xhr_add_event_listener),
1145 );
1146 b.props.insert(
1147 "removeEventListener".into(),
1148 nv("removeEventListener", xhr_remove_event_listener),
1149 );
1150 b.props.insert(
1151 "dispatchEvent".into(),
1152 nv("dispatchEvent", xhr_dispatch_event),
1153 );
1154 }
1155 Ok(Value::Object(o))
1156}
1157
1158pub(crate) fn xhr_noop(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
1159 Ok(Value::Undefined)
1160}
1161
1162pub(crate) fn xhr_set_request_header(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1164 if let Value::Object(o) = &this {
1165 let name = arg(a, 0).to_js_string();
1166 let value = arg(a, 1).to_js_string();
1167 if name.eq_ignore_ascii_case("content-type") {
1168 o.borrow_mut().props.insert("_content_type".into(), Value::str(value));
1169 } else {
1170 let hdrs = o.borrow().props.get("_req_headers").cloned();
1172 let hdrs = match hdrs {
1173 Some(Value::Object(h)) => h,
1174 _ => {
1175 let h = Obj::plain();
1176 o.borrow_mut().props.insert("_req_headers".into(), Value::Object(h.clone()));
1177 h
1178 }
1179 };
1180 hdrs.borrow_mut().props.insert(name.into(), Value::str(value));
1181 }
1182 }
1183 Ok(Value::Undefined)
1184}
1185
1186pub(crate) fn xhr_empty_str(_it: &mut Interp, _t: Value, _a: &[Value]) -> Result<Value, Value> {
1187 Ok(Value::str(""))
1188}
1189pub(crate) fn xhr_get_response_header(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1190 let name = arg(a, 0).to_js_string();
1191 if let Value::Object(o) = &this {
1192 if let Some(Value::Object(h)) = o.borrow().props.get("_resp_headers") {
1193 let mut map = alloc::collections::BTreeMap::new();
1194 for (k, v) in h.borrow().props.iter() {
1195 map.insert(String::from(k.as_str()), v.to_js_string());
1196 }
1197 if let Some(found) = crate::os_lib::web_apis::xhr_state::lookup_response_header(&map, &name) {
1198 return Ok(Value::str(found));
1199 }
1200 }
1201 }
1202 Ok(Value::Null)
1203}
1204
1205pub(crate) fn xhr_get_all_response_headers(_it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1207 if let Value::Object(o) = &this {
1208 if let Some(Value::Object(h)) = o.borrow().props.get("_resp_headers") {
1209 let mut map = alloc::collections::BTreeMap::new();
1210 for (k, v) in h.borrow().props.iter() {
1211 map.insert(String::from(k.as_str()), v.to_js_string());
1212 }
1213 return Ok(Value::str(
1214 crate::os_lib::web_apis::xhr_state::format_all_response_headers(&map),
1215 ));
1216 }
1217 }
1218 Ok(Value::str(""))
1219}
1220
1221pub(crate) fn xhr_add_event_listener(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1223 if let Value::Object(o) = &this {
1224 let evt_type = arg(a, 0).to_js_string();
1225 let cb = arg(a, 1);
1226 if callable_or_none(cb.clone()).is_none() {
1227 return Ok(Value::Undefined);
1228 }
1229 let list_key = format!("_listeners_{evt_type}");
1230 let existing = o.borrow().props.get(&list_key).cloned();
1231 match existing {
1232 Some(Value::Object(arr)) => {
1233 if let ObjKind::Array(ref mut items) = arr.borrow_mut().kind {
1234 let dup = items.iter().any(|item| match (item, &cb) {
1235 (Value::Object(a), Value::Object(b)) => Rc::ptr_eq(a, b),
1236 _ => false,
1237 });
1238 if !dup {
1239 items.push(cb);
1240 }
1241 }
1242 }
1243 _ => {
1244 let arr = Obj::array(alloc::vec![cb]);
1245 o.borrow_mut().props.insert(list_key.into(), Value::Object(arr));
1246 }
1247 }
1248 }
1249 Ok(Value::Undefined)
1250}
1251
1252pub(crate) fn xhr_remove_event_listener(_it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1254 if let Value::Object(o) = &this {
1255 let evt_type = arg(a, 0).to_js_string();
1256 let target = arg(a, 1);
1257 let list_key = format!("_listeners_{evt_type}");
1258 let existing = o.borrow().props.get(&list_key).cloned();
1259 if let Some(Value::Object(arr)) = existing {
1260 if let ObjKind::Array(ref mut items) = arr.borrow_mut().kind {
1261 items.retain(|item| !match (item, &target) {
1262 (Value::Object(stored), Value::Object(t)) => Rc::ptr_eq(stored, t),
1263 _ => false,
1264 });
1265 }
1266 }
1267 let on_key = format!("on{evt_type}");
1268 let matches = match (o.borrow().props.get(&on_key), &target) {
1269 (Some(Value::Object(stored)), Value::Object(t)) => Rc::ptr_eq(stored, t),
1270 _ => false,
1271 };
1272 if matches {
1273 o.borrow_mut().props.shift_remove(&on_key);
1274 }
1275 }
1276 Ok(Value::Undefined)
1277}
1278
1279pub(crate) fn xhr_dispatch_event(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1280 let ev = arg(a, 0);
1281 super::events::validate_dispatch_event(it, &ev)?;
1282 it.retarget_event_related_target(&ev);
1283 let Value::Object(o) = &this else {
1284 return Ok(Value::Bool(true));
1285 };
1286 let evt_type = if let Value::Object(eo) = &ev {
1287 eo.borrow().props.get("type").map(|v| v.to_js_string()).unwrap_or_default()
1288 } else {
1289 String::new()
1290 };
1291 if let Value::Object(eo) = &ev {
1292 let mut e = eo.borrow_mut();
1293 e.props.insert("_dispatch".into(), Value::Bool(true));
1294 e.props.insert("target".into(), this.clone());
1295 e.props.insert("srcElement".into(), this.clone());
1296 e.props.insert("currentTarget".into(), this.clone());
1297 e.props.insert("eventPhase".into(), Value::Number(2.0));
1298 e.props.insert("_composedPath".into(), Value::Object(Obj::array(alloc::vec![this.clone()])));
1299 }
1300 let prev_win = super::events::swap_window_event(it, ev.clone());
1301 let on_cb = o.borrow().props.get(&format!("on{evt_type}")).cloned();
1302 if let Some(cb @ Value::Object(_)) = on_cb {
1303 super::events::invoke_event_listener(it, &cb, this.clone(), &ev, "xhr.on");
1304 }
1305 let listeners: alloc::vec::Vec<Value> = match o.borrow().props.get(&format!("_listeners_{evt_type}")) {
1306 Some(Value::Object(arr)) => match &arr.borrow().kind {
1307 ObjKind::Array(items) => items.clone(),
1308 _ => alloc::vec::Vec::new(),
1309 },
1310 _ => alloc::vec::Vec::new(),
1311 };
1312 for cb in listeners {
1313 super::events::invoke_event_listener(it, &cb, this.clone(), &ev, "xhr listener");
1314 }
1315 super::events::restore_window_event(it, prev_win);
1316 if let Value::Object(eo) = &ev {
1317 let mut e = eo.borrow_mut();
1318 e.props.insert("_dispatch".into(), Value::Bool(false));
1319 e.props.insert("currentTarget".into(), Value::Null);
1320 e.props.insert("eventPhase".into(), Value::Number(0.0));
1321 e.props.insert("_composedPath".into(), Value::Object(Obj::array(alloc::vec::Vec::new())));
1322 }
1323 let default_prevented = if let Value::Object(eo) = &ev {
1324 matches!(eo.borrow().props.get("defaultPrevented"), Some(Value::Bool(true)))
1325 } else {
1326 false
1327 };
1328 Ok(Value::Bool(!default_prevented))
1329}
1330
1331pub(crate) fn fire_xhr_target_event(
1333 it: &mut Interp,
1334 this: &Value,
1335 evt_type: &str,
1336 loaded: usize,
1337 total: usize,
1338 ctx_prefix: &str,
1339) {
1340 let Value::Object(o) = this else { return };
1341 let on_cb = o.borrow().props.get(&format!("on{evt_type}")).cloned();
1342 let listeners: alloc::vec::Vec<Value> = match o.borrow().props.get(&format!("_listeners_{evt_type}")) {
1343 Some(Value::Object(arr)) => match &arr.borrow().kind {
1344 ObjKind::Array(items) => items.clone(),
1345 _ => alloc::vec::Vec::new(),
1346 },
1347 _ => alloc::vec::Vec::new(),
1348 };
1349 if on_cb.is_none() && listeners.is_empty() {
1350 return;
1351 }
1352 let ev = Obj::plain();
1353 {
1354 let mut b = ev.borrow_mut();
1355 b.props.insert("type".into(), Value::str(evt_type));
1356 b.props.insert("target".into(), this.clone());
1357 b.props.insert("currentTarget".into(), this.clone());
1358 b.props.insert("loaded".into(), Value::Number(loaded as f64));
1359 b.props.insert("total".into(), Value::Number(total as f64));
1360 b.props.insert("lengthComputable".into(), Value::Bool(total > 0));
1361 }
1362 let args = [Value::Object(ev)];
1363 let ctx = format!("{ctx_prefix} on{evt_type}");
1364 if let Some(f) = on_cb.and_then(callable_or_none) {
1365 it.call_listener(&f, this.clone(), &args, &ctx);
1366 }
1367 for l in listeners {
1368 if let Some(f) = callable_or_none(l) {
1369 it.call_listener(&f, this.clone(), &args, &ctx);
1370 }
1371 }
1372}
1373
1374pub(crate) fn xhr_abort(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1375 let Value::Object(o) = &this else {
1376 return Ok(Value::Undefined);
1377 };
1378 let (async_id, was_sent, prev_rs) = {
1379 let b = o.borrow();
1380 let id = b.props.get("_async_id").map(|v| v.to_number() as u64);
1381 let sent = b.props.get("_sent").map(|v| v.truthy()).unwrap_or(false);
1382 let rs = b.props.get("readyState").map(|v| v.to_number() as u8).unwrap_or(0);
1383 (id, sent, rs)
1384 };
1385 if let Some(id) = async_id {
1386 it.pending_xhrs().borrow_mut().remove(&id);
1387 let mut q = XHR_REQUEST_QUEUE.lock();
1388 q.retain(|r| r.id != id);
1389 drop(q);
1390 for i in 0..xhr_sched::MAX_WORKERS {
1392 if XHR_SLOT_REQ[i].load(core::sync::atomic::Ordering::Acquire) == id {
1393 xhr_cancel_slot(i);
1394 }
1395 }
1396 let mut r = XHR_RESULTS.lock();
1397 r.retain(|x| x.id != id);
1398 XHR_RESULTS_LEN.store(r.len(), core::sync::atomic::Ordering::Release);
1399 }
1400 let mut state = crate::os_lib::web_apis::xhr_state::XhrState::new();
1401 state.ready_state = prev_rs;
1402 state.sent = was_sent;
1403 let events = state.abort();
1404 {
1405 let mut b = o.borrow_mut();
1406 b.props.insert("_aborted".into(), Value::Bool(true));
1407 b.props.insert("_sent".into(), Value::Bool(false));
1408 b.props.insert("status".into(), Value::Number(0.0));
1409 b.props.insert("statusText".into(), Value::str(""));
1410 b.props.insert("responseText".into(), Value::str(""));
1411 b.props.insert("response".into(), Value::str(""));
1412 b.props.shift_remove("_resp_headers");
1413 }
1414 for ev in events {
1415 match ev {
1416 crate::os_lib::web_apis::xhr_state::XhrEvent::ReadyStateChange(rs) => {
1417 o.borrow_mut().props.insert("readyState".into(), Value::Number(rs as f64));
1418 fire_xhr_target_event(it, &this, "readystatechange", 0, 0, "XHR");
1419 }
1420 crate::os_lib::web_apis::xhr_state::XhrEvent::Abort => {
1421 fire_xhr_target_event(it, &this, "abort", 0, 0, "XHR");
1422 }
1423 crate::os_lib::web_apis::xhr_state::XhrEvent::LoadEnd { loaded, total } => {
1424 fire_xhr_target_event(it, &this, "loadend", loaded, total, "XHR");
1425 }
1426 _ => {}
1427 }
1428 }
1429 o.borrow_mut().props.insert("readyState".into(), Value::Number(state.ready_state as f64));
1430 Ok(Value::Undefined)
1431}
1432
1433pub struct XhrAsyncResult {
1434 pub id: u64,
1435 pub status: u16,
1436 pub body: String,
1437 pub raw: Vec<u8>,
1438 pub headers: alloc::collections::BTreeMap<String, String>,
1439 pub ok: bool,
1440 pub group: u8,
1442 pub arrived_ms: u64,
1444 pub runtime: u64,
1446}
1447
1448pub struct XhrRequestData {
1449 pub id: u64,
1450 pub base: String,
1451 pub url: String,
1452 pub method: String,
1453 pub body: Vec<u8>,
1454 pub content_type: String,
1455 pub headers: Vec<(String, String)>,
1456 pub group: u8,
1459 pub host: String,
1461 pub runtime: u64,
1464}
1465
1466pub fn forget_xhr_of_group(g: u8) -> (usize, usize) {
1470 let mut dq = 0;
1471 if let Some(mut q) = XHR_REQUEST_QUEUE.try_lock() {
1472 let before = q.len();
1473 q.retain(|r| r.group != g);
1474 dq = before - q.len();
1475 }
1476 let mut dr = 0;
1477 if let Some(mut r) = XHR_RESULTS.try_lock() {
1478 let before = r.len();
1479 r.retain(|x| x.group != g);
1480 dr = before - r.len();
1481 XHR_RESULTS_LEN.store(r.len(), core::sync::atomic::Ordering::Release);
1482 }
1483 (dq, dr)
1484}
1485
1486pub fn forget_xhr_of_runtime(rt: u64) -> (usize, usize, usize) {
1494 if rt == 0 {
1495 return (0, 0, 0);
1496 }
1497 XHR_CLOSED_RT.push(rt);
1498 let mut dq = 0;
1499 let mut df = 0;
1500 if let Some(mut q) = XHR_REQUEST_QUEUE.try_lock() {
1501 let before = q.len();
1502 q.retain(|r| r.runtime != rt);
1503 dq = before - q.len();
1504 }
1505 for i in 0..xhr_sched::MAX_WORKERS {
1508 if XHR_SLOT_RUNTIME[i].load(core::sync::atomic::Ordering::Acquire) == rt {
1509 xhr_cancel_slot(i);
1510 df += 1;
1511 }
1512 }
1513 let mut dr = 0;
1514 if let Some(mut r) = XHR_RESULTS.try_lock() {
1515 let before = r.len();
1516 r.retain(|x| x.runtime != rt);
1517 dr = before - r.len();
1518 XHR_RESULTS_LEN.store(r.len(), core::sync::atomic::Ordering::Release);
1519 }
1520 if dq + dr + df != 0 {
1521 crate::warn!(
1522 "[XHR] 捨てた実行環境 {} の要求 {} 件・結果 {} 件を捨て、取得中 {} 件をやめさせた",
1523 rt,
1524 dq,
1525 dr,
1526 df
1527 );
1528 }
1529 (dq, dr, df)
1530}
1531
1532static XHR_CLOSED_RT: xhr_sched::ClosedRing = xhr_sched::ClosedRing::new();
1534static XHR_SLOT_RUNTIME: [core::sync::atomic::AtomicU64; xhr_sched::MAX_WORKERS] =
1536 [const { core::sync::atomic::AtomicU64::new(0) }; xhr_sched::MAX_WORKERS];
1537static XHR_SLOT_REQ: [core::sync::atomic::AtomicU64; xhr_sched::MAX_WORKERS] =
1538 [const { core::sync::atomic::AtomicU64::new(0) }; xhr_sched::MAX_WORKERS];
1539static XHR_SLOT_CANCEL: [core::sync::atomic::AtomicBool; xhr_sched::MAX_WORKERS] =
1541 [const { core::sync::atomic::AtomicBool::new(false) }; xhr_sched::MAX_WORKERS];
1542static XHR_CANCEL_COUNT: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
1543
1544fn xhr_cancel_slot(i: usize) {
1545 if let Some(c) = XHR_SLOT_CANCEL.get(i) {
1546 if !c.swap(true, core::sync::atomic::Ordering::AcqRel) {
1547 XHR_CANCEL_COUNT.fetch_add(1, core::sync::atomic::Ordering::AcqRel);
1548 }
1549 }
1550}
1551
1552fn xhr_clear_slot(i: usize) -> bool {
1554 if let Some(r) = XHR_SLOT_RUNTIME.get(i) {
1555 r.store(0, core::sync::atomic::Ordering::Release);
1556 }
1557 if let Some(r) = XHR_SLOT_REQ.get(i) {
1558 r.store(0, core::sync::atomic::Ordering::Release);
1559 }
1560 let was = XHR_SLOT_CANCEL.get(i).is_some_and(|c| c.swap(false, core::sync::atomic::Ordering::AcqRel));
1561 if was {
1562 XHR_CANCEL_COUNT.fetch_sub(1, core::sync::atomic::Ordering::AcqRel);
1563 }
1564 was
1565}
1566
1567pub fn xhr_cancelled_for_current() -> bool {
1571 if XHR_CANCEL_COUNT.load(core::sync::atomic::Ordering::Acquire) == 0 {
1572 return false;
1573 }
1574 let Some(pid) = crate::os_lib::platform::current_process_id() else { return false };
1575 if pid == 0 {
1576 return false;
1577 }
1578 (0..xhr_sched::MAX_WORKERS).any(|i| {
1579 XHR_SLOT_PID[i].load(core::sync::atomic::Ordering::Acquire) == pid
1580 && XHR_SLOT_CANCEL[i].load(core::sync::atomic::Ordering::Acquire)
1581 })
1582}
1583
1584pub static XHR_REQUEST_QUEUE: spin::Mutex<alloc::collections::VecDeque<XhrRequestData>> =
1585 spin::Mutex::new(alloc::collections::VecDeque::new());
1586pub static XHR_RESULTS: spin::Mutex<alloc::vec::Vec<XhrAsyncResult>> = spin::Mutex::new(alloc::vec::Vec::new());
1587static XHR_ID_GEN: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(1);
1588
1589use crate::os_lib::web_apis::xhr_sched;
1599
1600struct XhrFlight {
1602 host: String,
1603 group: u8,
1604 slot: usize,
1605}
1606
1607struct XhrPool {
1609 in_flight: alloc::vec::Vec<XhrFlight>,
1610 slot_used: [bool; xhr_sched::MAX_WORKERS],
1611}
1612
1613static XHR_POOL: spin::Mutex<XhrPool> = spin::Mutex::new(XhrPool {
1614 in_flight: alloc::vec::Vec::new(),
1615 slot_used: [false; xhr_sched::MAX_WORKERS],
1616});
1617
1618static XHR_SLOT_PID: [core::sync::atomic::AtomicUsize; xhr_sched::MAX_WORKERS] =
1620 [const { core::sync::atomic::AtomicUsize::new(0) }; xhr_sched::MAX_WORKERS];
1621static XHR_DEAD_SLOTS: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
1623
1624pub fn xhr_pool_on_process_died(pid: usize) {
1627 if pid == 0 {
1628 return;
1629 }
1630 for (i, p) in XHR_SLOT_PID.iter().enumerate() {
1631 if p.compare_exchange(pid, 0, core::sync::atomic::Ordering::AcqRel, core::sync::atomic::Ordering::Acquire).is_ok() {
1632 XHR_DEAD_SLOTS.fetch_or(1 << i, core::sync::atomic::Ordering::AcqRel);
1633 return;
1634 }
1635 }
1636}
1637
1638fn xhr_reap_dead(p: &mut XhrPool) {
1640 let m = XHR_DEAD_SLOTS.swap(0, core::sync::atomic::Ordering::AcqRel);
1641 if m == 0 {
1642 return;
1643 }
1644 for i in 0..xhr_sched::MAX_WORKERS {
1645 if m & (1 << i) != 0 {
1646 p.slot_used[i] = false;
1647 p.in_flight.retain(|f| f.slot != i);
1648 xhr_clear_slot(i);
1649 crate::warn!("[XHR] 途中で止まったワーカーの枠 {} を空きに戻した", i);
1650 }
1651 }
1652}
1653
1654fn xhr_next_pick(q: &alloc::collections::VecDeque<XhrRequestData>, p: &XhrPool) -> Option<usize> {
1656 let flights: alloc::vec::Vec<(&str, u8)> = p.in_flight.iter().map(|f| (f.host.as_str(), f.group)).collect();
1657 xhr_sched::pick_next(
1658 q.iter().map(|r| (r.host.as_str(), r.group)),
1659 &flights,
1660 xhr_sched::MAX_WORKERS,
1661 xhr_sched::MAX_PER_HOST,
1662 )
1663}
1664
1665fn xhr_top_up_workers(q: &alloc::collections::VecDeque<XhrRequestData>, p: &mut XhrPool) -> bool {
1668 let workers = p.slot_used.iter().filter(|u| **u).count();
1669 let startable = xhr_next_pick(q, p).is_some();
1670 if !xhr_sched::need_worker(workers, p.in_flight.len(), startable, xhr_sched::MAX_WORKERS) {
1671 return workers > 0;
1672 }
1673 let Some(slot) = p.slot_used.iter().position(|u| !*u) else { return workers > 0 };
1674 p.slot_used[slot] = true;
1675 let pid = crate::os_lib::platform::spawn_shared(
1677 xhr_worker_thread,
1678 crate::os_lib::platform::Priority::Low,
1679 "xhr_fetch",
1680 );
1681 if pid == 0 {
1682 p.slot_used[slot] = false;
1683 return workers > 0;
1684 }
1685 XHR_SLOT_PID[slot].store(pid, core::sync::atomic::Ordering::Release);
1686 true
1687}
1688
1689fn xhr_finish_flight(slot: usize) {
1691 xhr_clear_slot(slot);
1692 let mut p = XHR_POOL.lock();
1693 if let Some(i) = p.in_flight.iter().position(|f| f.slot == slot) {
1694 p.in_flight.swap_remove(i);
1695 }
1696}
1697
1698fn xhr_worker_thread() {
1699 let my_pid = crate::os_lib::platform::current_process_id().unwrap_or(0);
1700 loop {
1701 let (req, slot) = {
1702 let mut q = XHR_REQUEST_QUEUE.lock();
1703 let mut p = XHR_POOL.lock();
1704 xhr_reap_dead(&mut p);
1705 let mine = (0..xhr_sched::MAX_WORKERS)
1706 .find(|&i| p.slot_used[i] && XHR_SLOT_PID[i].load(core::sync::atomic::Ordering::Acquire) == my_pid);
1707 let picked = match mine {
1708 Some(slot) => xhr_next_pick(&q, &p).and_then(|i| q.remove(i)).map(|r| (r, slot)),
1709 None => None,
1710 };
1711 match picked {
1712 Some((r, slot)) => {
1713 p.in_flight.push(XhrFlight { host: r.host.clone(), group: r.group, slot });
1714 xhr_clear_slot(slot);
1716 XHR_SLOT_RUNTIME[slot].store(r.runtime, core::sync::atomic::Ordering::Release);
1717 XHR_SLOT_REQ[slot].store(r.id, core::sync::atomic::Ordering::Release);
1718 xhr_top_up_workers(&q, &mut p);
1720 (r, slot)
1721 }
1722 None => {
1723 if let Some(slot) = mine {
1728 p.slot_used[slot] = false;
1729 XHR_SLOT_PID[slot].store(0, core::sync::atomic::Ordering::Release);
1730 }
1731 drop(p);
1732 drop(q);
1733 crate::os_lib::platform::exit_thread();
1737 }
1738 }
1739 };
1740 if crate::os_lib::platform::group_stopped(req.group) {
1742 crate::warn!("[XHR] 止めたアプリ(組 {})の要求を捨てた url={:?}", req.group, req.url);
1743 drop(req);
1744 xhr_finish_flight(slot);
1745 continue;
1746 }
1747 if XHR_CLOSED_RT.contains(req.runtime) {
1749 crate::warn!("[XHR] 閉じたタブ(実行環境 {})の要求を始めずに捨てた url={:?}", req.runtime, req.url);
1750 drop(req);
1751 xhr_finish_flight(slot);
1752 continue;
1753 }
1754 let borrowed = req.group != 0 && crate::os_lib::platform::set_current_mem_group(req.group);
1757
1758 let (status, body, ok, raw, resp_headers) = match do_http_request_full(
1759 &req.base,
1760 &req.url,
1761 &req.method,
1762 &req.body,
1763 &req.content_type,
1764 &req.headers,
1765 ) {
1766 Ok((s, b, raw, h)) => (s, b, true, raw, h),
1767 Err(e) => {
1768 if !crate::os_lib::platform::group_stopped(req.group)
1769 && !XHR_SLOT_CANCEL[slot].load(core::sync::atomic::Ordering::Acquire)
1770 {
1771 crate::warn!("[XHR] 非同期取得失敗 url={:?} 理由={}", req.url, e);
1772 }
1773 (0u16, String::new(), false, Vec::new(), alloc::collections::BTreeMap::new())
1774 }
1775 };
1776 let cancelled = XHR_SLOT_CANCEL[slot].load(core::sync::atomic::Ordering::Acquire);
1777 if cancelled || XHR_CLOSED_RT.contains(req.runtime) {
1778 crate::warn!(
1780 "[XHR] 閉じたタブ(実行環境 {})/中止した要求の取得を{}結果を捨てた url={:?} 受信 {} バイト",
1781 req.runtime,
1782 if cancelled { "途中でやめて" } else { "終えて" },
1783 req.url,
1784 raw.len()
1785 );
1786 drop((body, raw, resp_headers, req));
1787 if borrowed {
1788 crate::os_lib::platform::set_current_mem_group(0);
1789 }
1790 xhr_finish_flight(slot);
1791 continue;
1792 }
1793 if crate::os_lib::platform::group_stopped(req.group) {
1794 crate::warn!(
1796 "[XHR] 止めたアプリ(組 {})の取得をやめて結果を捨てた url={:?} 受信 {} バイト",
1797 req.group,
1798 req.url,
1799 raw.len()
1800 );
1801 drop((body, raw, resp_headers, req));
1802 if borrowed {
1803 crate::os_lib::platform::set_current_mem_group(0);
1804 }
1805 xhr_finish_flight(slot);
1806 continue;
1807 }
1808 {
1809 let mut results = XHR_RESULTS.lock();
1810 results.push(XhrAsyncResult {
1811 id: req.id,
1812 status,
1813 body,
1814 raw,
1815 headers: resp_headers,
1816 ok,
1817 group: req.group,
1818 arrived_ms: crate::os_lib::platform::now_ms(),
1819 runtime: req.runtime,
1820 });
1821 XHR_RESULTS_LEN.store(results.len(), core::sync::atomic::Ordering::Release);
1822 }
1823 drop(req);
1825 if borrowed {
1826 crate::os_lib::platform::set_current_mem_group(0);
1827 }
1828 xhr_finish_flight(slot);
1830 }
1831}
1832
1833static XHR_RESULTS_LEN: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
1835
1836pub(crate) fn has_pending_xhr_results() -> bool {
1837 XHR_RESULTS_LEN.load(core::sync::atomic::Ordering::Acquire) != 0
1838}
1839
1840pub(crate) fn has_pending_xhr_results_for(pending: &core::cell::RefCell<alloc::collections::BTreeMap<u64, Value>>) -> bool {
1844 if !has_pending_xhr_results() {
1845 return false;
1846 }
1847 let Ok(p) = pending.try_borrow() else { return true };
1848 if p.is_empty() {
1849 return false;
1850 }
1851 match XHR_RESULTS.try_lock() {
1852 Some(q) => q.iter().any(|r| p.contains_key(&r.id)),
1853 None => true,
1854 }
1855}
1856
1857pub(crate) fn pump_xhr_results(it: &mut Interp) -> bool {
1862 let results: alloc::vec::Vec<XhrAsyncResult> = {
1863 let mut q = XHR_RESULTS.lock();
1864 if q.is_empty() {
1865 return false;
1866 }
1867 let now = crate::os_lib::platform::now_ms();
1868 let all = core::mem::take(&mut *q);
1869 let pending = it.pending_xhrs().borrow();
1870 let (deliver, keep, dropped) = crate::os_lib::web_apis::xhr_route::split(
1871 all,
1872 |r| pending.contains_key(&r.id),
1873 |r| now.saturating_sub(r.arrived_ms),
1874 );
1875 drop(pending);
1876 if dropped != 0 {
1877 crate::warn!("[XHR] 受け取り手の無い古い結果を {} 件捨てた", dropped);
1878 }
1879 *q = keep;
1880 XHR_RESULTS_LEN.store(q.len(), core::sync::atomic::Ordering::Release);
1881 deliver
1882 };
1883 if results.is_empty() {
1884 return false;
1885 }
1886 for res in results {
1887 let xhr_val = it.pending_xhrs().borrow_mut().remove(&res.id);
1888 if let Some(this) = xhr_val {
1889 if obj_prop(&this, "_is_fetch").is_some() {
1890 settle_fetch(it, &this, res);
1891 } else {
1892 apply_xhr_response(it, &this, res.status, res.body, res.raw, res.headers, res.ok);
1893 }
1894 }
1895 }
1896 true
1897}
1898
1899fn settle_fetch(it: &mut Interp, marker: &Value, res: XhrAsyncResult) {
1901 let Some(Value::Object(p)) = obj_prop(marker, "_fetch_promise") else { return };
1902 let ObjKind::PromiseObj(state) = &p.borrow().kind else { return };
1903 let state = state.clone();
1904 if !res.ok {
1905 let e = it.type_error("Failed to fetch");
1906 it.promise_reject(&state, e);
1907 return;
1908 }
1909 let url = obj_prop(marker, "_fetch_url").map(|v| v.to_js_string()).unwrap_or_default();
1910 let resp = make_response_with_url(res.status, res.body, url);
1911 attach_raw_body(&resp, &res.raw);
1912 let stream = super::streams::make_readable_stream_from_bytes(it, &res.raw);
1913 if let Value::Object(r) = &resp {
1914 r.borrow_mut().props.insert("body".into(), stream);
1915 }
1916 it.promise_resolve(&state, resp);
1917}
1918
1919fn start_async_request(mut req: XhrRequestData) -> Result<(), alloc::boxed::Box<XhrRequestData>> {
1922 req.host = xhr_sched::host_key(&resolve_url(&req.base, &req.url));
1923 let mut q = XHR_REQUEST_QUEUE.lock();
1924 q.push_back(req);
1925 let mut p = XHR_POOL.lock();
1926 xhr_reap_dead(&mut p);
1927 if xhr_top_up_workers(&q, &mut p) {
1928 return Ok(());
1929 }
1930 match q.pop_back() {
1931 Some(r) => Err(alloc::boxed::Box::new(r)),
1932 None => Ok(()),
1933 }
1934}
1935
1936fn apply_xhr_response(
1937 it: &mut Interp,
1938 this: &Value,
1939 status: u16,
1940 body: String,
1941 raw: Vec<u8>,
1942 resp_headers: alloc::collections::BTreeMap<String, String>,
1943 ok: bool,
1944) {
1945 let o = match this {
1946 Value::Object(o) => o,
1947 _ => return,
1948 };
1949 if o.borrow().props.get("_aborted").is_some_and(|v| v.truthy()) {
1950 return;
1951 }
1952 let mut state = crate::os_lib::web_apis::xhr_state::XhrState::new();
1953 state.ready_state = 1;
1954 state.sent = true;
1955 let status_text = http_status_text(status);
1956 let events = if ok {
1957 state.complete_response(status, status_text, resp_headers.clone(), body.clone(), raw.clone())
1958 } else {
1959 state.complete_error("network error")
1960 };
1961 {
1962 let h = Obj::plain();
1963 for (k, v) in resp_headers {
1964 h.borrow_mut().props.insert(k.into(), Value::str(v));
1965 }
1966 o.borrow_mut().props.insert("_resp_headers".into(), Value::Object(h));
1967 }
1968 let response_type = o.borrow().props.get("responseType").map(|v| v.to_js_string()).unwrap_or_default();
1969 let json_response = (ok && response_type == "json")
1970 .then(|| super::console_math_json::json_parse(it, Value::Undefined, &[Value::str(body.clone())]).unwrap_or(Value::Null));
1971 let final_response = if ok {
1972 match response_type.as_str() {
1973 "arraybuffer" => crate::os_lib::ecma::builtins::typed_array::make_arraybuffer_with_bytes(raw.iter().map(|&x| x as f64).collect()),
1974 "blob" => make_blob(raw.iter().map(|&x| x as f64).collect(), String::new()),
1975 "json" => json_response.unwrap_or(Value::Null),
1976 _ => Value::str(body.clone()),
1977 }
1978 } else {
1979 Value::str("")
1980 };
1981 {
1982 let mut b = o.borrow_mut();
1983 b.props.insert("status".into(), Value::Number(state.status as f64));
1984 b.props.insert("statusText".into(), Value::str(state.status_text));
1985 if response_type.is_empty() || response_type == "text" {
1986 b.props.insert("responseText".into(), Value::str(state.response_body.clone()));
1987 } else {
1988 b.props.insert("responseText".into(), Value::str(body));
1989 }
1990 b.props.insert("response".into(), final_response);
1991 }
1992 for ev in events {
1993 if o.borrow().props.get("_aborted").is_some_and(|v| v.truthy()) {
1994 return;
1995 }
1996 match ev {
1997 crate::os_lib::web_apis::xhr_state::XhrEvent::ReadyStateChange(rs) => {
1998 {
1999 let mut b = o.borrow_mut();
2000 b.props.insert("readyState".into(), Value::Number(rs as f64));
2001 if rs == 4 {
2002 b.props.insert("_sent".into(), Value::Bool(false));
2003 }
2004 }
2005 fire_xhr_target_event(it, this, "readystatechange", 0, 0, "XHR");
2006 }
2007 crate::os_lib::web_apis::xhr_state::XhrEvent::Progress { loaded, total } => {
2008 fire_xhr_target_event(it, this, "progress", loaded, total, "XHR");
2009 }
2010 crate::os_lib::web_apis::xhr_state::XhrEvent::Load { .. } => {
2011 let n = raw.len();
2012 fire_xhr_target_event(it, this, "load", n, n, "XHR");
2013 }
2014 crate::os_lib::web_apis::xhr_state::XhrEvent::Error => {
2015 fire_xhr_target_event(it, this, "error", 0, 0, "XHR");
2016 }
2017 crate::os_lib::web_apis::xhr_state::XhrEvent::Abort => {
2018 fire_xhr_target_event(it, this, "abort", 0, 0, "XHR");
2019 }
2020 crate::os_lib::web_apis::xhr_state::XhrEvent::LoadEnd { loaded, total } => {
2021 fire_xhr_target_event(it, this, "loadend", loaded, total, "XHR");
2022 }
2023 }
2024 }
2025}
2026
2027pub(crate) fn xhr_open(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2028 let url = it.to_string_value(arg(a, 1))?;
2030 let method = arg(a, 0).to_js_string();
2031 let is_async = if a.len() > 2 {
2032 arg(a, 2).truthy()
2033 } else {
2034 true
2035 };
2036 let mut state = crate::os_lib::web_apis::xhr_state::XhrState::new();
2037 let events = state.open(&method, &url, is_async);
2038 if let Value::Object(o) = &this {
2039 let mut b = o.borrow_mut();
2040 b.props.insert("_method".into(), Value::str(state.method));
2041 b.props.insert("_url".into(), Value::str(state.url));
2042 b.props.insert("_async".into(), Value::Bool(state.is_async));
2043 b.props.insert("_aborted".into(), Value::Bool(false));
2044 b.props.insert("_sent".into(), Value::Bool(false));
2045 b.props.insert("status".into(), Value::Number(0.0));
2046 b.props.insert("statusText".into(), Value::str(""));
2047 b.props.insert("responseText".into(), Value::str(""));
2048 b.props.insert("response".into(), Value::str(""));
2049 b.props.shift_remove("_resp_headers");
2050 b.props.insert("readyState".into(), Value::Number(state.ready_state as f64));
2051 }
2052 for ev in events {
2053 if let crate::os_lib::web_apis::xhr_state::XhrEvent::ReadyStateChange(_) = ev {
2054 fire_xhr_target_event(it, &this, "readystatechange", 0, 0, "XHR");
2055 }
2056 }
2057 Ok(Value::Undefined)
2058}
2059
2060pub(crate) fn xhr_send(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
2061 let o = match &this {
2062 Value::Object(o) => o.clone(),
2063 _ => return Ok(Value::Undefined),
2064 };
2065 let (url, method, content_type, is_async) = {
2066 let mut b = o.borrow_mut();
2067 b.props.insert("_sent".into(), Value::Bool(true));
2068 b.props.insert("_aborted".into(), Value::Bool(false));
2069 (
2070 b.props
2071 .get("_url")
2072 .map(|v| v.to_js_string())
2073 .unwrap_or_default(),
2074 b.props
2075 .get("_method")
2076 .map(|v| v.to_js_string())
2077 .unwrap_or_else(|| String::from("GET")),
2078 b.props
2079 .get("_content_type")
2080 .map(|v| v.to_js_string())
2081 .unwrap_or_else(|| String::from("text/plain;charset=UTF-8")),
2082 b.props.get("_async").map(|v| v.truthy()).unwrap_or(true),
2083 )
2084 };
2085 let req_body = body_to_bytes(&arg(a, 0));
2087 let req_headers = headers_list(&o.borrow().props.get("_req_headers").cloned().unwrap_or(Value::Undefined));
2088 let base = it.base_url.clone();
2089 let mut state = crate::os_lib::web_apis::xhr_state::XhrState::new();
2090 state.open(&method, &url, is_async);
2091 state.mark_sent();
2092 let plan = state.plan_send(&req_body);
2093
2094 if matches!(
2095 plan,
2096 crate::os_lib::web_apis::xhr_state::XhrSendPlan::ImmediateDataUrl { .. }
2097 | crate::os_lib::web_apis::xhr_state::XhrSendPlan::SyncNetwork
2098 ) {
2099 let (status, body, ok, raw, resp_headers) = match do_http_request_full(&base, &url, &method, &req_body, &content_type, &req_headers) {
2100 Ok((s, b, raw, h)) => (s, b, true, raw, h),
2101 Err(e) => {
2102 crate::warn!("[XHR] 取得失敗 url={:?} 理由={}", url, e);
2103 (0u16, String::new(), false, Vec::new(), alloc::collections::BTreeMap::new())
2104 }
2105 };
2106 apply_xhr_response(it, &this, status, body, raw, resp_headers, ok);
2107 return Ok(Value::Undefined);
2108 }
2109
2110 let id = XHR_ID_GEN.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
2112 o.borrow_mut().props.insert("_async_id".into(), Value::Number(id as f64));
2113 it.pending_xhrs().borrow_mut().insert(id, this.clone());
2114
2115 let req_data = XhrRequestData {
2116 id,
2117 base: base.clone(),
2118 url: url.clone(),
2119 method: method.clone(),
2120 body: req_body.clone(),
2121 content_type: content_type.clone(),
2122 headers: req_headers.clone(),
2123 group: crate::os_lib::platform::current_mem_group(),
2124 host: String::new(),
2125 runtime: it.runtime_id,
2126 };
2127
2128 if let Err(req) = start_async_request(req_data) {
2129 let (status, body, ok, raw, resp_headers) = match do_http_request_full(
2131 &req.base, &req.url, &req.method, &req.body, &req.content_type, &req.headers,
2132 ) {
2133 Ok((s, b, raw, h)) => (s, b, true, raw, h),
2134 Err(e) => {
2135 crate::warn!("[XHR] 取得失敗 url={:?} 理由={}", req.url, e);
2136 (0u16, String::new(), false, Vec::new(), alloc::collections::BTreeMap::new())
2137 }
2138 };
2139 let target = it.pending_xhrs().borrow_mut().remove(&id);
2140 if let Some(target) = target {
2141 apply_xhr_response(it, &target, status, body, raw, resp_headers, ok);
2142 }
2143 }
2144
2145 Ok(Value::Undefined)
2146}