jsbind 0.1.44

Bindings for basic JS types required for webbind
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
pub use emlite;
pub use emlite::Console;
pub use emlite::FromVal;

use alloc::{format, vec};

pub use crate::any::{Any, AnyHandle};
pub use crate::array::{
    Array, ArrayBuffer, DataView, Endian, Float32Array, Float64Array, FrozenArray, Int8Array,
    Int32Array, ObservableArray, TypedArray, Uint8Array, Uint32Array,
};
pub use crate::bigint::BigInt;
pub use crate::date::Date;
pub use crate::error::*;
pub use crate::function::{Closure, Function};
pub use crate::json::JSON;
pub use crate::map::*;
pub use crate::math::Math;
pub use crate::null::Null;
pub use crate::number::Number;
pub use crate::object::Object;
pub use crate::promise::Promise;
pub use crate::record::Record;
pub use crate::reflect::Reflect;
pub use crate::regexp::{RegExp, RegExpFlags};
pub use crate::response::{fetch, fetch_val};
pub use crate::set::*;
pub use crate::string::JsString;
pub use crate::symbol::Symbol;
pub use crate::text::{TextDecoder, TextEncoder};
pub use crate::time::*;
pub use crate::undefined::Undefined;
pub use crate::url::URL;

/// Parse `src` with an optional `radix`.  Mirrors `parseInt(str, radix)`.
///
/// # Arguments
/// * `src` - String to parse
/// * `radix` - Optional radix (2-36)
///
/// # Returns
/// Result containing parsed integer or error
///
/// # Examples
/// ```rust
/// use jsbind::prelude::*;
///
/// let result = parse_int("42", None);
/// assert!(result.is_ok());
/// assert_eq!(result.unwrap(), 42);
///
/// let error_result = parse_int("not_a_number", None);
/// assert!(error_result.is_err());
/// ```
pub fn parse_int(src: &str, radix: Option<i32>) -> Result<i32, JsError> {
    let g = emlite::Val::global("parseInt");
    let result = match radix {
        Some(r) => {
            if !(2..=36).contains(&r) {
                return Err(JsError::new("Radix must be between 2 and 36"));
            }
            g.invoke(&[src.into(), r.into()])
        }
        None => g.invoke(&[src.into()]),
    };

    if is_nan(&result) {
        Err(JsError::new(&format!("Invalid number format: '{}'", src)))
    } else {
        Ok(result.as_::<i32>())
    }
}

/// Parse a floating-point value – identical to JS `parseFloat(str)`.
///
/// # Arguments
/// * `src` - String to parse
///
/// # Returns
/// Result containing parsed float or error
///
/// # Examples
/// ```rust
/// use jsbind::prelude::*;
///
/// let result = parse_float("3.14");
/// assert!(result.is_ok());
/// assert_eq!(result.unwrap(), 3.14);
///
/// let error_result = parse_float("not_a_number");
/// assert!(error_result.is_err());
/// ```
pub fn parse_float(src: &str) -> Result<f64, JsError> {
    let result = emlite::Val::global("parseFloat").invoke(&[src.into()]);

    if is_nan(&result) {
        Err(JsError::new(&format!("Invalid number format: '{}'", src)))
    } else {
        Ok(result.as_::<f64>())
    }
}

/// Trait analogous to `wasm-bindgen::JsCast`.
///
/// Automatically available on every wrapper that is:
/// * holds a single `emlite::Val`
/// * implements `AsRef<Val>` and `Into<Val>`
pub trait DynCast
where
    Self: AsRef<emlite::Val> + Into<emlite::Val> + AsMut<emlite::Val>,
{
    fn has_type<T>(&self) -> bool
    where
        T: DynCast,
    {
        T::is_type_of(self.as_ref())
    }

    fn dyn_into<T>(self) -> Result<T, Self>
    where
        T: DynCast,
    {
        if self.has_type::<T>() {
            Ok(self.unchecked_into())
        } else {
            Err(self)
        }
    }

    fn dyn_ref<T>(&self) -> Option<&T>
    where
        T: DynCast,
    {
        if self.has_type::<T>() {
            Some(self.unchecked_ref())
        } else {
            None
        }
    }

    fn dyn_mut<T>(&mut self) -> Option<&mut T>
    where
        T: DynCast,
    {
        if self.has_type::<T>() {
            Some(self.unchecked_mut())
        } else {
            None
        }
    }

    fn unchecked_into<T>(self) -> T
    where
        T: DynCast,
    {
        T::unchecked_from_val(self.into())
    }

    fn unchecked_ref<T>(&self) -> &T
    where
        T: DynCast,
    {
        T::unchecked_from_val_ref(self.as_ref())
    }

    fn unchecked_mut<T>(&mut self) -> &mut T
    where
        T: DynCast,
    {
        T::unchecked_from_val_mut(self.as_mut())
    }

    fn is_instance_of<T>(&self) -> bool
    where
        T: DynCast,
    {
        T::instanceof(self.as_ref())
    }

    /// Implementation of `val instanceof ThisType`.
    fn instanceof(val: &emlite::Val) -> bool;

    /// Customisable brand check – defaults to `instanceof`.
    fn is_type_of(val: &emlite::Val) -> bool {
        Self::instanceof(val)
    }

    /// Zero-cost unchecked conversion from `Val` into `Self`.
    fn unchecked_from_val(v: emlite::Val) -> Self;

    /// Zero-cost unchecked conversion from `&Val` into `&Self`.
    fn unchecked_from_val_ref(v: &emlite::Val) -> &Self;

    /// Zero-cost unchecked conversion from `&mut Val` into `&mut Self`.
    fn unchecked_from_val_mut(v: &mut emlite::Val) -> &mut Self;
}

/// Throws a JS exception.
#[cold]
#[inline(never)]
pub fn throw_str(s: &str) -> ! {
    throw_val(s.into())
}

/// Throws a JS exception
#[cold]
#[inline(never)]
pub fn throw_val(s: Any) -> ! {
    let handle = s.as_handle();
    core::mem::forget(s);
    emlite::Val::throw(emlite::Val::take_ownership(handle));
}

// Implementations copied from wasm-bindgen
pub trait UnwrapThrowExt<T>: Sized {
    fn unwrap_throw(self) -> T {
        let loc = core::panic::Location::caller();
        let msg = alloc::format!(
            "called `{}::unwrap_throw()` ({}:{}:{})",
            core::any::type_name::<Self>(),
            loc.file(),
            loc.line(),
            loc.column()
        );
        self.expect_throw(&msg)
    }

    fn expect_throw(self, message: &str) -> T;
}

// Implementations copied from wasm-bindgen
impl<T> UnwrapThrowExt<T> for Option<T> {
    fn unwrap_throw(self) -> T {
        const MSG: &str = "called `Option::unwrap_throw()` on a `None` value";
        if let Some(val) = self {
            val
        } else if cfg!(debug_assertions) {
            let loc = core::panic::Location::caller();
            let msg = alloc::format!("{} ({}:{}:{})", MSG, loc.file(), loc.line(), loc.column(),);

            throw_str(&msg)
        } else {
            throw_str(MSG)
        }
    }

    fn expect_throw(self, message: &str) -> T {
        if let Some(val) = self {
            val
        } else if cfg!(debug_assertions) {
            let loc = core::panic::Location::caller();
            let msg = alloc::format!(
                "{} ({}:{}:{})",
                message,
                loc.file(),
                loc.line(),
                loc.column(),
            );

            throw_str(&msg)
        } else {
            throw_str(message)
        }
    }
}

// Implementations copied from wasm-bindgen
impl<T, E> UnwrapThrowExt<T> for Result<T, E>
where
    E: core::fmt::Debug,
{
    fn unwrap_throw(self) -> T {
        const MSG: &str = "called `Result::unwrap_throw()` on an `Err` value";
        match self {
            Ok(val) => val,
            Err(err) => {
                if cfg!(debug_assertions) {
                    let loc = core::panic::Location::caller();
                    let msg = alloc::format!(
                        "{} ({}:{}:{}): {:?}",
                        MSG,
                        loc.file(),
                        loc.line(),
                        loc.column(),
                        err
                    );

                    throw_str(&msg)
                } else {
                    throw_str(MSG)
                }
            }
        }
    }

    fn expect_throw(self, message: &str) -> T {
        match self {
            Ok(val) => val,
            Err(err) => {
                if cfg!(debug_assertions) {
                    let loc = core::panic::Location::caller();
                    let msg = alloc::format!(
                        "{} ({}:{}:{}): {:?}",
                        message,
                        loc.file(),
                        loc.line(),
                        loc.column(),
                        err
                    );

                    throw_str(&msg)
                } else {
                    throw_str(message)
                }
            }
        }
    }
}

/// Encode string to base64.
///
/// # Arguments  
/// * `data` - String to encode
///
/// # Returns
/// Result containing base64 encoded string or error
///
/// # Examples
/// ```rust
/// use jsbind::prelude::*;
///
/// let input = JsString::from("Hello World");
/// let result = btoa(&input);
/// assert!(result.is_ok());
/// ```
pub fn btoa(data: &JsString) -> Result<JsString, JsError> {
    let result = emlite::Val::global("btoa").invoke(&[data.into()]);
    result.as_::<Result<JsString, JsError>>()
}

/// Decode base64 string.
///
/// # Arguments
/// * `encoded` - Base64 encoded string  
///
/// # Returns
/// Result containing decoded string or error
///
/// # Examples
/// ```rust
/// use jsbind::prelude::*;
///
/// let encoded = JsString::from("SGVsbG8gV29ybGQ=");
/// let result = atob(&encoded);
/// assert!(result.is_ok());
/// ```
pub fn atob(encoded: &JsString) -> Result<JsString, JsError> {
    let result = emlite::Val::global("atob").invoke(&[encoded.into()]);
    result.as_::<Result<JsString, JsError>>()
}

/// Checks if a value is NaN.
///
/// # Arguments
/// * `value` - Value to check
///
/// # Returns
/// `true` if the value is NaN, `false` otherwise
///
/// # Examples
/// ```rust
/// use jsbind::prelude::*;
///
/// assert!(is_nan(&(0.0/0.0).into()));
/// assert!(!is_nan(&42.into()));
/// ```
pub fn is_nan<V: Into<emlite::Val>>(value: V) -> bool {
    emlite::Val::global("isNaN")
        .invoke(&[value.into()])
        .as_::<bool>()
}

/// Queues a microtask to be executed.
///
/// # Arguments
/// * `callback` - Function to execute as microtask
///
/// # Examples
/// ```rust
/// use jsbind::prelude::*;
///
/// let callback = Function::from_closure(|| {
///     Console::get().log(&["Microtask executed!".into()]);
/// });
/// queue_microtask(&callback);
/// ```
pub fn queue_microtask<C: Into<emlite::Val>>(callback: C) {
    emlite::Val::global("queueMicrotask").invoke(&[callback.into()]);
}

/// Dynamically imports a module.
///
/// # Arguments
/// * `specifier` - Module specifier to import
///
/// # Returns
/// Promise that resolves to Result containing the module namespace object
///
/// # Examples
/// ```rust
/// use jsbind::prelude::*;
///
/// let import_promise = import_module("./my-module.js");
/// // import_promise resolves to the module's exports
/// ```
pub fn import_module(specifier: &str) -> Promise<Result<Object, JsError>> {
    let import_promise = emlite::Val::global("import").invoke(&[specifier.into()]);
    Promise::take_ownership(import_promise.as_handle())
}

/// Requires a CommonJS module.
///
/// # Arguments
/// * `specifier` - Module specifier to require
///
/// # Returns
/// Result containing the module exports
///
/// # Examples
/// ```rust
/// use jsbind::prelude::*;
///
/// let exports = require_module("fs")?;
/// // exports contains the CommonJS module exports
/// ```
pub fn require_module(specifier: &str) -> Result<Object, JsError> {
    let require_fn = emlite::Val::global("require");
    if require_fn.is_undefined() {
        return Err(JsError::new("require is not available in this environment"));
    }

    let module_exports = require_fn.invoke(&[specifier.into()]);
    Ok(Object::from_val(&module_exports.as_::<Any>()))
}

/// Creates a require function using import.meta.url.
///
/// # Arguments
/// * `import_meta_url` - The import.meta.url value
///
/// # Returns
/// Result containing require function for CommonJS module loading
///
/// # Examples
/// ```rust
/// use jsbind::prelude::*;
///
/// let import_meta = Any::global("import").get("meta");
/// let import_meta_url = import_meta.get("url");
/// let require_fn = create_require(&import_meta_url)?;
/// // require_fn can now be used to load CommonJS modules
/// ```
pub fn create_require<V: Into<emlite::Val>>(import_meta_url: V) -> Result<Function, JsError> {
    let module_obj = emlite::Val::global("module");
    if module_obj.is_undefined() {
        return Err(JsError::new(
            "module.createRequire not supported in this environment",
        ));
    }

    let create_require_fn = module_obj.get("createRequire");
    if create_require_fn.is_undefined() {
        return Err(JsError::new("module.createRequire not available"));
    }

    let require_fn = create_require_fn.invoke(&[import_meta_url.into()]);
    Ok(Function::from_val(&require_fn.as_::<Any>()))
}

/// Options for structured cloning operations.
#[derive(Clone, Debug)]
pub struct JsStructuredSerializeOptions {
    inner: emlite::Val,
}

impl JsStructuredSerializeOptions {
    /// Creates a new JsStructuredSerializeOptions object.
    pub fn new() -> Self {
        Self {
            inner: emlite::Val::object(),
        }
    }

    /// Gets the transfer list for transferable objects.
    pub fn transfer(&self) -> Option<TypedArray<Object>> {
        let val = self.inner.get("transfer");
        if val.is_undefined() {
            None
        } else {
            Some(val.as_::<TypedArray<Object>>())
        }
    }

    /// Sets the transfer list for transferable objects.
    pub fn set_transfer(&self, transfer: &TypedArray<Object>) {
        self.inner.set("transfer", transfer);
    }
}

impl Default for JsStructuredSerializeOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl AsRef<emlite::Val> for JsStructuredSerializeOptions {
    fn as_ref(&self) -> &emlite::Val {
        &self.inner
    }
}

impl From<JsStructuredSerializeOptions> for emlite::Val {
    fn from(options: JsStructuredSerializeOptions) -> Self {
        options.inner
    }
}

impl From<&JsStructuredSerializeOptions> for emlite::Val {
    fn from(options: &JsStructuredSerializeOptions) -> Self {
        options.inner.clone()
    }
}

/// Performs a structured clone of a value.
///
/// # Arguments
/// * `value` - The value to clone
/// * `options` - Optional structured clone options
///
/// # Returns
/// Deep clone of the input value
///
/// # Examples
/// ```rust
/// use jsbind::prelude::*;
///
/// let obj = Object::new();
/// obj.set("key", "value");
///
/// let cloned = structured_clone(&obj, None);
/// // cloned is a deep copy of obj
/// ```
pub fn structured_clone<T>(value: &T, options: Option<&JsStructuredSerializeOptions>) -> T
where
    T: emlite::FromVal + AsRef<emlite::Val>,
{
    let args = match options {
        Some(opts) => vec![value.as_ref().clone(), opts.into()],
        None => vec![value.as_ref().clone()],
    };

    emlite::Val::global("structuredClone")
        .invoke(&args)
        .as_::<T>()
}