Skip to main content

strata_js/
web.rs

1//! Universal Web Platform APIs implemented in pure standard-library Rust.
2
3use crate::JsValue;
4use std::cell::RefCell;
5use std::collections::BTreeMap;
6use std::rc::Rc;
7use std::time::{Duration, Instant};
8
9/// W3C-compliant case-insensitive HTTP Headers map.
10#[derive(Debug, Default, Clone, PartialEq)]
11pub struct Headers {
12    // Stores lowercase name -> (display_name, list of values)
13    entries: BTreeMap<String, (String, Vec<String>)>,
14}
15
16impl Headers {
17    /// Creates an empty `Headers` instance.
18    pub fn new() -> Self {
19        Self::default()
20    }
21
22    /// Sets a header, overwriting any previous values for this header name.
23    pub fn set(&mut self, name: impl Into<String>, value: impl Into<String>) {
24        let name_str = name.into();
25        let lower = name_str.to_ascii_lowercase();
26        self.entries.insert(lower, (name_str, vec![value.into()]));
27    }
28
29    /// Appends a value to an existing header, or creates it if it does not exist.
30    pub fn append(&mut self, name: impl Into<String>, value: impl Into<String>) {
31        let name_str = name.into();
32        let lower = name_str.to_ascii_lowercase();
33        self.entries
34            .entry(lower)
35            .or_insert_with(|| (name_str, Vec::new()))
36            .1
37            .push(value.into());
38    }
39
40    /// Retrieves the combined comma-separated string for a given header name, if it exists.
41    pub fn get(&self, name: &str) -> Option<String> {
42        let lower = name.to_ascii_lowercase();
43        self.entries.get(&lower).map(|(_, vals)| vals.join(", "))
44    }
45
46    /// Retrieves all individual values for a given header name.
47    pub fn get_all(&self, name: &str) -> Vec<&str> {
48        let lower = name.to_ascii_lowercase();
49        self.entries
50            .get(&lower)
51            .map(|(_, vals)| vals.iter().map(|s| s.as_str()).collect())
52            .unwrap_or_default()
53    }
54
55    /// Returns `true` if the specified header exists.
56    pub fn has(&self, name: &str) -> bool {
57        self.entries.contains_key(&name.to_ascii_lowercase())
58    }
59
60    /// Deletes a header by name (case-insensitive).
61    pub fn delete(&mut self, name: &str) {
62        self.entries.remove(&name.to_ascii_lowercase());
63    }
64
65    /// Returns all header entries as (name, comma-joined-value) pairs.
66    pub fn entries(&self) -> Vec<(String, String)> {
67        self.entries
68            .values()
69            .map(|(name, vals)| (name.clone(), vals.join(", ")))
70            .collect()
71    }
72}
73
74/// Request configuration passed to `fetch()`.
75#[derive(Debug, Clone)]
76pub struct RequestInit {
77    pub method: String,
78    pub headers: Headers,
79    pub body: Option<String>,
80}
81
82impl Default for RequestInit {
83    fn default() -> Self {
84        Self {
85            method: "GET".to_string(),
86            headers: Headers::new(),
87            body: None,
88        }
89    }
90}
91
92/// HTTP Response representing the result of an HTTP operation.
93#[derive(Debug, Clone)]
94pub struct Response {
95    pub status: u16,
96    pub status_text: String,
97    pub ok: bool,
98    pub headers: Headers,
99    body: Vec<u8>,
100}
101
102impl Response {
103    /// Constructs a new `Response` object.
104    pub fn new(body: Vec<u8>, status: u16, headers: Headers) -> Self {
105        let ok = (200..=299).contains(&status);
106        let status_text = match status {
107            200 => "OK",
108            201 => "Created",
109            204 => "No Content",
110            400 => "Bad Request",
111            401 => "Unauthorized",
112            403 => "Forbidden",
113            404 => "Not Found",
114            500 => "Internal Server Error",
115            _ => "Unknown",
116        }
117        .to_string();
118
119        Self {
120            status,
121            status_text,
122            ok,
123            headers,
124            body,
125        }
126    }
127
128    /// Decodes the response body as a UTF-8 text string.
129    pub async fn text(self) -> Result<String, String> {
130        String::from_utf8(self.body).map_err(|e| format!("Invalid UTF-8 in response body: {}", e))
131    }
132
133    /// Decodes and parses the response body as a dynamic `JsValue` via JSON parser.
134    pub async fn json(self) -> Result<JsValue, String> {
135        let text = self.text().await?;
136        crate::json::parse_json(&text)
137    }
138}
139
140/// Asynchronous fetch connecting to physical networking via `strata_web_api`.
141pub async fn fetch(url: &str, init: Option<RequestInit>) -> Result<Response, String> {
142    let init = init.unwrap_or_default();
143
144    // Check for explicit synthetic test mock scheme for offline hermetic tests
145    if url.starts_with("mock://") {
146        let body_bytes = b"{\"status\":\"ok\"}".to_vec();
147        let mut headers = Headers::new();
148        headers.set("content-type", "application/json");
149        return Ok(Response::new(body_bytes, 200, headers));
150    }
151
152    let mut web_req = strata_web_api::fetch::RequestInit {
153        method: init.method,
154        ..Default::default()
155    };
156    for (k, v) in init.headers.entries() {
157        web_req.headers.set(&k, &v);
158    }
159    if let Some(body_str) = init.body {
160        web_req = web_req.body(body_str.into_bytes());
161    }
162
163    let resp = strata_web_api::fetch::fetch(url, Some(web_req))
164        .map_err(|e| format!("TypeError: Failed to fetch {}: {}", url, e))?;
165
166    let mut headers = Headers::new();
167    for (k, v) in resp.headers.all_entries() {
168        headers.append(k, v);
169    }
170
171    let mut result_resp = Response::new(resp.bytes().to_vec(), resp.status, headers);
172    result_resp.status_text = resp.status_text;
173    Ok(result_resp)
174}
175
176/// URLSearchParams: Parsing, manipulating, and serializing URL query parameters.
177#[derive(Debug, Default, Clone, PartialEq)]
178pub struct URLSearchParams {
179    params: Vec<(String, String)>,
180}
181
182impl URLSearchParams {
183    /// Creates an empty `URLSearchParams`.
184    pub fn new() -> Self {
185        Self::default()
186    }
187
188    /// Parses a query string (with or without a leading '?').
189    pub fn parse(query: &str) -> Self {
190        let query = query.strip_prefix('?').unwrap_or(query);
191        let mut params = Vec::new();
192
193        if query.is_empty() {
194            return Self { params };
195        }
196
197        for pair in query.split('&') {
198            if pair.is_empty() {
199                continue;
200            }
201            let mut parts = pair.splitn(2, '=');
202            let key_enc = parts.next().unwrap_or("");
203            let val_enc = parts.next().unwrap_or("");
204
205            let key = decode_uri_component(key_enc);
206            let val = decode_uri_component(val_enc);
207            params.push((key, val));
208        }
209
210        Self { params }
211    }
212
213    /// Returns the first value associated with the given search parameter.
214    pub fn get(&self, name: &str) -> Option<&str> {
215        self.params
216            .iter()
217            .find(|(k, _)| k == name)
218            .map(|(_, v)| v.as_str())
219    }
220
221    /// Returns all values associated with the given search parameter.
222    pub fn get_all(&self, name: &str) -> Vec<&str> {
223        self.params
224            .iter()
225            .filter(|(k, _)| k == name)
226            .map(|(_, v)| v.as_str())
227            .collect()
228    }
229
230    /// Returns `true` if the search parameter exists.
231    pub fn has(&self, name: &str) -> bool {
232        self.params.iter().any(|(k, _)| k == name)
233    }
234
235    /// Appends a new name-value pair.
236    pub fn append(&mut self, name: impl Into<String>, value: impl Into<String>) {
237        self.params.push((name.into(), value.into()));
238    }
239
240    /// Sets the value associated with a given name, replacing all existing pairs with that name.
241    pub fn set(&mut self, name: impl Into<String>, value: impl Into<String>) {
242        let name_str = name.into();
243        let value_str = value.into();
244        let mut replaced = false;
245        let mut i = 0;
246
247        while i < self.params.len() {
248            if self.params[i].0 == name_str {
249                if !replaced {
250                    self.params[i].1 = value_str.clone();
251                    replaced = true;
252                    i += 1;
253                } else {
254                    self.params.remove(i);
255                }
256            } else {
257                i += 1;
258            }
259        }
260
261        if !replaced {
262            self.params.push((name_str, value_str));
263        }
264    }
265
266    /// Deletes all occurrences of the specified parameter.
267    pub fn delete(&mut self, name: &str) {
268        self.params.retain(|(k, _)| k != name);
269    }
270
271    /// Sorts all key/value pairs by their keys using unicode code points.
272    pub fn sort(&mut self) {
273        self.params.sort_by(|a, b| a.0.cmp(&b.0));
274    }
275
276    /// Serializes parameters back into standard application/x-www-form-urlencoded query string.
277    pub fn to_query_string(&self) -> String {
278        let mut out = String::new();
279        for (i, (k, v)) in self.params.iter().enumerate() {
280            if i > 0 {
281                out.push('&');
282            }
283            out.push_str(&encode_uri_component(k));
284            out.push('=');
285            out.push_str(&encode_uri_component(v));
286        }
287        out
288    }
289}
290
291fn decode_uri_component(s: &str) -> String {
292    let s = s.replace('+', " ");
293    let bytes = s.as_bytes();
294    let mut result = Vec::new();
295    let mut i = 0;
296
297    while i < bytes.len() {
298        if bytes[i] == b'%' && i + 2 < bytes.len() {
299            if let Ok(hex_str) = std::str::from_utf8(&bytes[i + 1..i + 3]) {
300                if let Ok(b) = u8::from_str_radix(hex_str, 16) {
301                    result.push(b);
302                    i += 3;
303                    continue;
304                }
305            }
306        }
307        result.push(bytes[i]);
308        i += 1;
309    }
310
311    String::from_utf8_lossy(&result).into_owned()
312}
313
314fn encode_uri_component(s: &str) -> String {
315    let mut out = String::new();
316    for b in s.as_bytes() {
317        match *b {
318            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
319                out.push(*b as char);
320            }
321            b' ' => out.push('+'),
322            other => {
323                out.push_str(&format!("%{:02X}", other));
324            }
325        }
326    }
327    out
328}
329
330/// Web Storage API (localStorage, sessionStorage).
331#[derive(Debug, Clone, Default)]
332pub struct Storage {
333    data: Rc<RefCell<BTreeMap<String, String>>>,
334}
335
336impl Storage {
337    pub fn new() -> Self {
338        Self::default()
339    }
340
341    pub fn length(&self) -> usize {
342        self.data.borrow().len()
343    }
344
345    pub fn key(&self, index: usize) -> Option<String> {
346        self.data.borrow().keys().nth(index).cloned()
347    }
348
349    pub fn get_item(&self, key: &str) -> Option<String> {
350        self.data.borrow().get(key).cloned()
351    }
352
353    pub fn set_item(&self, key: impl Into<String>, value: impl Into<String>) {
354        self.data.borrow_mut().insert(key.into(), value.into());
355    }
356
357    pub fn remove_item(&self, key: &str) {
358        self.data.borrow_mut().remove(key);
359    }
360
361    pub fn clear(&self) {
362        self.data.borrow_mut().clear();
363    }
364}
365
366thread_local! {
367    static LOCAL_STORAGE: Storage = Storage::new();
368    static SESSION_STORAGE: Storage = Storage::new();
369}
370
371/// Returns the singleton `localStorage` for the current thread/context.
372pub fn local_storage() -> Storage {
373    LOCAL_STORAGE.with(|s| s.clone())
374}
375
376/// Returns the singleton `sessionStorage` for the current thread/context.
377pub fn session_storage() -> Storage {
378    SESSION_STORAGE.with(|s| s.clone())
379}
380
381/// Zero-dependency High-Resolution Timer Scheduler.
382pub type TimerId = usize;
383
384enum TimerEntry {
385    Timeout {
386        id: TimerId,
387        trigger_at: Instant,
388        callback: Option<Box<dyn FnOnce()>>,
389        cancelled: bool,
390    },
391    Interval {
392        id: TimerId,
393        interval: Duration,
394        next_trigger: Instant,
395        callback: Box<dyn FnMut()>,
396        cancelled: bool,
397    },
398}
399
400struct TimerScheduler {
401    next_id: usize,
402    entries: Vec<TimerEntry>,
403    simulated_offset: Duration,
404}
405
406impl TimerScheduler {
407    fn new() -> Self {
408        Self {
409            next_id: 1,
410            entries: Vec::new(),
411            simulated_offset: Duration::ZERO,
412        }
413    }
414
415    fn current_time(&self) -> Instant {
416        Instant::now() + self.simulated_offset
417    }
418
419    fn add_timeout(&mut self, callback: Box<dyn FnOnce()>, delay_ms: u64) -> TimerId {
420        let id = self.next_id;
421        self.next_id += 1;
422        let trigger_at = self.current_time() + Duration::from_millis(delay_ms);
423        self.entries.push(TimerEntry::Timeout {
424            id,
425            trigger_at,
426            callback: Some(callback),
427            cancelled: false,
428        });
429        id
430    }
431
432    fn add_interval(&mut self, callback: Box<dyn FnMut()>, interval_ms: u64) -> TimerId {
433        let id = self.next_id;
434        self.next_id += 1;
435        let interval = Duration::from_millis(interval_ms);
436        let next_trigger = self.current_time() + interval;
437        self.entries.push(TimerEntry::Interval {
438            id,
439            interval,
440            next_trigger,
441            callback,
442            cancelled: false,
443        });
444        id
445    }
446
447    fn cancel(&mut self, id: TimerId) {
448        for entry in &mut self.entries {
449            match entry {
450                TimerEntry::Timeout {
451                    id: entry_id,
452                    cancelled,
453                    ..
454                }
455                | TimerEntry::Interval {
456                    id: entry_id,
457                    cancelled,
458                    ..
459                } => {
460                    if *entry_id == id {
461                        *cancelled = true;
462                    }
463                }
464            }
465        }
466    }
467
468    fn tick(&mut self) -> usize {
469        let now = self.current_time();
470        let mut fired = 0;
471        let mut pending_timeouts = Vec::new();
472        let mut pending_intervals = Vec::new();
473
474        for (idx, entry) in self.entries.iter_mut().enumerate() {
475            match entry {
476                TimerEntry::Timeout {
477                    trigger_at,
478                    cancelled,
479                    callback,
480                    ..
481                } => {
482                    if !*cancelled && now >= *trigger_at {
483                        if let Some(cb) = callback.take() {
484                            pending_timeouts.push(cb);
485                            *cancelled = true;
486                            fired += 1;
487                        }
488                    }
489                }
490                TimerEntry::Interval {
491                    next_trigger,
492                    interval,
493                    cancelled,
494                    ..
495                } => {
496                    if !*cancelled && now >= *next_trigger {
497                        pending_intervals.push(idx);
498                        *next_trigger = now + *interval;
499                        fired += 1;
500                    }
501                }
502            }
503        }
504
505        // Execute timeouts
506        for cb in pending_timeouts {
507            cb();
508        }
509
510        // Execute intervals
511        for idx in pending_intervals {
512            if let Some(TimerEntry::Interval {
513                callback,
514                cancelled,
515                ..
516            }) = self.entries.get_mut(idx)
517            {
518                if !*cancelled {
519                    callback();
520                }
521            }
522        }
523
524        // Purge cancelled and consumed timeouts
525        self.entries.retain(|e| match e {
526            TimerEntry::Timeout { cancelled, .. } => !*cancelled,
527            TimerEntry::Interval { cancelled, .. } => !*cancelled,
528        });
529
530        fired
531    }
532
533    fn advance_time(&mut self, delta: Duration) -> usize {
534        self.simulated_offset += delta;
535        self.tick()
536    }
537
538    fn time_until_next(&self) -> Option<Duration> {
539        let now = self.current_time();
540        self.entries
541            .iter()
542            .filter_map(|e| match e {
543                TimerEntry::Timeout {
544                    trigger_at,
545                    cancelled,
546                    ..
547                } if !*cancelled => {
548                    if *trigger_at > now {
549                        Some(*trigger_at - now)
550                    } else {
551                        Some(Duration::ZERO)
552                    }
553                }
554                TimerEntry::Interval {
555                    next_trigger,
556                    cancelled,
557                    ..
558                } if !*cancelled => {
559                    if *next_trigger > now {
560                        Some(*next_trigger - now)
561                    } else {
562                        Some(Duration::ZERO)
563                    }
564                }
565                _ => None,
566            })
567            .min()
568    }
569}
570
571thread_local! {
572    static TIMER_SCHEDULER: RefCell<TimerScheduler> = RefCell::new(TimerScheduler::new());
573}
574
575/// Schedules a callback to execute after `delay_ms` milliseconds.
576pub fn set_timeout<F: FnOnce() + 'static>(callback: F, delay_ms: u64) -> TimerId {
577    TIMER_SCHEDULER.with(|s| s.borrow_mut().add_timeout(Box::new(callback), delay_ms))
578}
579
580/// Cancels a previously scheduled timeout.
581pub fn clear_timeout(id: TimerId) {
582    TIMER_SCHEDULER.with(|s| s.borrow_mut().cancel(id));
583}
584
585/// Schedules a callback to execute repeatedly every `interval_ms` milliseconds.
586pub fn set_interval<F: FnMut() + 'static>(callback: F, interval_ms: u64) -> TimerId {
587    TIMER_SCHEDULER.with(|s| s.borrow_mut().add_interval(Box::new(callback), interval_ms))
588}
589
590/// Cancels a previously scheduled interval.
591pub fn clear_interval(id: TimerId) {
592    TIMER_SCHEDULER.with(|s| s.borrow_mut().cancel(id));
593}
594
595/// Ticks active timers and executes any due callbacks.
596pub fn tick_timers() -> usize {
597    TIMER_SCHEDULER.with(|s| s.borrow_mut().tick())
598}
599
600/// Returns the duration until the next timer is scheduled to fire, or None if no timers are active.
601pub fn time_until_next_timer() -> Option<Duration> {
602    TIMER_SCHEDULER.with(|s| s.borrow().time_until_next())
603}
604
605/// Returns true if there are any active, uncancelled timeouts or intervals.
606pub fn has_pending_timers() -> bool {
607    TIMER_SCHEDULER.with(|s| {
608        s.borrow().entries.iter().any(|e| match e {
609            TimerEntry::Timeout { cancelled, .. } | TimerEntry::Interval { cancelled, .. } => {
610                !*cancelled
611            }
612        })
613    })
614}
615
616/// Advances the simulated timer clock by a given duration and executes due timers.
617/// Essential for instant, deterministic timer testing without sleeping.
618pub fn advance_timers_by(delta: Duration) -> usize {
619    TIMER_SCHEDULER.with(|s| s.borrow_mut().advance_time(delta))
620}