expo-modules-rs 0.1.1

Rust SDK for writing Expo native modules via direct JSI integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
use crate::bridge::ffi::{self, FfiValue, RuntimeHandle, ValueKind};
use crate::bridge::current_runtime_ptr;
use std::collections::HashMap;

/// Error type for Expo module functions.
/// When a function returns `Result<T, ExpoError>`, the error is propagated
/// as a JavaScript exception.
#[derive(Debug, Clone, thiserror::Error)]
#[error("{message}")]
pub struct ExpoError {
    pub code: String,
    pub message: String,
}

impl ExpoError {
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
        }
    }
}

impl From<String> for ExpoError {
    fn from(message: String) -> Self {
        Self {
            code: "ERR_RUST_MODULE".to_owned(),
            message,
        }
    }
}

impl From<&str> for ExpoError {
    fn from(message: &str) -> Self {
        Self::from(message.to_owned())
    }
}

/// A JavaScript value that can be passed to/from native Rust code.
#[derive(Debug, Clone)]
pub enum JsValue {
    Undefined,
    Null,
    Bool(bool),
    Number(f64),
    String(String),
    Object(JsObject),
    Array(JsArray),
    /// A map of key-value pairs representing a JS object's properties.
    /// Used for Record conversion — avoids needing Runtime access in FromJsValue.
    /// The FFI layer converts this to/from real JSI objects.
    Map(HashMap<String, JsValue>),
    /// Internal variant representing an error that should become a JS exception.
    /// Not directly mapped to a JS value type — the install layer converts this
    /// to a thrown error.
    Error(String),
}

/// Handle to a JavaScript object living in the JSI runtime.
#[derive(Debug, Clone)]
pub struct JsObject {
    pub handle: u64,
}

/// Handle to a JavaScript array living in the JSI runtime.
#[derive(Debug, Clone)]
pub struct JsArray {
    pub handle: u64,
}

/// A reference to the JSI runtime, required for object/array operations.
pub struct Runtime {
    pub handle: RuntimeHandle,
}

// ---- JsValue conversions ----

impl JsValue {
    /// Convert an FFI value into a JsValue.
    /// Used internally by the bridge; also useful for integration tests.
    pub fn from_ffi(ffi: FfiValue) -> Self {
        match ffi.kind {
            ValueKind::Undefined => JsValue::Undefined,
            ValueKind::Null => JsValue::Null,
            ValueKind::Boolean => JsValue::Bool(ffi.bool_val),
            ValueKind::Number => JsValue::Number(ffi.number_val),
            ValueKind::String => JsValue::String(ffi.string_val.clone()),
            ValueKind::Object => JsValue::Object(JsObject { handle: ffi.handle }),
            ValueKind::Array => JsValue::Array(JsArray { handle: ffi.handle }),
            _ => JsValue::Undefined,
        }
    }

    /// Convert this JsValue to an FFI representation.
    /// Used internally by the bridge; also useful for integration tests.
    pub fn to_ffi(&self) -> FfiValue {
        match self {
            JsValue::Undefined => ffi::jsi_make_undefined(),
            JsValue::Null => ffi::jsi_make_null(),
            JsValue::Bool(v) => ffi::jsi_make_bool(*v),
            JsValue::Number(v) => ffi::jsi_make_number(*v),
            JsValue::String(s) => ffi::jsi_make_string(s.as_str()),
            JsValue::Object(obj) => FfiValue {
                kind: ValueKind::Object,
                bool_val: false,
                number_val: 0.0,
                string_val: String::new(),
                handle: obj.handle,
            },
            JsValue::Array(arr) => FfiValue {
                kind: ValueKind::Array,
                bool_val: false,
                number_val: 0.0,
                string_val: String::new(),
                handle: arr.handle,
            },
            // Map is converted to a real JSI object by creating one and setting properties.
            // This requires a Runtime — use the thread-local current runtime.
            JsValue::Map(map) => {
                if let Some(rt_ptr) = current_runtime_ptr() {
                    let rt_handle = RuntimeHandle { ptr: rt_ptr };
                    let obj_ffi = ffi::jsi_create_object(&rt_handle);
                    for (key, val) in map {
                        let val_ffi = val.to_ffi();
                        ffi::jsi_object_set_property(&rt_handle, obj_ffi.handle, key.as_str(), &val_ffi);
                    }
                    FfiValue {
                        kind: ValueKind::Object,
                        bool_val: false,
                        number_val: 0.0,
                        string_val: String::new(),
                        handle: obj_ffi.handle,
                    }
                } else {
                    // No runtime available (e.g. in tests) — fall back to undefined
                    ffi::jsi_make_undefined()
                }
            }
            // Error is serialized as a string; the callback dispatcher
            // checks for this and can throw a JS exception.
            JsValue::Error(msg) => ffi::jsi_make_string(msg.as_str()),
        }
    }

    pub fn is_error(&self) -> bool {
        matches!(self, JsValue::Error(_))
    }
    pub fn as_error(&self) -> Option<&str> {
        match self {
            JsValue::Error(s) => Some(s.as_str()),
            _ => None,
        }
    }

    /// Convert a JsObject to a HashMap by reading known property names via the FFI.
    /// Used by the ExpoRecord derive macro when a real JSI object is passed as a function arg.
    pub fn object_to_map(obj: &JsObject, keys: &[&str]) -> HashMap<String, JsValue> {
        let mut map = HashMap::new();
        if let Some(rt_ptr) = current_runtime_ptr() {
            let rt_handle = RuntimeHandle { ptr: rt_ptr };
            for &key in keys {
                let ffi_val = ffi::jsi_object_get_property(&rt_handle, obj.handle, key);
                let val = JsValue::from_ffi(ffi_val);
                if !val.is_undefined() {
                    map.insert(key.to_owned(), val);
                }
            }
        }
        map
    }

    pub fn is_undefined(&self) -> bool {
        matches!(self, JsValue::Undefined)
    }
    pub fn is_null(&self) -> bool {
        matches!(self, JsValue::Null)
    }
    pub fn is_bool(&self) -> bool {
        matches!(self, JsValue::Bool(_))
    }
    pub fn is_number(&self) -> bool {
        matches!(self, JsValue::Number(_))
    }
    pub fn is_string(&self) -> bool {
        matches!(self, JsValue::String(_))
    }
    pub fn is_object(&self) -> bool {
        matches!(self, JsValue::Object(_))
    }
    pub fn is_array(&self) -> bool {
        matches!(self, JsValue::Array(_))
    }
    pub fn is_map(&self) -> bool {
        matches!(self, JsValue::Map(_))
    }

    pub fn as_map(&self) -> Option<&HashMap<String, JsValue>> {
        match self {
            JsValue::Map(m) => Some(m),
            _ => None,
        }
    }
    pub fn into_map(self) -> Option<HashMap<String, JsValue>> {
        match self {
            JsValue::Map(m) => Some(m),
            _ => None,
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self {
            JsValue::Bool(v) => Some(*v),
            _ => None,
        }
    }
    pub fn as_number(&self) -> Option<f64> {
        match self {
            JsValue::Number(v) => Some(*v),
            _ => None,
        }
    }
    pub fn as_str(&self) -> Option<&str> {
        match self {
            JsValue::String(s) => Some(s.as_str()),
            _ => None,
        }
    }
    pub fn as_object(&self) -> Option<&JsObject> {
        match self {
            JsValue::Object(o) => Some(o),
            _ => None,
        }
    }
    pub fn as_array(&self) -> Option<&JsArray> {
        match self {
            JsValue::Array(a) => Some(a),
            _ => None,
        }
    }
}

// ---- Trait for types that can be converted to/from JsValue ----

/// Types that can be converted to a JavaScript value.
pub trait IntoJsValue {
    fn into_js_value(self) -> JsValue;
}

/// Types that can be extracted from a JavaScript value.
pub trait FromJsValue: Sized {
    fn from_js_value(value: &JsValue) -> Result<Self, String>;
}

// ---- Blanket implementations ----

impl IntoJsValue for () {
    fn into_js_value(self) -> JsValue {
        JsValue::Undefined
    }
}

impl IntoJsValue for bool {
    fn into_js_value(self) -> JsValue {
        JsValue::Bool(self)
    }
}

impl IntoJsValue for f64 {
    fn into_js_value(self) -> JsValue {
        JsValue::Number(self)
    }
}

impl IntoJsValue for i32 {
    fn into_js_value(self) -> JsValue {
        JsValue::Number(self as f64)
    }
}

impl IntoJsValue for i64 {
    fn into_js_value(self) -> JsValue {
        JsValue::Number(self as f64)
    }
}

impl IntoJsValue for u32 {
    fn into_js_value(self) -> JsValue {
        JsValue::Number(self as f64)
    }
}

impl IntoJsValue for String {
    fn into_js_value(self) -> JsValue {
        JsValue::String(self)
    }
}

impl IntoJsValue for &str {
    fn into_js_value(self) -> JsValue {
        JsValue::String(self.to_owned())
    }
}

impl IntoJsValue for JsValue {
    fn into_js_value(self) -> JsValue {
        self
    }
}

impl<T: IntoJsValue> IntoJsValue for Vec<T> {
    fn into_js_value(self) -> JsValue {
        if let Some(rt_ptr) = current_runtime_ptr() {
            let rt_handle = RuntimeHandle { ptr: rt_ptr };
            let arr_ffi = ffi::jsi_create_array(&rt_handle, self.len() as u32);
            for (i, elem) in self.into_iter().enumerate() {
                let val_ffi = elem.into_js_value().to_ffi();
                ffi::jsi_array_set_value(&rt_handle, arr_ffi.handle, i as u32, &val_ffi);
            }
            JsValue::Array(JsArray { handle: arr_ffi.handle })
        } else {
            JsValue::Undefined
        }
    }
}

impl<T: FromJsValue> FromJsValue for Vec<T> {
    fn from_js_value(value: &JsValue) -> Result<Self, String> {
        match value {
            JsValue::Array(arr) => {
                if let Some(rt_ptr) = current_runtime_ptr() {
                    let rt_handle = RuntimeHandle { ptr: rt_ptr };
                    let len = ffi::jsi_array_length(&rt_handle, arr.handle);
                    let mut result = Vec::with_capacity(len as usize);
                    for i in 0..len {
                        let ffi_val = ffi::jsi_array_get_value(&rt_handle, arr.handle, i);
                        let js_val = JsValue::from_ffi(ffi_val);
                        result.push(T::from_js_value(&js_val)?);
                    }
                    Ok(result)
                } else {
                    Err("no runtime available to read array".into())
                }
            }
            _ => Err("expected array".into()),
        }
    }
}

impl<T: IntoJsValue, E: Into<ExpoError>> IntoJsValue for Result<T, E> {
    fn into_js_value(self) -> JsValue {
        match self {
            Ok(v) => v.into_js_value(),
            Err(e) => {
                let err: ExpoError = e.into();
                JsValue::Error(format!("[{}] {}", err.code, err.message))
            }
        }
    }
}

impl<T: IntoJsValue> IntoJsValue for Option<T> {
    fn into_js_value(self) -> JsValue {
        match self {
            Some(v) => v.into_js_value(),
            None => JsValue::Null,
        }
    }
}

impl FromJsValue for bool {
    fn from_js_value(value: &JsValue) -> Result<Self, String> {
        value.as_bool().ok_or_else(|| "expected boolean".into())
    }
}

impl FromJsValue for f64 {
    fn from_js_value(value: &JsValue) -> Result<Self, String> {
        value.as_number().ok_or_else(|| "expected number".into())
    }
}

impl FromJsValue for i32 {
    fn from_js_value(value: &JsValue) -> Result<Self, String> {
        value.as_number().map(|n| n as i32).ok_or_else(|| "expected number".into())
    }
}

impl FromJsValue for i64 {
    fn from_js_value(value: &JsValue) -> Result<Self, String> {
        value.as_number().map(|n| n as i64).ok_or_else(|| "expected number".into())
    }
}

impl FromJsValue for u32 {
    fn from_js_value(value: &JsValue) -> Result<Self, String> {
        value.as_number().map(|n| n as u32).ok_or_else(|| "expected number".into())
    }
}

impl FromJsValue for String {
    fn from_js_value(value: &JsValue) -> Result<Self, String> {
        value.as_str().map(|s| s.to_owned()).ok_or_else(|| "expected string".into())
    }
}

impl FromJsValue for JsValue {
    fn from_js_value(value: &JsValue) -> Result<Self, String> {
        Ok(value.clone())
    }
}

impl<T: FromJsValue> FromJsValue for Option<T> {
    fn from_js_value(value: &JsValue) -> Result<Self, String> {
        if value.is_null() || value.is_undefined() {
            Ok(None)
        } else {
            T::from_js_value(value).map(Some)
        }
    }
}

// ---- HashMap (untyped Record / dictionary) ----

impl IntoJsValue for HashMap<String, JsValue> {
    fn into_js_value(self) -> JsValue {
        JsValue::Map(self)
    }
}

impl FromJsValue for HashMap<String, JsValue> {
    fn from_js_value(value: &JsValue) -> Result<Self, String> {
        match value {
            JsValue::Map(m) => Ok(m.clone()),
            JsValue::Object(obj) => {
                if let Some(rt_ptr) = current_runtime_ptr() {
                    let rt_handle = RuntimeHandle { ptr: rt_ptr };
                    let keys_ffi = ffi::jsi_object_get_property_names(&rt_handle, obj.handle);
                    let keys_val = JsValue::from_ffi(keys_ffi);
                    if let JsValue::Array(keys_arr) = keys_val {
                        let len = ffi::jsi_array_length(&rt_handle, keys_arr.handle);
                        let mut map = HashMap::new();
                        for i in 0..len {
                            let key_ffi = ffi::jsi_array_get_value(&rt_handle, keys_arr.handle, i);
                            let key_val = JsValue::from_ffi(key_ffi);
                            if let JsValue::String(key) = key_val {
                                let val_ffi = ffi::jsi_object_get_property(&rt_handle, obj.handle, &key);
                                map.insert(key, JsValue::from_ffi(val_ffi));
                            }
                        }
                        Ok(map)
                    } else {
                        Ok(HashMap::new())
                    }
                } else {
                    Err("no runtime available to read object properties".into())
                }
            }
            _ => Err("expected object/map".into()),
        }
    }
}

impl IntoJsValue for HashMap<String, String> {
    fn into_js_value(self) -> JsValue {
        let map: HashMap<String, JsValue> = self
            .into_iter()
            .map(|(k, v)| (k, JsValue::String(v)))
            .collect();
        JsValue::Map(map)
    }
}

impl FromJsValue for HashMap<String, String> {
    fn from_js_value(value: &JsValue) -> Result<Self, String> {
        let js_map = HashMap::<String, JsValue>::from_js_value(value)?;
        let mut result = HashMap::new();
        for (k, v) in &js_map {
            result.insert(k.clone(), String::from_js_value(v)?);
        }
        Ok(result)
    }
}

// ---- Object-to-Map conversion ----

// ---- Promise handle ----

/// Handle to a JS Promise's resolve/reject pair.
/// Used by async functions to settle the promise when work completes.
pub struct PromiseHandle {
    pub(crate) resolve_handle: u64,
    pub(crate) reject_handle: u64,
    pub(crate) rt_handle: ffi::RuntimeHandle,
}

impl PromiseHandle {
    /// Resolve the promise with a value. Consumes the handle.
    pub fn resolve(self, value: JsValue) {
        let ffi_val = value.to_ffi();
        ffi::jsi_call_function(&self.rt_handle, self.resolve_handle, &ffi_val);
    }

    /// Reject the promise with an error message. Consumes the handle.
    pub fn reject(self, error: impl Into<String>) {
        let msg = error.into();
        let ffi_val = ffi::jsi_make_string(msg.as_str());
        ffi::jsi_call_function(&self.rt_handle, self.reject_handle, &ffi_val);
    }
}

// ---- JsObject operations ----

impl JsObject {
    pub fn set(&self, rt: &Runtime, name: &str, value: &JsValue) {
        let ffi_val = value.to_ffi();
        ffi::jsi_object_set_property(&rt.handle, self.handle, name, &ffi_val);
    }

    pub fn get(&self, rt: &Runtime, name: &str) -> JsValue {
        JsValue::from_ffi(ffi::jsi_object_get_property(&rt.handle, self.handle, name))
    }
}

// ---- JsArray operations ----

impl JsArray {
    pub fn set(&self, rt: &Runtime, index: u32, value: &JsValue) {
        let ffi_val = value.to_ffi();
        ffi::jsi_array_set_value(&rt.handle, self.handle, index, &ffi_val);
    }

    pub fn get(&self, rt: &Runtime, index: u32) -> JsValue {
        JsValue::from_ffi(ffi::jsi_array_get_value(&rt.handle, self.handle, index))
    }

    pub fn length(&self, rt: &Runtime) -> u32 {
        ffi::jsi_array_length(&rt.handle, self.handle)
    }
}

// ---- Runtime operations ----

impl Runtime {
    pub fn create_object(&self) -> JsObject {
        let ffi = ffi::jsi_create_object(&self.handle);
        JsObject { handle: ffi.handle }
    }

    pub fn create_array(&self, length: u32) -> JsArray {
        let ffi = ffi::jsi_create_array(&self.handle, length);
        JsArray { handle: ffi.handle }
    }

    /// Create a JS Promise and return handles to the promise, resolve, and reject.
    /// The returned object has the promise's JSI handle; resolve/reject are in the PromiseHandle.
    pub fn create_promise(&self) -> (JsObject, PromiseHandle) {
        let result = ffi::jsi_create_promise(&self.handle);
        // The result is an object with "promise", "resolve", "reject" as number properties.
        // We need to extract the handles from the object.
        let promise_val = ffi::jsi_object_get_property(&self.handle, result.handle, "promise");
        let resolve_val = ffi::jsi_object_get_property(&self.handle, result.handle, "resolve");
        let reject_val = ffi::jsi_object_get_property(&self.handle, result.handle, "reject");

        let promise_handle = promise_val.number_val as u64;
        let resolve_handle = resolve_val.number_val as u64;
        let reject_handle = reject_val.number_val as u64;

        let promise = JsObject { handle: promise_handle };
        let handle = PromiseHandle {
            resolve_handle,
            reject_handle,
            rt_handle: ffi::RuntimeHandle { ptr: self.handle.ptr },
        };

        (promise, handle)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ---- IntoJsValue tests ----

    #[test]
    fn test_into_js_value_primitives() {
        assert!(matches!(().into_js_value(), JsValue::Undefined));
        assert!(matches!(true.into_js_value(), JsValue::Bool(true)));
        assert!(matches!(false.into_js_value(), JsValue::Bool(false)));
        assert!(matches!(42.0_f64.into_js_value(), JsValue::Number(n) if n == 42.0));
        assert!(matches!(42_i32.into_js_value(), JsValue::Number(n) if n == 42.0));
        assert!(matches!(42_i64.into_js_value(), JsValue::Number(n) if n == 42.0));
        assert!(matches!(42_u32.into_js_value(), JsValue::Number(n) if n == 42.0));
        assert!(matches!("hello".into_js_value(), JsValue::String(ref s) if s == "hello"));
        assert!(matches!(String::from("hello").into_js_value(), JsValue::String(ref s) if s == "hello"));
    }

    #[test]
    fn test_into_js_value_option() {
        let some: Option<f64> = Some(3.14);
        assert!(matches!(some.into_js_value(), JsValue::Number(n) if (n - 3.14).abs() < f64::EPSILON));

        let none: Option<f64> = None;
        assert!(matches!(none.into_js_value(), JsValue::Null));
    }

    #[test]
    fn test_into_js_value_result_ok() {
        let ok: Result<f64, ExpoError> = Ok(42.0);
        assert!(matches!(ok.into_js_value(), JsValue::Number(n) if n == 42.0));
    }

    #[test]
    fn test_into_js_value_result_err() {
        let err: Result<f64, ExpoError> = Err(ExpoError::new("TEST", "something failed"));
        let val = err.into_js_value();
        assert!(val.is_error());
        assert!(val.as_error().unwrap().contains("TEST"));
        assert!(val.as_error().unwrap().contains("something failed"));
    }

    // ---- FromJsValue tests ----

    #[test]
    fn test_from_js_value_bool() {
        assert_eq!(bool::from_js_value(&JsValue::Bool(true)).unwrap(), true);
        assert!(bool::from_js_value(&JsValue::Number(1.0)).is_err());
    }

    #[test]
    fn test_from_js_value_numbers() {
        assert_eq!(f64::from_js_value(&JsValue::Number(3.14)).unwrap(), 3.14);
        assert_eq!(i32::from_js_value(&JsValue::Number(42.0)).unwrap(), 42);
        assert_eq!(i64::from_js_value(&JsValue::Number(42.0)).unwrap(), 42);
        assert_eq!(u32::from_js_value(&JsValue::Number(42.0)).unwrap(), 42);
        assert!(f64::from_js_value(&JsValue::String("not a number".into())).is_err());
    }

    #[test]
    fn test_from_js_value_string() {
        assert_eq!(
            String::from_js_value(&JsValue::String("hello".into())).unwrap(),
            "hello"
        );
        assert!(String::from_js_value(&JsValue::Number(42.0)).is_err());
    }

    #[test]
    fn test_from_js_value_option() {
        let some: Option<f64> = Option::from_js_value(&JsValue::Number(42.0)).unwrap();
        assert_eq!(some, Some(42.0));

        let none: Option<f64> = Option::from_js_value(&JsValue::Null).unwrap();
        assert_eq!(none, None);

        let none2: Option<f64> = Option::from_js_value(&JsValue::Undefined).unwrap();
        assert_eq!(none2, None);
    }

    #[test]
    fn test_from_js_value_passthrough() {
        let val = JsValue::Number(42.0);
        let cloned = JsValue::from_js_value(&val).unwrap();
        assert!(matches!(cloned, JsValue::Number(n) if n == 42.0));
    }

    // ---- ExpoError tests ----

    #[test]
    fn test_expo_error_from_string() {
        let err: ExpoError = "oops".into();
        assert_eq!(err.code, "ERR_RUST_MODULE");
        assert_eq!(err.message, "oops");
    }

    #[test]
    fn test_expo_error_display() {
        let err = ExpoError::new("MY_CODE", "bad input");
        assert_eq!(err.to_string(), "bad input");
    }

    // ---- JsValue type checks ----

    #[test]
    fn test_js_value_type_checks() {
        assert!(JsValue::Undefined.is_undefined());
        assert!(JsValue::Null.is_null());
        assert!(JsValue::Bool(true).is_bool());
        assert!(JsValue::Number(1.0).is_number());
        assert!(JsValue::String("s".into()).is_string());
        assert!(JsValue::Object(JsObject { handle: 0 }).is_object());
        assert!(JsValue::Array(JsArray { handle: 0 }).is_array());
        assert!(JsValue::Error("e".into()).is_error());
        assert!(JsValue::Map(HashMap::new()).is_map());
    }

    // ---- HashMap / Map tests ----

    #[test]
    fn test_hashmap_into_js_value() {
        let mut map = HashMap::new();
        map.insert("name".to_owned(), JsValue::String("Alice".into()));
        map.insert("age".to_owned(), JsValue::Number(30.0));
        let val = map.into_js_value();
        assert!(val.is_map());
        let m = val.as_map().unwrap();
        assert_eq!(m.len(), 2);
        assert!(matches!(m.get("name"), Some(JsValue::String(s)) if s == "Alice"));
        assert!(matches!(m.get("age"), Some(JsValue::Number(n)) if *n == 30.0));
    }

    #[test]
    fn test_hashmap_from_js_value() {
        let mut map = HashMap::new();
        map.insert("x".to_owned(), JsValue::Number(1.0));
        let val = JsValue::Map(map);
        let result: HashMap<String, JsValue> = HashMap::from_js_value(&val).unwrap();
        assert_eq!(result.len(), 1);
        assert!(matches!(result.get("x"), Some(JsValue::Number(n)) if *n == 1.0));
    }

    #[test]
    fn test_hashmap_from_non_map_fails() {
        let result = HashMap::<String, JsValue>::from_js_value(&JsValue::Number(42.0));
        assert!(result.is_err());
    }

    // ---- Vec tests ----

    #[test]
    fn test_vec_into_js_value_without_runtime() {
        let v: Vec<f64> = vec![1.0, 2.0, 3.0];
        let val = v.into_js_value();
        // Without a runtime, Vec falls back to Undefined
        assert!(val.is_undefined());
    }

    #[test]
    fn test_vec_from_js_value_wrong_type() {
        let result = Vec::<f64>::from_js_value(&JsValue::Number(42.0));
        assert!(result.is_err());
    }

    #[test]
    fn test_vec_from_js_value_without_runtime() {
        let val = JsValue::Array(JsArray { handle: 0 });
        let result = Vec::<f64>::from_js_value(&val);
        // Without a runtime, reading array elements fails
        assert!(result.is_err());
    }

    // ---- HashMap<String, String> tests ----

    #[test]
    fn test_hashmap_string_string_into_js_value() {
        let mut map = HashMap::new();
        map.insert("name".to_owned(), "Alice".to_owned());
        map.insert("city".to_owned(), "Paris".to_owned());
        let val = map.into_js_value();
        assert!(val.is_map());
        let m = val.as_map().unwrap();
        assert_eq!(m.len(), 2);
        assert!(matches!(m.get("name"), Some(JsValue::String(s)) if s == "Alice"));
        assert!(matches!(m.get("city"), Some(JsValue::String(s)) if s == "Paris"));
    }

    #[test]
    fn test_hashmap_string_string_from_js_value() {
        let mut map = HashMap::new();
        map.insert("a".to_owned(), JsValue::String("hello".into()));
        map.insert("b".to_owned(), JsValue::String("world".into()));
        let val = JsValue::Map(map);
        let result: HashMap<String, String> = HashMap::from_js_value(&val).unwrap();
        assert_eq!(result.len(), 2);
        assert_eq!(result.get("a").unwrap(), "hello");
        assert_eq!(result.get("b").unwrap(), "world");
    }

    #[test]
    fn test_hashmap_string_string_from_js_value_type_mismatch() {
        let mut map = HashMap::new();
        map.insert("a".to_owned(), JsValue::Number(42.0));
        let val = JsValue::Map(map);
        let result = HashMap::<String, String>::from_js_value(&val);
        assert!(result.is_err());
    }

    #[test]
    fn test_hashmap_string_string_from_non_map_fails() {
        let result = HashMap::<String, String>::from_js_value(&JsValue::Number(42.0));
        assert!(result.is_err());
    }
}