Skip to main content

nodejs/stdlib/
fetch.rs

1//! The WHATWG Fetch globals: `fetch`, `Headers`, `Request`, `Response`, `Blob`,
2//! `FormData`, `AbortController` and `AbortSignal`.
3//!
4//! `fetch` is not a re-implementation of an HTTP client: it drives the SAME
5//! exchange `http.request`/`https.request` already perform (`http::exchange` /
6//! `https::exchange`), on a background thread, and hands the parsed result back
7//! over the host's I/O channel — the pattern every other async native in this
8//! frontend uses. That keeps one HTTP/1.1 wire implementation, one chunked
9//! decoder and one TLS configuration in the process.
10//!
11//! A body is held as raw BYTES (`@@body`, a JS array of byte numbers) rather
12//! than as a string, so `arrayBuffer()`/`bytes()` are exact for a binary
13//! response and `text()` decodes UTF-8 once, at the point the caller asks for
14//! text. A `Response` is fully buffered by the time the promise settles, so the
15//! body accessors are already-settled promises — the streaming `body`
16//! `ReadableStream` is the one part of the interface this does not provide.
17
18use crate::host::{with_host, JsObj};
19use fusevm::Value;
20use indexmap::IndexMap;
21
22/// The classes this module constructs, as bare globals.
23pub const CLASSES: &[&str] = &[
24    "Headers",
25    "Request",
26    "Response",
27    "Blob",
28    "File",
29    "FormData",
30    "AbortController",
31    "AbortSignal",
32];
33
34pub const HEADERS_METHODS: &[&str] = &[
35    "get",
36    "getSetCookie",
37    "has",
38    "set",
39    "append",
40    "delete",
41    "forEach",
42    "keys",
43    "values",
44    "entries",
45    "@@iterator",
46];
47pub const RESPONSE_METHODS: &[&str] = &[
48    "text",
49    "json",
50    "arrayBuffer",
51    "bytes",
52    "blob",
53    "formData",
54    "clone",
55];
56pub const REQUEST_METHODS: &[&str] = &[
57    "text",
58    "json",
59    "arrayBuffer",
60    "bytes",
61    "blob",
62    "formData",
63    "clone",
64];
65pub const BLOB_METHODS: &[&str] = &["text", "arrayBuffer", "bytes", "slice", "stream"];
66pub const FORM_DATA_METHODS: &[&str] = &[
67    "append",
68    "delete",
69    "get",
70    "getAll",
71    "has",
72    "set",
73    "forEach",
74    "keys",
75    "values",
76    "entries",
77    "@@iterator",
78];
79pub const ABORT_CONTROLLER_METHODS: &[&str] = &["abort"];
80// `addEventListener`/`removeEventListener`/`dispatchEvent` are inherited from
81// `EventTarget.prototype` (see `native_parent`), not listed here.
82pub const ABORT_SIGNAL_METHODS: &[&str] = &["throwIfAborted"];
83
84pub fn methods_for(tag: &str) -> &'static [&'static str] {
85    match tag {
86        "Headers" => HEADERS_METHODS,
87        "Response" => RESPONSE_METHODS,
88        "Request" => REQUEST_METHODS,
89        "Blob" | "File" => BLOB_METHODS,
90        "FormData" => FORM_DATA_METHODS,
91        "AbortController" => ABORT_CONTROLLER_METHODS,
92        "AbortSignal" => ABORT_SIGNAL_METHODS,
93        _ => &[],
94    }
95}
96
97pub fn is_class(name: &str) -> bool {
98    CLASSES.contains(&name)
99}
100
101// ── small helpers ────────────────────────────────────────────────────────────
102
103fn str_of(v: &Value) -> String {
104    with_host(|h| h.str_of(v))
105}
106
107fn new_str(s: impl Into<String>) -> Value {
108    let s = s.into();
109    with_host(|h| h.new_str(s))
110}
111
112fn prop(recv: &Value, key: &str) -> Option<Value> {
113    with_host(|h| match h.get(recv) {
114        Some(JsObj::Object(p)) => p.get(key).cloned(),
115        _ => None,
116    })
117    .filter(|v| !matches!(v, Value::Undef))
118}
119
120fn set_prop(recv: &Value, key: &str, val: Value) {
121    with_host(|h| {
122        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
123            p.insert(key.to_string(), val);
124        }
125    });
126}
127
128/// Wrap a synchronous outcome in an already-settled Promise. Same shape as
129/// `fs/promises`: the body of a fetched `Response` is already in memory, so
130/// `text()`/`json()` have nothing to wait for.
131fn settled(result: Result<Value, String>) -> Value {
132    let p = with_host(|h| h.new_promise());
133    let id = with_host(|h| h.promise_id(&p).unwrap_or(0));
134    match result {
135        Ok(v) => crate::host::resolve_promise_val(id, v),
136        Err(e) => {
137            let ev = with_host(|h| crate::builtins::synth_error(h, &e));
138            crate::host::reject_promise_val(id, ev);
139        }
140    }
141    p
142}
143
144/// The bytes stored under `@@body`, as a Rust byte vector.
145fn body_bytes(recv: &Value) -> Vec<u8> {
146    let Some(arr) = prop(recv, "@@body") else {
147        return Vec::new();
148    };
149    with_host(|h| match h.get(&arr) {
150        Some(JsObj::Array(items)) => items.iter().map(|v| h.to_number(v) as u8).collect(),
151        _ => Vec::new(),
152    })
153}
154
155fn store_body(bytes: &[u8]) -> Value {
156    with_host(|h| h.new_array(bytes.iter().map(|b| Value::Float(*b as f64)).collect()))
157}
158
159/// A `Uint8Array` over `bytes` — what `bytes()` answers and what
160/// `arrayBuffer()` is built from.
161fn to_uint8array(bytes: &[u8]) -> Result<Value, String> {
162    let arr = with_host(|h| h.new_array(bytes.iter().map(|b| Value::Float(*b as f64)).collect()));
163    super::typedarray::construct("Uint8Array", &[arr])
164}
165
166// ── Headers ──────────────────────────────────────────────────────────────────
167//
168// The entry list is kept in insertion order with LOWERCASED names, which is what
169// the Fetch standard's header list is and what makes `get`/`has` case-
170// insensitive without a second index.
171
172fn headers_entries(recv: &Value) -> Vec<(String, String)> {
173    let Some(arr) = prop(recv, "@@entries") else {
174        return Vec::new();
175    };
176    with_host(|h| match h.get(&arr) {
177        Some(JsObj::Array(items)) => items
178            .iter()
179            .filter_map(|pair| match h.get(pair) {
180                Some(JsObj::Array(kv)) if kv.len() == 2 => {
181                    Some((h.str_of(&kv[0]), h.str_of(&kv[1])))
182                }
183                _ => None,
184            })
185            .collect(),
186        _ => Vec::new(),
187    })
188}
189
190fn set_headers_entries(recv: &Value, entries: &[(String, String)]) {
191    let arr = with_host(|h| {
192        let pairs: Vec<Value> = entries
193            .iter()
194            .map(|(k, v)| {
195                let k = h.new_str(k.clone());
196                let v = h.new_str(v.clone());
197                h.new_array(vec![k, v])
198            })
199            .collect();
200        h.new_array(pairs)
201    });
202    set_prop(recv, "@@entries", arr);
203}
204
205/// `new Headers(init)`. `init` is another `Headers`, an array of `[name, value]`
206/// pairs, or a plain object.
207pub fn construct_headers(args: &[Value]) -> Result<Value, String> {
208    let obj = with_host(|h| {
209        let mut m = IndexMap::new();
210        m.insert("@@native".into(), h.new_str("Headers"));
211        let empty = h.new_array(Vec::new());
212        m.insert("@@entries".into(), empty);
213        h.new_object(m)
214    });
215    with_host(|h| h.hide_prop(&obj, "@@entries"));
216    if let Some(init) = args.first().filter(|v| !matches!(v, Value::Undef)) {
217        for (k, v) in init_header_entries(init) {
218            append_header(&obj, &k, &v);
219        }
220    }
221    Ok(obj)
222}
223
224/// The `(name, value)` pairs a `HeadersInit` contributes, in order.
225fn init_header_entries(init: &Value) -> Vec<(String, String)> {
226    if super::native_tag(init).as_deref() == Some("Headers") {
227        return headers_entries(init);
228    }
229    // An array of `[name, value]` pairs.
230    if with_host(|h| matches!(h.get(init), Some(JsObj::Array(_)))) {
231        return with_host(|h| match h.get(init) {
232            Some(JsObj::Array(items)) => items
233                .iter()
234                .filter_map(|pair| match h.get(pair) {
235                    Some(JsObj::Array(kv)) if kv.len() >= 2 => {
236                        Some((h.str_of(&kv[0]).to_ascii_lowercase(), h.str_of(&kv[1])))
237                    }
238                    _ => None,
239                })
240                .collect(),
241            _ => Vec::new(),
242        });
243    }
244    // A plain object: every own enumerable string key.
245    with_host(|h| match h.get(init) {
246        Some(JsObj::Object(p)) => p
247            .iter()
248            .filter(|(k, _)| !k.starts_with("@@"))
249            .map(|(k, v)| (k.to_ascii_lowercase(), h.str_of(v)))
250            .collect(),
251        _ => Vec::new(),
252    })
253}
254
255fn append_header(recv: &Value, name: &str, value: &str) {
256    let mut e = headers_entries(recv);
257    e.push((name.to_ascii_lowercase(), value.to_string()));
258    set_headers_entries(recv, &e);
259}
260
261fn set_header(recv: &Value, name: &str, value: &str) {
262    let name = name.to_ascii_lowercase();
263    let mut e = headers_entries(recv);
264    match e.iter().position(|(k, _)| *k == name) {
265        Some(i) => {
266            e[i].1 = value.to_string();
267            e.retain({
268                let mut seen = 0;
269                move |(k, _)| {
270                    if *k != name {
271                        return true;
272                    }
273                    seen += 1;
274                    seen == 1
275                }
276            });
277        }
278        None => e.push((name, value.to_string())),
279    }
280    set_headers_entries(recv, &e);
281}
282
283/// `Headers.get`: every value for `name`, joined with `", "` — the standard's
284/// combined value, which is why a repeated header reads back as one string.
285fn get_header(recv: &Value, name: &str) -> Option<String> {
286    let name = name.to_ascii_lowercase();
287    let vals: Vec<String> = headers_entries(recv)
288        .into_iter()
289        .filter(|(k, _)| *k == name)
290        .map(|(_, v)| v)
291        .collect();
292    (!vals.is_empty()).then(|| vals.join(", "))
293}
294
295pub fn headers_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
296    match method {
297        "get" => Ok(match get_header(recv, &super::arg_str(args, 0)) {
298            Some(v) => new_str(v),
299            None => with_host(|h| h.null()),
300        }),
301        "getSetCookie" => {
302            let vals: Vec<Value> = headers_entries(recv)
303                .into_iter()
304                .filter(|(k, _)| k == "set-cookie")
305                .map(|(_, v)| new_str(v))
306                .collect();
307            Ok(with_host(|h| h.new_array(vals)))
308        }
309        "has" => {
310            let name = super::arg_str(args, 0).to_ascii_lowercase();
311            Ok(Value::Bool(
312                headers_entries(recv).iter().any(|(k, _)| *k == name),
313            ))
314        }
315        "set" => {
316            set_header(recv, &super::arg_str(args, 0), &super::arg_str(args, 1));
317            Ok(Value::Undef)
318        }
319        "append" => {
320            append_header(recv, &super::arg_str(args, 0), &super::arg_str(args, 1));
321            Ok(Value::Undef)
322        }
323        "delete" => {
324            let name = super::arg_str(args, 0).to_ascii_lowercase();
325            let mut e = headers_entries(recv);
326            e.retain(|(k, _)| *k != name);
327            set_headers_entries(recv, &e);
328            Ok(Value::Undef)
329        }
330        // Iteration is over the SORTED, combined header list (the standard's
331        // "sorted and combined" order), not insertion order.
332        "forEach" => {
333            let cb = args.first().cloned().unwrap_or(Value::Undef);
334            for (k, v) in sorted_combined(recv) {
335                let (kv, vv) = (new_str(k), new_str(v));
336                crate::host::invoke(&cb, vec![vv, kv, recv.clone()], None)?;
337            }
338            Ok(Value::Undef)
339        }
340        "keys" | "values" | "entries" | "@@iterator" => {
341            let items: Vec<Value> = sorted_combined(recv)
342                .into_iter()
343                .map(|(k, v)| match method {
344                    "keys" => new_str(k),
345                    "values" => new_str(v),
346                    // `entries` and the default iterator both yield pairs.
347                    _ => {
348                        let (kv, vv) = (new_str(k), new_str(v));
349                        with_host(|h| h.new_array(vec![kv, vv]))
350                    }
351                })
352                .collect();
353            Ok(with_host(|h| {
354                h.alloc(JsObj::Iter {
355                    items,
356                    idx: 0,
357                    array: None,
358                    brand: Some("Headers Iterator"),
359                })
360            }))
361        }
362        _ => Err(crate::host::type_error(&format!(
363            "{method} is not a function"
364        ))),
365    }
366}
367
368/// The header list sorted by name with same-named values combined, which is the
369/// order every `Headers` iteration method observes.
370fn sorted_combined(recv: &Value) -> Vec<(String, String)> {
371    let mut names: Vec<String> = Vec::new();
372    for (k, _) in headers_entries(recv) {
373        if !names.contains(&k) {
374            names.push(k);
375        }
376    }
377    names.sort();
378    names
379        .into_iter()
380        .filter_map(|n| get_header(recv, &n).map(|v| (n, v)))
381        .collect()
382}
383
384// ── Response / Request bodies ────────────────────────────────────────────────
385
386fn build_response(
387    status: u16,
388    status_text: &str,
389    headers: &[(String, String)],
390    body: &[u8],
391    url: &str,
392) -> Value {
393    let headers_obj = construct_headers(&[]).unwrap_or(Value::Undef);
394    for (k, v) in headers {
395        append_header(&headers_obj, k, v);
396    }
397    let body_arr = store_body(body);
398    let obj = with_host(|h| {
399        let mut m = IndexMap::new();
400        m.insert("@@native".into(), h.new_str("Response"));
401        m.insert("status".into(), Value::Float(status as f64));
402        m.insert("statusText".into(), h.new_str(status_text.to_string()));
403        // 2xx (and only 2xx) is `ok` — 304 is not.
404        m.insert(
405            "ok".into(),
406            Value::Bool((200..300).contains(&(status as u32))),
407        );
408        m.insert("redirected".into(), Value::Bool(false));
409        m.insert("type".into(), h.new_str("basic"));
410        m.insert("url".into(), h.new_str(url.to_string()));
411        m.insert("bodyUsed".into(), Value::Bool(false));
412        m.insert("headers".into(), headers_obj);
413        m.insert("@@body".into(), body_arr);
414        h.new_object(m)
415    });
416    with_host(|h| h.hide_prop(&obj, "@@body"));
417    obj
418}
419
420/// `new Response(body, init)`.
421pub fn construct_response(args: &[Value]) -> Result<Value, String> {
422    let body = body_init_bytes(args.first());
423    let init = args.get(1).cloned().unwrap_or(Value::Undef);
424    let status = match prop(&init, "status") {
425        Some(v) => with_host(|h| h.to_number(&v)) as u16,
426        None => 200,
427    };
428    let status_text = prop(&init, "statusText")
429        .map(|v| str_of(&v))
430        .unwrap_or_default();
431    let mut headers: Vec<(String, String)> = Vec::new();
432    if let Some(hv) = prop(&init, "headers") {
433        headers = init_header_entries(&hv);
434    }
435    Ok(build_response(status, &status_text, &headers, &body, ""))
436}
437
438/// `new Request(input, init)`.
439pub fn construct_request(args: &[Value]) -> Result<Value, String> {
440    let input = args.first().cloned().unwrap_or(Value::Undef);
441    let url = if super::native_tag(&input).as_deref() == Some("Request") {
442        prop(&input, "url").map(|v| str_of(&v)).unwrap_or_default()
443    } else {
444        str_of(&input)
445    };
446    let init = args.get(1).cloned().unwrap_or(Value::Undef);
447    let method = prop(&init, "method")
448        .map(|v| str_of(&v).to_ascii_uppercase())
449        .unwrap_or_else(|| "GET".into());
450    let headers_obj = construct_headers(&[])?;
451    if let Some(hv) = prop(&init, "headers") {
452        for (k, v) in init_header_entries(&hv) {
453            append_header(&headers_obj, &k, &v);
454        }
455    }
456    let body = body_init_bytes(prop(&init, "body").as_ref());
457    let body_arr = store_body(&body);
458    let obj = with_host(|h| {
459        let mut m = IndexMap::new();
460        m.insert("@@native".into(), h.new_str("Request"));
461        m.insert("url".into(), h.new_str(url));
462        m.insert("method".into(), h.new_str(method));
463        m.insert("headers".into(), headers_obj);
464        m.insert("bodyUsed".into(), Value::Bool(false));
465        m.insert("@@body".into(), body_arr);
466        h.new_object(m)
467    });
468    with_host(|h| h.hide_prop(&obj, "@@body"));
469    Ok(obj)
470}
471
472/// The bytes a `BodyInit` contributes: a string encodes as UTF-8, a typed array
473/// / Buffer / `Blob` supplies its bytes, and anything else stringifies.
474fn body_init_bytes(v: Option<&Value>) -> Vec<u8> {
475    let Some(v) = v.filter(|v| !matches!(v, Value::Undef)) else {
476        return Vec::new();
477    };
478    if with_host(|h| h.is_null(v)) {
479        return Vec::new();
480    }
481    match super::native_tag(v).as_deref() {
482        Some("Blob") | Some("File") | Some("Response") | Some("Request") => return body_bytes(v),
483        // A byte view or an ArrayBuffer contributes the bytes it VIEWS: a
484        // `Uint16Array` part is two bytes per element (it was its truncated
485        // elements), and an `ArrayBuffer` or `DataView` is its bytes rather
486        // than the text `[object ArrayBuffer]`.
487        Some("TypedArray" | "Buffer" | "DataView" | "ArrayBuffer") => {
488            return super::buffer::view_bytes(v).unwrap_or_default();
489        }
490        _ => {}
491    }
492    if super::native_tag(v).as_deref() == Some("URLSearchParams") {
493        return str_of(v).into_bytes();
494    }
495    str_of(v).into_bytes()
496}
497
498/// The body accessors shared by `Response`, `Request` and `Blob`. Each answers a
499/// settled Promise, because the body is already fully buffered.
500pub fn body_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
501    match method {
502        "text" => {
503            set_prop(recv, "bodyUsed", Value::Bool(true));
504            let s = String::from_utf8_lossy(&body_bytes(recv)).into_owned();
505            Ok(settled(Ok(new_str(s))))
506        }
507        "json" => {
508            set_prop(recv, "bodyUsed", Value::Bool(true));
509            let s = String::from_utf8_lossy(&body_bytes(recv)).into_owned();
510            let parsed = crate::builtins::call_builtin_function("JSON.parse", vec![new_str(s)]);
511            Ok(settled(parsed))
512        }
513        "bytes" => {
514            set_prop(recv, "bodyUsed", Value::Bool(true));
515            Ok(settled(to_uint8array(&body_bytes(recv))))
516        }
517        "arrayBuffer" => {
518            set_prop(recv, "bodyUsed", Value::Bool(true));
519            let bytes = body_bytes(recv);
520            let buf = with_host(|h| {
521                let mut m = IndexMap::new();
522                m.insert("@@native".into(), h.new_str("ArrayBuffer"));
523                m.insert("byteLength".into(), Value::Float(bytes.len() as f64));
524                let arr = h.new_array(bytes.iter().map(|b| Value::Float(*b as f64)).collect());
525                m.insert("@@bytes".into(), arr);
526                h.new_object(m)
527            });
528            with_host(|h| h.hide_prop(&buf, "@@bytes"));
529            Ok(settled(Ok(buf)))
530        }
531        "blob" => {
532            set_prop(recv, "bodyUsed", Value::Bool(true));
533            let bytes = body_bytes(recv);
534            let ct = prop(recv, "headers")
535                .and_then(|h| get_header(&h, "content-type"))
536                .unwrap_or_default();
537            Ok(settled(Ok(new_blob(&bytes, &ct, None))))
538        }
539        "formData" => {
540            set_prop(recv, "bodyUsed", Value::Bool(true));
541            let s = String::from_utf8_lossy(&body_bytes(recv)).into_owned();
542            let fd = construct_form_data(&[])?;
543            // Only the urlencoded form is decoded here; a multipart body needs
544            // the boundary parser this does not have.
545            for pair in s.split('&').filter(|p| !p.is_empty()) {
546                let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
547                form_append(&fd, &percent_decode(k), &new_str(percent_decode(v)));
548            }
549            Ok(settled(Ok(fd)))
550        }
551        "clone" => {
552            let bytes = body_bytes(recv);
553            let clone = crate::builtins::deep_clone(recv)?;
554            set_prop(&clone, "@@body", store_body(&bytes));
555            set_prop(&clone, "bodyUsed", Value::Bool(false));
556            Ok(clone)
557        }
558        "slice" => {
559            let bytes = body_bytes(recv);
560            let start = args
561                .first()
562                .map(|v| with_host(|h| h.to_number(v)) as usize)
563                .unwrap_or(0)
564                .min(bytes.len());
565            let end = args
566                .get(1)
567                .filter(|v| !matches!(v, Value::Undef))
568                .map(|v| with_host(|h| h.to_number(v)) as usize)
569                .unwrap_or(bytes.len())
570                .clamp(start, bytes.len());
571            let ct = args.get(2).map(str_of).unwrap_or_default();
572            let parts = slice_parts(&blob_parts(recv), start, end);
573            Ok(new_blob_parts(&bytes[start..end], &parts, &ct, None))
574        }
575        "stream" => blob_stream(recv),
576        _ => Err(crate::host::type_error(&format!(
577            "{method} is not a function"
578        ))),
579    }
580}
581
582/// Throw `v` as the JS exception value (rather than as an internal message), so
583/// `catch (e)` receives the object the spec says it should.
584fn throw_js(v: Value) -> String {
585    let msg = with_host(|h| h.str_of(&v));
586    with_host(|h| h.exc = Some(v));
587    msg
588}
589
590fn percent_decode(s: &str) -> String {
591    let bytes = s.replace('+', " ").into_bytes();
592    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
593    let mut i = 0;
594    while i < bytes.len() {
595        if bytes[i] == b'%' && i + 2 < bytes.len() {
596            if let Ok(b) = u8::from_str_radix(&String::from_utf8_lossy(&bytes[i + 1..i + 3]), 16) {
597                out.push(b);
598                i += 3;
599                continue;
600            }
601        }
602        out.push(bytes[i]);
603        i += 1;
604    }
605    String::from_utf8_lossy(&out).into_owned()
606}
607
608// ── Blob / File ──────────────────────────────────────────────────────────────
609
610fn new_blob(bytes: &[u8], content_type: &str, file_name: Option<&str>) -> Value {
611    new_blob_parts(bytes, &[bytes.len()], content_type, file_name)
612}
613
614/// A `Blob` (or `File`) over `bytes`, made of parts of the lengths `parts`
615/// (summing to `bytes.len()`). node keeps a blob as the list of its parts — a
616/// `DataQueue` entry each — and `stream()` reads it part by part, so the
617/// boundaries are observable as its chunks.
618fn new_blob_parts(
619    bytes: &[u8],
620    parts: &[usize],
621    content_type: &str,
622    file_name: Option<&str>,
623) -> Value {
624    let body = store_body(bytes);
625    let part_lens = with_host(|h| {
626        h.new_array(
627            parts
628                .iter()
629                .filter(|&&n| n > 0)
630                .map(|&n| Value::Float(n as f64))
631                .collect(),
632        )
633    });
634    let obj = with_host(|h| {
635        let mut m = IndexMap::new();
636        m.insert(
637            "@@native".into(),
638            h.new_str(if file_name.is_some() { "File" } else { "Blob" }),
639        );
640        m.insert("size".into(), Value::Float(bytes.len() as f64));
641        m.insert("type".into(), h.new_str(content_type.to_ascii_lowercase()));
642        if let Some(n) = file_name {
643            m.insert("name".into(), h.new_str(n.to_string()));
644            m.insert("lastModified".into(), Value::Float(0.0));
645        }
646        m.insert("@@body".into(), body);
647        m.insert("@@parts".into(), part_lens);
648        h.new_object(m)
649    });
650    with_host(|h| {
651        h.hide_prop(&obj, "@@body");
652        h.hide_prop(&obj, "@@parts");
653    });
654    obj
655}
656
657/// The lengths of a blob's non-empty parts, in order.
658fn blob_parts(blob: &Value) -> Vec<usize> {
659    let Some(arr) = prop(blob, "@@parts") else {
660        let n = body_bytes(blob).len();
661        return if n > 0 { vec![n] } else { Vec::new() };
662    };
663    with_host(|h| match h.get(&arr) {
664        Some(JsObj::Array(items)) => items.iter().map(|v| h.to_number(v) as usize).collect(),
665        _ => Vec::new(),
666    })
667}
668
669/// The parts of the byte range `start..end` of a blob made of `parts`: each
670/// part cut to the range, as slicing a `DataQueue` keeps its entries.
671fn slice_parts(parts: &[usize], start: usize, end: usize) -> Vec<usize> {
672    let mut out = Vec::new();
673    let mut at = 0;
674    for &n in parts {
675        let (lo, hi) = (at.max(start), (at + n).min(end));
676        if lo < hi {
677            out.push(hi - lo);
678        }
679        at += n;
680    }
681    out
682}
683
684/// The part lengths a `BlobPart` list contributes: a blob part brings its own
685/// parts, anything else is one part.
686fn parts_of(parts: &[Value]) -> (Vec<u8>, Vec<usize>) {
687    let mut bytes = Vec::new();
688    let mut lens = Vec::new();
689    for p in parts {
690        let b = blob_part_bytes(p);
691        match super::native_tag(p).as_deref() {
692            Some("Blob") | Some("File") => lens.extend(blob_parts(p)),
693            _ => lens.push(b.len()),
694        }
695        bytes.extend(b);
696    }
697    (bytes, lens)
698}
699
700/// `Blob.prototype.stream()`: node's `createBlobReaderStream`
701/// (`lib/internal/blob.js`, ported in `blob_stream.js`) over a reader that
702/// hands back one part per pull, as the in-memory `DataQueue` reader does.
703fn blob_stream(blob: &Value) -> Result<Value, String> {
704    thread_local! {
705        static MAKE: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
706    }
707    let make = match MAKE.with(|m| m.borrow().clone()) {
708        Some(f) => f,
709        None => {
710            let f = crate::eval_internal(include_str!("blob_stream.js"))?;
711            MAKE.with(|m| *m.borrow_mut() = Some(f.clone()));
712            f
713        }
714    };
715    let bytes = body_bytes(blob);
716    let mut at = 0;
717    let mut chunks = Vec::new();
718    for n in blob_parts(blob) {
719        chunks.push(to_uint8array(&bytes[at..at + n])?);
720        at += n;
721    }
722    let chunks = with_host(|h| h.new_array(chunks));
723    crate::host::invoke(&make, vec![chunks], None)
724}
725
726/// One `BlobPart`: a `body_init_bytes` source, except that a `null` part is
727/// the text `"null"` (a null BODY is no body, but a part is stringified, as is `undefined`).
728fn blob_part_bytes(p: &Value) -> Vec<u8> {
729    if matches!(p, Value::Undef) {
730        return b"undefined".to_vec();
731    }
732    if with_host(|h| h.is_null(p)) {
733        return b"null".to_vec();
734    }
735    body_init_bytes(Some(p))
736}
737
738pub fn construct_blob(args: &[Value]) -> Result<Value, String> {
739    let parts = match args.first() {
740        Some(parts) => crate::host::iter_all(parts).unwrap_or_default(),
741        None => Vec::new(),
742    };
743    let (bytes, lens) = parts_of(&parts);
744    let ct = args
745        .get(1)
746        .and_then(|o| prop(o, "type"))
747        .map(|v| str_of(&v))
748        .unwrap_or_default();
749    Ok(new_blob_parts(&bytes, &lens, &ct, None))
750}
751
752/// `new File(parts, name[, options])` — a `Blob` that also carries a name.
753pub fn construct_file(args: &[Value]) -> Result<Value, String> {
754    let parts = match args.first() {
755        Some(parts) => crate::host::iter_all(parts).unwrap_or_default(),
756        None => Vec::new(),
757    };
758    let (bytes, lens) = parts_of(&parts);
759    let name = super::arg_str(args, 1);
760    let ct = args
761        .get(2)
762        .and_then(|o| prop(o, "type"))
763        .map(|v| str_of(&v))
764        .unwrap_or_default();
765    Ok(new_blob_parts(&bytes, &lens, &ct, Some(&name)))
766}
767
768// ── FormData ─────────────────────────────────────────────────────────────────
769
770pub fn construct_form_data(_args: &[Value]) -> Result<Value, String> {
771    let obj = with_host(|h| {
772        let mut m = IndexMap::new();
773        m.insert("@@native".into(), h.new_str("FormData"));
774        let empty = h.new_array(Vec::new());
775        m.insert("@@entries".into(), empty);
776        h.new_object(m)
777    });
778    with_host(|h| h.hide_prop(&obj, "@@entries"));
779    Ok(obj)
780}
781
782fn form_entries(recv: &Value) -> Vec<(String, Value)> {
783    let Some(arr) = prop(recv, "@@entries") else {
784        return Vec::new();
785    };
786    with_host(|h| match h.get(&arr) {
787        Some(JsObj::Array(items)) => items
788            .iter()
789            .filter_map(|pair| match h.get(pair) {
790                Some(JsObj::Array(kv)) if kv.len() == 2 => Some((h.str_of(&kv[0]), kv[1].clone())),
791                _ => None,
792            })
793            .collect(),
794        _ => Vec::new(),
795    })
796}
797
798fn set_form_entries(recv: &Value, entries: &[(String, Value)]) {
799    let arr = with_host(|h| {
800        let pairs: Vec<Value> = entries
801            .iter()
802            .map(|(k, v)| {
803                let k = h.new_str(k.clone());
804                h.new_array(vec![k, v.clone()])
805            })
806            .collect();
807        h.new_array(pairs)
808    });
809    set_prop(recv, "@@entries", arr);
810}
811
812fn form_append(recv: &Value, name: &str, value: &Value) {
813    let mut e = form_entries(recv);
814    e.push((name.to_string(), value.clone()));
815    set_form_entries(recv, &e);
816}
817
818pub fn form_data_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
819    let name = super::arg_str(args, 0);
820    match method {
821        "append" => {
822            form_append(recv, &name, args.get(1).unwrap_or(&Value::Undef));
823            Ok(Value::Undef)
824        }
825        "set" => {
826            let mut e = form_entries(recv);
827            e.retain(|(k, _)| *k != name);
828            e.push((name, args.get(1).cloned().unwrap_or(Value::Undef)));
829            set_form_entries(recv, &e);
830            Ok(Value::Undef)
831        }
832        "delete" => {
833            let mut e = form_entries(recv);
834            e.retain(|(k, _)| *k != name);
835            set_form_entries(recv, &e);
836            Ok(Value::Undef)
837        }
838        "get" => Ok(form_entries(recv)
839            .into_iter()
840            .find(|(k, _)| *k == name)
841            .map(|(_, v)| v)
842            .unwrap_or_else(|| with_host(|h| h.null()))),
843        "getAll" => {
844            let vals: Vec<Value> = form_entries(recv)
845                .into_iter()
846                .filter(|(k, _)| *k == name)
847                .map(|(_, v)| v)
848                .collect();
849            Ok(with_host(|h| h.new_array(vals)))
850        }
851        "has" => Ok(Value::Bool(
852            form_entries(recv).iter().any(|(k, _)| *k == name),
853        )),
854        "forEach" => {
855            let cb = args.first().cloned().unwrap_or(Value::Undef);
856            for (k, v) in form_entries(recv) {
857                let kv = new_str(k);
858                crate::host::invoke(&cb, vec![v, kv, recv.clone()], None)?;
859            }
860            Ok(Value::Undef)
861        }
862        "keys" | "values" | "entries" | "@@iterator" => {
863            let items: Vec<Value> = form_entries(recv)
864                .into_iter()
865                .map(|(k, v)| match method {
866                    "keys" => new_str(k),
867                    "values" => v,
868                    _ => {
869                        let kv = new_str(k);
870                        with_host(|h| h.new_array(vec![kv, v]))
871                    }
872                })
873                .collect();
874            Ok(with_host(|h| {
875                h.alloc(JsObj::Iter {
876                    items,
877                    idx: 0,
878                    array: None,
879                    brand: Some("FormData Iterator"),
880                })
881            }))
882        }
883        _ => Err(crate::host::type_error(&format!(
884            "{method} is not a function"
885        ))),
886    }
887}
888
889// ── AbortController / AbortSignal ────────────────────────────────────────────
890
891pub fn new_abort_signal() -> Value {
892    let listeners = super::event_target::new_listener_map();
893    with_host(|h| {
894        let mut m = IndexMap::new();
895        m.insert("@@native".into(), h.new_str("AbortSignal"));
896        m.insert("@@aborted".into(), Value::Bool(false));
897        m.insert("@@reason".into(), Value::Undef);
898        m.insert("@@onabort".into(), h.null());
899        // The `EventTarget` listener map: `abort` listeners and the `onabort`
900        // handler slot live here, dispatched by `event_target::dispatch`.
901        m.insert("@@listeners".into(), listeners);
902        h.new_object(m)
903    })
904}
905
906pub fn construct_abort_controller(_args: &[Value]) -> Result<Value, String> {
907    let signal = new_abort_signal();
908    Ok(with_host(|h| {
909        let mut m = IndexMap::new();
910        m.insert("@@native".into(), h.new_str("AbortController"));
911        m.insert("@@signal".into(), signal);
912        h.new_object(m)
913    }))
914}
915
916/// The `DOMException`-shaped reason an abort carries. node's `AbortSignal`
917/// rejects with a `DOMException` whose `name` is `AbortError`/`TimeoutError`;
918/// `synth_error` only knows the ECMAScript error classes, so the name, the
919/// constructor label and the `stack` head are stamped on afterwards.
920fn dom_exception(name: &str, message: &str) -> Value {
921    let msg = with_host(|h| h.new_str(message.to_string()));
922    let nm = with_host(|h| h.new_str(name.to_string()));
923    crate::builtins::dom_exception(&[msg, nm])
924}
925
926/// Fire an `AbortSignal.timeout` deadline: abort the signal at heap index `idx`
927/// with a `TimeoutError`. Reached from the `@@aborttimeout:<idx>` thunk.
928pub fn fire_timeout_abort(idx: u32) -> Result<Value, String> {
929    let signal = Value::Obj(idx);
930    let e = dom_exception("TimeoutError", "The operation was aborted due to timeout");
931    abort_signal(&signal, e)?;
932    Ok(Value::Undef)
933}
934
935/// Port of lib/internal/abort_controller.js `abortSignal`: mark the signal
936/// aborted, mark every not-yet-aborted signal `AbortSignal.any` made dependent
937/// on it aborted with the same reason, then run the abort steps — the signal's
938/// own first, then each dependent's. The abort steps dispatch an `abort`
939/// event: `onabort` and every `addEventListener('abort')` listener receive a
940/// real `Event` whose `target` is the signal, in registration order, through
941/// the same `EventTarget` dispatch a script's own `dispatchEvent` uses.
942fn abort_signal(signal: &Value, reason: Value) -> Result<(), String> {
943    if is_aborted(signal) {
944        return Ok(());
945    }
946    let reason = if matches!(reason, Value::Undef) {
947        dom_exception("AbortError", "This operation was aborted")
948    } else {
949        reason
950    };
951    set_prop(signal, "@@aborted", Value::Bool(true));
952    set_prop(signal, "@@reason", reason.clone());
953    let dependents: Vec<Value> = signal_list(signal, "@@dependents")
954        .into_iter()
955        .filter(|d| !is_aborted(d))
956        .collect();
957    for d in &dependents {
958        set_prop(d, "@@reason", reason.clone());
959        set_prop(d, "@@aborted", Value::Bool(true));
960    }
961    run_abort(signal)?;
962    for d in &dependents {
963        run_abort(d)?;
964    }
965    Ok(())
966}
967
968/// `runAbort`: dispatch the `abort` event at `signal`.
969fn run_abort(signal: &Value) -> Result<(), String> {
970    let ty = new_str("abort");
971    let event = super::event_target::construct("Event", &[ty]).unwrap_or(Ok(Value::Undef))?;
972    super::event_target::dispatch(signal, &[event])?;
973    Ok(())
974}
975
976fn is_aborted(signal: &Value) -> bool {
977    matches!(prop(signal, "@@aborted"), Some(Value::Bool(true)))
978}
979
980/// A hidden array of signals on `signal` (`@@sources` / `@@dependents`).
981fn signal_list(signal: &Value, key: &str) -> Vec<Value> {
982    let Some(list) = prop(signal, key) else {
983        return Vec::new();
984    };
985    with_host(|h| match h.get(&list) {
986        Some(JsObj::Array(items)) => items.clone(),
987        _ => Vec::new(),
988    })
989}
990
991/// Append `item` to the hidden array `key` on `signal`, creating it.
992fn push_signal(signal: &Value, key: &str, item: Value) {
993    let mut items = signal_list(signal, key);
994    items.push(item);
995    let list = with_host(|h| h.new_array(items));
996    set_prop(signal, key, list);
997}
998
999/// `AbortSignal.any(signals)`: a composite signal that aborts with the first
1000/// of `signals` to abort — at once, if one already has. Its sources are the
1001/// NON-composite signals behind `signals` (a composite argument contributes
1002/// its own sources), and each source records it as a dependent, so a nested
1003/// `any` aborts in the same step as the one it was built from.
1004fn abort_signal_any(signals: &Value) -> Result<Value, String> {
1005    let not_sequence = || {
1006        crate::host::coded_error(
1007            "TypeError",
1008            "ERR_INVALID_ARG_TYPE",
1009            "signals cannot be converted to sequence.",
1010        )
1011    };
1012    // WebIDL `sequence<AbortSignal>`: an Object with an `@@iterator`.
1013    let is_object =
1014        with_host(|h| matches!(signals, Value::Obj(_)) && h.type_of(signals) == "object");
1015    if !is_object {
1016        return Err(not_sequence());
1017    }
1018    let iter = crate::builtins::get_property(signals, "@@iterator")?;
1019    if !with_host(|h| crate::host::is_callable(h, &iter)) {
1020        return Err(not_sequence());
1021    }
1022    let items = crate::host::iter_all(signals)?;
1023    for (i, s) in items.iter().enumerate() {
1024        if super::native_tag(s).as_deref() != Some("AbortSignal") {
1025            return Err(crate::host::coded_error(
1026                "TypeError",
1027                "ERR_INVALID_ARG_TYPE",
1028                &format!("signals[{i}] is not of type AbortSignal."),
1029            ));
1030        }
1031    }
1032    let result = new_abort_signal();
1033    set_prop(&result, "@@composite", Value::Bool(true));
1034    for s in &items {
1035        let sources = if matches!(prop(s, "@@composite"), Some(Value::Bool(true))) {
1036            signal_list(s, "@@sources")
1037        } else {
1038            vec![s.clone()]
1039        };
1040        if is_aborted(s) {
1041            abort_signal(&result, prop(s, "@@reason").unwrap_or(Value::Undef))?;
1042            return Ok(result);
1043        }
1044        for src in sources {
1045            if is_aborted(&src) {
1046                abort_signal(&result, prop(&src, "@@reason").unwrap_or(Value::Undef))?;
1047                return Ok(result);
1048            }
1049            push_signal(&result, "@@sources", src.clone());
1050            push_signal(&src, "@@dependents", result.clone());
1051        }
1052    }
1053    Ok(result)
1054}
1055
1056pub fn abort_controller_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
1057    match method {
1058        "abort" => {
1059            let signal = prop(recv, "@@signal").unwrap_or(Value::Undef);
1060            abort_signal(&signal, args.first().cloned().unwrap_or(Value::Undef))?;
1061            Ok(Value::Undef)
1062        }
1063        _ => Err(crate::host::type_error(&format!(
1064            "{method} is not a function"
1065        ))),
1066    }
1067}
1068
1069pub fn abort_signal_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
1070    match method {
1071        "throwIfAborted" => {
1072            if matches!(prop(recv, "@@aborted"), Some(Value::Bool(true))) {
1073                let reason = prop(recv, "@@reason").unwrap_or(Value::Undef);
1074                return Err(throw_js(reason));
1075            }
1076            Ok(Value::Undef)
1077        }
1078        // The `EventTarget` surface a signal inherits.
1079        "addEventListener" | "removeEventListener" | "dispatchEvent" => {
1080            super::event_target::event_target_call(recv, method, args)
1081        }
1082        _ => Err(crate::host::type_error(&format!(
1083            "{method} is not a function"
1084        ))),
1085    }
1086}
1087
1088/// `AbortSignal.abort(reason)` / `AbortSignal.timeout(ms)` / `AbortSignal.any(signals)`.
1089pub fn abort_signal_static(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
1090    match method {
1091        "abort" => {
1092            let s = new_abort_signal();
1093            let r = abort_signal(&s, args.first().cloned().unwrap_or(Value::Undef));
1094            Some(r.map(|_| s))
1095        }
1096        "timeout" => {
1097            let s = new_abort_signal();
1098            // The abort is a real scheduled macrotask: a native continuation
1099            // thunk (the `@@`-prefixed convention `@@presolve:<id>` already
1100            // uses) carries the signal's heap index to the timer callback.
1101            // node arms it with `setUnrefTimeout`, so a pending timeout signal
1102            // does not keep the process alive.
1103            let ms = super::arg_num(args, 0);
1104            let Value::Obj(idx) = s else {
1105                return Some(Ok(s));
1106            };
1107            let cb = with_host(|h| h.alloc(JsObj::Builtin(format!("@@aborttimeout:{idx}"))));
1108            with_host(|h| {
1109                let id = h.add_timer(ms, cb, Vec::new(), None);
1110                h.set_timer_refed(id, false);
1111            });
1112            Some(Ok(s))
1113        }
1114        "any" => Some(abort_signal_any(
1115            &args.first().cloned().unwrap_or(Value::Undef),
1116        )),
1117        _ => None,
1118    }
1119}
1120
1121// ── fetch ────────────────────────────────────────────────────────────────────
1122
1123/// `fetch(input[, init])` — a Promise for a fully buffered `Response`.
1124pub fn fetch(args: &[Value]) -> Result<Value, String> {
1125    let promise = with_host(|h| h.new_promise());
1126    let id = with_host(|h| h.promise_id(&promise).unwrap_or(0));
1127
1128    let input = args.first().cloned().unwrap_or(Value::Undef);
1129    let init = args.get(1).cloned().unwrap_or(Value::Undef);
1130
1131    // `input` is a URL string, a `URL`, or a `Request` (whose method/headers/
1132    // body seed the request, and `init` overrides them).
1133    let from_request = super::native_tag(&input).as_deref() == Some("Request");
1134    let url = if from_request {
1135        prop(&input, "url").map(|v| str_of(&v)).unwrap_or_default()
1136    } else {
1137        str_of(&input)
1138    };
1139
1140    let mut method = if from_request {
1141        prop(&input, "method")
1142            .map(|v| str_of(&v))
1143            .unwrap_or_else(|| "GET".into())
1144    } else {
1145        "GET".into()
1146    };
1147    if let Some(m) = prop(&init, "method") {
1148        method = str_of(&m);
1149    }
1150    method = method.to_ascii_uppercase();
1151
1152    let mut headers: Vec<(String, String)> = Vec::new();
1153    if from_request {
1154        if let Some(h) = prop(&input, "headers") {
1155            headers = headers_entries(&h);
1156        }
1157    }
1158    if let Some(hv) = prop(&init, "headers") {
1159        headers.extend(init_header_entries(&hv));
1160    }
1161
1162    let body = match prop(&init, "body") {
1163        Some(b) => body_init_bytes(Some(&b)),
1164        None if from_request => body_bytes(&input),
1165        None => Vec::new(),
1166    };
1167
1168    // An already-aborted signal rejects before any connection is made.
1169    if let Some(sig) = prop(&init, "signal") {
1170        if matches!(prop(&sig, "@@aborted"), Some(Value::Bool(true))) {
1171            let reason = prop(&sig, "@@reason")
1172                .unwrap_or_else(|| dom_exception("AbortError", "This operation was aborted"));
1173            crate::host::reject_promise_val(id, reason);
1174            return Ok(promise);
1175        }
1176    }
1177
1178    let Some(target) = parse_target(&url) else {
1179        crate::host::reject_promise_val(id, fetch_failed("unknown scheme"));
1180        return Ok(promise);
1181    };
1182
1183    let wire = build_request_bytes(&target, &method, &headers, &body);
1184    let io_tx = with_host(|h| h.io_sender());
1185    with_host(|h| h.incr_handle());
1186    let url_for_response = url.clone();
1187    std::thread::spawn(move || {
1188        let raw = if target.tls {
1189            let config = crate::stdlib::tls::client_config(true);
1190            crate::stdlib::https::exchange(&target.host, target.port, &target.host, config, &wire)
1191        } else {
1192            crate::stdlib::http::exchange(&target.host, target.port, &wire)
1193        };
1194        let _ = io_tx.send(Box::new(move || {
1195            with_host(|h| h.decr_handle());
1196            match raw {
1197                Ok(raw) => {
1198                    let parsed = crate::stdlib::http::parse_raw_response(&raw);
1199                    let (status, message, headers, body) =
1200                        (parsed.status, parsed.message, parsed.headers, parsed.body);
1201                    let resp = build_response(status, &message, &headers, &body, &url_for_response);
1202                    crate::host::resolve_promise_val(id, resp);
1203                }
1204                Err(msg) => crate::host::reject_promise_val(id, fetch_failed(&msg)),
1205            }
1206            Ok(())
1207        }));
1208    });
1209    Ok(promise)
1210}
1211
1212/// node reports EVERY fetch transport failure as `TypeError: fetch failed` and
1213/// puts the detail on `.cause` as a nested `Error`, so the reason is available
1214/// without the message itself varying by platform.
1215fn fetch_failed(cause: &str) -> Value {
1216    with_host(|h| {
1217        let e = crate::builtins::synth_error(h, "TypeError: fetch failed");
1218        let c = crate::builtins::synth_error(h, &format!("Error: {cause}"));
1219        if let Some(JsObj::Object(p)) = h.get_mut(&e) {
1220            p.insert("cause".into(), c);
1221        }
1222        e
1223    })
1224}
1225
1226struct Target {
1227    host: String,
1228    port: u16,
1229    path: String,
1230    tls: bool,
1231}
1232
1233fn parse_target(url: &str) -> Option<Target> {
1234    // Only `http`/`https` are fetchable here; every other scheme (`file:`,
1235    // `data:`, `blob:`) rejects as an unknown scheme.
1236    let (tls, rest) = match url.strip_prefix("https://") {
1237        Some(r) => (true, r),
1238        None => (false, url.strip_prefix("http://")?),
1239    };
1240    let (authority, path) = match rest.find('/') {
1241        Some(i) => (&rest[..i], rest[i..].to_string()),
1242        None => (rest, "/".to_string()),
1243    };
1244    let authority = authority.split('@').next_back().unwrap_or(authority);
1245    let (host, port) = match authority.rsplit_once(':') {
1246        Some((h, p)) => match p.parse::<u16>() {
1247            Ok(n) => (h.to_string(), n),
1248            Err(_) => (authority.to_string(), if tls { 443 } else { 80 }),
1249        },
1250        None => (authority.to_string(), if tls { 443 } else { 80 }),
1251    };
1252    if host.is_empty() {
1253        return None;
1254    }
1255    Some(Target {
1256        host,
1257        port,
1258        path,
1259        tls,
1260    })
1261}
1262
1263fn build_request_bytes(
1264    target: &Target,
1265    method: &str,
1266    headers: &[(String, String)],
1267    body: &[u8],
1268) -> Vec<u8> {
1269    let mut has_host = false;
1270    let mut has_len = false;
1271    let mut block = String::new();
1272    for (k, v) in headers {
1273        if k.eq_ignore_ascii_case("host") {
1274            has_host = true;
1275        }
1276        if k.eq_ignore_ascii_case("content-length") {
1277            has_len = true;
1278        }
1279        if k.eq_ignore_ascii_case("connection") {
1280            continue;
1281        }
1282        block.push_str(&format!("{k}: {v}\r\n"));
1283    }
1284    let default_port = if target.tls { 443 } else { 80 };
1285    let host_header = if target.port == default_port {
1286        target.host.clone()
1287    } else {
1288        format!("{}:{}", target.host, target.port)
1289    };
1290    let mut req = format!("{method} {} HTTP/1.1\r\n", target.path);
1291    if !has_host {
1292        req.push_str(&format!("Host: {host_header}\r\n"));
1293    }
1294    req.push_str(&block);
1295    if !has_len && !body.is_empty() {
1296        req.push_str(&format!("Content-Length: {}\r\n", body.len()));
1297    }
1298    // Every exchange reads to EOF, so the connection must not be kept alive.
1299    req.push_str("Connection: close\r\n\r\n");
1300    let mut wire = req.into_bytes();
1301    wire.extend_from_slice(body);
1302    wire
1303}
1304
1305// ── dispatch ─────────────────────────────────────────────────────────────────
1306
1307pub fn instance_call(
1308    tag: &str,
1309    recv: &Value,
1310    method: &str,
1311    args: &[Value],
1312) -> Result<Value, String> {
1313    match tag {
1314        "Headers" => headers_call(recv, method, args),
1315        "FormData" => form_data_call(recv, method, args),
1316        "AbortController" => abort_controller_call(recv, method, args),
1317        "AbortSignal" => abort_signal_call(recv, method, args),
1318        _ => body_call(recv, method, args),
1319    }
1320}
1321
1322pub fn construct(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
1323    Some(match name {
1324        "Headers" => construct_headers(args),
1325        "Request" => construct_request(args),
1326        "Response" => construct_response(args),
1327        "Blob" => construct_blob(args),
1328        "File" => construct_file(args),
1329        "FormData" => construct_form_data(args),
1330        "AbortController" => construct_abort_controller(args),
1331        "AbortSignal" => Err(crate::host::type_error(
1332            "Illegal constructor: use AbortSignal.abort() or AbortSignal.timeout()",
1333        )),
1334        _ => return None,
1335    })
1336}
1337
1338/// The static methods of these classes (`Response.json`, `AbortSignal.abort`, …).
1339pub fn static_call(ns: &str, method: &str, args: &[Value]) -> Option<Result<Value, String>> {
1340    match ns {
1341        "AbortSignal" => abort_signal_static(method, args),
1342        "Response" => match method {
1343            "json" => {
1344                let body = crate::builtins::call_builtin_function(
1345                    "JSON.stringify",
1346                    vec![args.first()?.clone()],
1347                )
1348                .map(|v| str_of(&v))
1349                .unwrap_or_default();
1350                let init = args.get(1).cloned().unwrap_or(Value::Undef);
1351                let status = match prop(&init, "status") {
1352                    Some(v) => with_host(|h| h.to_number(&v)) as u16,
1353                    None => 200,
1354                };
1355                let mut headers =
1356                    vec![("content-type".to_string(), "application/json".to_string())];
1357                if let Some(hv) = prop(&init, "headers") {
1358                    headers.extend(init_header_entries(&hv));
1359                }
1360                Some(Ok(build_response(
1361                    status,
1362                    "",
1363                    &headers,
1364                    body.as_bytes(),
1365                    "",
1366                )))
1367            }
1368            "error" => Some(Ok(build_response(0, "", &[], &[], ""))),
1369            "redirect" => {
1370                let loc = super::arg_str(args, 0);
1371                let status = match args.get(1) {
1372                    Some(v) => with_host(|h| h.to_number(v)) as u16,
1373                    None => 302,
1374                };
1375                Some(Ok(build_response(
1376                    status,
1377                    "",
1378                    &[("location".into(), loc)],
1379                    &[],
1380                    "",
1381                )))
1382            }
1383            _ => None,
1384        },
1385        _ => None,
1386    }
1387}
1388
1389pub const RESPONSE_STATICS: &[&str] = &["json", "error", "redirect"];
1390pub const ABORT_SIGNAL_STATICS: &[&str] = &["abort", "timeout", "any"];