-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathNodeApiJsiRuntime.cpp
2002 lines (1584 loc) · 72.1 KB
/
NodeApiJsiRuntime.cpp
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#define NAPI_EXPERIMENTAL
#include "NodeApiJsiRuntime.h"
// Standard Library
#include <string_view>
#include <unordered_set>
#pragma region Macros
// We use macros to report errors.
// Macros provide more flexibility to show assert and provide failure context.
// Check condition and crash process if it fails.
#define CHECK_ELSE_CRASH(condition, message) \
do { \
if (!(condition)) { \
assert(false && "Failed: " #condition && (message)); \
*((int *)0) = 1; \
} \
} while (false)
// Check condition and throw native exception if it fails.
#define CHECK_ELSE_THROW(condition, message) \
do { \
if (!(condition)) { \
ThrowNativeException(message); \
} \
} while (false)
// Check NAPI result and and throw JS exception if it is not napi_ok.
#define CHECK_NAPI(expression) \
do { \
napi_status temp_error_code_ = (expression); \
if (temp_error_code_ != napi_status::napi_ok) { \
ThrowJsException(temp_error_code_); \
} \
} while (false)
// Check NAPI result and and crash if it is not napi_ok.
#define CHECK_NAPI_ELSE_CRASH(expression) \
do { \
napi_status temp_error_code_ = (expression); \
if (temp_error_code_ != napi_status::napi_ok) { \
CHECK_ELSE_CRASH(false, "Failed: " #expression); \
} \
} while (false)
#pragma endregion Macros
#pragma region Declarations
#ifdef __cpp_lib_span
#include <span>
#endif // __cpp_lib_span
namespace Microsoft::JSI {
namespace {
#ifdef __cpp_lib_span
using std::span;
#else
/**
* @brief A span of values that can be used to pass arguments to a function.
*
* This should be replaced with std::span once C++ 2020 is supported.
*/
template <typename T>
struct span {
constexpr span(std::initializer_list<T> il) noexcept : m_data{const_cast<T *>(il.begin())}, m_size{il.size()} {}
constexpr span(T *data, size_t size) noexcept : m_data{data}, m_size{size} {}
[[nodiscard]] constexpr T *data() const noexcept {
return m_data;
}
[[nodiscard]] constexpr size_t size() const noexcept {
return m_size;
}
[[nodiscard]] constexpr T *begin() const noexcept {
return m_data;
}
[[nodiscard]] constexpr T *end() const noexcept {
return *(m_data + m_size);
}
const T &operator[](size_t index) const noexcept {
return *(m_data + index);
}
private:
T *m_data;
size_t m_size;
};
#endif // __cpp_lib_span
// Implementation of N-API JSI Runtime
struct NapiJsiRuntime : facebook::jsi::Runtime {
NapiJsiRuntime(napi_env env) noexcept;
#pragma region facebook::jsi::Runtime
facebook::jsi::Value evaluateJavaScript(
const std::shared_ptr<const facebook::jsi::Buffer> &buffer,
const std::string &sourceURL) override;
std::shared_ptr<const facebook::jsi::PreparedJavaScript> prepareJavaScript(
const std::shared_ptr<const facebook::jsi::Buffer> &buffer,
std::string sourceURL) override;
facebook::jsi::Value evaluatePreparedJavaScript(
const std::shared_ptr<const facebook::jsi::PreparedJavaScript> &js) override;
bool drainMicrotasks(int maxMicrotasksHint = -1) override;
facebook::jsi::Object global() override;
std::string description() override;
bool isInspectable() override;
// We use the default instrumentation() implementation that returns an
// Instrumentation instance which returns no metrics.
protected:
PointerValue *cloneSymbol(const PointerValue *pointerValue) override;
PointerValue *cloneString(const PointerValue *pointerValue) override;
PointerValue *cloneObject(const PointerValue *pointerValue) override;
PointerValue *clonePropNameID(const PointerValue *pointerValue) override;
facebook::jsi::PropNameID createPropNameIDFromAscii(const char *str, size_t length) override;
facebook::jsi::PropNameID createPropNameIDFromUtf8(const uint8_t *utf8, size_t length) override;
facebook::jsi::PropNameID createPropNameIDFromString(const facebook::jsi::String &str) override;
facebook::jsi::PropNameID createPropNameIDFromSymbol(const facebook::jsi::Symbol &sym);
std::string utf8(const facebook::jsi::PropNameID &id) override;
bool compare(const facebook::jsi::PropNameID &lhs, const facebook::jsi::PropNameID &rhs) override;
std::string symbolToString(const facebook::jsi::Symbol &s) override;
facebook::jsi::String createStringFromAscii(const char *str, size_t length) override;
facebook::jsi::String createStringFromUtf8(const uint8_t *utf8, size_t length) override;
std::string utf8(const facebook::jsi::String &str) override;
facebook::jsi::Object createObject() override;
facebook::jsi::Object createObject(std::shared_ptr<facebook::jsi::HostObject> ho) override;
std::shared_ptr<facebook::jsi::HostObject> getHostObject(const facebook::jsi::Object &) override;
facebook::jsi::HostFunctionType &getHostFunction(const facebook::jsi::Function &) override;
facebook::jsi::Value getProperty(const facebook::jsi::Object &obj, const facebook::jsi::PropNameID &name) override;
facebook::jsi::Value getProperty(const facebook::jsi::Object &obj, const facebook::jsi::String &name) override;
bool hasProperty(const facebook::jsi::Object &obj, const facebook::jsi::PropNameID &name) override;
bool hasProperty(const facebook::jsi::Object &obj, const facebook::jsi::String &name) override;
void setPropertyValue(
facebook::jsi::Object &obj,
const facebook::jsi::PropNameID &name,
const facebook::jsi::Value &value) override;
void setPropertyValue(
facebook::jsi::Object &obj,
const facebook::jsi::String &name,
const facebook::jsi::Value &value) override;
bool isArray(const facebook::jsi::Object &obj) const override;
bool isArrayBuffer(const facebook::jsi::Object &obj) const override;
bool isFunction(const facebook::jsi::Object &obj) const override;
bool isHostObject(const facebook::jsi::Object &obj) const override;
bool isHostFunction(const facebook::jsi::Function &func) const override;
// Returns the names of all enumerable properties of an object.
// This corresponds to the properties iterated through by the JavaScript for..in loop.
facebook::jsi::Array getPropertyNames(const facebook::jsi::Object &obj) override;
facebook::jsi::WeakObject createWeakObject(const facebook::jsi::Object &obj) override;
facebook::jsi::Value lockWeakObject(facebook::jsi::WeakObject &weakObj) override;
facebook::jsi::Array createArray(size_t length) override;
size_t size(const facebook::jsi::Array &arr) override;
size_t size(const facebook::jsi::ArrayBuffer &arrBuf) override;
// The lifetime of the buffer returned is the same as the lifetime of the ArrayBuffer.
// The returned buffer pointer does not count as a reference to ArrayBuffer for the purpose of garbage collection.
uint8_t *data(const facebook::jsi::ArrayBuffer &arrBuff) override;
facebook::jsi::Value getValueAtIndex(const facebook::jsi::Array &arr, size_t index) override;
void setValueAtIndexImpl(facebook::jsi::Array &arr, size_t index, const facebook::jsi::Value &value) override;
facebook::jsi::Function createFunctionFromHostFunction(
const facebook::jsi::PropNameID &name,
unsigned int paramCount,
facebook::jsi::HostFunctionType type) override;
facebook::jsi::Value call(
const facebook::jsi::Function &func,
const facebook::jsi::Value &jsThis,
const facebook::jsi::Value *args,
size_t count) override;
facebook::jsi::Value
callAsConstructor(const facebook::jsi::Function &func, const facebook::jsi::Value *args, size_t count) override;
// Corresponds to napi_open_handle_scope and napi_close_handle_scope.
ScopeState *pushScope() override;
void popScope(ScopeState *) override;
bool strictEquals(const facebook::jsi::Symbol &a, const facebook::jsi::Symbol &b) const override;
bool strictEquals(const facebook::jsi::String &a, const facebook::jsi::String &b) const override;
bool strictEquals(const facebook::jsi::Object &a, const facebook::jsi::Object &b) const override;
bool instanceOf(const facebook::jsi::Object &obj, const facebook::jsi::Function &func) override;
#pragma endregion facebook::jsi::facebook::jsi::Runtime
private:
// Smart pointer to napi_env
struct EnvHolder {
EnvHolder(napi_env env) noexcept;
~EnvHolder() noexcept;
EnvHolder(const EnvHolder &) = delete;
EnvHolder &operator=(const EnvHolder &) = delete;
operator napi_env() const noexcept;
private:
napi_env m_env{};
};
// RAII struct to open and close the environment scope.
struct EnvScope {
EnvScope(napi_env env) noexcept;
~EnvScope() noexcept;
private:
napi_env m_env{};
napi_ext_env_scope m_envScope{};
};
// Sets the variable in the constructor and then restores its value in the destructor.
template <typename T>
struct AutoRestore {
AutoRestore(T *var, T value);
~AutoRestore();
private:
T *m_var;
T m_value;
};
// NapiRefHolder is a smart pointer to napi_ext_ref.
struct NapiRefHolder {
NapiRefHolder(std::nullptr_t = nullptr) noexcept {}
explicit NapiRefHolder(NapiJsiRuntime *runtime, napi_ext_ref ref) noexcept;
explicit NapiRefHolder(NapiJsiRuntime *runtime, napi_value value);
// The class is movable.
NapiRefHolder(NapiRefHolder &&other) noexcept;
NapiRefHolder &operator=(NapiRefHolder &&other) noexcept;
// The class is not copyable.
NapiRefHolder &operator=(NapiRefHolder const &other) = delete;
NapiRefHolder(NapiRefHolder const &other) = delete;
~NapiRefHolder() noexcept;
[[nodiscard]] napi_ext_ref CloneRef() const noexcept;
operator napi_value() const;
explicit operator bool() const noexcept;
private:
NapiJsiRuntime *m_runtime{};
napi_ext_ref m_ref{};
};
// NapiPointerValueView is the base class for NapiPointerValue.
// It holds either napi_value or napi_ext_ref. It does nothing in its invalidate() method.
// It is used directly by the JsiValueView, JsiValueViewArgs, and PropNameIDView classes
// to keep temporary PointerValues on the call stack and avoid extra memory allocations.
// In these cases, it is assumed that it holds a napi_value instead of napi_ext_ref.
struct NapiPointerValueView : PointerValue {
NapiPointerValueView(const NapiJsiRuntime *runtime, void *valueOrRef) noexcept;
void invalidate() noexcept override;
NapiPointerValueView(const NapiPointerValueView &) = delete;
NapiPointerValueView &operator=(const NapiPointerValueView &) = delete;
virtual napi_value GetValue() const;
virtual napi_ext_ref GetRef() const;
const NapiJsiRuntime *GetRuntime() const noexcept;
private:
const NapiJsiRuntime *m_runtime;
void *m_valueOrRef; // napi_value or napi_ext_ref
};
// NapiPointerValue is used by facebook::jsi::Pointer class and must only be used for this purpose.
// Every instance of NapiPointerValue should be allocated on the heap and be used as an argument
// to the constructor of facebook::jsi::Pointer or one of its derived classes.
// facebook::jsi::Pointer makes sure that the invalidate() method, which frees the heap-allocated NapiPointerValue,
// is called upon destruction.
// Since the the constructor of facebook::jsi::Pointer is protected, we usually have to invoke it through
// facebook::jsi::Runtime::make. The code should look something like:
//
// make<Pointer>(new NapiPointerValue(...));
//
// or you can use the helper function MakePointer().
struct NapiPointerValue final : NapiPointerValueView {
NapiPointerValue(const NapiJsiRuntime *runtime, napi_ext_ref ref);
NapiPointerValue(const NapiJsiRuntime *runtime, napi_value value);
void invalidate() noexcept override;
napi_value GetValue() const override;
napi_ext_ref GetRef() const override;
private:
// ~NapiPointerValue() must only be invoked by invalidate(). Hence, we make it private.
~NapiPointerValue() noexcept override;
};
// SmallBuffer keeps InplaceSize elements in place in the class, and uses heap memory for more elements.
template <typename T, size_t InplaceSize>
struct SmallBuffer {
SmallBuffer(size_t size) noexcept;
T *Data() noexcept;
size_t Size() const noexcept;
private:
size_t m_size{};
std::array<T, InplaceSize> m_stackData{};
std::unique_ptr<T[]> m_heapData{};
};
// The number of arguments that we keep on stack. We use heap if we have more arguments.
constexpr static size_t MaxStackArgCount = 8;
// NapiValueArgs helps optimize passing arguments to NAPI functions.
// If number of arguments is below or equal to MaxStackArgCount, they are kept on the call stack,
// otherwise arguments are allocated on the heap.
struct NapiValueArgs {
NapiValueArgs(NapiJsiRuntime &runtime, span<const facebook::jsi::Value> args);
operator span<napi_value>();
private:
SmallBuffer<napi_value, MaxStackArgCount> m_args;
};
// Helps to use the stack storage for a temporary conversion from napi_value to facebook::jsi::Value.
// It also helps to avoid a conversion to a relatively expensive napi_ext_ref.
struct JsiValueView {
JsiValueView(NapiJsiRuntime *runtime, napi_value jsValue);
operator const facebook::jsi::Value &() const noexcept;
using StoreType = std::aligned_storage_t<sizeof(NapiPointerValueView)>;
static facebook::jsi::Value InitValue(NapiJsiRuntime *runtime, napi_value jsValue, StoreType *store);
private:
StoreType m_pointerStore{};
facebook::jsi::Value m_value{};
};
// Helps to use stack storage for passing arguments that must be temporarily converted
// from napi_value to facebook::jsi::value.
// It helps to avoid conversion to a relatively expensive napi_ext_ref.
struct JsiValueViewArgs {
JsiValueViewArgs(NapiJsiRuntime *runtime, span<napi_value> args) noexcept;
const facebook::jsi::Value *Data() noexcept;
size_t Size() const noexcept;
private:
SmallBuffer<JsiValueView::StoreType, MaxStackArgCount> m_pointerStore{0};
SmallBuffer<facebook::jsi::Value, MaxStackArgCount> m_args{0};
};
// Helps to use stack storage for a temporary conversion from napi_value to facebook::jsi::PropNameID.
// It helps to avoid conversions to a relatively expensive napi_ext_ref.
struct PropNameIDView {
PropNameIDView(NapiJsiRuntime *runtime, napi_value propertyId) noexcept;
operator const facebook::jsi::PropNameID &() const noexcept;
using StoreType = std::aligned_storage_t<sizeof(NapiPointerValueView)>;
private:
StoreType m_pointerStore{};
facebook::jsi::PropNameID const m_propertyId;
};
// Wraps up the facebook::jsi::HostFunctionType along with the NapiJsiRuntime.
struct HostFunctionWrapper {
HostFunctionWrapper(facebook::jsi::HostFunctionType &&hostFunction, NapiJsiRuntime &runtime);
// Does not suppor copying.
HostFunctionWrapper(const HostFunctionWrapper &) = delete;
HostFunctionWrapper &operator=(const HostFunctionWrapper &) = delete;
facebook::jsi::HostFunctionType &GetHostFunction() noexcept;
NapiJsiRuntime &GetRuntime() noexcept;
private:
facebook::jsi::HostFunctionType m_hostFunction;
NapiJsiRuntime &m_runtime;
};
// Packs the source buffer and the byte code together.
struct NapiPreparedJavaScript final : facebook::jsi::PreparedJavaScript {
NapiPreparedJavaScript(
std::unique_ptr<const facebook::jsi::Buffer> serializedBuffer,
const std::shared_ptr<const facebook::jsi::Buffer> &sourceBuffer,
std::string sourceUrl);
const facebook::jsi::Buffer &SerializedBuffer() const;
const facebook::jsi::Buffer &SourceBuffer() const;
const std::string &SourceUrl() const;
private:
std::unique_ptr<const facebook::jsi::Buffer> m_serializedBuffer;
std::shared_ptr<const facebook::jsi::Buffer> m_sourceBuffer;
std::string m_sourceUrl;
};
// Implements facebook::jsi::Buffer using std::vector<uint8_t>.
struct VectorBuffer final : facebook::jsi::Buffer {
VectorBuffer(std::vector<uint8_t> data);
uint8_t const *data() const override;
size_t size() const override;
private:
std::vector<uint8_t> m_data;
};
private: // Error-handling utility methods
[[noreturn]] void ThrowJsException(napi_status errorCode) const;
[[noreturn]] void ThrowNativeException(char const *errorMessage) const;
void RewriteErrorMessage(napi_value jsError) const;
template <typename TLambda>
auto RunInMethodContext(char const *methodName, TLambda lambda);
template <typename TLambda>
napi_value HandleCallbackExceptions(TLambda lambda) const noexcept;
bool SetException(napi_value error) const noexcept;
bool SetException(std::string_view message) const noexcept;
private: // Shared NAPI call helpers
napi_value RunScript(napi_value script, const char *sourceUrl);
std::vector<uint8_t> SerializeScript(napi_value script, const char *sourceUrl);
napi_value RunSerializedScript(span<const uint8_t> serialized, napi_value source, const char *sourceUrl);
napi_ext_ref CreateReference(napi_value value) const;
void ReleaseReference(napi_ext_ref ref) const;
napi_value GetReferenceValue(napi_ext_ref ref) const;
napi_valuetype TypeOf(napi_value value) const;
bool StrictEquals(napi_value left, napi_value right) const;
napi_value GetUndefined() const;
napi_value GetNull() const;
napi_value GetGlobal() const;
napi_value GetBoolean(bool value) const;
bool GetValueBool(napi_value value) const;
napi_value CreateInt32(int32_t value) const;
napi_value CreateDouble(double value) const;
double GetValueDouble(napi_value value) const;
napi_value CreateStringLatin1(std::string_view value) const;
napi_value CreateStringUtf8(std::string_view value) const;
napi_value CreateStringUtf8(const uint8_t *data, size_t length) const;
std::string StringToStdString(napi_value stringValue) const;
napi_ext_ref GetPropertyIdFromName(std::string_view value) const;
napi_ext_ref GetPropertyIdFromName(const uint8_t *data, size_t length) const;
napi_ext_ref GetPropertyIdFromName(napi_value str) const;
std::string PropertyIdToStdString(napi_value propertyId);
napi_value CreateSymbol(std::string_view symbolDescription) const;
std::string SymbolToStdString(napi_value symbolValue);
napi_value CallFunction(napi_value thisArg, napi_value function, span<napi_value> args = {}) const;
napi_value ConstructObject(napi_value constructor, span<napi_value> args = {}) const;
bool InstanceOf(napi_value object, napi_value constructor) const;
napi_value CreateObject() const;
bool HasProperty(napi_value object, napi_value propertyId) const;
napi_value GetProperty(napi_value object, napi_value propertyId) const;
void SetProperty(napi_value object, napi_value propertyId, napi_value value) const;
void SetProperty(napi_value object, napi_value propertyId, napi_value value, napi_property_attributes attrs) const;
napi_value CreateArray(size_t length) const;
void SetElement(napi_value array, uint32_t index, napi_value value) const;
static napi_value JsiHostFunctionCallback(napi_env env, napi_callback_info info) noexcept;
napi_value CreateExternalFunction(napi_value name, int32_t paramCount, napi_callback callback, void *callbackData);
napi_value CreateExternalObject(void *data, napi_finalize finalizeCallback) const;
template <typename T>
napi_value CreateExternalObject(std::unique_ptr<T> &&data) const;
void *GetExternalData(napi_value object) const;
const std::shared_ptr<facebook::jsi::HostObject> &GetJsiHostObject(napi_value obj);
napi_value GetHostObjectProxyHandler();
template <napi_value (NapiJsiRuntime::*trapMethod)(span<napi_value>), size_t argCount>
void SetProxyTrap(napi_value handler, napi_value propertyName);
napi_value HostObjectGetTrap(span<napi_value> args);
napi_value HostObjectSetTrap(span<napi_value> args);
napi_value HostObjectOwnKeysTrap(span<napi_value> args);
napi_value HostObjectGetOwnPropertyDescriptorTrap(span<napi_value> args);
private: // Miscellaneous utility methods
span<const uint8_t> ToSpan(const facebook::jsi::Buffer &buffer);
facebook::jsi::Value ToJsiValue(napi_value value) const;
napi_value GetNapiValue(const facebook::jsi::Value &value) const;
static NapiPointerValue *CloneNapiPointerValue(const PointerValue *pointerValue);
static napi_value GetNapiValue(const facebook::jsi::Pointer &p);
static napi_ext_ref GetNapiRef(const facebook::jsi::Pointer &p);
template <typename T, typename TValue, std::enable_if_t<std::is_base_of_v<facebook::jsi::Pointer, T>, int> = 0>
T MakePointer(TValue value) const;
private: // Fields
EnvHolder m_env;
// Property ID cache to improve execution speed.
struct PropertyId {
NapiRefHolder Error;
NapiRefHolder Object;
NapiRefHolder Proxy;
NapiRefHolder Symbol;
NapiRefHolder byteLength;
NapiRefHolder configurable;
NapiRefHolder enumerable;
NapiRefHolder get;
NapiRefHolder getOwnPropertyDescriptor;
NapiRefHolder hostFunctionSymbol;
NapiRefHolder hostObjectSymbol;
NapiRefHolder length;
NapiRefHolder message;
NapiRefHolder ownKeys;
NapiRefHolder propertyIsEnumerable;
NapiRefHolder prototype;
NapiRefHolder set;
NapiRefHolder toString;
NapiRefHolder value;
NapiRefHolder writable;
} m_propertyId;
// Cache of commonly used values.
struct CachedValue final {
NapiRefHolder Error;
NapiRefHolder Global;
NapiRefHolder False;
NapiRefHolder HostObjectProxyHandler;
NapiRefHolder Null;
NapiRefHolder ProxyConstructor;
NapiRefHolder SymbolToString;
NapiRefHolder True;
NapiRefHolder Undefined;
} m_value;
bool m_pendingJSError{false};
};
} // namespace
} // namespace Microsoft::JSI
#pragma endregion Declarations
using namespace facebook::jsi;
using namespace std::string_view_literals;
using std::shared_ptr;
using std::string;
using std::string_view;
using std::unique_ptr;
using std::vector;
namespace Microsoft::JSI {
namespace {
constexpr char s_description[] = "NapiJsiRuntime";
constexpr char s_refHolderError[] = "Error";
constexpr char s_refHolderObject[] = "Object";
constexpr char s_refHolderProxy[] = "Proxy";
constexpr char s_refHolderSymbol[] = "Symbol";
constexpr char s_refHolderByteLength[] = "byteLength";
constexpr char s_refHolderConfigurable[] = "configurable";
constexpr char s_refHolderEnumerable[] = "enumerable";
constexpr char s_refHolderGet[] = "get";
constexpr char s_refHolderGetOwnPropertyDescriptor[] = "getOwnPropertyDescriptor";
constexpr char s_refHolderHostFunctionSymbol[] = "hostFunctionSymbol";
constexpr char s_refHolderHostObjectSymbol[] = "hostObjectSymbol";
constexpr char s_refHolderLength[] = "length";
constexpr char s_refHolderMessage[] = "message";
constexpr char s_refHolderOwnKeys[] = "ownKeys";
constexpr char s_refHolderPropertyIsEnumerable[] = "propertyIsEnumerable";
constexpr char s_refHolderPrototype[] = "prototype";
constexpr char s_refHolderSet[] = "set";
constexpr char s_refHolderToString[] = "toString";
constexpr char s_refHolderValue[] = "value";
constexpr char s_refHolderWritable[] = "writable";
#pragma region NapiJsiRuntime
NapiJsiRuntime::NapiJsiRuntime(napi_env env) noexcept : m_env{env} {
EnvScope scope{m_env};
m_propertyId.Error = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderError)};
m_propertyId.Object = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderObject)};
m_propertyId.Proxy = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderProxy)};
m_propertyId.Symbol = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderSymbol)};
m_propertyId.byteLength = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderByteLength)};
m_propertyId.configurable = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderConfigurable)};
m_propertyId.enumerable = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderEnumerable)};
m_propertyId.get = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderGet)};
m_propertyId.getOwnPropertyDescriptor =
NapiRefHolder{this, GetPropertyIdFromName(s_refHolderGetOwnPropertyDescriptor)};
m_propertyId.hostFunctionSymbol = NapiRefHolder{this, CreateSymbol(s_refHolderHostFunctionSymbol)};
m_propertyId.hostObjectSymbol = NapiRefHolder{this, CreateSymbol(s_refHolderHostObjectSymbol)};
m_propertyId.length = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderLength)};
m_propertyId.message = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderMessage)};
m_propertyId.ownKeys = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderOwnKeys)};
m_propertyId.propertyIsEnumerable = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderPropertyIsEnumerable)};
m_propertyId.prototype = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderPrototype)};
m_propertyId.set = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderSet)};
m_propertyId.toString = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderToString)};
m_propertyId.value = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderValue)};
m_propertyId.writable = NapiRefHolder{this, GetPropertyIdFromName(s_refHolderWritable)};
m_value.Undefined = NapiRefHolder{this, GetUndefined()};
m_value.Null = NapiRefHolder{this, GetNull()};
m_value.True = NapiRefHolder{this, GetBoolean(true)};
m_value.False = NapiRefHolder{this, GetBoolean(false)};
m_value.Global = NapiRefHolder{this, GetGlobal()};
m_value.Error = NapiRefHolder{this, GetProperty(m_value.Global, m_propertyId.Error)};
}
Value NapiJsiRuntime::evaluateJavaScript(const shared_ptr<const Buffer> &buffer, const string &sourceUrl) {
EnvScope envScope{m_env};
napi_value script = CreateStringUtf8(buffer->data(), buffer->size());
napi_value result = RunScript(script, sourceUrl.c_str());
return ToJsiValue(result);
}
shared_ptr<const PreparedJavaScript> NapiJsiRuntime::prepareJavaScript(
const shared_ptr<const Buffer> &sourceBuffer,
string sourceUrl) {
EnvScope scope{m_env};
napi_value source = CreateStringUtf8(sourceBuffer->data(), sourceBuffer->size());
vector<uint8_t> serialized = SerializeScript(source, sourceUrl.c_str());
unique_ptr<const Buffer> serializedBuffer{new VectorBuffer{std::move(serialized)}};
return std::make_shared<NapiPreparedJavaScript>(std::move(serializedBuffer), sourceBuffer, std::move(sourceUrl));
}
Value NapiJsiRuntime::evaluatePreparedJavaScript(const shared_ptr<const PreparedJavaScript> &preparedJs) {
EnvScope scope{m_env};
auto preparedScript = static_cast<const NapiPreparedJavaScript *>(preparedJs.get());
napi_value source = CreateStringUtf8(preparedScript->SourceBuffer().data(), preparedScript->SourceBuffer().size());
napi_value result =
RunSerializedScript(ToSpan(preparedScript->SerializedBuffer()), source, preparedScript->SourceUrl().c_str());
return ToJsiValue(result);
}
bool NapiJsiRuntime::drainMicrotasks(int /*maxMicrotasksHint*/) {
return true;
}
Object NapiJsiRuntime::global() {
EnvScope scope{m_env};
return MakePointer<Object>(m_value.Global.CloneRef());
}
string NapiJsiRuntime::description() {
return s_description;
}
bool NapiJsiRuntime::isInspectable() {
return false;
}
Runtime::PointerValue *NapiJsiRuntime::cloneSymbol(const Runtime::PointerValue *pointerValue) {
EnvScope scope{m_env};
return CloneNapiPointerValue(pointerValue);
}
Runtime::PointerValue *NapiJsiRuntime::cloneString(const Runtime::PointerValue *pointerValue) {
EnvScope scope{m_env};
return CloneNapiPointerValue(pointerValue);
}
Runtime::PointerValue *NapiJsiRuntime::cloneObject(const Runtime::PointerValue *pointerValue) {
EnvScope scope{m_env};
return CloneNapiPointerValue(pointerValue);
}
Runtime::PointerValue *NapiJsiRuntime::clonePropNameID(const Runtime::PointerValue *pointerValue) {
EnvScope scope{m_env};
return CloneNapiPointerValue(pointerValue);
}
PropNameID NapiJsiRuntime::createPropNameIDFromAscii(const char *str, size_t length) {
EnvScope scope{m_env};
napi_value napiStr = CreateStringLatin1({str, length});
napi_ext_ref uniqueStr = GetPropertyIdFromName(napiStr);
return MakePointer<PropNameID>(uniqueStr);
}
PropNameID NapiJsiRuntime::createPropNameIDFromUtf8(const uint8_t *utf8, size_t length) {
EnvScope scope{m_env};
napi_ext_ref uniqueStr = GetPropertyIdFromName(utf8, length);
return MakePointer<PropNameID>(uniqueStr);
}
PropNameID NapiJsiRuntime::createPropNameIDFromString(const String &str) {
EnvScope scope{m_env};
napi_ext_ref uniqueStr = GetPropertyIdFromName(GetNapiValue(str));
return MakePointer<PropNameID>(uniqueStr);
}
PropNameID NapiJsiRuntime::createPropNameIDFromSymbol(const Symbol &sym) {
// TODO: Support for symbols through the native API in JSC is very limited.
// While we could construct a PropNameID here, we would not be able to get a
// symbol property through the C++ API.
UNREFERENCED_PARAMETER(sym);
throw;
}
string NapiJsiRuntime::utf8(const PropNameID &id) {
EnvScope scope{m_env};
return PropertyIdToStdString(GetNapiValue(id));
}
bool NapiJsiRuntime::compare(const PropNameID &lhs, const PropNameID &rhs) {
EnvScope scope{m_env};
return StrictEquals(GetNapiValue(lhs), GetNapiValue(rhs));
}
string NapiJsiRuntime::symbolToString(const Symbol &s) {
EnvScope scope{m_env};
if (!m_value.SymbolToString) {
napi_value symbolCtor = GetProperty(m_value.Global, m_propertyId.Symbol);
napi_value symbolPrototype = GetProperty(symbolCtor, m_propertyId.prototype);
m_value.SymbolToString = NapiRefHolder{this, GetProperty(symbolPrototype, m_propertyId.toString)};
}
napi_value jsString = CallFunction(GetNapiValue(s), m_value.SymbolToString, {});
return StringToStdString(jsString);
}
String NapiJsiRuntime::createStringFromAscii(const char *str, size_t length) {
EnvScope scope{m_env};
return MakePointer<String>(CreateStringLatin1({str, length}));
}
String NapiJsiRuntime::createStringFromUtf8(const uint8_t *str, size_t length) {
EnvScope scope{m_env};
return MakePointer<String>(CreateStringUtf8(str, length));
}
string NapiJsiRuntime::utf8(const String &str) {
EnvScope scope{m_env};
return StringToStdString(GetNapiValue(str));
}
Object NapiJsiRuntime::createObject() {
EnvScope scope{m_env};
return MakePointer<Object>(CreateObject());
}
Object NapiJsiRuntime::createObject(shared_ptr<HostObject> hostObject) {
// The hostObjectHolder keeps the hostObject as external data.
// Then, the hostObjectHolder is wrapped up by a Proxy object to provide access
// to the hostObject's get, set and getPropertyNames methods.
// There is a special symbol property ID, 'hostObjectSymbol', used to access the hostObjectWrapper from the Proxy.
EnvScope scope{m_env};
napi_value hostObjectHolder = CreateExternalObject(std::make_unique<shared_ptr<HostObject>>(std::move(hostObject)));
napi_value obj = CreateObject();
SetProperty(obj, m_propertyId.hostObjectSymbol, hostObjectHolder);
if (!m_value.ProxyConstructor) {
m_value.ProxyConstructor = NapiRefHolder{this, GetProperty(m_value.Global, m_propertyId.Proxy)};
}
napi_value proxy = ConstructObject(m_value.ProxyConstructor, {obj, GetHostObjectProxyHandler()});
return MakePointer<Object>(proxy);
}
shared_ptr<HostObject> NapiJsiRuntime::getHostObject(const Object &obj) {
EnvScope scope{m_env};
return GetJsiHostObject(GetNapiValue(obj));
}
HostFunctionType &NapiJsiRuntime::getHostFunction(const Function &func) {
EnvScope scope{m_env};
napi_value hostFunctionHolder = GetProperty(GetNapiValue(func), m_propertyId.hostFunctionSymbol);
if (TypeOf(hostFunctionHolder) == napi_valuetype::napi_external) {
return static_cast<HostFunctionWrapper *>(GetExternalData(hostFunctionHolder))->GetHostFunction();
} else {
throw JSINativeException("getHostFunction() can only be called with HostFunction.");
}
}
Value NapiJsiRuntime::getProperty(const Object &obj, const PropNameID &name) {
EnvScope scope{m_env};
return ToJsiValue(GetProperty(GetNapiValue(obj), GetNapiValue(name)));
}
Value NapiJsiRuntime::getProperty(const Object &obj, const String &name) {
EnvScope scope{m_env};
return ToJsiValue(GetProperty(GetNapiValue(obj), GetNapiValue(name)));
}
bool NapiJsiRuntime::hasProperty(const Object &obj, const PropNameID &name) {
EnvScope scope{m_env};
return HasProperty(GetNapiValue(obj), GetNapiValue(name));
}
bool NapiJsiRuntime::hasProperty(const Object &obj, const String &name) {
EnvScope scope{m_env};
return HasProperty(GetNapiValue(obj), GetNapiValue(name));
}
void NapiJsiRuntime::setPropertyValue(Object &obj, const PropNameID &name, const Value &value) {
EnvScope scope{m_env};
SetProperty(GetNapiValue(obj), GetNapiValue(name), GetNapiValue(value));
}
void NapiJsiRuntime::setPropertyValue(Object &obj, const String &name, const Value &value) {
EnvScope scope{m_env};
SetProperty(GetNapiValue(obj), GetNapiValue(name), GetNapiValue(value));
}
bool NapiJsiRuntime::isArray(const Object &obj) const {
EnvScope scope{m_env};
bool result{};
CHECK_NAPI(napi_is_array(m_env, GetNapiValue(obj), &result));
return result;
}
bool NapiJsiRuntime::isArrayBuffer(const Object &obj) const {
EnvScope scope{m_env};
bool result{};
CHECK_NAPI(napi_is_arraybuffer(m_env, GetNapiValue(obj), &result));
return result;
}
bool NapiJsiRuntime::isFunction(const Object &obj) const {
EnvScope scope{m_env};
return TypeOf(GetNapiValue(obj)) == napi_valuetype::napi_function;
}
bool NapiJsiRuntime::isHostObject(const Object &obj) const {
EnvScope scope{m_env};
napi_value hostObjectHolder = GetProperty(GetNapiValue(obj), m_propertyId.hostObjectSymbol);
if (TypeOf(hostObjectHolder) == napi_valuetype::napi_external) {
return GetExternalData(hostObjectHolder) != nullptr;
} else {
return false;
}
}
bool NapiJsiRuntime::isHostFunction(const Function &func) const {
EnvScope scope{m_env};
napi_value hostFunctionHolder = GetProperty(GetNapiValue(func), m_propertyId.hostFunctionSymbol);
if (TypeOf(hostFunctionHolder) == napi_valuetype::napi_external) {
return GetExternalData(hostFunctionHolder) != nullptr;
} else {
return false;
}
}
Array NapiJsiRuntime::getPropertyNames(const Object &obj) {
EnvScope scope{m_env};
napi_value properties;
CHECK_NAPI(napi_get_all_property_names(
m_env,
GetNapiValue(obj),
napi_key_collection_mode::napi_key_include_prototypes,
napi_key_filter(napi_key_enumerable | napi_key_skip_symbols),
napi_key_numbers_to_strings,
&properties));
return MakePointer<Object>(properties).asArray(*this);
}
WeakObject NapiJsiRuntime::createWeakObject(const Object &obj) {
EnvScope scope{m_env};
napi_ext_ref weakRef{};
CHECK_NAPI(napi_ext_create_weak_reference(m_env, GetNapiValue(obj), &weakRef));
return MakePointer<WeakObject>(weakRef);
}
Value NapiJsiRuntime::lockWeakObject(WeakObject &weakObject) {
EnvScope scope{m_env};
napi_value value = GetNapiValue(weakObject);
if (value) {
return ToJsiValue(value);
} else {
return Value::undefined();
}
}
Array NapiJsiRuntime::createArray(size_t length) {
EnvScope scope{m_env};
napi_value result{};
CHECK_NAPI(napi_create_array_with_length(m_env, length, &result));
return MakePointer<Object>(result).asArray(*this);
}
size_t NapiJsiRuntime::size(const Array &arr) {
EnvScope scope{m_env};
size_t result{};
CHECK_NAPI(napi_get_array_length(m_env, GetNapiValue(arr), reinterpret_cast<uint32_t *>(&result)));
return result;
}
size_t NapiJsiRuntime::size(const ArrayBuffer &arrBuf) {
EnvScope scope{m_env};
size_t result{};
CHECK_NAPI(napi_get_arraybuffer_info(m_env, GetNapiValue(arrBuf), nullptr, &result));
return result;
}
uint8_t *NapiJsiRuntime::data(const ArrayBuffer &arrBuf) {
EnvScope scope{m_env};
uint8_t *result{};
CHECK_NAPI(napi_get_arraybuffer_info(m_env, GetNapiValue(arrBuf), reinterpret_cast<void **>(&result), nullptr));
return result;
}
Value NapiJsiRuntime::getValueAtIndex(const Array &arr, size_t index) {
EnvScope scope{m_env};
napi_value result{};
CHECK_NAPI(napi_get_element(m_env, GetNapiValue(arr), static_cast<int32_t>(index), &result));
return ToJsiValue(result);
}
void NapiJsiRuntime::setValueAtIndexImpl(Array &arr, size_t index, const Value &value) {
EnvScope scope{m_env};
SetElement(GetNapiValue(arr), static_cast<uint32_t>(index), GetNapiValue(value));
}
Function
NapiJsiRuntime::createFunctionFromHostFunction(const PropNameID &name, unsigned int paramCount, HostFunctionType func) {
EnvScope scope{m_env};
auto hostFunctionWrapper = std::make_unique<HostFunctionWrapper>(std::move(func), *this);
napi_value function = CreateExternalFunction(
GetNapiValue(name), static_cast<int32_t>(paramCount), JsiHostFunctionCallback, hostFunctionWrapper.get());
const napi_value hostFunctionHolder = CreateExternalObject(std::move(hostFunctionWrapper));
SetProperty(function, m_propertyId.hostFunctionSymbol, hostFunctionHolder, napi_property_attributes::napi_default);
return MakePointer<Object>(function).getFunction(*this);
}
Value NapiJsiRuntime::call(const Function &func, const Value &jsThis, const Value *args, size_t count) {
EnvScope scope{m_env};
return ToJsiValue(
CallFunction(GetNapiValue(jsThis), GetNapiValue(func), NapiValueArgs(*this, span<const Value>(args, count))));
}
Value NapiJsiRuntime::callAsConstructor(const Function &func, const Value *args, size_t count) {
EnvScope scope{m_env};
return ToJsiValue(ConstructObject(GetNapiValue(func), NapiValueArgs(*this, span<Value const>(args, count))));
}
Runtime::ScopeState *NapiJsiRuntime::pushScope() {
EnvScope scope{m_env};
napi_handle_scope result{};
CHECK_NAPI(napi_open_handle_scope(m_env, &result));
return reinterpret_cast<Runtime::ScopeState *>(result);
}
void NapiJsiRuntime::popScope(Runtime::ScopeState *state) {
EnvScope scope{m_env};
CHECK_NAPI(napi_close_handle_scope(m_env, reinterpret_cast<napi_handle_scope>(state)));