quickjs_runtime 0.8.7

Wrapper API and utils for the QuickJS JavaScript engine with support for Promise, Module, Async/await
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
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
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
//! utils for implementing proxy classes which can be used to use rust structs from JS (define method/getters/setters/etc)

use crate::quickjs_utils;
use crate::quickjs_utils::functions::new_native_function_q;
use crate::quickjs_utils::objects::{get_property, set_property2_q};
use crate::quickjs_utils::primitives::from_string;
use crate::quickjs_utils::{atoms, errors, functions, objects, parse_args, primitives};
use crate::quickjsrealmadapter::QuickJsRealmAdapter;
use crate::quickjsruntimeadapter::QuickJsRuntimeAdapter;
use crate::valueref::JSValueRef;
use hirofa_utils::js_utils::adapters::JsValueAdapter;
use hirofa_utils::js_utils::JsError;
use libquickjs_sys as q;
use log::trace;
use rand::{thread_rng, Rng};
use std::cell::RefCell;
use std::collections::HashMap;
use std::os::raw::{c_char, c_void};
use std::rc::Rc;

pub mod eventtarget;

pub type ProxyConstructor =
    dyn Fn(&QuickJsRealmAdapter, usize, Vec<JSValueRef>) -> Result<(), JsError> + 'static;
pub type ProxyFinalizer = dyn Fn(&QuickJsRealmAdapter, usize) + 'static;
pub type ProxyMethod =
    dyn Fn(&QuickJsRealmAdapter, &usize, Vec<JSValueRef>) -> Result<JSValueRef, JsError> + 'static;
pub type ProxyNativeMethod = q::JSCFunction;
pub type ProxyStaticMethod =
    dyn Fn(&QuickJsRealmAdapter, Vec<JSValueRef>) -> Result<JSValueRef, JsError> + 'static;
pub type ProxyStaticNativeMethod = q::JSCFunction;
pub type ProxyStaticGetter = dyn Fn(&QuickJsRealmAdapter) -> Result<JSValueRef, JsError> + 'static;
pub type ProxyStaticSetter =
    dyn Fn(&QuickJsRealmAdapter, JSValueRef) -> Result<(), JsError> + 'static;
pub type ProxyGetter =
    dyn Fn(&QuickJsRealmAdapter, &usize) -> Result<JSValueRef, JsError> + 'static;
pub type ProxySetter =
    dyn Fn(&QuickJsRealmAdapter, &usize, JSValueRef) -> Result<(), JsError> + 'static;

static CNAME: &str = "ProxyInstanceClass\0";
static SCNAME: &str = "ProxyStaticClass\0";

thread_local! {

    static PROXY_STATIC_EXOTIC: RefCell<q::JSClassExoticMethods> = RefCell::new(q::JSClassExoticMethods {
        get_own_property: None,
        get_own_property_names: None,
        delete_property: None,
        define_own_property: None,
        has_property: Some(proxy_static_has_prop),
        get_property: Some(proxy_static_get_prop),
        set_property: Some(proxy_static_set_prop),
    });

    static PROXY_INSTANCE_EXOTIC: RefCell<q::JSClassExoticMethods> = RefCell::new(q::JSClassExoticMethods {
        get_own_property: None,
        get_own_property_names: None,
        delete_property: None,
        define_own_property: None,
        has_property: Some(proxy_instance_has_prop),
        get_property: Some(proxy_instance_get_prop),
        set_property: Some(proxy_instance_set_prop),
    });

    static PROXY_STATIC_CLASS_DEF: RefCell<q::JSClassDef> = {
        PROXY_STATIC_EXOTIC.with(|e_rc|{
            let exotic = &mut *e_rc.borrow_mut();
            RefCell::new(q::JSClassDef {
                class_name: SCNAME.as_ptr() as *const c_char,
                finalizer: None,
                gc_mark: None,
                call: None,
                exotic,
            })
        })
    };

    static PROXY_INSTANCE_CLASS_DEF: RefCell<q::JSClassDef> = {
        PROXY_INSTANCE_EXOTIC.with(|e_rc|{
            let exotic = &mut *e_rc.borrow_mut();
            RefCell::new(q::JSClassDef {
                class_name: CNAME.as_ptr() as *const c_char,
                finalizer: Some(finalizer),
                gc_mark: None,
                call: None,
                exotic,
            })
        })
    };
    pub static PROXY_STATIC_CLASS_ID: RefCell<u32> = {
        let mut c_id: u32 = 0;
        let class_id: u32 = unsafe { q::JS_NewClassID(&mut c_id) };
        log::trace!("got static class id {}", class_id);

        PROXY_STATIC_CLASS_DEF.with(|cd_rc| {
            let class_def = &*cd_rc.borrow();
            QuickJsRuntimeAdapter::do_with(|q_js_rt| {
                let res = unsafe { q::JS_NewClass(q_js_rt.runtime, class_id, class_def) };
                log::trace!("new static class res {}", res);
                // todo res should be 0 for ok
            });
        });

        RefCell::new(class_id)
    };
    pub static PROXY_INSTANCE_CLASS_ID: RefCell<u32> = {
        let mut c_id: u32 = 0;
        let class_id: u32 = unsafe { q::JS_NewClassID(&mut c_id) };
        log::trace!("got class id {}", class_id);

        PROXY_INSTANCE_CLASS_DEF.with(|cd_rc| {
            let class_def = &*cd_rc.borrow();
            QuickJsRuntimeAdapter::do_with(|q_js_rt| {
                let res = unsafe { q::JS_NewClass(q_js_rt.runtime, class_id, class_def) };

                log::trace!("new class res {}", res);
                // todo res should be 0 for ok
            });
        });

        RefCell::new(class_id)
    };
}

const MAX_INSTANCE_NUM: usize = u32::MAX as usize;

pub(crate) fn init_statics() {
    PROXY_INSTANCE_CLASS_ID.with(|_rc| {
        //
    });
}

fn next_id(proxy: &Proxy) -> usize {
    let mappings = &*proxy.proxy_instance_id_mappings.borrow();
    if mappings.len() == MAX_INSTANCE_NUM {
        panic!("too many instances"); // todo report ex
    }
    let mut rng = thread_rng();
    let mut r: usize = rng.gen();
    while mappings.contains_key(&r) {
        r += 1;
    }
    r
}

/// The Proxy struct can be used to create a class in JavaScript who's methods can be implemented in rust
/// # Example
/// ```rust
/// use quickjs_runtime::builder::QuickJsRuntimeBuilder;
/// use quickjs_runtime::reflection::Proxy;
/// use quickjs_runtime::quickjsrealmadapter::QuickJsRealmAdapter;
/// use quickjs_runtime::valueref::JSValueRef;
/// use std::cell::RefCell;
/// use std::collections::HashMap;
/// use quickjs_runtime::quickjs_utils::primitives;
/// use hirofa_utils::js_utils::Script;
/// use quickjs_runtime::esvalue::EsValueFacade;
///
/// struct MyFunkyStruct{
///     name: String
/// }
///
/// impl Drop for MyFunkyStruct {fn drop(&mut self) {
///         println!("Funky drop: {}", self.name.as_str());
///     }
/// }
///
/// thread_local! {
///    static INSTANCES: RefCell<HashMap<usize, MyFunkyStruct>> = RefCell::new(HashMap::new());
/// }
///
/// //create a new EsRuntime
/// let rt = QuickJsRuntimeBuilder::new().build();
///
/// // install our proxy class as com.hirofa.FunkyClass
/// rt.exe_rt_task_in_event_loop(|q_js_rt| {
///    let q_ctx = q_js_rt.get_main_context();
///    Proxy::new()
///    .namespace(vec!["com", "hirofa"])
///    .name("FunkyClass")
///    // the constructor is called when a script does new com.hirofa.FunkyClass, the reflection utils
///    // generate an instance_id which may be used to identify the instance
///    .constructor(|q_ctx: &QuickJsRealmAdapter, instance_id: usize, args: Vec<JSValueRef>| {
///        // we'll assume our script always constructs the Proxy with a single name argument
///        let name = primitives::to_string_q(q_ctx, &args[0]).ok().expect("bad constructor! bad!");
///        // create a new instance of our struct and store it in a map
///        let instance = MyFunkyStruct{name};
///        // store our struct in a thread_local map
///        INSTANCES.with(move |rc| {
///            let map = &mut *rc.borrow_mut();
///            map.insert(instance_id, instance);
///        });
///        // return Ok, or Err if the constructor failed (e.g. wrong args were passed)
///        Ok(())
///     })
///    // next we create a simple getName method, this will return a String
///    .method("getName", |q_ctx, instance_id, args| {
///        INSTANCES.with(move |rc| {
///            let map = & *rc.borrow();
///            let instance = map.get(instance_id).unwrap();
///            primitives::from_string_q(q_ctx, instance.name.as_str())
///        })
///    })
///    // and lastly (but very important) implement a finalizer so our rust struct may be dropped
///    .finalizer(|q_ctx, instance_id| {
///        INSTANCES.with(move |rc| {
///            let map = &mut *rc.borrow_mut();
///            map.remove(&instance_id);
///        });
///     })
///     // install the Proxy in the context
///    .install(q_ctx, true);      
/// });
///
/// match rt.eval_sync(Script::new("test_proxy.es",
///     "{let inst = new com.hirofa.FunkyClass('FooBar'); let name = inst.getName(); inst = null; name;}"
/// )) {
///     Ok(name_esvf) => {
///         // assert correct getName result
///         assert_eq!(name_esvf.get_str(), "FooBar");
///         let i_ct = INSTANCES.with(|rc| rc.borrow().len());
///         // assert instance was finalized
///         assert_eq!(i_ct, 0);
///     }
///     Err(e) => {
///         panic!("script failed: {}", e);
///     }
/// }
/// rt.gc_sync();
///
/// ```
pub struct Proxy {
    name: Option<String>,
    namespace: Option<Vec<String>>,
    pub(crate) constructor: Option<Box<ProxyConstructor>>,
    finalizers: Vec<Box<ProxyFinalizer>>,
    methods: HashMap<String, Box<ProxyMethod>>,
    native_methods: HashMap<String, ProxyNativeMethod>,
    static_methods: HashMap<String, Box<ProxyStaticMethod>>,
    static_native_methods: HashMap<String, ProxyStaticNativeMethod>,
    static_getters_setters: HashMap<String, (Box<ProxyStaticGetter>, Box<ProxyStaticSetter>)>,
    getters_setters: HashMap<String, (Box<ProxyGetter>, Box<ProxySetter>)>,
    is_event_target: bool,
    is_static_event_target: bool,
    pub(crate) proxy_instance_id_mappings: RefCell<HashMap<usize, Box<ProxyInstanceInfo>>>,
}

impl Default for crate::reflection::Proxy {
    fn default() -> Self {
        Self::new()
    }
}

/// get a proxy by class_name (namespace.ClassName)
pub fn get_proxy(q_ctx: &QuickJsRealmAdapter, class_name: &str) -> Option<Rc<Proxy>> {
    let registry = &*q_ctx.proxy_registry.borrow();
    registry.get(class_name).cloned()
}

impl Proxy {
    #[allow(dead_code)]
    pub fn new() -> Self {
        Proxy {
            name: None,
            namespace: None,
            constructor: None,
            finalizers: Default::default(),
            methods: Default::default(),
            native_methods: Default::default(),
            static_methods: Default::default(),
            static_native_methods: Default::default(),
            static_getters_setters: Default::default(),
            getters_setters: Default::default(),
            is_event_target: false,
            is_static_event_target: false,
            proxy_instance_id_mappings: RefCell::new(Default::default()),
        }
    }

    /// set the name of the proxy class
    /// this will indicate how to construct the class from script
    pub fn name(mut self, name: &str) -> Self {
        self.name = Some(name.to_string());
        self
    }
    /// set the namespace of the proxy class
    /// # Example
    /// ```
    /// use quickjs_runtime::reflection::Proxy;
    /// Proxy::new().namespace(vec!["com", "hirofa"]).name("SomeClass");
    /// ```
    /// means from script you can access the class by
    /// ```javascript
    /// let instance = new com.hirofa.SomeClass();
    /// ```
    pub fn namespace(mut self, namespace: Vec<&str>) -> Self {
        if namespace.is_empty() {
            self.namespace = None;
        } else {
            self.namespace = Some(namespace.iter().map(|s| s.to_string()).collect());
        }
        self
    }
    /// get the canonical classname of a Proxy
    /// # example
    /// ```
    /// use quickjs_runtime::reflection::Proxy;
    /// Proxy::new().namespace(vec!["com", "hirofa"]).name("SomeClass");
    /// ```
    /// will result in a class_name of "com.hirofa.SomeClass"
    pub fn get_class_name(&self) -> String {
        let cn = if let Some(n) = self.name.as_ref() {
            n.as_str()
        } else {
            "__nameless_class__"
        };
        if self.namespace.is_some() {
            format!("{}.{}", self.namespace.as_ref().unwrap().join("."), cn)
        } else {
            cn.to_string()
        }
    }
    /// add a constructor for the Proxy class
    /// this will enable a script to create a new instance of a Proxy class
    /// if omitted the Proxy class will not be constructable from script
    pub fn constructor<C>(mut self, constructor: C) -> Self
    where
        C: Fn(&QuickJsRealmAdapter, usize, Vec<JSValueRef>) -> Result<(), JsError> + 'static,
    {
        self.constructor = Some(Box::new(constructor));
        self
    }
    /// add a finalizer for the Proxy class
    /// this will be called when an instance of the Proxy class is dropped or garbage collected
    pub fn finalizer<C>(mut self, finalizer: C) -> Self
    where
        C: Fn(&QuickJsRealmAdapter, usize) + 'static,
    {
        self.finalizers.push(Box::new(finalizer));
        self
    }
    /// add a method to the Proxy class, this method will be available as a member of instances of the Proxy class
    pub fn method<M>(mut self, name: &str, method: M) -> Self
    where
        M: Fn(&QuickJsRealmAdapter, &usize, Vec<JSValueRef>) -> Result<JSValueRef, JsError>
            + 'static,
    {
        self.methods.insert(name.to_string(), Box::new(method));
        self
    }
    /// add a method to the Proxy class, this method will be available as a member of instances of the Proxy class
    pub fn native_method(mut self, name: &str, method: ProxyNativeMethod) -> Self {
        self.native_methods.insert(name.to_string(), method);
        self
    }
    /// add a static method to the Proxy class, this method will be available as a member of the Proxy class itself
    pub fn static_method<M>(mut self, name: &str, method: M) -> Self
    where
        M: Fn(&QuickJsRealmAdapter, Vec<JSValueRef>) -> Result<JSValueRef, JsError> + 'static,
    {
        self.static_methods
            .insert(name.to_string(), Box::new(method));
        self
    }
    /// add a static method to the Proxy class, this method will be available as a member of the Proxy class itself
    pub fn static_native_method(mut self, name: &str, method: ProxyStaticNativeMethod) -> Self {
        self.static_native_methods.insert(name.to_string(), method);
        self
    }

    /// add a static getter and setter to the Proxy class
    pub fn static_getter_setter<G, S>(mut self, name: &str, getter: G, setter: S) -> Self
    where
        G: Fn(&QuickJsRealmAdapter) -> Result<JSValueRef, JsError> + 'static,
        S: Fn(&QuickJsRealmAdapter, JSValueRef) -> Result<(), JsError> + 'static,
    {
        self.static_getters_setters
            .insert(name.to_string(), (Box::new(getter), Box::new(setter)));
        self
    }
    /// add a getter and setter to the Proxy class, these will be available as a member of an instance of this Proxy class
    pub fn getter_setter<G, S>(mut self, name: &str, getter: G, setter: S) -> Self
    where
        G: Fn(&QuickJsRealmAdapter, &usize) -> Result<JSValueRef, JsError> + 'static,
        S: Fn(&QuickJsRealmAdapter, &usize, JSValueRef) -> Result<(), JsError> + 'static,
    {
        self.getters_setters
            .insert(name.to_string(), (Box::new(getter), Box::new(setter)));
        self
    }
    /// indicate the Proxy class should implement the EventTarget interface, this will result in the addEventListener, removeEventListener and dispatchEvent methods to be available on instances of the Proxy class
    pub fn event_target(mut self) -> Self {
        self.is_event_target = true;
        self
    }
    /// indicate the Proxy class should implement the EventTarget interface, this will result in the addEventListener, removeEventListener and dispatchEvent methods to be available
    pub fn static_event_target(mut self) -> Self {
        self.is_static_event_target = true;
        self
    }
    /// install the Proxy class in a QuickJsContext, this is always needed as a final step to actually make the Proxy class work
    pub fn install(
        mut self,
        q_ctx: &QuickJsRealmAdapter,
        add_variable_to_global: bool,
    ) -> Result<JSValueRef, JsError> {
        if self.name.is_none() {
            return Err(JsError::new_str("Proxy needs a name"));
        }

        let prim_cn = self.get_class_name();
        self = self.method("Symbol.toPrimitive", move |q_ctx, id, _args| {
            let prim = primitives::from_string_q(
                q_ctx,
                format!("Proxy::instance({})::{}", id, prim_cn).as_str(),
            )?;
            Ok(prim)
        });
        let prim_cn = self.get_class_name();
        self = self.static_method("Symbol.toPrimitive", move |q_ctx, _args| {
            let prim = primitives::from_string_q(q_ctx, format!("Proxy::{}", prim_cn).as_str())?;
            Ok(prim)
        });

        let class_ref = self.install_class_prop(q_ctx, add_variable_to_global)?;
        eventtarget::impl_event_target(self).install_move_to_registry(q_ctx);

        Ok(class_ref)
    }

    fn install_move_to_registry(self, q_ctx: &QuickJsRealmAdapter) {
        let proxy = self;

        let reg_map = &mut *q_ctx.proxy_registry.borrow_mut();
        reg_map.insert(proxy.get_class_name(), Rc::new(proxy));
    }
    fn install_class_prop(
        &self,
        q_ctx: &QuickJsRealmAdapter,
        add_variable_to_global: bool,
    ) -> Result<JSValueRef, JsError> {
        // this creates a constructor function, adds it to the global scope and then makes an instance of the static_proxy_class its prototype so we can add static_getters_setters and static_methods

        log::trace!("reflection::Proxy::install_class_prop / 1");

        let static_class_id = PROXY_STATIC_CLASS_ID.with(|rc| *rc.borrow());

        log::trace!("reflection::Proxy::install_class_prop / 2");

        let constructor_ref = new_native_function_q(
            q_ctx,
            self.name.as_ref().unwrap().as_str(),
            Some(constructor),
            1,
            true,
        )?;

        log::trace!("reflection::Proxy::install_class_prop / 3");

        let class_val: q::JSValue =
            unsafe { q::JS_NewObjectClass(q_ctx.context, static_class_id as i32) };

        log::trace!("reflection::Proxy::install_class_prop / 4");

        let class_val_ref = JSValueRef::new(
            q_ctx.context,
            class_val,
            false,
            true,
            "reflection::Proxy::install_class_prop class_val",
        );

        assert_eq!(1, class_val_ref.get_ref_count());

        log::trace!("reflection::Proxy::install_class_prop / 5");

        if class_val_ref.is_exception() {
            return if let Some(e) = unsafe { QuickJsRealmAdapter::get_exception(q_ctx.context) } {
                Err(e)
            } else {
                Err(JsError::new_string(format!(
                    "could not create class:{}",
                    self.get_class_name()
                )))
            };
        }

        log::trace!("reflection::Proxy::install_class_prop / 6");

        unsafe {
            let res = q::JS_SetPrototype(
                q_ctx.context,
                *constructor_ref.borrow_value(),
                *class_val_ref.borrow_value(),
            );
            if res < 0 {
                return if let Some(err) = QuickJsRealmAdapter::get_exception(q_ctx.context) {
                    Err(err)
                } else {
                    Err(JsError::new_str("could not set class proto"))
                };
            }
        }

        assert_eq!(2, class_val_ref.get_ref_count());

        log::trace!("reflection::Proxy::install_class_prop / 7");

        objects::set_property2_q(
            q_ctx,
            &constructor_ref,
            "name",
            &primitives::from_string_q(q_ctx, &self.get_class_name())?,
            0,
        )?;

        // todo impl namespace here
        if add_variable_to_global {
            log::trace!("reflection::Proxy::install_class_prop / 8");
            let ns = if let Some(namespace) = &self.namespace {
                objects::get_namespace_q(
                    q_ctx,
                    namespace.iter().map(|s| s.as_str()).collect(),
                    true,
                )?
            } else {
                quickjs_utils::get_global_q(q_ctx)
            };

            log::trace!("reflection::Proxy::install_class_prop / 9");

            objects::set_property2_q(
                q_ctx,
                &ns,
                self.name.as_ref().unwrap().as_str(),
                &constructor_ref,
                0,
            )?;
        }
        log::trace!("reflection::Proxy::install_class_prop / 10");

        log::trace!("install_class_prop done");

        Ok(constructor_ref)
    }
}

pub fn get_proxy_instance_proxy_and_instance_id_q(
    q_ctx: &QuickJsRealmAdapter,
    obj: &JSValueRef,
) -> Option<(Rc<Proxy>, usize)> {
    if !is_proxy_instance_q(q_ctx, obj) {
        None
    } else {
        let info = get_proxy_instance_info(obj.borrow_value());
        let cn = info.class_name.as_str();
        let registry = &*q_ctx.proxy_registry.borrow();
        registry.get(cn).cloned().map(|proxy| (proxy, info.id))
    }
}

pub fn is_proxy_instance_q(q_ctx: &QuickJsRealmAdapter, obj: &JSValueRef) -> bool {
    unsafe { is_proxy_instance(q_ctx.context, obj) }
}

/// check if an object is an instance of a Proxy class
/// # Safety
/// please make sure context is still valid
pub unsafe fn is_proxy_instance(ctx: *mut q::JSContext, obj: &JSValueRef) -> bool {
    if !obj.is_object() {
        false
    } else {
        // workaround for instanceof not yet working
        let prop_res = get_property(ctx, obj, "__proxy__");
        if let Ok(prop) = prop_res {
            if prop.is_bool() && prop.js_to_bool() {
                return true;
            }
        }

        let class_id = PROXY_INSTANCE_CLASS_ID.with(|rc| *rc.borrow());
        let proxy_class_proto: q::JSValue = q::JS_GetClassProto(ctx, class_id);
        //let proto_ref: JSValueRef = JSValueRef::new(ctx, proxy_class_proto, false, false, "proxy_class_proto");

        let proxy_class_proto_obj = q::JS_GetPrototype(ctx, proxy_class_proto);
        let res = q::JS_IsInstanceOf(ctx, *obj.borrow_value(), proxy_class_proto_obj);

        if res == -1 {
            // log err
            if let Some(ex) = QuickJsRealmAdapter::get_exception(ctx) {
                log::error!("is_proxy_instance failed: {}", ex);
            } else {
                log::error!("is_proxy_instance failed");
            }
        }

        res > 0
    }
}

pub fn new_instance2(
    proxy: &Proxy,
    q_ctx: &QuickJsRealmAdapter,
) -> Result<(usize, JSValueRef), JsError> {
    let instance_id = next_id(proxy);
    Ok((instance_id, new_instance3(proxy, instance_id, q_ctx)?))
}

pub(crate) fn new_instance3(
    proxy: &Proxy,
    instance_id: usize,
    q_ctx: &QuickJsRealmAdapter,
) -> Result<JSValueRef, JsError> {
    let ctx = q_ctx.context;
    let class_id = PROXY_INSTANCE_CLASS_ID.with(|rc| *rc.borrow());

    let class_val: q::JSValue = unsafe { q::JS_NewObjectClass(ctx, class_id as i32) };

    let class_name = proxy.get_class_name();

    let class_val_ref = JSValueRef::new(
        q_ctx.context,
        class_val,
        false,
        true,
        format!("reflection::Proxy; cn={}", class_name).as_str(),
    );

    if class_val_ref.is_exception() {
        return if let Some(e) = q_ctx.get_exception_ctx() {
            Err(JsError::new_string(format!(
                "could not create class:{} due to: {}",
                class_name, e
            )))
        } else {
            Err(JsError::new_string(format!(
                "could not create class:{}",
                class_name
            )))
        };
    }

    let mappings = &mut *proxy.proxy_instance_id_mappings.borrow_mut();
    assert!(!mappings.contains_key(&instance_id));

    let mut bx = Box::new(ProxyInstanceInfo {
        id: instance_id,
        class_name: proxy.get_class_name(),
        context_id: q_ctx.id.clone(),
    });

    let ibp: &mut ProxyInstanceInfo = &mut bx;
    let info_ptr = ibp as *mut _ as *mut c_void;

    mappings.insert(instance_id, bx);
    unsafe { q::JS_SetOpaque(*class_val_ref.borrow_value(), info_ptr) };

    // todo this is a workaround.. i need to set a prototype for classes using JS_setClassProto per context on init..
    set_property2_q(
        q_ctx,
        &class_val_ref,
        "__proxy__",
        &primitives::from_bool(true),
        0,
    )?;

    Ok(class_val_ref)
}

pub fn new_instance(
    class_name: &str,
    q_ctx: &QuickJsRealmAdapter,
) -> Result<(usize, JSValueRef), JsError> {
    // todo

    let registry = &*q_ctx.proxy_registry.borrow();

    if let Some(proxy) = registry.get(class_name) {
        // construct

        new_instance2(proxy, q_ctx)
    } else {
        Err(JsError::new_str("no such proxy"))
    }
}

#[allow(dead_code)]
unsafe extern "C" fn constructor(
    context: *mut q::JSContext,
    this_val: q::JSValue,
    argc: ::std::os::raw::c_int,
    argv: *mut q::JSValue,
) -> q::JSValue {
    log::trace!("constructor called, this_tag={}", this_val.tag);

    // this is the function we created earlier (the constructor)
    // so classname = this.name;
    let this_ref = JSValueRef::new(
        context,
        this_val,
        false,
        false,
        "reflection::constructor this_val",
    );
    QuickJsRuntimeAdapter::do_with(|q_js_rt| {
        let name_ref = objects::get_property(context, &this_ref, "name").expect("name get failed");
        let class_name =
            functions::call_to_string(context, &name_ref).expect("name.toString failed");

        let q_ctx = q_js_rt.get_quickjs_context(context);

        let registry = &*q_ctx.proxy_registry.borrow();
        if let Some(proxy) = registry.get(&class_name) {
            if let Some(constructor) = &proxy.constructor {
                // construct

                let args_vec = parse_args(context, argc, argv);
                let instance_id = next_id(proxy);
                let constructor_res = constructor(q_ctx, instance_id, args_vec);

                match constructor_res {
                    Ok(()) => {
                        let instance_ref_res = new_instance3(proxy, instance_id, q_ctx);

                        match instance_ref_res {
                            Ok(instance_ref) => instance_ref.clone_value_incr_rc(),
                            Err(e) => q_ctx.report_ex(
                                format!(
                                    "could not create proxy instance for {} due to {}",
                                    class_name, e
                                )
                                .as_str(),
                            ),
                        }
                    }
                    Err(es_err) => q_ctx.report_ex(
                        format!("constructor for {} failed with {}", class_name, es_err).as_str(),
                    ),
                }
            } else {
                q_ctx.report_ex("not a constructor")
            }
        } else {
            q_ctx.report_ex("no such proxy")
        }
    })
}

pub(crate) struct ProxyInstanceInfo {
    id: usize,
    class_name: String, // todo, store all proxies in an autoidmap with a usize as key and store proxy_class_id here instead of string
    context_id: String, // todo store all context ids in an autoidmap with a usize as key and store context_id here instead of string
}

fn get_proxy_instance_info(val: &q::JSValue) -> &ProxyInstanceInfo {
    let class_id = PROXY_INSTANCE_CLASS_ID.with(|rc| *rc.borrow());
    let info_ptr: *mut c_void = unsafe { q::JS_GetOpaque(*val, class_id) };
    let info: &mut ProxyInstanceInfo = unsafe { &mut *(info_ptr as *mut ProxyInstanceInfo) };
    info
}

#[allow(dead_code)]
unsafe extern "C" fn finalizer(_rt: *mut q::JSRuntime, val: q::JSValue) {
    //todo
    log::trace!("finalizer called");

    let info: &ProxyInstanceInfo = get_proxy_instance_info(&val);
    trace!("finalize {}", info.id);

    QuickJsRuntimeAdapter::do_with(|q_js_rt| {
        let q_ctx = q_js_rt.get_context(&info.context_id);
        log::trace!("finalizer called, got q_ctx");
        let registry = &*q_ctx.proxy_registry.borrow();
        let proxy = registry.get(&info.class_name).unwrap();

        for finalizer in &proxy.finalizers {
            log::trace!("calling Proxy's finalizer");
            finalizer(q_ctx, info.id);
            log::trace!("after calling Proxy's finalizer");
        }

        {
            log::trace!("reflection::finalizer: remove from INSTANCE_ID_MAPPINGS");
            let id_map = &mut *proxy.proxy_instance_id_mappings.borrow_mut();
            let _ = id_map.remove(&info.id).expect("no such id to finalize");
            log::trace!("reflection::finalizer: remove from INSTANCE_ID_MAPPINGS -> done");
        }
        log::trace!("reflection::finalizer: 2");

        log::trace!("reflection::finalizer: 3, exit");
    });
}

#[allow(dead_code)]
unsafe extern "C" fn proxy_static_get_prop(
    context: *mut q::JSContext,
    obj: q::JSValue,
    atom: q::JSAtom,
    receiver: q::JSValue,
) -> q::JSValue {
    // static proxy class, not an instance
    trace!("proxy_static_get_prop");

    let _obj_ref = JSValueRef::new(
        context,
        obj,
        false,
        false,
        "reflection::proxy_static_get_prop obj",
    );
    let receiver_ref = JSValueRef::new(
        context,
        receiver,
        false,
        false,
        "reflection::proxy_static_get_prop receiver",
    );

    QuickJsRuntimeAdapter::do_with(|q_js_rt| {
        let q_ctx = q_js_rt.get_quickjs_context(context);

        let proxy_name_ref = objects::get_property(context, &receiver_ref, "name")
            .ok()
            .unwrap();
        let proxy_name = primitives::to_string(context, &proxy_name_ref)
            .ok()
            .unwrap();
        trace!("proxy_static_get_prop: {}", proxy_name);

        let prop_name = atoms::to_string2(context, &atom).expect("could not get name");
        trace!("proxy_static_get_prop: prop: {}", prop_name);

        let registry = &*q_ctx.proxy_registry.borrow();
        if let Some(proxy) = registry.get(proxy_name.as_str()) {
            if proxy.static_methods.contains_key(&prop_name) {
                trace!("found method for {}", prop_name);

                let function_data_ref = from_string(context, prop_name.as_str())
                    .expect("could not create function_data_ref");

                let func_ref = functions::new_native_function_data(
                    context,
                    Some(proxy_static_method),
                    prop_name.as_str(),
                    1,
                    function_data_ref,
                )
                .expect("could not create func");

                objects::set_property(context, &receiver_ref, prop_name.as_str(), &func_ref)
                    .expect("set_property 9656738 failed");

                func_ref.clone_value_incr_rc()
            } else if let Some(native_static_method) = proxy.static_native_methods.get(&prop_name) {
                trace!("found static native method for {}", prop_name);

                let func_ref = functions::new_native_function(
                    context,
                    &prop_name,
                    *native_static_method,
                    1,
                    false,
                )
                .expect("could not create func");

                objects::set_property(context, &receiver_ref, prop_name.as_str(), &func_ref)
                    .expect("set_property 36099 failed");

                func_ref.clone_value_incr_rc()
            } else if let Some(getter_setter) = proxy.static_getters_setters.get(&prop_name) {
                // call the getter
                let getter = &getter_setter.0;
                let res: Result<JSValueRef, JsError> = getter(q_ctx);
                match res {
                    Ok(g_val) => g_val.clone_value_incr_rc(),
                    Err(e) => {
                        let es = format!("proxy_static_get_prop failed: {}", e);
                        q_ctx.report_ex(es.as_str())
                    }
                }
            } else {
                quickjs_utils::new_null()
            }
        } else {
            q_ctx.report_ex("proxy class not found")
        }
    })
}

#[allow(dead_code)]
unsafe extern "C" fn proxy_instance_get_prop(
    context: *mut q::JSContext,
    obj: q::JSValue,
    atom: q::JSAtom,
    receiver: q::JSValue,
) -> q::JSValue {
    trace!("proxy_instance_get_prop");

    let _obj_ref = JSValueRef::new(
        context,
        obj,
        false,
        false,
        "reflection::proxy_instance_get_prop obj",
    );
    let receiver_ref = JSValueRef::new(
        context,
        receiver,
        false,
        false,
        "reflection::proxy_instance_get_prop receiver",
    );

    QuickJsRuntimeAdapter::do_with(|q_js_rt| {
        let q_ctx = q_js_rt.get_quickjs_context(context);

        let prop_name = atoms::to_string2(context, &atom).expect("could not get name");
        trace!("proxy_instance_get_prop: {}", prop_name);

        let info = get_proxy_instance_info(&obj);

        trace!("obj_ref.classname = {}", info.class_name);

        // see if we have a matching method

        let registry = &*q_ctx.proxy_registry.borrow();
        let proxy = registry.get(&info.class_name).unwrap();
        if proxy.methods.contains_key(&prop_name) {
            trace!("found method for {}", prop_name);

            let function_data_ref = from_string(context, prop_name.as_str())
                .expect("could not create function_data_ref");

            let func_ref = functions::new_native_function_data(
                context,
                Some(proxy_instance_method),
                prop_name.as_str(),
                1,
                function_data_ref,
            )
            .expect("could not create func");

            objects::set_property(context, &receiver_ref, prop_name.as_str(), &func_ref)
                .expect("set_property 96385 failed"); // todo report ex

            func_ref.clone_value_incr_rc()
        } else if let Some(native_method) = proxy.native_methods.get(&prop_name) {
            trace!("found native method for {}", prop_name);

            let func_ref =
                functions::new_native_function(context, &prop_name, *native_method, 1, false)
                    .expect("could not create func"); // tyodo report ex

            objects::set_property(context, &receiver_ref, prop_name.as_str(), &func_ref)
                .expect("set_property 49671 failed"); // todo report ex

            func_ref.clone_value_incr_rc()
        } else if let Some(getter_setter) = proxy.getters_setters.get(&prop_name) {
            // call the getter
            let getter = &getter_setter.0;
            let res: Result<JSValueRef, JsError> = getter(q_ctx, &info.id);
            match res {
                Ok(g_val) => g_val.clone_value_incr_rc(),
                Err(e) => {
                    let msg = format!("proxy_instance_get failed: {}", e.get_message());
                    let nat_stack = format!(
                        "    at Proxy instance getter [{}]\n{}",
                        prop_name,
                        e.get_stack()
                    );
                    let err =
                        errors::new_error(context, e.get_name(), msg.as_str(), nat_stack.as_str())
                            .expect("create error failed");
                    errors::throw(context, err)
                }
            }
        } else {
            // return null if nothing was returned
            quickjs_utils::new_null()
        }
    })

    // get constructor name
    // get proxy
    // get method or getter or setter
    // return native func (cache those?)
}
#[allow(dead_code)]
unsafe extern "C" fn proxy_instance_has_prop(
    _context: *mut q::JSContext,
    _obj: q::JSValue,
    _atom: q::JSAtom,
) -> ::std::os::raw::c_int {
    todo!()
}
#[allow(dead_code)]
unsafe extern "C" fn proxy_static_has_prop(
    _context: *mut q::JSContext,
    _obj: q::JSValue,
    _atom: q::JSAtom,
) -> ::std::os::raw::c_int {
    todo!()
}

unsafe extern "C" fn proxy_instance_method(
    context: *mut q::JSContext,
    this_val: q::JSValue,
    argc: ::std::os::raw::c_int,
    argv: *mut q::JSValue,
    _magic: ::std::os::raw::c_int,
    func_data: *mut q::JSValue,
) -> q::JSValue {
    trace!("proxy_instance_method");
    QuickJsRuntimeAdapter::do_with(|q_js_rt| {
        let q_ctx = q_js_rt.get_quickjs_context(context);

        let proxy_instance_info: &ProxyInstanceInfo = get_proxy_instance_info(&this_val);

        let args_vec = parse_args(context, argc, argv);

        let func_name_ref = JSValueRef::new(
            context,
            *func_data,
            false,
            false,
            "reflection::proxy_instance_method func_data",
        );
        let func_name = primitives::to_string(context, &func_name_ref)
            .expect("could not to_string func_name_ref");

        trace!("proxy_instance_method: {}", func_name);

        let registry = &*q_ctx.proxy_registry.borrow();
        let proxy = registry
            .get(proxy_instance_info.class_name.as_str())
            .unwrap();
        if let Some(method) = proxy.methods.get(func_name.as_str()) {
            // todo report ex
            let m_res: Result<JSValueRef, JsError> =
                method(q_ctx, &proxy_instance_info.id, args_vec);

            match m_res {
                Ok(m_res_ref) => m_res_ref.clone_value_incr_rc(),
                Err(e) => {
                    let msg = format!("proxy_instance_method failed: {}", e.get_message());
                    let nat_stack = format!(
                        "    at Proxy instance method [{}]\n{}",
                        func_name,
                        e.get_stack()
                    );
                    let err =
                        errors::new_error(context, e.get_name(), msg.as_str(), nat_stack.as_str())
                            .expect("create error failed");
                    errors::throw(context, err)
                }
            }
        } else {
            // return null if nothing was returned
            quickjs_utils::new_null()
        }
    })
}

#[allow(dead_code)]
unsafe extern "C" fn proxy_static_method(
    context: *mut q::JSContext,
    this_val: q::JSValue,
    argc: ::std::os::raw::c_int,
    argv: *mut q::JSValue,
    _magic: ::std::os::raw::c_int,
    func_data: *mut q::JSValue,
) -> q::JSValue {
    trace!("proxy_static_method");
    QuickJsRuntimeAdapter::do_with(|q_js_rt| {
        let q_ctx = q_js_rt.get_quickjs_context(context);
        let this_ref = JSValueRef::new(
            context,
            this_val,
            false,
            false,
            "reflection::proxy_static_method this_val",
        );

        let proxy_name_ref = objects::get_property(context, &this_ref, "name")
            .ok()
            .unwrap();
        let proxy_name =
            primitives::to_string(context, &proxy_name_ref).expect("could not to_string classname");

        let args_vec = parse_args(context, argc, argv);

        let func_name_ref = JSValueRef::new(
            context,
            *func_data,
            false,
            false,
            "reflection::proxy_static_method func_data",
        );
        let func_name = primitives::to_string(context, &func_name_ref)
            .expect("could not to_string func_name_ref");

        trace!("proxy_static_method: {}", func_name);

        let registry = &*q_ctx.proxy_registry.borrow();
        let proxy = registry.get(proxy_name.as_str()).unwrap();
        if let Some(method) = proxy.static_methods.get(func_name.as_str()) {
            let m_res: Result<JSValueRef, JsError> = method(q_ctx, args_vec);
            match m_res {
                Ok(m_res_ref) => m_res_ref.clone_value_incr_rc(),
                Err(e) => {
                    let msg = format!("proxy_static_method failed: {}", e.get_message());
                    let nat_stack = format!(
                        "    at Proxy static method [{}]\n{}",
                        func_name,
                        e.get_stack()
                    );
                    let err =
                        errors::new_error(context, e.get_name(), msg.as_str(), nat_stack.as_str())
                            .expect("create error failed");
                    errors::throw(context, err)
                }
            }
        } else {
            // return null if nothing was returned
            quickjs_utils::new_null()
        }
    })
}

unsafe extern "C" fn proxy_static_set_prop(
    context: *mut q::JSContext,
    _obj: q::JSValue,
    atom: q::JSAtom,
    value: q::JSValue,
    receiver: q::JSValue,
    _flags: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int {
    trace!("proxy_instance_set_prop");

    let value_ref = JSValueRef::new(
        context,
        value,
        false,
        false,
        "reflection::proxy_instance_set_prop value",
    );
    let receiver_ref = JSValueRef::new(
        context,
        receiver,
        false,
        false,
        "reflection::proxy_instance_set_prop value",
    );

    QuickJsRuntimeAdapter::do_with(|q_js_rt| {
        let q_ctx = q_js_rt.get_quickjs_context(context);

        let prop_name = atoms::to_string2(context, &atom).expect("could not get name");
        trace!("proxy_static_set_prop: {}", prop_name);

        // see if we have a matching gettersetter

        let proxy_name_ref = objects::get_property(context, &receiver_ref, "name")
            .ok()
            .unwrap();
        let proxy_name = primitives::to_string(context, &proxy_name_ref)
            .ok()
            .unwrap();
        trace!("proxy_static_get_prop: {}", proxy_name);

        let prop_name = atoms::to_string2(context, &atom).expect("could not get name");
        trace!("proxy_static_get_prop: prop: {}", prop_name);

        let registry = &*q_ctx.proxy_registry.borrow();
        if let Some(proxy) = registry.get(proxy_name.as_str()) {
            if let Some(getter_setter) = proxy.static_getters_setters.get(&prop_name) {
                // call the setter
                let setter = &getter_setter.1;
                let res: Result<(), JsError> = setter(q_ctx, value_ref);
                match res {
                    Ok(_) => 0,
                    Err(e) => {
                        // fail, todo do i need ex?
                        let err = format!("proxy_instance_set_prop failed: {}", e);
                        log::error!("{}", err);
                        //let _ = q_ctx.report_ex(err.as_str());
                        -1
                    }
                }
            } else {
                // fail
                -1
            }
        } else {
            -1
        }
    })
}

unsafe extern "C" fn proxy_instance_set_prop(
    context: *mut q::JSContext,
    obj: q::JSValue,
    atom: q::JSAtom,
    value: q::JSValue,
    _receiver: q::JSValue,
    _flags: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int {
    trace!("proxy_instance_set_prop");

    let value_ref = JSValueRef::new(
        context,
        value,
        false,
        false,
        "reflection::proxy_instance_set_prop value",
    );

    QuickJsRuntimeAdapter::do_with(|q_js_rt| {
        let q_ctx = q_js_rt.get_quickjs_context(context);

        let prop_name = atoms::to_string2(context, &atom).expect("could not get name");
        trace!("proxy_instance_set_prop: {}", prop_name);

        let info = get_proxy_instance_info(&obj);

        trace!("obj_ref.classname = {}", info.class_name);

        // see if we have a matching gettersetter

        let registry = &*q_ctx.proxy_registry.borrow();
        let proxy = registry.get(&info.class_name).unwrap();

        if let Some(getter_setter) = proxy.getters_setters.get(&prop_name) {
            // call the setter
            let setter = &getter_setter.1;
            let res: Result<(), JsError> = setter(q_ctx, &info.id, value_ref);
            match res {
                Ok(_) => 0,
                Err(e) => {
                    // fail, todo do i need ex?
                    let err = format!("proxy_instance_set_prop failed: {}", e);
                    log::error!("{}", err);
                    //let _ = q_ctx.report_ex(err.as_str());
                    -1
                }
            }
        } else {
            // fail
            -1
        }
    })
}

#[cfg(test)]
pub mod tests {
    use crate::facades::tests::init_test_rt;
    use crate::quickjs_utils::objects::create_object_q;
    use crate::quickjs_utils::{functions, primitives};
    use crate::reflection::{
        get_proxy_instance_proxy_and_instance_id_q, is_proxy_instance_q, Proxy,
        PROXY_INSTANCE_CLASS_ID,
    };
    use hirofa_utils::js_utils::JsError;
    use hirofa_utils::js_utils::Script;
    use libquickjs_sys as q;
    use log::trace;
    use std::cell::RefCell;
    use std::collections::HashMap;
    use std::time::Duration;

    thread_local! {
        static TEST_INSTANCES: RefCell<HashMap<usize, String>> = RefCell::new(HashMap::new())
    }

    #[test]
    pub fn test_proxy1() {
        log::info!("> test_proxy");

        let rt = init_test_rt();
        rt.exe_rt_task_in_event_loop(|q_js_rt| {
            q_js_rt.gc();
            let q_ctx = q_js_rt.get_main_context();
            let _ = Proxy::new()
                .constructor(|_q_ctx, _id, _args| Ok(()))
                .name("Test")
                .install(q_ctx, true);
            q_ctx
                .eval(Script::new("test.es", "let t = new Test();"))
                .expect("script failed");
        });
    }

    #[test]
    pub fn test_proxy_ex() {
        log::info!("> test_proxy");

        let rt = init_test_rt();
        let err = rt.exe_rt_task_in_event_loop(|q_js_rt| {
            q_js_rt.gc();
            let q_ctx = q_js_rt.get_main_context();
            let _ = Proxy::new()
                .constructor(|_q_ctx, _id, _args| Ok(()))
                .method("run", |_realm, _instance_id, _args| {
                    Err(JsError::new_str("cant run"))
                })
                .name("Test")
                .install(q_ctx, true);
            let err = q_ctx
                .eval(Script::new("test.es", "let t = new Test(); \nt.run();"))
                .expect_err("script failed");

            format!("{}", err)
        });

        assert!(err.contains("test.es:2"));
        assert!(err.contains("at Proxy instance method [run]"));
        assert!(err.contains("cant run"));
    }

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

        let rt = init_test_rt();
        rt.exe_rt_task_in_event_loop(|q_js_rt| {
            q_js_rt.gc();
            let q_ctx = q_js_rt.get_main_context();
            let _ = Proxy::new()
                .constructor(|_q_ctx, _id, _args| Ok(()))
                .namespace(vec!["com", "company"])
                .name("Test")
                .install(q_ctx, true);
            let res = q_ctx
                .eval(Script::new("test_tostring.es", "new com.company.Test()"))
                .expect("script failed");
            assert!(is_proxy_instance_q(q_ctx, &res));
            let info = get_proxy_instance_proxy_and_instance_id_q(q_ctx, &res)
                .expect("could not get info");
            let id = info.1;
            let p = info.0;
            println!("id={}", id);
            assert_eq!(p.get_class_name().as_str(), "com.company.Test");

            let some_obj = create_object_q(q_ctx).expect("could not create obj");
            assert!(some_obj.is_object());

            let class_id = PROXY_INSTANCE_CLASS_ID.with(|rc| *rc.borrow());
            let proxy_class_proto: q::JSValue =
                unsafe { q::JS_GetClassProto(q_ctx.context, class_id) };
            //println!("proxy_class_proto = {}", proxy_class_proto);
            let res = unsafe {
                q::JS_IsInstanceOf(q_ctx.context, *some_obj.borrow_value(), proxy_class_proto) != 0
            };
            println!("res = {}", res);
            let res2 = is_proxy_instance_q(q_ctx, &some_obj);
            println!("res2 = {}", res2);
            assert!(!res2);
        });
    }

    #[test]
    pub fn test_to_string() {
        log::info!("> test_proxy");

        let rt = init_test_rt();
        rt.exe_rt_task_in_event_loop(|q_js_rt| {
            q_js_rt.gc();
            let q_ctx = q_js_rt.get_main_context();
            let _ = Proxy::new()
                .constructor(|_q_ctx, _id, _args| Ok(()))
                .namespace(vec!["com", "company"])
                .name("Test")
                .install(q_ctx, true);
            let res = q_ctx
                .eval(Script::new(
                    "test_tostring.es",
                    "com.company.Test + '-' + new com.company.Test()",
                ))
                .expect("script failed");
            let str = primitives::to_string_q(q_ctx, &res).expect("could not tostring");
            assert!(str.starts_with("Proxy::com.company.Test-Proxy::instance("));
            assert!(str.ends_with(")::com.company.Test"));
        });
    }

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

        let rt = init_test_rt();
        rt.exe_rt_task_in_event_loop(|q_js_rt| {
            let q_ctx = q_js_rt.get_main_context();
            let res = Proxy::new()
                .name("TestClass1")
                .constructor(|_context, id, _args| {
                    TEST_INSTANCES.with(|rc| {
                        let map = &mut *rc.borrow_mut();
                        map.insert(id, "hi".to_string())
                    });
                    Ok(())
                })
                .method("doIt", |_context, _obj_id, _args| {
                    Ok(primitives::from_i32(531))
                })
                .method("doIt2", |_context, _obj_id, _args| {
                    Err(JsError::new_str("aaargh"))
                })
                .getter_setter(
                    "gVar",
                    |_context, _id| Ok(primitives::from_i32(147)),
                    |_context, _id, _val| Ok(()),
                )
                .static_method("sDoIt", |_context, _args| Ok(primitives::from_i32(9876)))
                .static_method("sDoIt2", |_context, _args| Ok(primitives::from_i32(140)))
                .static_getter_setter(
                    "someThing",
                    |_context| {
                        trace!("static getter called, returning 754");
                        Ok(primitives::from_i32(754))
                    },
                    |q_ctx, val| {
                        trace!(
                            "static setter called, set to {}",
                            functions::call_to_string_q(q_ctx, &val)?
                        );
                        Ok(())
                    },
                )
                .finalizer(|_context, id| {
                    TEST_INSTANCES.with(|rc| {
                        let map = &mut *rc.borrow_mut();
                        let _ = map.remove(&id);
                    });
                    log::trace!("ran finalizer: {}", id);
                })
                .install(q_ctx, true);

            match res {
                Ok(_) => {}
                Err(e) => panic!("could not install proxy: {}", e),
            }
        });

        let i2_res = rt.eval_sync(Script::new(
            "test_proxy.es",
            "let tc2 = new TestClass1(1, true, 'abc'); let r2 = tc2.doIt(1, true, 'abc'); console.log('< setting tc2 to null'); tc2 = null; console.log('> setting tc2 to null'); r2;"
            ,
        ));
        log::debug!("test_proxy.es done, ok = {}", i2_res.is_ok());
        match i2_res {
            Ok(i2) => {
                assert!(i2.is_i32());
                assert_eq!(i2.get_i32(), 531);
            }
            Err(e) => {
                log::error!("test_proxy.es failed with: {}", e);
                panic!("test_proxy.es failed");
            }
        }

        let i = rt.eval_sync(Script::new(
            "test_proxy2.es",
            "let tc1 = new TestClass1(1, true, 'abc'); let r = tc1.doIt(1, true, 'abc'); r = tc1.doIt(1, true, 'abc'); tc1 = null; r;"
        ))
            .ok()
            .expect("script failed");

        assert!(i.is_i32());
        assert_eq!(i.get_i32(), 531);

        let i3_res = rt.eval_sync(Script::new("test_proxy.es", "TestClass1.sDoIt();"));

        if i3_res.is_err() {
            panic!("script failed: {}", i3_res.err().unwrap());
        }
        let i3 = i3_res.ok().unwrap();

        assert!(i3.is_i32());
        assert_eq!(i3.get_i32(), 9876);

        let i4 = rt
            .eval_sync(Script::new(
                "test_proxy.es",
                "TestClass1.someThing = 1; TestClass1.someThing;",
            ))
            .expect("script failed");

        assert!(i4.is_i32());
        assert_eq!(i4.get_i32(), 754);

        let i5 = rt
            .eval_sync(Script::new(
                "test_proxy.es",
                "let tc5 = new TestClass1(); let r5 = tc5.gVar; tc5 = null; r5;",
            ))
            .expect("script failed");

        assert!(i5.is_i32());
        assert_eq!(i5.get_i32(), 147);

        let i6_res = rt.eval_sync(Script::new(
            "test_proxy.es",
            "let tc6 = new TestClass1(); let r6 = tc6.doIt2(); tc6 = null; r6;",
        ));
        assert!(i6_res.is_err());
        let e = i6_res.err().unwrap();
        let e_msg = e.get_message();
        assert_eq!(e_msg, "proxy_instance_method failed: aaargh");

        assert!(e.get_stack().contains("[doIt2]"));

        rt.gc_sync();

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

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