emit_web 0.2.2

Instrument Web-based applications using emit.
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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
/*!
`emit_web`

Use [`emit`](https://docs.rs/emit) in WebAssembly applications targeting NodeJS and the browser.

`emit` itself and some emitters, like [`emit_otlp`](https://docs.rs/emit_otlp) support WebAssembly directly. This library includes support for emitting events to the [Console API](https://developer.mozilla.org/en-US/docs/Web/API/console). It also has alternative clocks and randomness using different web features. These aren't required for configuration, but can be used to more directly control the JavaScript APIs `emit` makes use of.

# Getting started

First, add `emit` and `emit_web` to your `Cargo.toml`:

```toml
[dependencies.emit]
version = "1"

[dependencies.emit_web]
version = "0.2.2"
```

Next, configure `emit` to use web APIs in its runtime:

```rust
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn setup() {
    let _ = emit::setup()
        .emit_to(emit_web::console())
        .try_init();
}
```

The name of this `setup` function doesn't matter, you'll just need to call it somewhere early in your application.
*/

#![doc(html_logo_url = "https://raw.githubusercontent.com/emit-rs/emit/main/asset/logo.svg")]
#![deny(missing_docs)]
#![cfg_attr(not(test), no_std)]

extern crate alloc;

use alloc::string::ToString;
use core::{ops::ControlFlow, time::Duration};

use emit::Props as _;
use js_sys::{Date, Object, Reflect};
use wasm_bindgen::prelude::*;

/**
An emitter based on the [Console API](https://developer.mozilla.org/en-US/docs/Web/API/Console_API).
*/
pub const fn console() -> ConsoleEmitter {
    ConsoleEmitter::new()
}

/**
An emitter based on the [Console API](https://developer.mozilla.org/en-US/docs/Web/API/Console_API).
*/
pub struct ConsoleEmitter {}

impl ConsoleEmitter {
    /**
    Create a new instance of the console emitter.
    */
    pub const fn new() -> Self {
        ConsoleEmitter {}
    }
}

impl emit::Emitter for ConsoleEmitter {
    fn emit<E: emit::event::ToEvent>(&self, evt: E) {
        let evt = evt.to_event();

        let msg = evt.msg().to_string();
        let extent = encode_extent(evt.extent());
        let props = encode_props(evt.props());

        match evt.props().pull("lvl") {
            Some(emit::Level::Debug) => console::debug(&msg, extent, props),
            Some(emit::Level::Info) => console::info(&msg, extent, props),
            Some(emit::Level::Warn) => console::warn(&msg, extent, props),
            Some(emit::Level::Error) => console::error(&msg, extent, props),
            _ => console::log(&msg, extent, props),
        }
    }

    fn blocking_flush(&self, _: core::time::Duration) -> bool {
        true
    }
}

fn encode_extent(extent: Option<&emit::Extent>) -> JsValue {
    let Some(extent) = extent else {
        return JsValue::NULL;
    };

    let map = Object::new();

    let timestamp_millis = duration_millis_f64(extent.as_point().to_unix());

    let _ = Reflect::set(
        &map,
        &JsValue::from_str("timestamp"),
        &JsValue::from(Date::new(&JsValue::from_f64(timestamp_millis))),
    );

    if let Some(len) = extent.len() {
        let len_millis = duration_millis_f64(len);

        let _ = Reflect::set(
            &map,
            &JsValue::from_str("milliseconds"),
            &JsValue::from_f64(len_millis),
        );
    }

    map.into()
}

fn duration_millis_f64(d: Duration) -> f64 {
    let d_secs = d.as_secs() as f64;
    let d_subsec_nanos = d.subsec_nanos() as f64;

    d_secs * 1_000.0 + d_subsec_nanos / 1_000_000.0
}

fn encode_props(props: impl emit::Props) -> JsValue {
    struct PropsObject<P>(P);

    impl<P: emit::Props> serde::Serialize for PropsObject<P> {
        fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            use serde::ser::SerializeMap as _;

            let mut map = serializer.serialize_map(None)?;

            let mut r = Ok(());
            let _ = self.0.for_each(|k, v| {
                match (|| {
                    map.serialize_key(&k)?;
                    map.serialize_value(&v)
                })() {
                    Ok(()) => ControlFlow::Continue(()),
                    Err(e) => {
                        r = Err(e);
                        ControlFlow::Break(())
                    }
                }
            });
            r?;

            map.end()
        }
    }

    to_jsvalue(PropsObject(props))
}

fn to_jsvalue(v: impl serde::Serialize) -> JsValue {
    match ser::jsvalue(v) {
        Ok(value) => value,
        Err(err) => err,
    }
}

// NOTE: `Temporal.Now.instant()` would be good to support when available

/**
A clock based on the [Performance API](https://developer.mozilla.org/en-US/docs/Web/API/Performance_API).
*/
pub struct PerformanceClock {}

impl PerformanceClock {
    /**
    Create a new instance of the performance clock.
    */
    pub const fn new() -> Self {
        PerformanceClock {}
    }
}

/**
A clock based on the [Performance API](https://developer.mozilla.org/en-US/docs/Web/API/Performance_API).
*/
pub const fn performance_clock() -> PerformanceClock {
    PerformanceClock::new()
}

impl emit::Clock for PerformanceClock {
    fn now(&self) -> Option<emit::Timestamp> {
        emit::Timestamp::from_unix(performance_now())
    }
}

fn performance_now() -> Duration {
    let origin_millis = performance::PERFORMANCE.with(|performance| performance.time_origin());
    let now_millis = performance::now();

    let origin_nanos = (origin_millis * 1_000_000.0) as u128;
    let now_nanos = (now_millis * 1_000_000.0) as u128;

    let timestamp_nanos = origin_nanos + now_nanos;

    let timestamp_secs = (timestamp_nanos / 1_000_000_000) as u64;
    let timestamp_subsec_nanos = (timestamp_nanos % 1_000_000_000) as u32;

    Duration::new(timestamp_secs, timestamp_subsec_nanos)
}

/**
A clock based on the [Date type](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date).
*/
pub const fn date_clock() -> DateClock {
    DateClock::new()
}

/**
A clock based on the [Date type](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date).
*/
pub struct DateClock {}

impl DateClock {
    /**
    Create a new instance of the date clock.
    */
    pub const fn new() -> Self {
        DateClock {}
    }
}

impl emit::Clock for DateClock {
    fn now(&self) -> Option<emit::Timestamp> {
        emit::Timestamp::from_unix(date_now())
    }
}

fn date_now() -> Duration {
    let timestamp_millis = Date::new_0().get_time();

    let timestamp_nanos = (timestamp_millis * 1_000_000.0) as u128;

    let timestamp_secs = (timestamp_nanos / 1_000_000_000) as u64;
    let timestamp_subsec_nanos = (timestamp_nanos % 1_000_000_000) as u32;

    Duration::new(timestamp_secs, timestamp_subsec_nanos)
}

/**
A source of randomness based on the [Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Crypto).
*/
pub const fn crypto_rng() -> CryptoRng {
    CryptoRng::new()
}

/**
An RNG based on the [Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Crypto).
*/
pub struct CryptoRng {}

impl CryptoRng {
    /**
    Create a new instance of the crypto RNG.
    */
    pub const fn new() -> Self {
        CryptoRng {}
    }
}

impl emit::Rng for CryptoRng {
    fn fill<A: AsMut<[u8]>>(&self, mut arr: A) -> Option<A> {
        crypto_fill(arr.as_mut());

        Some(arr)
    }
}

fn crypto_fill(buf: &mut [u8]) {
    crypto::get_random_values(buf);
}

mod console {
    use wasm_bindgen::prelude::*;

    #[wasm_bindgen]
    extern "C" {
        #[wasm_bindgen(js_namespace = console)]
        pub fn log(msg: &str, extent: JsValue, props: JsValue);
        #[wasm_bindgen(js_namespace = console)]
        pub fn debug(msg: &str, extent: JsValue, props: JsValue);
        #[wasm_bindgen(js_namespace = console)]
        pub fn info(msg: &str, extent: JsValue, props: JsValue);
        #[wasm_bindgen(js_namespace = console)]
        pub fn warn(msg: &str, extent: JsValue, props: JsValue);
        #[wasm_bindgen(js_namespace = console)]
        pub fn error(msg: &str, extent: JsValue, props: JsValue);
    }
}

mod performance {
    use wasm_bindgen::prelude::*;

    #[wasm_bindgen]
    extern "C" {
        pub type Performance;

        #[wasm_bindgen(thread_local_v2, js_name = performance)]
        pub static PERFORMANCE: Performance;

        #[wasm_bindgen(method, getter = timeOrigin)]
        pub fn time_origin(this: &Performance) -> f64;

        #[wasm_bindgen(js_namespace = performance)]
        pub fn now() -> f64;
    }
}

mod crypto {
    use wasm_bindgen::prelude::*;

    #[wasm_bindgen]
    extern "C" {
        #[wasm_bindgen(js_namespace = crypto, js_name = getRandomValues)]
        pub fn get_random_values(buf: &mut [u8]);
    }
}

mod ser {
    use alloc::string::ToString;
    use core::fmt;

    use js_sys::{Array, Object, Reflect, Uint8Array};
    use serde::ser::{
        Error, Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant,
        SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, Serializer, StdError,
    };
    use wasm_bindgen::prelude::*;

    pub fn jsvalue(v: impl Serialize) -> Result<JsValue, JsValue> {
        v.serialize(JsSerializer)
            .map_err(|e| JsValue::from(e.to_string()))
    }

    #[derive(Debug)]
    struct JsError;

    impl From<JsValue> for JsError {
        fn from(_: JsValue) -> Self {
            JsError
        }
    }

    impl fmt::Display for JsError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("failed to serialize a value to JavaScript")
        }
    }

    impl StdError for JsError {}

    impl Error for JsError {
        fn custom<T>(_: T) -> Self
        where
            T: fmt::Display,
        {
            JsError
        }
    }

    struct JsSerializer;

    struct JsArraySerializer {
        variant: Option<&'static str>,
        result: Array,
    }

    struct JsObjectSerializer {
        variant: Option<&'static str>,
        key: Option<JsValue>,
        result: Object,
    }

    impl Serializer for JsSerializer {
        type Ok = JsValue;
        type Error = JsError;
        type SerializeSeq = JsArraySerializer;
        type SerializeTuple = JsArraySerializer;
        type SerializeTupleStruct = JsArraySerializer;
        type SerializeTupleVariant = JsArraySerializer;
        type SerializeMap = JsObjectSerializer;
        type SerializeStruct = JsObjectSerializer;
        type SerializeStructVariant = JsObjectSerializer;

        fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
            Ok(JsValue::from(v))
        }

        fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
            self.serialize_i128(v as i128)
        }

        fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
            self.serialize_i128(v as i128)
        }

        fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
            self.serialize_i128(v as i128)
        }

        fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
            self.serialize_i128(v as i128)
        }

        fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
            if v.abs() > (i128::MAX >> 74) {
                Ok(JsValue::bigint_from_str(&v.to_string()))
            } else {
                Ok(JsValue::from(v as f64))
            }
        }

        fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
            self.serialize_u128(v as u128)
        }

        fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
            self.serialize_u128(v as u128)
        }

        fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
            self.serialize_u128(v as u128)
        }

        fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
            self.serialize_u128(v as u128)
        }

        fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
            if v > (u128::MAX >> 75) {
                Ok(JsValue::bigint_from_str(&v.to_string()))
            } else {
                Ok(JsValue::from(v as f64))
            }
        }

        fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
            Ok(JsValue::from(v as f64))
        }

        fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
            Ok(JsValue::from(v))
        }

        fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
            let mut buf = [0; 4];
            let v = v.encode_utf8(&mut buf);

            Ok(JsValue::from(&*v))
        }

        fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
            Ok(JsValue::from(v))
        }

        fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
            let buf = Uint8Array::from(v);

            Ok(JsValue::from(buf))
        }

        fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
            Ok(JsValue::null())
        }

        fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
        where
            T: ?Sized + Serialize,
        {
            value.serialize(self)
        }

        fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
            Ok(JsValue::null())
        }

        fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
            Ok(JsValue::from(name))
        }

        fn serialize_unit_variant(
            self,
            _: &'static str,
            _: u32,
            variant: &'static str,
        ) -> Result<Self::Ok, Self::Error> {
            Ok(JsValue::from(variant))
        }

        fn serialize_newtype_struct<T>(
            self,
            _: &'static str,
            value: &T,
        ) -> Result<Self::Ok, Self::Error>
        where
            T: ?Sized + Serialize,
        {
            value.serialize(self)
        }

        fn serialize_newtype_variant<T>(
            self,
            _: &'static str,
            _: u32,
            variant: &'static str,
            value: &T,
        ) -> Result<Self::Ok, Self::Error>
        where
            T: ?Sized + Serialize,
        {
            jsvariant(variant, jsvalue(value)?)
        }

        fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
            Ok(JsArraySerializer {
                variant: None,
                result: Array::new(),
            })
        }

        fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
            Ok(JsArraySerializer {
                variant: None,
                result: Array::new(),
            })
        }

        fn serialize_tuple_struct(
            self,
            _: &'static str,
            _: usize,
        ) -> Result<Self::SerializeTupleStruct, Self::Error> {
            Ok(JsArraySerializer {
                variant: None,
                result: Array::new(),
            })
        }

        fn serialize_tuple_variant(
            self,
            _: &'static str,
            _: u32,
            variant: &'static str,
            _: usize,
        ) -> Result<Self::SerializeTupleVariant, Self::Error> {
            Ok(JsArraySerializer {
                variant: Some(variant),
                result: Array::new(),
            })
        }

        fn serialize_map(self, _: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
            Ok(JsObjectSerializer {
                variant: None,
                key: None,
                result: Object::new(),
            })
        }

        fn serialize_struct(
            self,
            _: &'static str,
            _: usize,
        ) -> Result<Self::SerializeStruct, Self::Error> {
            Ok(JsObjectSerializer {
                variant: None,
                key: None,
                result: Object::new(),
            })
        }

        fn serialize_struct_variant(
            self,
            _: &'static str,
            _: u32,
            variant: &'static str,
            _: usize,
        ) -> Result<Self::SerializeStructVariant, Self::Error> {
            Ok(JsObjectSerializer {
                variant: Some(variant),
                key: None,
                result: Object::new(),
            })
        }
    }

    impl SerializeSeq for JsArraySerializer {
        type Ok = JsValue;
        type Error = JsError;

        fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
        where
            T: ?Sized + Serialize,
        {
            self.result.push(&jsvalue(value)?);

            Ok(())
        }

        fn end(self) -> Result<Self::Ok, Self::Error> {
            Ok(JsValue::from(self.result))
        }
    }

    impl SerializeTuple for JsArraySerializer {
        type Ok = JsValue;
        type Error = JsError;

        fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
        where
            T: ?Sized + Serialize,
        {
            self.result.push(&jsvalue(value)?);

            Ok(())
        }

        fn end(self) -> Result<Self::Ok, Self::Error> {
            Ok(JsValue::from(self.result))
        }
    }

    impl SerializeTupleStruct for JsArraySerializer {
        type Ok = JsValue;
        type Error = JsError;

        fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
        where
            T: ?Sized + Serialize,
        {
            self.result.push(&jsvalue(value)?);

            Ok(())
        }

        fn end(self) -> Result<Self::Ok, Self::Error> {
            Ok(JsValue::from(self.result))
        }
    }

    impl SerializeTupleVariant for JsArraySerializer {
        type Ok = JsValue;
        type Error = JsError;

        fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
        where
            T: ?Sized + Serialize,
        {
            self.result.push(&jsvalue(value)?);

            Ok(())
        }

        fn end(self) -> Result<Self::Ok, Self::Error> {
            jsvariant(
                self.variant
                    .ok_or_else(|| JsError::custom("missing variant"))?,
                JsValue::from(self.result),
            )
        }
    }

    impl SerializeMap for JsObjectSerializer {
        type Ok = JsValue;
        type Error = JsError;

        fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error>
        where
            T: ?Sized + Serialize,
        {
            self.key = Some(jsvalue(key)?);

            Ok(())
        }

        fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
        where
            T: ?Sized + Serialize,
        {
            let key = self
                .key
                .take()
                .ok_or_else(|| JsError::custom("missing key for a value"))?;

            Reflect::set(&self.result, &key, &jsvalue(value)?)?;

            Ok(())
        }

        fn end(self) -> Result<Self::Ok, Self::Error> {
            Ok(JsValue::from(self.result))
        }
    }

    impl SerializeStruct for JsObjectSerializer {
        type Ok = JsValue;
        type Error = JsError;

        fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
        where
            T: ?Sized + Serialize,
        {
            Reflect::set(&self.result, &JsValue::from(key), &jsvalue(value)?)?;

            Ok(())
        }

        fn end(self) -> Result<Self::Ok, Self::Error> {
            Ok(JsValue::from(self.result))
        }
    }

    impl SerializeStructVariant for JsObjectSerializer {
        type Ok = JsValue;
        type Error = JsError;

        fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
        where
            T: ?Sized + Serialize,
        {
            Reflect::set(&self.result, &JsValue::from(key), &jsvalue(value)?)?;

            Ok(())
        }

        fn end(self) -> Result<Self::Ok, Self::Error> {
            jsvariant(
                self.variant
                    .ok_or_else(|| JsError::custom("missing variant"))?,
                JsValue::from(self.result),
            )
        }
    }

    fn jsvariant(variant: &str, value: JsValue) -> Result<JsValue, JsError> {
        let result = Object::new();

        Reflect::set(&result, &JsValue::from(variant), &value)?;

        Ok(JsValue::from(result))
    }
}

#[cfg(all(test, target_arch = "wasm32"))]
mod tests {
    use super::*;
    use wasm_bindgen_test::*;

    use emit::{Clock as _, Rng as _};

    use std::collections::BTreeMap;

    #[wasm_bindgen_test]
    #[test]
    fn date_clock_produces_timestamps() {
        assert_ne!(emit::Timestamp::MIN, DateClock::new().now().unwrap());
    }

    #[wasm_bindgen_test]
    #[test]
    fn performance_clock_produces_timestamps() {
        assert_ne!(emit::Timestamp::MIN, PerformanceClock::new().now().unwrap());
    }

    #[wasm_bindgen_test]
    #[test]
    fn crypto_rng_produces_random_data() {
        let mut buf = [0; 32];

        CryptoRng::new().fill(&mut buf).unwrap();

        assert_ne!([0; 32], buf);
    }

    #[wasm_bindgen_test]
    #[test]
    fn emit() {
        let rt = emit::runtime::Runtime::default()
            .with_emitter(console())
            .with_clock(date_clock())
            .with_rng(crypto_rng());

        let data = {
            let mut map = BTreeMap::new();

            map.insert("c", 1);
            map.insert("d", 2);

            map
        };

        let name = "event";

        emit::emit!(rt, "test {name} with {#[emit::as_serde] data}");
    }

    #[wasm_bindgen_test]
    #[test]
    fn emit_span() {
        static RT: emit::runtime::Runtime<
            ConsoleEmitter,
            emit::Empty,
            emit::platform::thread_local_ctxt::ThreadLocalCtxt,
            DateClock,
            CryptoRng,
        > = emit::runtime::Runtime::build(
            console(),
            emit::Empty,
            emit::platform::thread_local_ctxt::ThreadLocalCtxt::shared(),
            date_clock(),
            crypto_rng(),
        );

        #[emit::span(rt: RT, "test {name} with {#[emit::as_serde] data}")]
        fn exec(name: &str, data: &BTreeMap<&str, i32>) {}

        let data = {
            let mut map = BTreeMap::new();

            map.insert("c", 1);
            map.insert("d", 2);

            map
        };

        let name = "event";

        exec(name, &data);
    }
}