Skip to main content

eggfetch_node/
response.rs

1//! Eggfetch Response for Node.js.
2
3use napi::bindgen_prelude::Buffer;
4use napi_derive::napi;
5use std::collections::HashMap;
6use std::ptr;
7
8/// HTTP response from eggfetch.
9#[napi]
10pub struct EggfetchResponse {
11    status: u32,
12    url: String,
13    /// All header pairs in wire order. Duplicates (e.g. multiple
14    /// `Set-Cookie` headers) are preserved; use `getAll` to observe
15    /// every value for a name.
16    headers: Vec<(String, String)>,
17    body: Vec<u8>,
18}
19
20impl EggfetchResponse {
21    /// Create from a raw FFI response handle, consuming it immediately.
22    pub(crate) fn from_raw(resp: *mut eggfetch_ffi::ResponseHandle) -> napi::Result<Self> {
23        unsafe {
24            let status = u32::from(eggfetch_ffi::eggfetch_response_status(resp));
25            let url_ptr = eggfetch_ffi::eggfetch_response_url(resp);
26            let url = if url_ptr.is_null() {
27                String::new()
28            } else {
29                std::ffi::CStr::from_ptr(url_ptr)
30                    .to_string_lossy()
31                    .into_owned()
32            };
33            if !url_ptr.is_null() {
34                eggfetch_ffi::eggfetch_string_free(url_ptr);
35            }
36
37            let header_count = eggfetch_ffi::eggfetch_response_header_count(resp);
38            let mut headers = Vec::with_capacity(header_count);
39            for i in 0..header_count {
40                let mut name: *mut std::os::raw::c_char = ptr::null_mut();
41                let mut value: *mut std::os::raw::c_char = ptr::null_mut();
42                let rc =
43                    eggfetch_ffi::eggfetch_response_header(resp, i, &raw mut name, &raw mut value);
44                if rc == 0 {
45                    let n = if name.is_null() {
46                        String::new()
47                    } else {
48                        std::ffi::CStr::from_ptr(name)
49                            .to_string_lossy()
50                            .into_owned()
51                    };
52                    let v = if value.is_null() {
53                        String::new()
54                    } else {
55                        std::ffi::CStr::from_ptr(value)
56                            .to_string_lossy()
57                            .into_owned()
58                    };
59                    if !name.is_null() {
60                        eggfetch_ffi::eggfetch_string_free(name);
61                    }
62                    if !value.is_null() {
63                        eggfetch_ffi::eggfetch_string_free(value);
64                    }
65                    headers.push((n, v));
66                } else {
67                    // Interior-NUL or out-of-range header: fail loudly
68                    // instead of silently dropping the header.
69                    eggfetch_ffi::eggfetch_response_free(resp);
70                    return Err(napi::Error::from_reason(format!(
71                        "failed to read response header at index {i} (code {rc})"
72                    )));
73                }
74            }
75
76            let mut body_ptr = ptr::null_mut();
77            let mut body_len = 0;
78            let rc =
79                eggfetch_ffi::eggfetch_response_body(resp, &raw mut body_ptr, &raw mut body_len);
80            let body = if rc == 0 && (body_len == 0 || !body_ptr.is_null()) {
81                if body_len == 0 {
82                    Vec::new()
83                } else {
84                    let body = std::slice::from_raw_parts(body_ptr, body_len).to_vec();
85                    eggfetch_ffi::eggfetch_body_free(body_ptr, body_len);
86                    body
87                }
88            } else {
89                // Allocation failure or backend error: propagate instead
90                // of returning an empty body indistinguishable from `""`.
91                eggfetch_ffi::eggfetch_response_free(resp);
92                return Err(napi::Error::from_reason(format!(
93                    "failed to read response body (code {rc})"
94                )));
95            };
96
97            eggfetch_ffi::eggfetch_response_free(resp);
98
99            Ok(Self {
100                status,
101                url,
102                headers,
103                body,
104            })
105        }
106    }
107}
108
109/// Strip `userinfo@` from a URL for display (mirrors the CLI/Python
110/// `safe_url_for_display` so credentials never leak through the getter).
111fn safe_url_for_display(url: &str) -> String {
112    let authority_start = url.find("://").map_or(0, |i| i + 3);
113    let (prefix, rest) = url.split_at(authority_start);
114    let after_userinfo = match rest.find('@') {
115        Some(at) => {
116            let slash = rest.find('/').unwrap_or(rest.len());
117            if at < slash {
118                &rest[at + 1..]
119            } else {
120                rest
121            }
122        }
123        None => rest,
124    };
125    format!("{prefix}{after_userinfo}")
126}
127
128#[napi]
129impl EggfetchResponse {
130    /// HTTP status code.
131    #[napi(getter)]
132    pub fn status(&self) -> u32 {
133        self.status
134    }
135
136    /// Response URL.
137    #[napi(getter)]
138    pub fn url(&self) -> String {
139        safe_url_for_display(&self.url)
140    }
141
142    /// Response body as text.
143    #[napi(getter)]
144    pub fn text(&self) -> String {
145        String::from_utf8_lossy(&self.body).into_owned()
146    }
147
148    /// Response body as a Node.js `Buffer`.
149    #[napi(getter)]
150    pub fn bytes(&self) -> Buffer {
151        Buffer::from(self.body.clone())
152    }
153
154    /// Response body as JSON (parsed).
155    ///
156    /// # Errors
157    ///
158    /// Returns an error if the body is not valid JSON.
159    #[napi(getter)]
160    pub fn json(&self) -> napi::Result<serde_json::Value> {
161        serde_json::from_slice(&self.body)
162            .map_err(|e| napi::Error::from_reason(format!("JSON parse error: {e}")))
163    }
164
165    /// Response headers as an object.
166    ///
167    /// When a header appears multiple times, the object joins the values
168    /// with `", "` (standard HTTP combining). Use [`Self::get_all`] to
169    /// retrieve every value individually. Keys are lowercased so mixed-case
170    /// duplicates (e.g. `X-Foo` + `x-foo`) join instead of splitting.
171    #[napi(getter)]
172    pub fn headers(&self) -> HashMap<String, String> {
173        let mut map: HashMap<String, String> = HashMap::with_capacity(self.headers.len());
174        for (name, value) in &self.headers {
175            match map.entry(name.to_ascii_lowercase()) {
176                std::collections::hash_map::Entry::Occupied(mut existing) => {
177                    let joined = existing.get_mut();
178                    joined.push_str(", ");
179                    joined.push_str(value);
180                }
181                std::collections::hash_map::Entry::Vacant(slot) => {
182                    slot.insert(value.clone());
183                }
184            }
185        }
186        map
187    }
188
189    /// All values for a response header, case-insensitively.
190    ///
191    /// Unlike the `headers` object, this preserves duplicate headers
192    /// such as multiple `Set-Cookie` lines.
193    // N-API method arguments must be owned (`FromNapiValue`) values;
194    // taking `&str` is not expressible here.
195    #[allow(clippy::needless_pass_by_value)]
196    #[napi]
197    pub fn get_all(&self, name: String) -> Vec<String> {
198        self.headers
199            .iter()
200            .filter(|(header_name, _)| header_name.eq_ignore_ascii_case(&name))
201            .map(|(_, value)| value.clone())
202            .collect()
203    }
204
205    /// Whether the response status is 2xx.
206    #[napi(getter)]
207    pub fn ok(&self) -> bool {
208        (200..300).contains(&self.status)
209    }
210}