-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjsc-api.cpp
More file actions
2726 lines (2260 loc) · 87.4 KB
/
jsc-api.cpp
File metadata and controls
2726 lines (2260 loc) · 87.4 KB
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
#include "jsc-api.h"
#include <list>
#include <thread>
#include <cassert>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstring>
#include <functional>
#include <stdexcept>
#include <string>
#include <vector>
#include <locale>
#include <codecvt>
struct napi_callback_info__ {
napi_value newTarget;
napi_value thisArg;
napi_value* argv;
void* data;
uint16_t argc;
};
namespace {
class JSString {
public:
JSString(const JSString&) = delete;
JSString(JSString&& other) {
_string = other._string;
other._string = nullptr;
}
JSString(const char* string, size_t length = NAPI_AUTO_LENGTH)
: _string{CreateUTF8(string, length)} {
}
JSString(const JSChar* string, size_t length = NAPI_AUTO_LENGTH)
: _string{JSStringCreateWithCharacters(string, length == NAPI_AUTO_LENGTH ? std::char_traits<JSChar>::length(string) : length)} {
}
~JSString() {
if (_string != nullptr) {
JSStringRelease(_string);
}
}
static JSString Attach(JSStringRef string) {
return {string};
}
operator JSStringRef() const {
return _string;
}
size_t Length() const {
return JSStringGetLength(_string);
}
size_t LengthUTF8() const {
std::vector<char> buffer(JSStringGetMaximumUTF8CStringSize(_string));
return JSStringGetUTF8CString(_string, buffer.data(), buffer.size()) - 1;
}
size_t LengthLatin1() const {
// Latin1 has the same length as Unicode.
return JSStringGetLength(_string);
}
void CopyTo(JSChar* buf, size_t bufsize, size_t* result) const {
size_t length{JSStringGetLength(_string)};
const JSChar* chars{JSStringGetCharactersPtr(_string)};
size_t size{std::min(length, bufsize - 1)};
std::memcpy(buf, chars, size);
buf[size] = 0;
if (result != nullptr) {
*result = size;
}
}
void CopyToUTF8(char* buf, size_t bufsize, size_t* result) const {
size_t size{JSStringGetUTF8CString(_string, buf, bufsize)};
if (result != nullptr) {
// JSStringGetUTF8CString returns size with null terminator.
*result = size - 1;
}
}
void CopyToLatin1(char* buf, size_t bufsize, size_t* result) const {
size_t length{JSStringGetLength(_string)};
const JSChar* chars{JSStringGetCharactersPtr(_string)};
size_t size{std::min(length, bufsize - 1)};
for (int i = 0; i < size; ++i) {
const JSChar ch{chars[i]};
buf[i] = (ch < 256) ? ch : '?';
}
if (result != nullptr) {
*result = size;
}
}
private:
static JSStringRef CreateUTF8(const char* string, size_t length) {
if (length == NAPI_AUTO_LENGTH) {
return JSStringCreateWithUTF8CString(string);
}
std::u16string u16str{std::wstring_convert<
std::codecvt_utf8_utf16<char16_t>, char16_t>{}.from_bytes(string, string + length)};
return JSStringCreateWithCharacters(reinterpret_cast<JSChar*>(u16str.data()), u16str.size());
}
JSString(JSStringRef string)
: _string{string} {
}
JSStringRef _string;
};
inline JSValueRef ToJSValue(const napi_value value) {
return reinterpret_cast<JSValueRef>(value);
}
inline const JSValueRef* ToJSValues(const napi_value* values) {
return reinterpret_cast<const JSValueRef*>(values);
}
inline JSObjectRef ToJSObject(napi_env env, const napi_value value) {
assert(value == nullptr || JSValueIsObject(env->context, reinterpret_cast<JSValueRef>(value)));
return reinterpret_cast<JSObjectRef>(value);
}
inline JSString ToJSString(napi_env env, napi_value value, JSValueRef* exception) {
return JSString::Attach(JSValueToStringCopy(env->context, ToJSValue(value), exception));
}
inline napi_value ToNapi(const JSValueRef value) {
return reinterpret_cast<napi_value>(const_cast<OpaqueJSValue*>(value));
}
static inline napi_value* ToNapi(const JSValueRef* values) {
return reinterpret_cast<napi_value*>(const_cast<OpaqueJSValue**>(values));
}
napi_status napi_clear_last_error(napi_env env) {
env->last_error.error_code = napi_ok;
env->last_error.engine_error_code = 0;
env->last_error.engine_reserved = nullptr;
return napi_ok;
}
napi_status napi_set_last_error(napi_env env, napi_status error_code, uint32_t engine_error_code = 0, void* engine_reserved = nullptr) {
env->last_error.error_code = error_code;
env->last_error.engine_error_code = engine_error_code;
env->last_error.engine_reserved = engine_reserved;
return error_code;
}
napi_status napi_set_exception(napi_env env, JSValueRef exception) {
env->last_exception = exception;
return napi_set_last_error(env, napi_pending_exception);
}
napi_status napi_set_error_code(napi_env env,
napi_value error,
napi_value code,
const char* code_cstring) {
napi_value code_value{code};
if (code_value == nullptr) {
code_value = ToNapi(JSValueMakeString(env->context, JSString(code_cstring)));
} else {
RETURN_STATUS_IF_FALSE(env, JSValueIsString(env->context, ToJSValue(code_value)), napi_string_expected);
}
CHECK_NAPI(napi_set_named_property(env, error, "code", code_value));
return napi_ok;
}
enum class NativeType {
Constructor,
External,
Function,
Reference,
Wrapper,
};
class NativeInfo {
public:
NativeType Type() const {
return _type;
}
template<typename T>
static T* Get(JSObjectRef obj) {
return reinterpret_cast<T*>(JSObjectGetPrivate(obj));
}
template<typename T>
static T* FindInPrototypeChain(JSContextRef ctx, JSObjectRef obj) {
while (true) {
JSValueRef exception{};
JSObjectRef prototype = JSValueToObject(ctx, JSObjectGetPrototype(ctx, obj), &exception);
if (exception != nullptr) {
return nullptr;
}
NativeInfo* info = Get<NativeInfo>(prototype);
if (info != nullptr && info->Type() == T::StaticType) {
return reinterpret_cast<T*>(info);
}
obj = prototype;
}
}
template<typename T>
static T* GetNativeInfo(JSContextRef ctx, JSObjectRef obj, const char * propertyKey) {
JSValueRef exception {};
JSValueRef native_info = JSObjectGetProperty(ctx, obj, JSString(propertyKey), &exception);
NativeInfo* info = Get<NativeInfo>(JSValueToObject(ctx, native_info, &exception));
if (info != nullptr && info->Type() == T::StaticType) {
return reinterpret_cast<T*>(info);
}
return nullptr;
}
static void SetNativeInfoKey(JSContextRef ctx, JSObjectRef obj, JSClassRef classRef,JSValueRef propertyKey, void * data) {
JSObjectRef info{JSObjectMake(ctx, classRef, data)};
JSObjectSetPropertyForKey(ctx, obj, propertyKey, info, kJSPropertyAttributeDontEnum | kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete, nullptr);
}
static void SetNativeInfo(JSContextRef ctx, JSObjectRef obj, JSClassRef classRef, const char * propertyKey, void * data) {
JSObjectRef info{JSObjectMake(ctx, classRef, data)};
JSObjectSetProperty(ctx, obj, JSString(propertyKey), info, kJSPropertyAttributeDontEnum | kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete, nullptr);
}
protected:
NativeInfo(NativeType type)
: _type{type} {}
private:
NativeType _type;
};
class ConstructorInfo : public NativeInfo {
public:
static const NativeType StaticType = NativeType::Constructor;
static napi_status Create(napi_env env,
const char* utf8name,
size_t length,
napi_callback cb,
void* data,
napi_value* result) {
ConstructorInfo* info{new ConstructorInfo(env, utf8name, length, cb, data)};
if (info == nullptr) {
return napi_set_last_error(env, napi_generic_failure);
}
JSObjectRef constructor{JSObjectMakeConstructor(env->context, info->_class, CallAsConstructor)};
JSValueRef exception{};
if (length) {
napi_value name;
napi_create_string_utf8(env, utf8name, length, &name);
JSObjectSetProperty(env->context, constructor, JSString("name"), ToJSValue(name), kJSPropertyAttributeNone, &exception);
}
JSObjectRef prototype{(JSObjectRef) JSObjectGetProperty(env->context, constructor, JSString("prototype"), &exception)};
// JSObjectSetPrototype(env->context, prototype, JSObjectGetPrototype(env->context, constructor));
// JSObjectSetPrototype(env->context, constructor, prototype);
NativeInfo::SetNativeInfo(env->context, constructor, info->_class, "[[jsc_constructor_info]]", info);
JSObjectSetProperty(env->context, prototype, JSString("constructor"), constructor,
kJSPropertyAttributeNone, &exception);
CHECK_JSC(env, exception);
*result = ToNapi(constructor);
return napi_ok;
}
private:
ConstructorInfo(napi_env env, const char* name, size_t length, napi_callback cb, void* data)
: NativeInfo{NativeType::Constructor}
, _env{env}
, _name{name, (length == NAPI_AUTO_LENGTH ? std::strlen(name) : length)}
, _cb{cb}
, _data{data} {
JSClassDefinition classDefinition{kJSClassDefinitionEmpty};
classDefinition.className = _name.data();
classDefinition.finalize = Finalize;
_class = JSClassCreate(&classDefinition);
}
~ConstructorInfo() {
JSClassRelease(_class);
}
// JSObjectCallAsConstructorCallback
static JSObjectRef CallAsConstructor(JSContextRef ctx,
JSObjectRef constructor,
size_t argumentCount,
const JSValueRef arguments[],
JSValueRef* exception) {
// ConstructorInfo* info = NativeInfo::FindInPrototypeChain<ConstructorInfo>(ctx, constructor);
ConstructorInfo* info = NativeInfo::GetNativeInfo<ConstructorInfo>(ctx, constructor, "[[jsc_constructor_info]]");
// Make sure any errors encountered last time we were in N-API are gone.
napi_clear_last_error(info->_env);
JSObjectRef instance{JSObjectMake(ctx, info->_class, nullptr)};
// JSObjectSetPrototype(ctx, instance, JSObjectGetPrototype(ctx, constructor));
//
// JSObjectSetProperty(ctx, instance, JSString("prototype"), JSObjectGetProperty(ctx, constructor, JSString("prototype"), nullptr), kJSPropertyAttributeNone,
// nullptr);
napi_callback_info__ cbinfo{};
cbinfo.thisArg = ToNapi(instance);
cbinfo.newTarget = ToNapi(constructor);
cbinfo.argc = argumentCount;
cbinfo.argv = ToNapi(arguments);
cbinfo.data = info->_data;
napi_value result = info->_cb(info->_env, &cbinfo);
if (info->_env->last_exception != nullptr) {
*exception = info->_env->last_exception;
info->_env->last_exception = nullptr;
}
return ToJSObject(info->_env, result);
}
// JSObjectFinalizeCallback
static void Finalize(JSObjectRef object) {
ConstructorInfo* info = NativeInfo::Get<ConstructorInfo>(object);
if (!info) return;
assert(info->Type() == NativeType::Constructor);
delete info;
}
private:
napi_env _env;
std::string _name;
napi_callback _cb;
void* _data;
JSClassRef _class;
};
namespace xyz {
static std::once_flag functionInfoOnceFlag;
JSClassRef functionInfoClass {};
}
class FunctionInfo : public NativeInfo {
public:
static const NativeType StaticType = NativeType::Function;
static napi_status Create(napi_env env,
const char* utf8name,
size_t length,
napi_callback cb,
void* data,
napi_value* result) {
FunctionInfo* info{new FunctionInfo(env, cb, data)};
if (info == nullptr) {
return napi_set_last_error(env, napi_generic_failure);
}
JSObjectRef function = JSObjectMake(env->context, xyz::functionInfoClass, info);
*result = ToNapi(function);
return napi_ok;
}
private:
FunctionInfo(napi_env env, napi_callback cb, void* data)
: NativeInfo{NativeType::Function}
, _env{env}
, _cb{cb}
, _data{data} {
std::call_once(xyz::functionInfoOnceFlag, []() {
JSClassDefinition definition{kJSClassDefinitionEmpty};
definition.className = "NapiFunctionCallback";
definition.callAsFunction = FunctionInfo::CallAsFunction;
definition.attributes = kJSClassAttributeNoAutomaticPrototype;
definition.initialize = FunctionInfo::initialize;
definition.finalize = Finalize;
xyz::functionInfoClass = JSClassCreate(&definition);
});
}
~FunctionInfo() {}
static void initialize(JSContextRef ctx, JSObjectRef object) {
JSObjectRef global = JSContextGetGlobalObject(ctx);
JSValueRef value =
JSObjectGetProperty(ctx, global, JSString("Function"), nullptr);
JSObjectRef funcCtor = JSValueToObject(ctx, value, nullptr);
if (!funcCtor) {
// We can't do anything if Function is not an object
return;
}
JSValueRef funcProto = JSObjectGetPrototype(ctx, funcCtor);
JSObjectSetPrototype(ctx, object, funcProto);
}
// JSObjectCallAsFunctionCallback
static JSValueRef CallAsFunction(JSContextRef ctx,
JSObjectRef function,
JSObjectRef thisObject,
size_t argumentCount,
const JSValueRef arguments[],
JSValueRef* exception) {
// FunctionInfo* info = NativeInfo::Get<FunctionInfo>(function);
FunctionInfo* info = reinterpret_cast<FunctionInfo *>(JSObjectGetPrivate(function));
// Make sure any errors encountered last time we were in N-API are gone.
napi_clear_last_error(info->_env);
napi_callback_info__ cbinfo{};
cbinfo.thisArg = ToNapi(thisObject);
cbinfo.newTarget = nullptr;
cbinfo.argc = argumentCount;
cbinfo.argv = ToNapi(arguments);
cbinfo.data = info->_data;
napi_value result = info->_cb(info->_env, &cbinfo);
if (info->_env->last_exception != nullptr) {
*exception = info->_env->last_exception;
info->_env->last_exception = nullptr;
}
return ToJSValue(result);
}
// JSObjectFinalizeCallback
static void Finalize(JSObjectRef object) {
FunctionInfo* info = NativeInfo::Get<FunctionInfo>(object);
assert(info->Type() == NativeType::Function);
delete info;
}
napi_env _env;
napi_callback _cb;
void* _data;
};
template<typename T, NativeType TType>
class BaseInfoT : public NativeInfo {
public:
static const NativeType StaticType = TType;
~BaseInfoT() {
JSClassRelease(_class);
}
napi_env Env() const {
return _env;
}
void Data(void* value) {
_data = value;
}
void* Data() const {
return _data;
}
using FinalizerT = std::function<void(T*)>;
void AddFinalizer(FinalizerT finalizer) {
_finalizers.push_back(finalizer);
}
protected:
BaseInfoT(napi_env env, const char* className)
: NativeInfo{TType}
, _env{env} {
JSClassDefinition definition{kJSClassDefinitionEmpty};
definition.className = className;
definition.finalize = Finalize;
_class = JSClassCreate(&definition);
}
// JSObjectFinalizeCallback
static void Finalize(JSObjectRef object) {
T* info = Get<T>(object);
assert(info->Type() == TType);
for (const FinalizerT& finalizer : info->_finalizers) {
finalizer(info);
}
delete info;
}
napi_env _env;
void* _data{};
std::vector<FinalizerT> _finalizers{};
JSClassRef _class{};
};
class ExternalInfo: public BaseInfoT<ExternalInfo, NativeType::External> {
public:
static napi_status Create(napi_env env,
void* data,
napi_finalize finalize_cb,
void* finalize_hint,
napi_value* result) {
ExternalInfo* info = new ExternalInfo(env);
if (info == nullptr) {
return napi_set_last_error(env, napi_generic_failure);
}
info->Data(data);
if (finalize_cb != nullptr) {
info->AddFinalizer([finalize_cb, finalize_hint](ExternalInfo* info) {
finalize_cb(info->Env(), info->Data(), finalize_hint);
});
}
*result = ToNapi(JSObjectMake(env->context, info->_class, info));
return napi_ok;
}
private:
ExternalInfo(napi_env env)
: BaseInfoT{env, "Native (External)"} {
}
};
class ReferenceInfo : public BaseInfoT<ReferenceInfo, NativeType::Reference> {
public:
static napi_status Initialize(napi_env env, napi_value object, FinalizerT finalizer) {
napi_valuetype type;
napi_typeof(env, object, &type);
if (type == napi_object || type == napi_function) {
ReferenceInfo* info = new ReferenceInfo(env);
if (info == nullptr) {
return napi_set_last_error(env, napi_generic_failure);
}
// JSObjectRef ref{JSObjectMake(env->context, info->_class, info)};
// JSObjectSetPrototype(env->context, prototype, JSObjectGetPrototype(env->context, ToJSObject(env, object)));
// JSObjectSetPrototype(env->context, ToJSObject(env, object), prototype);
NativeInfo::SetNativeInfo(env->context, ToJSObject(env, object), info->_class, "[[jsc_reference_info]]", info);
info->AddFinalizer(finalizer);
}
return napi_ok;
}
private:
ReferenceInfo(napi_env env)
: BaseInfoT{env, "Native (Reference)"} {
}
};
class WrapperInfo : public BaseInfoT<WrapperInfo, NativeType::Wrapper> {
public:
static napi_status Wrap(napi_env env, napi_value object, WrapperInfo** result) {
WrapperInfo* info{};
napi_value propertyKey;
napi_create_string_utf8(env, "[[jsc_wrapper_info]]", NAPI_AUTO_LENGTH, &propertyKey);
bool hasOwnProperty;
napi_has_own_property(env, object, propertyKey, &hasOwnProperty);
if (hasOwnProperty) {
return napi_generic_failure;
// CHECK_NAPI(Unwrap(env, object, &info));
}
if (info == nullptr) {
info = new WrapperInfo(env);
if (info == nullptr) {
return napi_set_last_error(env, napi_generic_failure);
}
NativeInfo::SetNativeInfoKey(env->context, ToJSObject(env, object), info->_class, ToJSValue(propertyKey), info);
}
*result = info;
return napi_ok;
}
static napi_status Unwrap(napi_env env, napi_value object, WrapperInfo** result) {
*result = NativeInfo::GetNativeInfo<WrapperInfo>(env->context, ToJSObject(env, object), "[[jsc_wrapper_info]]");
return napi_ok;
}
private:
WrapperInfo(napi_env env)
: BaseInfoT{env, "Native (Wrapper)"} {
}
};
class ExternalArrayBufferInfo {
public:
static napi_status Create(napi_env env,
void* external_data,
size_t byte_length,
napi_finalize finalize_cb,
void* finalize_hint,
napi_value* result) {
ExternalArrayBufferInfo* info{new ExternalArrayBufferInfo(env, finalize_cb, finalize_hint)};
if (info == nullptr) {
return napi_set_last_error(env, napi_generic_failure);
}
JSValueRef exception{};
*result = ToNapi(JSObjectMakeArrayBufferWithBytesNoCopy(
env->context,
external_data,
byte_length,
BytesDeallocator,
info,
&exception));
CHECK_JSC(env, exception);
return napi_ok;
}
private:
ExternalArrayBufferInfo(napi_env env, napi_finalize finalize_cb, void* hint)
: _env{env}
, _cb{finalize_cb}
, _hint{hint} {
}
// JSTypedArrayBytesDeallocator
static void BytesDeallocator(void* bytes, void* deallocatorContext) {
ExternalArrayBufferInfo* info{reinterpret_cast<ExternalArrayBufferInfo*>(deallocatorContext)};
if (info->_cb != nullptr) {
info->_cb(info->_env, bytes, info->_hint);
}
delete info;
}
napi_env _env;
napi_finalize _cb;
void* _hint;
};
}
struct napi_ref__ {
napi_ref__(napi_value value, uint32_t count)
: _value{value}
, _count{count} {
}
napi_status init(napi_env env) {
// track the ref values to support weak refs
auto pair{env->active_ref_values.insert(_value)};
if (pair.second) {
CHECK_NAPI(ReferenceInfo::Initialize(env, _value, [value = _value](ReferenceInfo* info) {
info->Env()->active_ref_values.erase(value);
}));
}
if (_count != 0) {
protect(env);
}
return napi_ok;
}
void deinit(napi_env env) {
if (_count != 0) {
unprotect(env);
}
_value = nullptr;
_count = 0;
}
void ref(napi_env env) {
if (_count++ == 0) {
protect(env);
}
}
void unref(napi_env env) {
if (--_count == 0) {
unprotect(env);
}
}
uint32_t count() const {
return _count;
}
napi_value value(napi_env env) const {
if (env->active_ref_values.find(_value) == env->active_ref_values.end()) {
return nullptr;
}
return _value;
}
private:
void protect(napi_env env) {
_iter = env->strong_refs.insert(env->strong_refs.end(), this);
JSValueProtect(env->context, ToJSValue(_value));
}
void unprotect(napi_env env) {
env->strong_refs.erase(_iter);
JSValueUnprotect(env->context, ToJSValue(_value));
}
napi_value _value{};
uint32_t _count{};
std::list<napi_ref>::iterator _iter{};
};
void napi_env__::deinit_refs() {
while (!strong_refs.empty()) {
napi_ref ref{strong_refs.front()};
ref->deinit(this);
}
}
void napi_env__::init_symbol(JSValueRef &symbol, const char *description) {
symbol = JSValueMakeSymbol(context, JSString(description));
JSValueProtect(context, symbol);
}
void napi_env__::deinit_symbol(JSValueRef symbol) {
JSValueUnprotect(context, symbol);
}
// Warning: Keep in-sync with napi_status enum
static const char* error_messages[] = {
nullptr,
"Invalid argument",
"An object was expected",
"A string was expected",
"A string or symbol was expected",
"A function was expected",
"A number was expected",
"A boolean was expected",
"An array was expected",
"Unknown failure",
"An exception is pending",
"The async work item was cancelled",
"napi_escape_handle already called on scope",
"Invalid handle scope usage",
"Invalid callback scope usage",
"Thread-safe function queue is full",
"Thread-safe function handle is closing",
"A bigint was expected",
};
napi_status napi_get_last_error_info(napi_env env,
const napi_extended_error_info** result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
// you must update this assert to reference the last message
// in the napi_status enum each time a new error message is added.
// We don't have a napi_status_last as this would result in an ABI
// change each time a message was added.
static_assert(
std::size(error_messages) == napi_bigint_expected + 1,
"Count of error messages must match count of error values");
assert(env->last_error.error_code <= napi_callback_scope_mismatch);
// Wait until someone requests the last error information to fetch the error
// message string
env->last_error.error_message =
error_messages[env->last_error.error_code];
*result = &env->last_error;
return napi_ok;
}
napi_status napi_create_function(napi_env env,
const char* utf8name,
size_t length,
napi_callback cb,
void* callback_data,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
CHECK_NAPI(FunctionInfo::Create(env, utf8name, length, cb, callback_data, result));
return napi_ok;
}
napi_status napi_define_class(napi_env env,
const char* utf8name,
size_t length,
napi_callback cb,
void* data,
size_t property_count,
const napi_property_descriptor* properties,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
napi_value constructor{};
CHECK_NAPI(ConstructorInfo::Create(env, utf8name, length, cb, data, &constructor));
int instancePropertyCount{0};
int staticPropertyCount{0};
for (size_t i = 0; i < property_count; i++) {
if ((properties[i].attributes & napi_static) != 0) {
staticPropertyCount++;
} else {
instancePropertyCount++;
}
}
std::vector<napi_property_descriptor> staticDescriptors{};
std::vector<napi_property_descriptor> instanceDescriptors{};
staticDescriptors.reserve(staticPropertyCount);
instanceDescriptors.reserve(instancePropertyCount);
for (size_t i = 0; i < property_count; i++) {
if ((properties[i].attributes & napi_static) != 0) {
staticDescriptors.push_back(properties[i]);
} else {
instanceDescriptors.push_back(properties[i]);
}
}
if (staticPropertyCount > 0) {
CHECK_NAPI(napi_define_properties(env,
constructor,
staticDescriptors.size(),
staticDescriptors.data()));
}
if (instancePropertyCount > 0) {
napi_value prototype{};
CHECK_NAPI(napi_get_named_property(env, constructor, "prototype", &prototype));
// CHECK_NAPI(napi_get_prototype(env, constructor, &prototype));
CHECK_NAPI(napi_define_properties(env,
prototype,
instanceDescriptors.size(),
instanceDescriptors.data()));
}
*result = constructor;
return napi_ok;
}
napi_status napi_get_property_names(napi_env env,
napi_value object,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
napi_value global{}, object_ctor{}, function{};
CHECK_NAPI(napi_get_global(env, &global));
CHECK_NAPI(napi_get_named_property(env, global, "Object", &object_ctor));
CHECK_NAPI(napi_get_named_property(env, object_ctor, "getOwnPropertyNames", &function));
CHECK_NAPI(napi_call_function(env, object_ctor, function, 0, nullptr, result));
return napi_ok;
}
napi_status napi_set_property(napi_env env,
napi_value object,
napi_value key,
napi_value value) {
CHECK_ENV(env);
CHECK_ARG(env, key);
CHECK_ARG(env, value);
JSValueRef exception{};
JSString key_str{ToJSString(env, key, &exception)};
CHECK_JSC(env, exception);
JSObjectSetProperty(
env->context,
ToJSObject(env, object),
key_str,
ToJSValue(value),
kJSPropertyAttributeNone,
&exception);
CHECK_JSC(env, exception);
return napi_ok;
}
napi_status napi_has_property(napi_env env,
napi_value object,
napi_value key,
bool* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
CHECK_ARG(env, key);
JSValueRef exception{};
JSString key_str{ToJSString(env, key, &exception)};
CHECK_JSC(env, exception);
*result = JSObjectHasProperty(
env->context,
ToJSObject(env, object),
key_str);
return napi_ok;
}
napi_status napi_get_property(napi_env env,
napi_value object,
napi_value key,
napi_value* result) {
CHECK_ENV(env);
CHECK_ARG(env, key);
CHECK_ARG(env, result);
JSValueRef exception{};
JSString key_str{ToJSString(env, key, &exception)};
CHECK_JSC(env, exception);
*result = ToNapi(JSObjectGetProperty(
env->context,
ToJSObject(env, object),
key_str,
&exception));
CHECK_JSC(env, exception);
return napi_ok;
}
napi_status napi_delete_property(napi_env env,
napi_value object,
napi_value key,
bool* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
JSValueRef exception{};
JSString key_str{ToJSString(env, key, &exception)};
CHECK_JSC(env, exception);
*result = JSObjectDeleteProperty(
env->context,
ToJSObject(env, object),
key_str,
&exception);
CHECK_JSC(env, exception);
return napi_ok;
}
NAPI_EXTERN napi_status napi_has_own_property(napi_env env,
napi_value object,
napi_value key,
bool* result) {
CHECK_ENV(env);
CHECK_ARG(env, result);
napi_value global{}, object_ctor{}, function{}, value{};
CHECK_NAPI(napi_get_global(env, &global));
CHECK_NAPI(napi_get_named_property(env, global, "Object", &object_ctor));
CHECK_NAPI(napi_get_named_property(env, object_ctor, "hasOwnProperty", &function));
CHECK_NAPI(napi_call_function(env, object_ctor, function, 0, nullptr, &value));
*result = JSValueToBoolean(env->context, ToJSValue(value));
return napi_ok;
}
napi_status napi_set_named_property(napi_env env,
napi_value object,
const char* utf8name,
napi_value value) {
CHECK_ENV(env);
CHECK_ARG(env, value);
JSValueRef exception{};
JSObjectSetProperty(
env->context,
ToJSObject(env, object),
JSString(utf8name),
ToJSValue(value),
kJSPropertyAttributeNone,
&exception);
CHECK_JSC(env, exception);
return napi_ok;
}
napi_status napi_has_named_property(napi_env env,
napi_value object,
const char* utf8name,