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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
//! contains the QuickJsRuntimeFacade

use crate::builder::QuickJsRuntimeBuilder;
use crate::jsutils::{JsError, Script};
use crate::quickjs_utils::{functions, objects};
use crate::quickjsrealmadapter::QuickJsRealmAdapter;
use crate::quickjsruntimeadapter::{
    CompiledModuleLoaderAdapter, MemoryUsage, NativeModuleLoaderAdapter, QuickJsRuntimeAdapter,
    ScriptModuleLoaderAdapter, QJS_RT,
};
use crate::quickjsvalueadapter::QuickJsValueAdapter;
use crate::reflection;
use crate::values::JsValueFacade;
use hirofa_utils::eventloop::EventLoop;
use hirofa_utils::task_manager::TaskManager;
use libquickjs_sys as q;
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::{Arc, Weak};
use tokio::task::JoinError;

lazy_static! {
    /// a static Multithreaded task manager used to run rust ops async and multithreaded ( in at least 2 threads)
    static ref HELPER_TASKS: TaskManager = TaskManager::new(std::cmp::max(2, num_cpus::get()));
}

impl Drop for QuickJsRuntimeFacade {
    fn drop(&mut self) {
        log::trace!("> EsRuntime::drop");
        self.clear_contexts();
        log::trace!("< EsRuntime::drop");
    }
}

pub struct QuickjsRuntimeFacadeInner {
    event_loop: EventLoop,
}

impl QuickjsRuntimeFacadeInner {
    /// this is how you add a closure to the worker thread which has an instance of the QuickJsRuntime
    /// this will run and return synchronously
    /// # example
    /// ```rust
    /// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
    /// use quickjs_runtime::jsutils::Script;
    /// use quickjs_runtime::quickjs_utils::primitives;
    /// let rt = QuickJsRuntimeBuilder::new().build();
    /// let res = rt.exe_rt_task_in_event_loop(|q_js_rt| {
    ///     let q_ctx = q_js_rt.get_main_realm();
    ///     // here you are in the worker thread and you can use the quickjs_utils
    ///     let val_ref = q_ctx.eval(Script::new("test.es", "(11 * 6);")).ok().expect("script failed");
    ///     primitives::to_i32(&val_ref).ok().expect("could not get i32")
    /// });
    /// assert_eq!(res, 66);
    /// ```
    pub fn exe_rt_task_in_event_loop<C, R>(&self, consumer: C) -> R
    where
        C: FnOnce(&QuickJsRuntimeAdapter) -> R + Send + 'static,
        R: Send + 'static,
    {
        self.exe_task_in_event_loop(|| QuickJsRuntimeAdapter::do_with(consumer))
    }

    /// this is how you add a closure to the worker thread which has an instance of the QuickJsRuntime
    /// this will run asynchronously
    /// # example
    /// ```rust
    /// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
    /// let rt = QuickJsRuntimeBuilder::new().build();
    /// rt.add_rt_task_to_event_loop(|q_js_rt| {
    ///     // here you are in the worker thread and you can use the quickjs_utils
    ///     q_js_rt.gc();
    /// });
    /// ```
    pub fn add_rt_task_to_event_loop<C, R: Send + 'static>(
        &self,
        consumer: C,
    ) -> impl Future<Output = R>
    where
        C: FnOnce(&QuickJsRuntimeAdapter) -> R + Send + 'static,
    {
        self.add_task_to_event_loop(|| QuickJsRuntimeAdapter::do_with(consumer))
    }

    pub fn add_rt_task_to_event_loop_void<C>(&self, consumer: C)
    where
        C: FnOnce(&QuickJsRuntimeAdapter) + Send + 'static,
    {
        self.add_task_to_event_loop_void(|| QuickJsRuntimeAdapter::do_with(consumer))
    }

    /// this can be used to run a function in the event_queue thread for the QuickJSRuntime
    /// without borrowing the q_js_rt
    pub fn add_task_to_event_loop_void<C>(&self, task: C)
    where
        C: FnOnce() + Send + 'static,
    {
        self.event_loop.add_void(move || {
            task();
            EventLoop::add_local_void(|| {
                QuickJsRuntimeAdapter::do_with(|q_js_rt| {
                    q_js_rt.run_pending_jobs_if_any();
                })
            })
        });
    }

    pub fn exe_task_in_event_loop<C, R: Send + 'static>(&self, task: C) -> R
    where
        C: FnOnce() -> R + Send + 'static,
    {
        self.event_loop.exe(move || {
            let res = task();
            EventLoop::add_local_void(|| {
                QuickJsRuntimeAdapter::do_with(|q_js_rt| {
                    q_js_rt.run_pending_jobs_if_any();
                })
            });
            res
        })
    }

    pub fn add_task_to_event_loop<C, R: Send + 'static>(&self, task: C) -> impl Future<Output = R>
    where
        C: FnOnce() -> R + Send + 'static,
    {
        self.event_loop.add(move || {
            let res = task();
            EventLoop::add_local_void(|| {
                QuickJsRuntimeAdapter::do_with(|q_js_rt| {
                    q_js_rt.run_pending_jobs_if_any();
                });
            });
            res
        })
    }

    /// used to add tasks from the worker threads which require run_pending_jobs_if_any to run after it
    #[allow(dead_code)]
    pub(crate) fn add_local_task_to_event_loop<C>(consumer: C)
    where
        C: FnOnce(&QuickJsRuntimeAdapter) + 'static,
    {
        EventLoop::add_local_void(move || {
            QuickJsRuntimeAdapter::do_with(|q_js_rt| {
                consumer(q_js_rt);
            });
            EventLoop::add_local_void(|| {
                QuickJsRuntimeAdapter::do_with(|q_js_rt| {
                    q_js_rt.run_pending_jobs_if_any();
                })
            })
        });
    }
}

/// EsRuntime is the main public struct representing a JavaScript runtime.
/// You can construct a new QuickJsRuntime by using the [QuickJsRuntimeBuilder] struct
/// # Example
/// ```rust
/// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
/// let rt = QuickJsRuntimeBuilder::new().build();
/// ```
pub struct QuickJsRuntimeFacade {
    inner: Arc<QuickjsRuntimeFacadeInner>,
}

impl QuickJsRuntimeFacade {
    pub(crate) fn new(mut builder: QuickJsRuntimeBuilder) -> Self {
        let ret = Self {
            inner: Arc::new(QuickjsRuntimeFacadeInner {
                event_loop: EventLoop::new(),
            }),
        };

        ret.exe_task_in_event_loop(|| {
            let rt_ptr = unsafe { q::JS_NewRuntime() };
            let rt = QuickJsRuntimeAdapter::new(rt_ptr);
            QuickJsRuntimeAdapter::init_rt_for_current_thread(rt);
            functions::init_statics();
            reflection::init_statics();
        });

        // init ref in q_js_rt

        let rti_weak = Arc::downgrade(&ret.inner);

        ret.exe_task_in_event_loop(move || {
            QuickJsRuntimeAdapter::do_with_mut(move |m_q_js_rt| {
                m_q_js_rt.init_rti_ref(rti_weak);
            })
        });

        // run single job in eventQueue to init thread_local weak<rtref>

        #[cfg(any(
            feature = "settimeout",
            feature = "setinterval",
            feature = "console",
            feature = "setimmediate"
        ))]
        {
            let res = crate::features::init(&ret);
            if res.is_err() {
                panic!("could not init features: {}", res.err().unwrap());
            }
        }

        if let Some(interval) = builder.opt_gc_interval {
            let rti_ref: Weak<QuickjsRuntimeFacadeInner> = Arc::downgrade(&ret.inner);
            std::thread::spawn(move || loop {
                std::thread::sleep(interval);
                if let Some(el) = rti_ref.upgrade() {
                    log::debug!("running gc from gc interval thread");
                    el.event_loop.add_void(|| {
                        QJS_RT
                            .try_with(|rc| {
                                let rt = &*rc.borrow();
                                rt.as_ref().unwrap().gc();
                            })
                            .expect("QJS_RT.try_with failed");
                    });
                } else {
                    break;
                }
            });
        }

        let init_hooks: Vec<_> = builder.runtime_init_hooks.drain(..).collect();

        ret.exe_task_in_event_loop(move || {
            QuickJsRuntimeAdapter::do_with_mut(|q_js_rt| {
                for native_module_loader in builder.native_module_loaders {
                    q_js_rt.add_native_module_loader(NativeModuleLoaderAdapter::new(
                        native_module_loader,
                    ));
                }
                for script_module_loader in builder.script_module_loaders {
                    q_js_rt.add_script_module_loader(ScriptModuleLoaderAdapter::new(
                        script_module_loader,
                    ));
                }
                for compiled_module_loader in builder.compiled_module_loaders {
                    q_js_rt.add_compiled_module_loader(CompiledModuleLoaderAdapter::new(
                        compiled_module_loader,
                    ));
                }
                q_js_rt.script_pre_processors = builder.script_pre_processors;

                if let Some(limit) = builder.opt_memory_limit_bytes {
                    unsafe {
                        q::JS_SetMemoryLimit(q_js_rt.runtime, limit as _);
                    }
                }
                if let Some(threshold) = builder.opt_gc_threshold {
                    unsafe {
                        q::JS_SetGCThreshold(q_js_rt.runtime, threshold as _);
                    }
                }
                if let Some(stack_size) = builder.opt_max_stack_size {
                    unsafe {
                        q::JS_SetMaxStackSize(q_js_rt.runtime, stack_size as _);
                    }
                }
                if let Some(interrupt_handler) = builder.interrupt_handler {
                    q_js_rt.set_interrupt_handler(interrupt_handler);
                }
            })
        });

        for hook in init_hooks {
            match hook(&ret) {
                Ok(_) => {}
                Err(e) => {
                    panic!("runtime_init_hook failed: {}", e);
                }
            }
        }

        ret
    }

    /// get memory usage for this runtime
    pub async fn memory_usage(&self) -> MemoryUsage {
        self.loop_async(|rt| rt.memory_usage()).await
    }

    pub(crate) fn clear_contexts(&self) {
        log::trace!("EsRuntime::clear_contexts");
        self.exe_task_in_event_loop(|| {
            let context_ids = QuickJsRuntimeAdapter::get_context_ids();
            for id in context_ids {
                QuickJsRuntimeAdapter::remove_context(id.as_str());
            }
        });
    }

    /// this can be used to run a function in the event_queue thread for the QuickJSRuntime
    /// without borrowing the q_js_rt
    pub fn add_task_to_event_loop_void<C>(&self, task: C)
    where
        C: FnOnce() + Send + 'static,
    {
        self.inner.add_task_to_event_loop_void(task)
    }

    pub fn exe_task_in_event_loop<C, R: Send + 'static>(&self, task: C) -> R
    where
        C: FnOnce() -> R + Send + 'static,
    {
        self.inner.exe_task_in_event_loop(task)
    }

    pub fn add_task_to_event_loop<C, R: Send + 'static>(&self, task: C) -> impl Future<Output = R>
    where
        C: FnOnce() -> R + Send + 'static,
    {
        self.inner.add_task_to_event_loop(task)
    }

    /// this is how you add a closure to the worker thread which has an instance of the QuickJsRuntime
    /// this will run asynchronously
    /// # example
    /// ```rust
    /// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
    /// let rt = QuickJsRuntimeBuilder::new().build();
    /// rt.add_rt_task_to_event_loop(|q_js_rt| {
    ///     // here you are in the worker thread and you can use the quickjs_utils
    ///     q_js_rt.gc();
    /// });
    /// ```
    pub fn add_rt_task_to_event_loop<C, R: Send + 'static>(
        &self,
        task: C,
    ) -> impl Future<Output = R>
    where
        C: FnOnce(&QuickJsRuntimeAdapter) -> R + Send + 'static,
    {
        self.inner.add_rt_task_to_event_loop(task)
    }

    pub fn add_rt_task_to_event_loop_void<C>(&self, task: C)
    where
        C: FnOnce(&QuickJsRuntimeAdapter) + Send + 'static,
    {
        self.inner.add_rt_task_to_event_loop_void(task)
    }

    /// used to add tasks from the worker threads which require run_pending_jobs_if_any to run after it
    #[allow(dead_code)]
    pub(crate) fn add_local_task_to_event_loop<C>(consumer: C)
    where
        C: FnOnce(&QuickJsRuntimeAdapter) + 'static,
    {
        QuickjsRuntimeFacadeInner::add_local_task_to_event_loop(consumer)
    }

    pub fn builder() -> QuickJsRuntimeBuilder {
        QuickJsRuntimeBuilder::new()
    }

    /// run the garbage collector asynchronously
    pub async fn gc(&self) {
        self.add_rt_task_to_event_loop(|q_js_rt| q_js_rt.gc()).await
    }

    /// run the garbage collector and wait for it to be done
    pub fn gc_sync(&self) {
        self.exe_rt_task_in_event_loop(|q_js_rt| q_js_rt.gc())
    }

    /// this is how you add a closure to the worker thread which has an instance of the QuickJsRuntime
    /// this will run and return synchronously
    /// # example
    /// ```rust
    /// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
    /// use quickjs_runtime::jsutils::Script;
    /// use quickjs_runtime::quickjs_utils::primitives;
    /// let rt = QuickJsRuntimeBuilder::new().build();
    /// let res = rt.exe_rt_task_in_event_loop(|q_js_rt| {
    ///     let q_ctx = q_js_rt.get_main_realm();
    ///     // here you are in the worker thread and you can use the quickjs_utils
    ///     let val_ref = q_ctx.eval(Script::new("test.es", "(11 * 6);")).ok().expect("script failed");
    ///     primitives::to_i32(&val_ref).ok().expect("could not get i32")
    /// });
    /// assert_eq!(res, 66);
    /// ```
    pub fn exe_rt_task_in_event_loop<C, R>(&self, consumer: C) -> R
    where
        C: FnOnce(&QuickJsRuntimeAdapter) -> R + Send + 'static,
        R: Send + 'static,
    {
        self.exe_task_in_event_loop(|| QuickJsRuntimeAdapter::do_with(consumer))
    }

    /// this adds a rust function to JavaScript, it is added for all current and future contexts
    /// # Example
    /// ```rust
    /// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
    /// use quickjs_runtime::quickjs_utils::primitives;
    /// use quickjs_runtime::jsutils::Script;
    /// use quickjs_runtime::values::{JsValueConvertable, JsValueFacade};
    ///  
    /// let rt = QuickJsRuntimeBuilder::new().build();
    ///
    /// rt.set_function(&["com", "mycompany", "util"], "methodA", |q_ctx, args: Vec<JsValueFacade>|{
    ///     let a = args[0].get_i32();
    ///     let b = args[1].get_i32();
    ///     Ok((a * b).to_js_value_facade())
    /// }).expect("set func failed");
    ///
    /// let res = rt.eval_sync(None, Script::new("test.es", "let a = com.mycompany.util.methodA(13, 17); a * 2;")).ok().expect("script failed");
    ///
    /// assert_eq!(res.get_i32(), (13*17*2));
    /// ```
    pub fn set_function<F>(
        &self,
        namespace: &[&str],
        name: &str,
        function: F,
    ) -> Result<(), JsError>
    where
        F: Fn(&QuickJsRealmAdapter, Vec<JsValueFacade>) -> Result<JsValueFacade, JsError>
            + Send
            + 'static,
    {
        let name = name.to_string();

        let namespace = namespace
            .iter()
            .map(|s| s.to_string())
            .collect::<Vec<String>>();

        self.exe_rt_task_in_event_loop(move |q_js_rt| {
            let func_rc = Rc::new(function);
            let name = name.to_string();

            q_js_rt.add_context_init_hook(move |_q_js_rt, realm| {
                let namespace_slice = namespace.iter().map(|s| s.as_str()).collect::<Vec<&str>>();
                let ns = objects::get_namespace_q(realm, &namespace_slice, true)?;

                let func_rc = func_rc.clone();

                let func = functions::new_function_q(
                    realm,
                    name.as_str(),
                    move |realm, _this_ref, args| {
                        let mut args_facades = vec![];

                        for arg_ref in args {
                            args_facades.push(realm.to_js_value_facade(arg_ref)?);
                        }

                        let res = func_rc(realm, args_facades);

                        match res {
                            Ok(val_jsvf) => realm.from_js_value_facade(val_jsvf),
                            Err(e) => Err(e),
                        }
                    },
                    1,
                )?;

                objects::set_property2_q(realm, &ns, name.as_str(), &func, 0)?;

                Ok(())
            })
        })
    }

    /// add a task the the "helper" thread pool
    pub fn add_helper_task<T>(task: T)
    where
        T: FnOnce() + Send + 'static,
    {
        log::trace!("adding a helper task");
        HELPER_TASKS.add_task(task);
    }

    /// add an async task the the "helper" thread pool
    pub fn add_helper_task_async<R: Send + 'static, T: Future<Output = R> + Send + 'static>(
        task: T,
    ) -> impl Future<Output = Result<R, JoinError>> {
        log::trace!("adding an async helper task");
        HELPER_TASKS.add_task_async(task)
    }

    /// create a new context besides the always existing main_context
    /// # Example
    /// ```
    /// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
    /// use quickjs_runtime::jsutils::Script;
    /// let rt = QuickJsRuntimeBuilder::new().build();
    /// rt.create_context("my_context");
    /// rt.exe_rt_task_in_event_loop(|q_js_rt| {
    ///    let my_ctx = q_js_rt.get_context("my_context");
    ///    my_ctx.eval(Script::new("ctx_test.es", "this.myVar = 'only exists in my_context';"));
    /// });
    /// ```
    pub fn create_context(&self, id: &str) -> Result<(), JsError> {
        let id = id.to_string();
        self.inner
            .event_loop
            .exe(move || QuickJsRuntimeAdapter::create_context(id.as_str()))
    }

    /// drop a context which was created earlier with a call to [create_context()](struct.EsRuntime.html#method.create_context)
    pub fn drop_context(&self, id: &str) {
        let id = id.to_string();
        self.inner
            .event_loop
            .exe(move || QuickJsRuntimeAdapter::remove_context(id.as_str()))
    }
}

fn loop_realm_func<
    R: Send + 'static,
    C: FnOnce(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter) -> R + Send + 'static,
>(
    realm_name: Option<String>,
    consumer: C,
) -> R {
    let res = QuickJsRuntimeAdapter::do_with(|q_js_rt| {
        if let Some(realm_str) = realm_name.as_ref() {
            if let Some(realm) = q_js_rt.get_realm(realm_str) {
                (Some(consumer(q_js_rt, realm)), None)
            } else {
                (None, Some(consumer))
            }
        } else {
            (Some(consumer(q_js_rt, q_js_rt.get_main_realm())), None)
        }
    });

    if let Some(res) = res.0 {
        res
    } else {
        // create realm first
        let consumer = res.1.unwrap();
        let realm_str = realm_name.expect("invalid state");

        QuickJsRuntimeAdapter::do_with_mut(|m_rt| {
            let ctx = QuickJsRealmAdapter::new(realm_str.to_string(), m_rt);
            m_rt.contexts.insert(realm_str.to_string(), ctx);
        });

        QuickJsRuntimeAdapter::do_with(|q_js_rt| {
            let realm = q_js_rt
                .get_realm(realm_str.as_str())
                .expect("invalid state");
            let hooks = &*q_js_rt.context_init_hooks.borrow();
            for hook in hooks {
                let res = hook(q_js_rt, realm);
                if res.is_err() {
                    panic!("realm init hook failed: {}", res.err().unwrap());
                }
            }

            consumer(q_js_rt, realm)
        })
    }
}

impl QuickJsRuntimeFacade {
    pub fn create_realm(&self, name: &str) -> Result<(), JsError> {
        let name = name.to_string();
        self.inner
            .event_loop
            .exe(move || QuickJsRuntimeAdapter::create_context(name.as_str()))
    }

    pub fn destroy_realm(&self, name: &str) -> Result<(), JsError> {
        let name = name.to_string();
        self.exe_task_in_event_loop(move || {
            QuickJsRuntimeAdapter::do_with_mut(|rt| {
                if rt.get_realm(name.as_str()).is_some() {
                    rt.remove_realm(name.as_str());
                }
                Ok(())
            })
        })
    }

    pub fn has_realm(&self, name: &str) -> Result<bool, JsError> {
        let name = name.to_string();
        self.exe_rt_task_in_event_loop(move |rt| Ok(rt.get_realm(name.as_str()).is_some()))
    }

    /// add a job to the eventloop which will execute sync(placed at end of eventloop)
    pub fn loop_sync<R: Send + 'static, C: FnOnce(&QuickJsRuntimeAdapter) -> R + Send + 'static>(
        &self,
        consumer: C,
    ) -> R {
        self.exe_rt_task_in_event_loop(consumer)
    }

    pub fn loop_sync_mut<
        R: Send + 'static,
        C: FnOnce(&mut QuickJsRuntimeAdapter) -> R + Send + 'static,
    >(
        &self,
        consumer: C,
    ) -> R {
        self.exe_task_in_event_loop(|| QuickJsRuntimeAdapter::do_with_mut(consumer))
    }

    /// add a job to the eventloop which will execute async(placed at end of eventloop)
    /// returns a Future which can be waited ob with .await
    pub fn loop_async<
        R: Send + 'static,
        C: FnOnce(&QuickJsRuntimeAdapter) -> R + Send + 'static,
    >(
        &self,
        consumer: C,
    ) -> Pin<Box<dyn Future<Output = R> + Send>> {
        Box::pin(self.add_rt_task_to_event_loop(consumer))
    }

    /// add a job to the eventloop (placed at end of eventloop) without expecting a result
    pub fn loop_void<C: FnOnce(&QuickJsRuntimeAdapter) + Send + 'static>(&self, consumer: C) {
        self.add_rt_task_to_event_loop_void(consumer)
    }

    /// add a job to the eventloop which will be executed synchronously (placed at end of eventloop)
    pub fn loop_realm_sync<
        R: Send + 'static,
        C: FnOnce(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter) -> R + Send + 'static,
    >(
        &self,
        realm_name: Option<&str>,
        consumer: C,
    ) -> R {
        let realm_name = realm_name.map(|s| s.to_string());
        self.exe_task_in_event_loop(|| loop_realm_func(realm_name, consumer))
    }

    /// add a job to the eventloop which will be executed async (placed at end of eventloop)
    /// returns a Future which can be waited ob with .await
    pub fn loop_realm<
        R: Send + 'static,
        C: FnOnce(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter) -> R + Send + 'static,
    >(
        &self,
        realm_name: Option<&str>,
        consumer: C,
    ) -> Pin<Box<dyn Future<Output = R>>> {
        let realm_name = realm_name.map(|s| s.to_string());
        Box::pin(self.add_task_to_event_loop(|| loop_realm_func(realm_name, consumer)))
    }

    /// add a job for a specific realm without expecting a result.
    /// the job will be added to the end of the eventloop
    pub fn loop_realm_void<
        C: FnOnce(&QuickJsRuntimeAdapter, &QuickJsRealmAdapter) + Send + 'static,
    >(
        &self,
        realm_name: Option<&str>,
        consumer: C,
    ) {
        let realm_name = realm_name.map(|s| s.to_string());
        self.add_task_to_event_loop_void(|| loop_realm_func(realm_name, consumer));
    }

    /// Evaluate a script asynchronously
    /// # Example
    /// ```rust
    /// use futures::executor::block_on;
    /// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
    /// use quickjs_runtime::jsutils::Script;
    /// let rt = QuickJsRuntimeBuilder::new().build();
    /// let my_script = r#"
    ///    console.log("i'm a script");
    /// "#;
    /// block_on(rt.eval(None, Script::new("my_script.js", my_script))).expect("script failed");
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn eval(
        &self,
        realm_name: Option<&str>,
        script: Script,
    ) -> Pin<Box<dyn Future<Output = Result<JsValueFacade, JsError>>>> {
        self.loop_realm(realm_name, |_rt, realm| {
            let res = realm.eval(script);
            match res {
                Ok(jsvr) => realm.to_js_value_facade(&jsvr),
                Err(e) => Err(e),
            }
        })
    }

    /// Evaluate a script and return the result synchronously
    /// # example
    /// ```rust
    /// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
    /// use quickjs_runtime::jsutils::Script;
    /// let rt = QuickJsRuntimeBuilder::new().build();
    /// let script = Script::new("my_file.js", "(9 * 3);");
    /// let res = rt.eval_sync(None, script).ok().expect("script failed");
    /// assert_eq!(res.get_i32(), 27);
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn eval_sync(
        &self,
        realm_name: Option<&str>,
        script: Script,
    ) -> Result<JsValueFacade, JsError> {
        self.loop_realm_sync(realm_name, |_rt, realm| {
            let res = realm.eval(script);
            match res {
                Ok(jsvr) => realm.to_js_value_facade(&jsvr),
                Err(e) => Err(e),
            }
        })
    }

    /// evaluate a module, you need this if you want to compile a script that contains static imports
    /// e.g.
    /// ```javascript
    /// import {util} from 'file.js';
    /// console.log(util(1, 2, 3));
    /// ```
    /// please note that the module is cached under the absolute path you passed in the Script object
    /// and thus you should take care to make the path unique (hence the absolute_ name)
    /// also to use this you need to build the QuickJsRuntimeFacade with a module loader
    /// # example
    /// ```rust
    /// use futures::executor::block_on;
    /// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
    /// use quickjs_runtime::jsutils::modules::ScriptModuleLoader;
    /// use quickjs_runtime::jsutils::Script;
    /// use quickjs_runtime::quickjsrealmadapter::QuickJsRealmAdapter;
    /// struct TestModuleLoader {}
    /// impl ScriptModuleLoader for TestModuleLoader {
    ///     fn normalize_path(&self, _realm: &QuickJsRealmAdapter, ref_path: &str,path: &str) -> Option<String> {
    ///         Some(path.to_string())
    ///     }
    ///
    ///     fn load_module(&self, _realm: &QuickJsRealmAdapter, absolute_path: &str) -> String {
    ///         "export const util = function(a, b, c){return a+b+c;};".to_string()
    ///     }
    /// }
    /// let rt = QuickJsRuntimeBuilder::new().script_module_loader(TestModuleLoader{}).build();
    /// let script = Script::new("/opt/files/my_module.js", r#"
    ///     import {util} from 'other_module.js';\n
    ///     console.log(util(1, 2, 3));
    /// "#);
    /// // in real life you would .await this
    /// let _res = block_on(rt.eval_module(None, script));
    /// ```
    pub fn eval_module(
        &self,
        realm_name: Option<&str>,
        script: Script,
    ) -> Pin<Box<dyn Future<Output = Result<JsValueFacade, JsError>>>> {
        self.loop_realm(realm_name, |_rt, realm| {
            let res = realm.eval_module(script)?;
            realm.to_js_value_facade(&res)
        })
    }

    /// evaluate a module synchronously, you need this if you want to compile a script that contains static imports
    /// e.g.
    /// ```javascript
    /// import {util} from 'file.js';
    /// console.log(util(1, 2, 3));
    /// ```
    /// please note that the module is cached under the absolute path you passed in the Script object
    /// and thus you should take care to make the path unique (hence the absolute_ name)
    /// also to use this you need to build the QuickJsRuntimeFacade with a module loader
    /// # example
    /// ```rust
    /// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
    /// use quickjs_runtime::jsutils::modules::ScriptModuleLoader;
    /// use quickjs_runtime::jsutils::Script;
    /// use quickjs_runtime::quickjsrealmadapter::QuickJsRealmAdapter;
    /// struct TestModuleLoader {}
    /// impl ScriptModuleLoader for TestModuleLoader {
    ///     fn normalize_path(&self, _realm: &QuickJsRealmAdapter, ref_path: &str,path: &str) -> Option<String> {
    ///         Some(path.to_string())
    ///     }
    ///
    ///     fn load_module(&self, _realm: &QuickJsRealmAdapter, absolute_path: &str) -> String {
    ///         "export const util = function(a, b, c){return a+b+c;};".to_string()
    ///     }
    /// }
    /// let rt = QuickJsRuntimeBuilder::new().script_module_loader(TestModuleLoader{}).build();
    /// let script = Script::new("/opt/files/my_module.js", r#"
    ///     import {util} from 'other_module.js';\n
    ///     console.log(util(1, 2, 3));
    /// "#);
    /// let _res = rt.eval_module_sync(None, script);
    /// ```
    pub fn eval_module_sync(
        &self,
        realm_name: Option<&str>,
        script: Script,
    ) -> Result<JsValueFacade, JsError> {
        self.loop_realm_sync(realm_name, |_rt, realm| {
            let res = realm.eval_module(script)?;
            realm.to_js_value_facade(&res)
        })
    }

    /// invoke a function in the engine and get the result synchronously
    /// # example
    /// ```rust
    /// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
    /// use quickjs_runtime::jsutils::Script;
    /// use quickjs_runtime::values::JsValueConvertable;
    /// let rt = QuickJsRuntimeBuilder::new().build();
    /// let script = Script::new("my_file.es", "this.com = {my: {methodA: function(a, b, someStr, someBool){return a*b;}}};");
    /// rt.eval_sync(None, script).ok().expect("script failed");
    /// let res = rt.invoke_function_sync(None, &["com", "my"], "methodA", vec![7i32.to_js_value_facade(), 5i32.to_js_value_facade(), "abc".to_js_value_facade(), true.to_js_value_facade()]).ok().expect("func failed");
    /// assert_eq!(res.get_i32(), 35);
    /// ```
    #[warn(clippy::type_complexity)]
    pub fn invoke_function_sync(
        &self,
        realm_name: Option<&str>,
        namespace: &[&str],
        method_name: &str,
        args: Vec<JsValueFacade>,
    ) -> Result<JsValueFacade, JsError> {
        let movable_namespace: Vec<String> = namespace.iter().map(|s| s.to_string()).collect();
        let movable_method_name = method_name.to_string();

        self.loop_realm_sync(realm_name, move |_rt, realm| {
            let args_adapters: Vec<QuickJsValueAdapter> = args
                .into_iter()
                .map(|jsvf| realm.from_js_value_facade(jsvf).expect("conversion failed"))
                .collect();

            let namespace = movable_namespace
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<&str>>();

            let res = realm.invoke_function_by_name(
                namespace.as_slice(),
                movable_method_name.as_str(),
                args_adapters.as_slice(),
            );

            match res {
                Ok(jsvr) => realm.to_js_value_facade(&jsvr),
                Err(e) => Err(e),
            }
        })
    }

    /// invoke a function in the engine asynchronously
    /// N.B. func_name is not a &str because of <https://github.com/rust-lang/rust/issues/56238> (i think)
    /// # example
    /// ```rust
    /// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
    /// use quickjs_runtime::jsutils::Script;
    /// use quickjs_runtime::values::JsValueConvertable;
    /// let rt = QuickJsRuntimeBuilder::new().build();
    /// let script = Script::new("my_file.es", "this.com = {my: {methodA: function(a, b){return a*b;}}};");
    /// rt.eval_sync(None, script).ok().expect("script failed");
    /// rt.invoke_function(None, &["com", "my"], "methodA", vec![7.to_js_value_facade(), 5.to_js_value_facade()]);
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn invoke_function(
        &self,
        realm_name: Option<&str>,
        namespace: &[&str],
        method_name: &str,
        args: Vec<JsValueFacade>,
    ) -> Pin<Box<dyn Future<Output = Result<JsValueFacade, JsError>>>> {
        let movable_namespace: Vec<String> = namespace.iter().map(|s| s.to_string()).collect();
        let movable_method_name = method_name.to_string();

        self.loop_realm(realm_name, move |_rt, realm| {
            let args_adapters: Vec<QuickJsValueAdapter> = args
                .into_iter()
                .map(|jsvf| realm.from_js_value_facade(jsvf).expect("conversion failed"))
                .collect();

            let namespace = movable_namespace
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<&str>>();

            let res = realm.invoke_function_by_name(
                namespace.as_slice(),
                movable_method_name.as_str(),
                args_adapters.as_slice(),
            );

            match res {
                Ok(jsvr) => realm.to_js_value_facade(&jsvr),
                Err(e) => Err(e),
            }
        })
    }

    pub fn invoke_function_void(
        &self,
        realm_name: Option<&str>,
        namespace: &[&str],
        method_name: &str,
        args: Vec<JsValueFacade>,
    ) {
        let movable_namespace: Vec<String> = namespace.iter().map(|s| s.to_string()).collect();
        let movable_method_name = method_name.to_string();

        self.loop_realm_void(realm_name, move |_rt, realm| {
            let args_adapters: Vec<QuickJsValueAdapter> = args
                .into_iter()
                .map(|jsvf| realm.from_js_value_facade(jsvf).expect("conversion failed"))
                .collect();

            let namespace = movable_namespace
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<&str>>();

            let res = realm
                .invoke_function_by_name(
                    namespace.as_slice(),
                    movable_method_name.as_str(),
                    args_adapters.as_slice(),
                )
                .map(|jsvr| realm.to_js_value_facade(&jsvr));

            match res {
                Ok(_) => {
                    log::trace!(
                        "js_function_invoke_void succeeded: {}",
                        movable_method_name.as_str()
                    );
                }
                Err(err) => {
                    log::trace!(
                        "js_function_invoke_void failed: {}: {}",
                        movable_method_name.as_str(),
                        err
                    );
                }
            }
        })
    }
}

#[cfg(test)]
lazy_static! {
    static ref INITTED: std::sync::Mutex<bool> = std::sync::Mutex::new(false);
}

#[cfg(test)]
pub mod tests {

    use crate::facades::QuickJsRuntimeFacade;
    use crate::jsutils::modules::{NativeModuleLoader, ScriptModuleLoader};
    use crate::jsutils::JsError;
    use crate::jsutils::Script;
    use crate::quickjs_utils::{primitives, promises};
    use crate::quickjsrealmadapter::QuickJsRealmAdapter;
    use crate::quickjsvalueadapter::QuickJsValueAdapter;
    use crate::values::{JsValueConvertable, JsValueFacade};
    use backtrace::Backtrace;
    use futures::executor::block_on;
    use log::debug;
    use std::panic;
    use std::time::Duration;

    struct TestNativeModuleLoader {}
    struct TestScriptModuleLoader {}

    impl NativeModuleLoader for TestNativeModuleLoader {
        fn has_module(&self, _q_ctx: &QuickJsRealmAdapter, module_name: &str) -> bool {
            module_name.starts_with("greco://")
        }

        fn get_module_export_names(
            &self,
            _q_ctx: &QuickJsRealmAdapter,
            _module_name: &str,
        ) -> Vec<&str> {
            vec!["a", "b", "c"]
        }

        fn get_module_exports(
            &self,
            _q_ctx: &QuickJsRealmAdapter,
            _module_name: &str,
        ) -> Vec<(&str, QuickJsValueAdapter)> {
            vec![
                ("a", primitives::from_i32(1234)),
                ("b", primitives::from_i32(64834)),
                ("c", primitives::from_i32(333)),
            ]
        }
    }

    impl ScriptModuleLoader for TestScriptModuleLoader {
        fn normalize_path(
            &self,
            _realm: &QuickJsRealmAdapter,
            _ref_path: &str,
            path: &str,
        ) -> Option<String> {
            if path.eq("notfound.mes") || path.starts_with("greco://") {
                None
            } else {
                Some(path.to_string())
            }
        }

        fn load_module(&self, _realm: &QuickJsRealmAdapter, absolute_path: &str) -> String {
            if absolute_path.eq("notfound.mes") || absolute_path.starts_with("greco://") {
                panic!("tht realy should not happen");
            } else if absolute_path.eq("invalid.mes") {
                "I am the great cornholio! thou'gh shalt&s not p4arse mie!".to_string()
            } else {
                "export const foo = 'bar';\nexport const mltpl = function(a, b){return a*b;}; globalThis;".to_string()
            }
        }
    }

    #[test]
    fn test_rt_drop() {
        let rt = init_test_rt();
        log::trace!("before drop");

        drop(rt);
        log::trace!("after before drop");
        std::thread::sleep(Duration::from_secs(5));
        log::trace!("after sleep");
    }

    #[test]
    pub fn test_stack_size() {
        let rt = init_test_rt();
        // 120 is ok, 200 fails
        let res = rt.eval_sync(
            None,
            Script::new(
                "stack_test.js",
                "let f = function(a){let f2 = arguments.callee; if (a < 120) {f2(a + 1);}}; f(1);",
            ),
        );
        match res {
            Ok(_) => {}
            Err(e) => {
                log::error!("fail: {}", e);
                panic!("fail: {}", e);
            }
        }

        let res = rt.eval_sync(
            None,
            Script::new(
                "stack_test.js",
                "let f = function(a){let f2 = arguments.callee; if (a < 1000) {f2(a + 1);}}; f(1);",
            ),
        );
        if res.is_ok() {
            panic!("stack should have overflowed");
        }
    }

    pub fn init_logging() {
        {
            let i_lock = &mut *crate::facades::INITTED.lock().unwrap();
            if !*i_lock {
                panic::set_hook(Box::new(|panic_info| {
                    let backtrace = Backtrace::new();
                    println!("thread panic occurred: {panic_info}\nbacktrace: {backtrace:?}");
                    log::error!(
                        "thread panic occurred: {}\nbacktrace: {:?}",
                        panic_info,
                        backtrace
                    );
                }));

                simple_logging::log_to_file("./quickjs_runtime.log", log::LevelFilter::max())
                    .expect("could not init logger");

                *i_lock = true;
            }
        }
    }

    pub fn init_test_rt() -> QuickJsRuntimeFacade {
        init_logging();

        QuickJsRuntimeFacade::builder()
            .gc_interval(Duration::from_secs(1))
            .max_stack_size(128 * 1024)
            .script_module_loader(TestScriptModuleLoader {})
            .native_module_loader(TestNativeModuleLoader {})
            .build()
    }

    #[test]
    fn test_func() {
        let rt = init_test_rt();
        let res = rt.set_function(&["nl", "my", "utils"], "methodA", |_q_ctx, args| {
            if args.len() != 2 || !args.first().unwrap().is_i32() || !args.get(1).unwrap().is_i32()
            {
                Err(JsError::new_str(
                    "i'd really like 2 args of the int32 kind please",
                ))
            } else {
                let a = args.first().unwrap().get_i32();
                let b = args.get(1).unwrap().get_i32();
                Ok((a * b).to_js_value_facade())
            }
        });

        match res {
            Ok(_) => {}
            Err(e) => {
                panic!("set_function failed: {}", e);
            }
        }

        let res = rt.eval_sync(
            None,
            Script::new("test_func.es", "(nl.my.utils.methodA(13, 56));"),
        );

        match res {
            Ok(val) => {
                assert!(val.is_i32());
                assert_eq!(val.get_i32(), 13 * 56);
            }
            Err(e) => {
                panic!("test_func.es failed: {}", e);
            }
        }
    }

    #[test]
    fn test_eval_sync() {
        let rt = init_test_rt();
        let res = rt.eval_sync(None, Script::new("test.es", "console.log('foo bar');"));

        match res {
            Ok(_) => {}
            Err(e) => {
                panic!("eval failed: {}", e);
            }
        }

        let res = rt
            .eval_sync(None, Script::new("test.es", "(2 * 7);"))
            .expect("script failed");

        assert_eq!(res.get_i32(), 14);
    }

    #[test]
    fn t1234() {
        // test stack overflow
        let rt = init_test_rt();

        rt.exe_rt_task_in_event_loop(|q_js_rt| {
            //q_js_rt.run_pending_jobs_if_any();
            let q_ctx = q_js_rt.get_main_realm();
            let r = q_ctx.eval(Script::new(
                "test_async.es",
                "let f = async function(){let p = new Promise((resolve, reject) => {resolve(12345);}); const p2 = await p; return p2}; f();",
            )).ok().unwrap();
            log::trace!("tag = {}", r.get_tag());
            //std::thread::sleep(Duration::from_secs(1));

            assert!(promises::is_promise_q(q_ctx, &r));

            if promises::is_promise_q(q_ctx, &r) {
                log::info!("r IS a Promise");
            } else {
                log::error!("r is NOT a Promise");
            }

            std::thread::sleep(Duration::from_secs(1));

            //q_js_rt.run_pending_jobs_if_any();
        });
        rt.exe_rt_task_in_event_loop(|q_js_rt| {
            q_js_rt.run_pending_jobs_if_any();
        });

        std::thread::sleep(Duration::from_secs(1));
    }

    #[test]
    fn test_eval_await() {
        let rt = init_test_rt();

        let res = rt.eval_sync(None, Script::new(
            "test_async.es",
            "{let f = async function(){let p = new Promise((resolve, reject) => {resolve(12345);}); const p2 = await p; return p2}; f()};",
        ));

        match res {
            Ok(esvf) => {
                assert!(esvf.is_js_promise());
                match esvf {
                    JsValueFacade::JsPromise { cached_promise } => {
                        let p_res = cached_promise
                            .get_promise_result_sync()
                            .expect("promise timed out");
                        if p_res.is_err() {
                            panic!("{:?}", p_res.err().unwrap());
                        }
                        let res = p_res.ok().unwrap();
                        assert!(res.is_i32());
                        assert_eq!(res.get_i32(), 12345);
                    }
                    _ => {}
                }
            }
            Err(e) => {
                panic!("eval failed: {}", e);
            }
        }
    }

    #[test]
    fn test_promise() {
        let rt = init_test_rt();

        let res = rt.eval_sync(None, Script::new(
            "testp2.es",
            "let test_promise_P = (new Promise(function(res, rej) {console.log('before res');res(123);console.log('after res');}).then(function (a) {console.log('prom ressed to ' + a);}).catch(function(x) {console.log('p.ca ex=' + x);}))",
        ));

        match res {
            Ok(_) => {}
            Err(e) => panic!("p script failed: {}", e),
        }
        std::thread::sleep(Duration::from_secs(1));
    }

    #[test]
    fn test_module_sync() {
        log::info!("> test_module_sync");

        let rt = init_test_rt();
        debug!("test static import");
        let res: Result<JsValueFacade, JsError> = rt.eval_module_sync(
            None,
            Script::new(
                "test.es",
                "import {foo} from 'test_module.mes';\n console.log('static imp foo = ' + foo);",
            ),
        );

        match res {
            Ok(_) => {
                log::debug!("static import ok");
            }
            Err(e) => {
                log::error!("static import failed: {}", e);
            }
        }

        debug!("test dynamic import");
        let res: Result<JsValueFacade, JsError> = rt.eval_sync(None, Script::new(
            "test_dyn.es",
            "console.log('about to load dynamic module');let dyn_p = import('test_module.mes');dyn_p.then(function (some) {console.log('after dyn');console.log('after dyn ' + typeof some);console.log('mltpl 5, 7 = ' + some.mltpl(5, 7));});dyn_p.catch(function (x) {console.log('imp.cat x=' + x);});console.log('dyn done');",
        ));

        match res {
            Ok(_) => {
                log::debug!("dynamic import ok");
            }
            Err(e) => {
                log::error!("dynamic import failed: {}", e);
            }
        }
        std::thread::sleep(Duration::from_secs(1));

        log::info!("< test_module_sync");
    }

    async fn test_async1() -> i32 {
        let rt = init_test_rt();

        let a = rt
            .eval(None, Script::new("test_async.es", "122 + 1;"))
            .await;
        match a {
            Ok(a) => a.get_i32(),
            Err(e) => panic!("script failed: {}", e),
        }
    }

    #[test]
    fn test_async() {
        let fut = test_async1();
        let res = block_on(fut);
        assert_eq!(res, 123);
    }
}

#[cfg(test)]
pub mod abstraction_tests {
    use crate::builder::QuickJsRuntimeBuilder;
    use crate::facades::tests::init_test_rt;
    use crate::facades::QuickJsRuntimeFacade;
    use crate::jsutils::Script;
    use crate::values::JsValueFacade;
    use futures::executor::block_on;
    use serde::Deserialize;
    use serde::Serialize;

    async fn example(rt: &QuickJsRuntimeFacade) -> JsValueFacade {
        // add a job for the main realm (None as realm_name)
        rt.loop_realm(None, |_rt_adapter, realm_adapter| {
            let script = Script::new("example.js", "7 + 13");
            let value_adapter = realm_adapter.eval(script).expect("script failed");
            // convert value_adapter to value_facade because value_adapter is not Send
            realm_adapter
                .to_js_value_facade(&value_adapter)
                .expect("conversion failed")
        })
        .await
    }

    #[test]
    fn test1() {
        // start a new runtime
        let rt = QuickJsRuntimeBuilder::new().build();
        let val = block_on(example(&rt));
        if let JsValueFacade::I32 { val } = val {
            assert_eq!(val, 20);
        } else {
            panic!("not an i32");
        }
    }

    #[tokio::test]
    async fn test_serde() {
        let json = r#"
            {
                "a": 1,
                "b": true,
                "c": {
                    "d": "q",
                    "e": [1, 2, 3.3]
                }
            }
        "#;

        let value = serde_json::from_str::<serde_json::Value>(json).expect("json fail");
        let input: JsValueFacade = JsValueFacade::SerdeValue { value };
        let rt = init_test_rt();

        let _ = rt.eval(None, Script::new("t.js", r#"
            function testSerde(input) {
                return "" + input.a + input.b + input.c.d + input.c.e[0] + input.c.e[1] + input.c.e[2];
            }
        "#)).await.expect("script failed");

        let res = rt
            .invoke_function(None, &[], "testSerde", vec![input])
            .await
            .expect("func failed");

        assert!(res.is_string());
        assert_eq!(res.get_str(), "1trueq123.3");
    }

    #[derive(Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    struct User {
        name: String,
        last_name: String,
    }

    #[tokio::test]
    async fn serde_tests_serialize() {
        let rtb: QuickJsRuntimeBuilder = QuickJsRuntimeBuilder::new();
        let rt = rtb.build();

        // init my function
        rt.eval(
            None,
            Script::new(
                "test.js",
                r#"
                function myTest(user) {
                    return {
                        name: "proc_" + user.name,
                        lastName: "proc_" + user.lastName
                    }
                }
                "#,
            ),
        )
        .await
        .expect("script failed");

        // create a user obj
        let test_user_input = User {
            last_name: "Anderson".to_string(),
            name: "Mister".to_string(),
        };

        let args = vec![JsValueFacade::from_serializable(&test_user_input)
            .expect("could not serialize to JsValueFacade")];

        let res: JsValueFacade = rt
            .invoke_function(None, &[], "myTest", args)
            .await
            .expect("func failed");

        let json_result = res
            .to_json_string()
            .await
            .expect("could not serialize to json");

        assert_eq!(
            json_result.as_str(),
            r#"{"name":"proc_Mister","lastName":"proc_Anderson"}"#
        );

        // serialize back to user
        let user_output: User = serde_json::from_str(json_result.as_str()).unwrap();
        assert_eq!(user_output.name.as_str(), "proc_Mister");
        assert_eq!(user_output.last_name.as_str(), "proc_Anderson");
    }

    #[tokio::test]
    async fn serde_tests_value() {
        let rtb: QuickJsRuntimeBuilder = QuickJsRuntimeBuilder::new();
        let rt = rtb.build();

        // init my function
        rt.eval(
            None,
            Script::new(
                "test.js",
                r#"
                function myTest(user) {
                    return {
                        name: "proc_" + user.name,
                        lastName: "proc_" + user.lastName
                    }
                }
                "#,
            ),
        )
        .await
        .expect("script failed");

        // create a user obj
        let test_user_input = User {
            last_name: "Anderson".to_string(),
            name: "Mister".to_string(),
        };

        let input_value: serde_json::Value =
            serde_json::to_value(test_user_input).expect("could not to_value");
        let args = vec![JsValueFacade::SerdeValue { value: input_value }];

        let res: JsValueFacade = rt
            .invoke_function(None, &[], "myTest", args)
            .await
            .expect("func failed");

        // as value
        let value_result: serde_json::Value = res
            .to_serde_value()
            .await
            .expect("could not serialize to json");

        assert!(value_result.is_object());

        // serialize back to user
        let user_output: User = serde_json::from_value(value_result).unwrap();
        assert_eq!(user_output.name.as_str(), "proc_Mister");
        assert_eq!(user_output.last_name.as_str(), "proc_Anderson");
    }
}