forked from nodejs/node-addon-api
-
Notifications
You must be signed in to change notification settings - Fork 1
/
napi.h
1121 lines (954 loc) · 45.6 KB
/
napi.h
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
#ifndef SRC_NAPI_H_
#define SRC_NAPI_H_
#include "node_api.h"
#include <functional>
#include <initializer_list>
#include <string>
#include <vector>
#ifdef _NOEXCEPT
#define NAPI_NOEXCEPT _NOEXCEPT
#else
#define NAPI_NOEXCEPT noexcept
#endif
////////////////////////////////////////////////////////////////////////////////
/// N-API C++ Wrapper Classes
///
/// These classes wrap the "N-API" ABI-stable C APIs for Node.js, providing a
/// C++ object model and C++ exception-handling semantics with low overhead.
/// The wrappers are all header-only so that they do not affect the ABI.
////////////////////////////////////////////////////////////////////////////////
namespace Napi {
// Forward declarations
class Env;
class Value;
class Boolean;
class Number;
class String;
class Object;
class Array;
class Function;
template <typename T> class Buffer;
class Error;
class PropertyDescriptor;
class CallbackInfo;
template <typename T> class Reference;
template <typename Key> class PropertyLValue;
class TypedArray;
template <typename T> class TypedArrayOf;
typedef TypedArrayOf<int8_t> Int8Array; ///< Typed-array of signed 8-bit integers
typedef TypedArrayOf<uint8_t> Uint8Array; ///< Typed-array of unsigned 8-bit integers
typedef TypedArrayOf<int16_t> Int16Array; ///< Typed-array of signed 16-bit integers
typedef TypedArrayOf<uint16_t> Uint16Array; ///< Typed-array of unsigned 16-bit integers
typedef TypedArrayOf<int32_t> Int32Array; ///< Typed-array of signed 32-bit integers
typedef TypedArrayOf<uint32_t> Uint32Array; ///< Typed-array of unsigned 32-bit integers
typedef TypedArrayOf<float> Float32Array; ///< Typed-array of 32-bit floating-point values
typedef TypedArrayOf<double> Float64Array; ///< Typed-array of 64-bit floating-point values
/// Defines the signature of a N-API C++ module's registration callback (init) function.
typedef void ModuleRegisterCallback(Env env, Object exports, Object module);
/// Environment for N-API values and operations.
///
/// All N-API values and operations must be associated with an environment. An environment
/// instance is always provided to callback functions; that environment must then be used for any
/// creation of N-API values or other N-API operations within the callback. (Many methods infer
/// the environment from the `this` instance that the method is called on.)
///
/// In the future, multiple environments per process may be supported, although current
/// implementations only support one environment per process.
///
/// In the V8 JavaScript engine, a N-API environment approximately corresponds to an Isolate.
class Env {
public:
Env(napi_env env);
operator napi_env() const;
Object Global() const;
Value Undefined() const;
Value Null() const;
bool IsExceptionPending() const;
private:
napi_env _env;
};
/// A JavaScript value of unknown type.
///
/// For type-specific operations, convert to one of the Value subclasses using a `To*` or `As()`
/// method. The `To*` methods do type coercion; the `As()` method does not.
///
/// Napi::Value value = ...
/// if (!value.IsString()) throw Napi::TypeError::New(env, "Invalid arg...");
/// Napi::String str = value.As<Napi::String>(); // Cast to a string value
///
/// Napi::Value anotherValue = ...
/// bool isTruthy = anotherValue.ToBoolean(); // Coerce to a boolean value
class Value {
public:
Value(); ///< Creates a new _empty_ Value instance.
Value(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
/// Converts to a N-API value primitive.
///
/// If the instance is _empty_, this returns `nullptr`.
operator napi_value() const;
/// Tests if this value strictly equals another value.
bool operator ==(const Value& other) const;
/// Tests if this value does not strictly equal another value.
bool operator !=(const Value& other) const;
/// Tests if this value strictly equals another value.
bool StrictEquals(const Value& other) const;
/// Gets the environment the value is associated with.
Napi::Env Env() const;
napi_valuetype Type() const; ///< Gets the type of the value.
bool IsUndefined() const; ///< Tests if a value is an undefined JavaScript value.
bool IsNull() const; ///< Tests if a value is a null JavaScript value.
bool IsBoolean() const; ///< Tests if a value is a JavaScript boolean.
bool IsNumber() const; ///< Tests if a value is a JavaScript number.
bool IsString() const; ///< Tests if a value is a JavaScript string.
bool IsSymbol() const; ///< Tests if a value is a JavaScript symbol.
bool IsArray() const; ///< Tests if a value is a JavaScript array.
bool IsArrayBuffer() const; ///< Tests if a value is a JavaScript array buffer.
bool IsTypedArray() const; ///< Tests if a value is a JavaScript typed array.
bool IsObject() const; ///< Tests if a value is a JavaScript object.
bool IsFunction() const; ///< Tests if a value is a JavaScript function.
bool IsBuffer() const; ///< Tests if a value is a Node buffer.
/// Casts to another type of `Napi::Value`, when the actual type is known or assumed.
///
/// This conversion does NOT coerce the type. Calling any methods inappropriate for the actual
/// value type will throw `Napi::Error`.
template <typename T> T As() const;
Boolean ToBoolean() const; ///< Coerces a value to a JavaScript boolean.
Number ToNumber() const; ///< Coerces a value to a JavaScript number.
String ToString() const; ///< Coerces a value to a JavaScript string.
Object ToObject() const; ///< Coerces a value to a JavaScript object.
protected:
/// !cond INTERNAL
napi_env _env;
napi_value _value;
/// !endcond
};
class Boolean : public Value {
public:
static Boolean New(napi_env env, bool val);
Boolean();
Boolean(napi_env env, napi_value value);
operator bool() const;
bool Value() const;
};
class Number : public Value {
public:
static Number New(napi_env env, double val);
Number();
Number(napi_env env, napi_value value);
operator int32_t() const;
operator uint32_t() const;
operator int64_t() const;
operator float() const;
operator double() const;
int32_t Int32Value() const;
uint32_t Uint32Value() const;
int64_t Int64Value() const;
float FloatValue() const;
double DoubleValue() const;
};
/// A JavaScript string or symbol value (that can be used as a property name).
class Name : public Value {
public:
Name(); ///< Creates a new _empty_ Name instance.
Name(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
};
/// A JavaScript string value.
class String : public Name {
public:
/// Creates a new String value from a UTF-8 encoded C++ string.
static String New(
napi_env env, ///< N-API environment
const std::string& value ///< UTF-8 encoded C++ string
);
/// Creates a new String value from a UTF-16 encoded C++ string.
static String New(
napi_env env, ///< N-API environment
const std::u16string& value ///< UTF-16 encoded C++ string
);
/// Creates a new String value from a UTF-8 encoded C string.
static String New(
napi_env env, ///< N-API environment
const char* value ///< UTF-8 encoded null-terminated C string
);
/// Creates a new String value from a UTF-16 encoded C string.
static String New(
napi_env env, ///< N-API environment
const char16_t* value ///< UTF-16 encoded null-terminated C string
);
/// Creates a new String value from a UTF-8 encoded C string with specified length.
static String New(
napi_env env, ///< N-API environment
const char* value, ///< UTF-8 encoded C string (not necessarily null-terminated)
size_t length ///< length of the string in bytes
);
/// Creates a new String value from a UTF-16 encoded C string with specified length.
static String New(
napi_env env, ///< N-API environment
const char16_t* value, ///< UTF-16 encoded C string (not necessarily null-terminated)
size_t length ///< Length of the string in 2-byte code units
);
String(); ///< Creates a new _empty_ String instance.
String(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
operator std::string() const; ///< Converts a String value to a UTF-8 encoded C++ string.
operator std::u16string() const; ///< Converts a String value to a UTF-16 encoded C++ string.
std::string Utf8Value() const; ///< Converts a String value to a UTF-8 encoded C++ string.
std::u16string Utf16Value() const; ///< Converts a String value to a UTF-16 encoded C++ string.
};
class Symbol : public Name {
public:
static Symbol New(napi_env env, const char* description = nullptr);
static Symbol New(napi_env env, const std::string& description);
static Symbol New(napi_env env, String description);
static Symbol New(napi_env env, napi_value description);
Symbol();
Symbol(napi_env env, napi_value value);
};
class Object : public Value {
public:
static Object New(napi_env env);
Object();
Object(napi_env env, napi_value value);
PropertyLValue<std::string> operator [](const char* name);
PropertyLValue<std::string> operator [](const std::string& name);
PropertyLValue<uint32_t> operator [](uint32_t index);
Value operator [](const char* name) const;
Value operator [](const std::string& name) const;
Value operator [](uint32_t index) const;
bool Has(napi_value name) const;
bool Has(Value name) const;
bool Has(const char* utf8name) const;
bool Has(const std::string& utf8name) const;
Value Get(napi_value name) const;
Value Get(Value name) const;
Value Get(const char* utf8name) const;
Value Get(const std::string& utf8name) const;
void Set(napi_value name, napi_value value);
void Set(const char* utf8name, napi_value value);
void Set(const char* utf8name, Value value);
void Set(const char* utf8name, const char* utf8value);
void Set(const char* utf8name, bool boolValue);
void Set(const char* utf8name, double numberValue);
void Set(const std::string& utf8name, napi_value value);
void Set(const std::string& utf8name, Value value);
void Set(const std::string& utf8name, std::string& utf8value);
void Set(const std::string& utf8name, bool boolValue);
void Set(const std::string& utf8name, double numberValue);
bool Has(uint32_t index) const;
Value Get(uint32_t index) const;
void Set(uint32_t index, napi_value value);
void Set(uint32_t index, Value value);
void Set(uint32_t index, const char* utf8value);
void Set(uint32_t index, const std::string& utf8value);
void Set(uint32_t index, bool boolValue);
void Set(uint32_t index, double numberValue);
void DefineProperty(const PropertyDescriptor& property);
void DefineProperties(const std::initializer_list<PropertyDescriptor>& properties);
void DefineProperties(const std::vector<PropertyDescriptor>& properties);
bool InstanceOf(const Function& constructor) const;
};
template <typename Key>
class PropertyLValue {
public:
operator Value() const;
// |ValueType| can be anything supported by Object::Set.
template <typename ValueType>
PropertyLValue& operator =(ValueType value);
PropertyLValue() = delete;
private:
PropertyLValue(Object object, Key key);
Object _object;
Key _key;
friend class Napi::Object;
};
template <typename T>
class External : public Value {
public:
static External New(napi_env env, T* data);
// Finalizer must implement operator() accepting a T* and returning void.
template <typename Finalizer>
static External New(napi_env env,
T* data,
Finalizer finalizeCallback);
// Finalizer must implement operator() accepting a T* and Hint* and returning void.
template <typename Finalizer, typename Hint>
static External New(napi_env env,
T* data,
Finalizer finalizeCallback,
Hint* finalizeHint);
External();
External(napi_env env, napi_value value);
T* Data() const;
};
class Array : public Object {
public:
static Array New(napi_env env);
static Array New(napi_env env, size_t length);
Array();
Array(napi_env env, napi_value value);
uint32_t Length() const;
};
/// A JavaScript array buffer value.
class ArrayBuffer : public Object {
public:
/// Creates a new ArrayBuffer instance over a new automatically-allocated buffer.
static ArrayBuffer New(
napi_env env, ///< N-API environment
size_t byteLength ///< Length of the buffer to be allocated, in bytes
);
/// Creates a new ArrayBuffer instance, using an external buffer with specified byte length.
static ArrayBuffer New(
napi_env env, ///< N-API environment
void* externalData, ///< Pointer to the external buffer to be used by the array
size_t byteLength ///< Length of the external buffer to be used by the array, in bytes
);
/// Creates a new ArrayBuffer instance, using an external buffer with specified byte length.
template <typename Finalizer>
static ArrayBuffer New(
napi_env env, ///< N-API environment
void* externalData, ///< Pointer to the external buffer to be used by the array
size_t byteLength, ///< Length of the external buffer to be used by the array,
/// in bytes
Finalizer finalizeCallback ///< Function to be called when the array buffer is destroyed;
/// must implement `operator()`, accept a `void*` (which is the
/// data buffer pointer), and return `void`
);
/// Creates a new ArrayBuffer instance, using an external buffer with specified byte length.
template <typename Finalizer, typename Hint>
static ArrayBuffer New(
napi_env env, ///< N-API environment
void* externalData, ///< Pointer to the external buffer to be used by the array
size_t byteLength, ///< Length of the external buffer to be used by the array,
/// in bytes
Finalizer finalizeCallback, ///< Function to be called when the array buffer is destroyed;
/// must implement `operator()`, accept a `void*` (which is the
/// data buffer pointer) and `Hint*`, and return `void`
Hint* finalizeHint ///< Hint (second parameter) to be passed to the finalize callback
);
ArrayBuffer(); ///< Creates a new _empty_ ArrayBuffer instance.
ArrayBuffer(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
void* Data(); ///< Gets a pointer to the data buffer.
size_t ByteLength(); ///< Gets the length of the array buffer in bytes.
private:
mutable void* _data;
mutable size_t _length;
ArrayBuffer(napi_env env, napi_value value, void* data, size_t length);
void EnsureInfo() const;
};
/// A JavaScript typed-array value with unknown array type.
///
/// For type-specific operations, cast to a `TypedArrayOf<T>` instance using the `As()`
/// method:
///
/// Napi::TypedArray array = ...
/// if (t.TypedArrayType() == napi_int32_array) {
/// Napi::Int32Array int32Array = t.As<Napi::Int32Array>();
/// }
class TypedArray : public Object {
public:
TypedArray(); ///< Creates a new _empty_ TypedArray instance.
TypedArray(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
napi_typedarray_type TypedArrayType() const; ///< Gets the type of this typed-array.
Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer.
uint8_t ElementSize() const; ///< Gets the size in bytes of one element in the array.
size_t ElementLength() const; ///< Gets the number of elements in the array.
size_t ByteOffset() const; ///< Gets the offset into the buffer where the array starts.
size_t ByteLength() const; ///< Gets the length of the array in bytes.
protected:
/// !cond INTERNAL
napi_typedarray_type _type;
size_t _length;
TypedArray(napi_env env, napi_value value, napi_typedarray_type type, size_t length);
static const napi_typedarray_type unknown_array_type = static_cast<napi_typedarray_type>(-1);
template <typename T>
static constexpr napi_typedarray_type TypedArrayTypeForPrimitiveType() {
return std::is_same<T, int8_t>::value ? napi_int8_array
: std::is_same<T, uint8_t>::value ? napi_uint8_array
: std::is_same<T, int16_t>::value ? napi_int16_array
: std::is_same<T, uint16_t>::value ? napi_uint16_array
: std::is_same<T, int32_t>::value ? napi_int32_array
: std::is_same<T, uint32_t>::value ? napi_uint32_array
: std::is_same<T, float>::value ? napi_float32_array
: std::is_same<T, double>::value ? napi_float64_array
: unknown_array_type;
}
/// !endcond
};
/// A JavaScript typed-array value with known array type.
///
/// Note while it is possible to create and access Uint8 "clamped" arrays using this class,
/// the _clamping_ behavior is only applied in JavaScript.
template <typename T>
class TypedArrayOf : public TypedArray {
public:
/// Creates a new TypedArray instance over a new automatically-allocated array buffer.
///
/// The array type parameter can normally be omitted (because it is inferred from the template
/// parameter T), except when creating a "clamped" array:
///
/// Uint8Array::New(env, length, napi_uint8_clamped_array)
static TypedArrayOf New(
napi_env env, ///< N-API environment
size_t elementLength, ///< Length of the created array, as a number of elements
napi_typedarray_type type = TypedArray::TypedArrayTypeForPrimitiveType<T>()
///< Type of array, if different from the default array type for the template parameter T.
);
/// Creates a new TypedArray instance over a provided array buffer.
///
/// The array type parameter can normally be omitted (because it is inferred from the template
/// parameter T), except when creating a "clamped" array:
///
/// Uint8Array::New(env, length, buffer, 0, napi_uint8_clamped_array)
static TypedArrayOf New(
napi_env env, ///< N-API environment
size_t elementLength, ///< Length of the created array, as a number of elements
Napi::ArrayBuffer arrayBuffer, ///< Backing array buffer instance to use
size_t bufferOffset, ///< Offset into the array buffer where the typed-array starts
napi_typedarray_type type = TypedArray::TypedArrayTypeForPrimitiveType<T>()
///< Type of array, if different from the default array type for the template parameter T.
);
TypedArrayOf(); ///< Creates a new _empty_ TypedArray instance.
TypedArrayOf(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
T& operator [](size_t index); ///< Gets or sets an element in the array.
const T& operator [](size_t index) const; ///< Gets an element in the array.
/// Gets a pointer to the array's backing buffer.
///
/// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, because the
/// typed-array may have a non-zero `ByteOffset()` into the `ArrayBuffer`.
T* Data();
/// Gets a pointer to the array's backing buffer.
///
/// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, because the
/// typed-array may have a non-zero `ByteOffset()` into the `ArrayBuffer`.
const T* Data() const;
private:
T* _data;
TypedArrayOf(napi_env env,
napi_value value,
napi_typedarray_type type,
size_t length,
T* data);
};
class Function : public Object {
public:
// Callable must implement operator() accepting a const CallbackInfo&
// and return either void or Value.
template <typename Callable>
static Function New(napi_env env,
Callable cb,
const char* utf8name = nullptr,
void* data = nullptr);
template <typename Callable>
static Function New(napi_env env,
Callable cb,
const std::string& utf8name,
void* data = nullptr);
Function();
Function(napi_env env, napi_value value);
Value operator ()(const std::initializer_list<napi_value>& args) const;
Value Call(const std::initializer_list<napi_value>& args) const;
Value Call(const std::vector<napi_value>& args) const;
Value Call(napi_value recv, const std::initializer_list<napi_value>& args) const;
Value Call(napi_value recv, const std::vector<napi_value>& args) const;
Value MakeCallback(napi_value recv, const std::initializer_list<napi_value>& args) const;
Value MakeCallback(napi_value recv, const std::vector<napi_value>& args) const;
Object New(const std::initializer_list<napi_value>& args) const;
Object New(const std::vector<napi_value>& args) const;
};
template <typename T>
class Buffer : public Object {
public:
static Buffer<T> New(napi_env env, size_t length);
static Buffer<T> New(napi_env env, T* data, size_t length);
// Finalizer must implement operator() accepting a T* and returning void.
template <typename Finalizer>
static Buffer<T> New(napi_env env, T* data,
size_t length,
Finalizer finalizeCallback);
// Finalizer must implement operator() accepting a T* and Hint* and returning void.
template <typename Finalizer, typename Hint>
static Buffer<T> New(napi_env env, T* data,
size_t length,
Finalizer finalizeCallback,
Hint* finalizeHint);
static Buffer<T> Copy(napi_env env, const T* data, size_t length);
Buffer();
Buffer(napi_env env, napi_value value);
size_t Length() const;
T* Data() const;
private:
mutable size_t _length;
mutable T* _data;
Buffer(napi_env env, napi_value value, size_t length, T* data);
void EnsureInfo() const;
};
/// Holds a counted reference to a value; initially a weak reference unless otherwise specified,
/// may be changed to/from a strong reference by adjusting the refcount.
///
/// The referenced value is not immediately destroyed when the reference count is zero; it is
/// merely then eligible for garbage-collection if there are no other references to the value.
template <typename T>
class Reference {
public:
static Reference<T> New(const T& value, uint32_t initialRefcount = 0);
Reference();
Reference(napi_env env, napi_ref ref);
~Reference();
// A reference can be moved but cannot be copied.
Reference(Reference<T>&& other);
Reference<T>& operator =(Reference<T>&& other);
Reference(const Reference<T>&) = delete;
Reference<T>& operator =(Reference<T>&) = delete;
operator napi_ref() const;
bool operator ==(const Reference<T> &other) const;
bool operator !=(const Reference<T> &other) const;
Napi::Env Env() const;
bool IsEmpty() const;
// Note when getting the value of a Reference it is usually correct to do so
// within a HandleScope so that the value handle gets cleaned up efficiently.
T Value() const;
uint32_t Ref();
uint32_t Unref();
void Reset();
void Reset(const T& value, uint32_t refcount = 0);
// Call this on a reference that is declared as static data, to prevent its destructor
// from running at program shutdown time, which would attempt to reset the reference when
// the environment is no longer valid.
void SuppressDestruct();
protected:
/// !cond INTERNAL
napi_env _env;
napi_ref _ref;
/// !endcond
private:
bool _suppressDestruct;
};
class ObjectReference: public Reference<Object> {
public:
ObjectReference();
ObjectReference(napi_env env, napi_ref ref);
// A reference can be moved but cannot be copied.
ObjectReference(Reference<Object>&& other);
ObjectReference& operator =(Reference<Object>&& other);
ObjectReference(ObjectReference&& other);
ObjectReference& operator =(ObjectReference&& other);
ObjectReference(const ObjectReference&) = delete;
ObjectReference& operator =(ObjectReference&) = delete;
Napi::Value Get(const char* utf8name) const;
Napi::Value Get(const std::string& utf8name) const;
void Set(const char* utf8name, napi_value value);
void Set(const char* utf8name, Napi::Value value);
void Set(const char* utf8name, const char* utf8value);
void Set(const char* utf8name, bool boolValue);
void Set(const char* utf8name, double numberValue);
void Set(const std::string& utf8name, napi_value value);
void Set(const std::string& utf8name, Napi::Value value);
void Set(const std::string& utf8name, std::string& utf8value);
void Set(const std::string& utf8name, bool boolValue);
void Set(const std::string& utf8name, double numberValue);
Napi::Value Get(uint32_t index) const;
void Set(uint32_t index, const napi_value value);
void Set(uint32_t index, const Napi::Value value);
void Set(uint32_t index, const char* utf8value);
void Set(uint32_t index, const std::string& utf8value);
void Set(uint32_t index, bool boolValue);
void Set(uint32_t index, double numberValue);
};
class FunctionReference: public Reference<Function> {
public:
FunctionReference();
FunctionReference(napi_env env, napi_ref ref);
// A reference can be moved but cannot be copied.
FunctionReference(Reference<Function>&& other);
FunctionReference& operator =(Reference<Function>&& other);
FunctionReference(FunctionReference&& other);
FunctionReference& operator =(FunctionReference&& other);
FunctionReference(const FunctionReference&) = delete;
FunctionReference& operator =(FunctionReference&) = delete;
Napi::Value operator ()(const std::initializer_list<napi_value>& args) const;
Napi::Value Call(const std::initializer_list<napi_value>& args) const;
Napi::Value Call(const std::vector<napi_value>& args) const;
Napi::Value Call(napi_value recv, const std::initializer_list<napi_value>& args) const;
Napi::Value Call(napi_value recv, const std::vector<napi_value>& args) const;
Napi::Value MakeCallback(napi_value recv, const std::initializer_list<napi_value>& args) const;
Napi::Value MakeCallback(napi_value recv, const std::vector<napi_value>& args) const;
Object New(const std::initializer_list<napi_value>& args) const;
Object New(const std::vector<napi_value>& args) const;
};
// Shortcuts to creating a new reference with inferred type and refcount = 0.
template <typename T> Reference<T> Weak(T value);
ObjectReference Weak(Object value);
FunctionReference Weak(Function value);
// Shortcuts to creating a new reference with inferred type and refcount = 1.
template <typename T> Reference<T> Persistent(T value);
ObjectReference Persistent(Object value);
FunctionReference Persistent(Function value);
/// Wraps a JavaScript error object in a way that enables it to traverse a C++ stack and be
/// thrown and caught as a C++ exception.
///
/// If a N-API call fails without executing any JavaScript code (for example due to an invalid
/// argument), then the N-API wrapper automatically converts and throws the error as a C++
/// exception of type `Napi::Error`. Or if a JavaScript function called by C++ code via N-API
/// throws a JavaScript exception, then the N-API wrapper automatically converts and throws it as
/// a C++ exception of type `Napi::Error`.
///
/// If a C++ exception of type `Napi::Error` escapes from a N-API C++ callback, then the N-API
/// wrapper automatically converts and throws it as a JavaScript exception. Therefore, catching
/// a C++ exception of type `Napi::Error` prevents a JavaScript exception from being thrown.
///
/// #### Example 1 - Throwing an exception:
///
/// Napi::Env env = ...
/// throw Napi::Error::New(env, "Example exception");
///
/// Following C++ statements will not be executed. The exception will bubble up as a C++
/// exception of type `Napi::Error`, until it is either caught while still in C++, or else
/// automatically re-thrown as a JavaScript exception when the callback returns to JavaScript.
///
/// #### Example 2 - Not catching a N-API exception:
///
/// Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>();
/// jsFunctionThatThrows({ arg1, arg2 });
///
/// Following C++ statements will not be executed. The exception will bubble up as a C++
/// exception of type `Napi::Error`, until it is either caught while still in C++, or else
/// automatically re-thrown as a JavaScript exception when the callback returns to JavaScript.
///
/// #### Example 3 - Handling a N-API exception:
///
/// Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>();
/// try {
/// jsFunctionThatThrows({ arg1, arg2 });
/// } catch (const Napi::Error& e) {
/// cerr << "Caught JavaScript exception: " + e.what();
/// }
///
/// Since the exception was caught here, it will not be re-thrown as a JavaScript exception.
class Error : public ObjectReference, public std::exception {
public:
static Error New(napi_env env);
static Error New(napi_env env, const char* message);
static Error New(napi_env env, const std::string& message);
Error();
Error(napi_env env, napi_value value);
// An error can be moved or copied.
Error(Error&& other);
Error& operator =(Error&& other);
Error(const Error&);
Error& operator =(Error&);
const std::string& Message() const NAPI_NOEXCEPT;
void ThrowAsJavaScriptException() const;
const char* what() const NAPI_NOEXCEPT override;
protected:
/// !cond INTERNAL
typedef napi_status (*create_error_fn)(napi_env envb, napi_value msg, napi_value* result);
template <typename TError>
static TError New(napi_env env,
const char* message,
size_t length,
create_error_fn create_error);
/// !endcond
private:
mutable std::string _message;
};
class TypeError : public Error {
public:
static TypeError New(napi_env env, const char* message);
static TypeError New(napi_env env, const std::string& message);
TypeError();
TypeError(napi_env env, napi_value value);
};
class RangeError : public Error {
public:
static RangeError New(napi_env env, const char* message);
static RangeError New(napi_env env, const std::string& message);
RangeError();
RangeError(napi_env env, napi_value value);
};
class CallbackInfo {
public:
CallbackInfo(napi_env env, napi_callback_info info);
~CallbackInfo();
Napi::Env Env() const;
size_t Length() const;
const Value operator [](size_t index) const;
Value This() const;
void* Data() const;
void SetData(void* data);
private:
const size_t _staticArgCount = 6;
napi_env _env;
napi_value _this;
size_t _argc;
napi_value* _argv;
napi_value _staticArgs[6];
napi_value* _dynamicArgs;
void* _data;
};
class PropertyDescriptor {
public:
template <typename Getter>
static PropertyDescriptor Accessor(const char* utf8name,
Getter getter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter>
static PropertyDescriptor Accessor(const std::string& utf8name,
Getter getter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter>
static PropertyDescriptor Accessor(napi_value name,
Getter getter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter>
static PropertyDescriptor Accessor(Name name,
Getter getter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter, typename Setter>
static PropertyDescriptor Accessor(const char* utf8name,
Getter getter,
Setter setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter, typename Setter>
static PropertyDescriptor Accessor(const std::string& utf8name,
Getter getter,
Setter setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter, typename Setter>
static PropertyDescriptor Accessor(napi_value name,
Getter getter,
Setter setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter, typename Setter>
static PropertyDescriptor Accessor(Name name,
Getter getter,
Setter setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Callable>
static PropertyDescriptor Function(const char* utf8name,
Callable cb,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Callable>
static PropertyDescriptor Function(const std::string& utf8name,
Callable cb,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Callable>
static PropertyDescriptor Function(napi_value name,
Callable cb,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Callable>
static PropertyDescriptor Function(Name name,
Callable cb,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
static PropertyDescriptor Value(const char* utf8name,
napi_value value,
napi_property_attributes attributes = napi_default);
static PropertyDescriptor Value(const std::string& utf8name,
napi_value value,
napi_property_attributes attributes = napi_default);
static PropertyDescriptor Value(napi_value name,
napi_value value,
napi_property_attributes attributes = napi_default);
static PropertyDescriptor Value(Name name,
Napi::Value value,
napi_property_attributes attributes = napi_default);
PropertyDescriptor(napi_property_descriptor desc);
operator napi_property_descriptor&();
operator const napi_property_descriptor&() const;
private:
napi_property_descriptor _desc;
};
/// Property descriptor for use with `ObjectWrap::DefineClass()`.
///
/// This is different from the standalone `PropertyDescriptor` because it is specific to each
/// `ObjectWrap<T>` subclass. This prevents using descriptors from a different class when
/// defining a new class (preventing the callbacks from having incorrect `this` pointers).
template <typename T>
class ClassPropertyDescriptor {
public:
ClassPropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {}
operator napi_property_descriptor&() { return _desc; }
operator const napi_property_descriptor&() const { return _desc; }
private:
napi_property_descriptor _desc;
};
/// Base class to be extended by C++ classes exposed to JavaScript; each C++ class instance gets
/// "wrapped" by a JavaScript object that is managed by this class.
///
/// At initialization time, the `DefineClass()` method must be used to
/// hook up the accessor and method callbacks. It takes a list of
/// property descriptors, which can be constructed via the various
/// static methods on the base class.
///
/// #### Example:
///
/// class Example: public Napi::ObjectWrap<Example> {
/// public:
/// static void Initialize(Napi::Env& env, Napi::Object& target) {
/// Napi::Function constructor = DefineClass(env, "Example", {
/// InstanceAccessor("value", &GetSomething, &SetSomething),
/// InstanceMethod("doSomething", &DoSomething),
/// });
/// target.Set("Example", constructor);
/// }
///
/// Example(const Napi::CallbackInfo& info); // Constructor
/// Napi::Value GetSomething(const Napi::CallbackInfo& info);
/// void SetSomething(const Napi::CallbackInfo& info, const Napi::Value& value);
/// Napi::Value DoSomething(const Napi::CallbackInfo& info);
/// }
template <typename T>
class ObjectWrap : public Reference<Object> {
public:
ObjectWrap();
static T* Unwrap(Object wrapper);
// Methods exposed to JavaScript must conform to one of these callback signatures.
typedef void (*StaticVoidMethodCallback)(const CallbackInfo& info);
typedef Napi::Value (*StaticMethodCallback)(const CallbackInfo& info);
typedef Napi::Value (*StaticGetterCallback)(const CallbackInfo& info);
typedef void (*StaticSetterCallback)(const CallbackInfo& info, const Napi::Value& value);
typedef void (T::*InstanceVoidMethodCallback)(const CallbackInfo& info);
typedef Napi::Value (T::*InstanceMethodCallback)(const CallbackInfo& info);
typedef Napi::Value (T::*InstanceGetterCallback)(const CallbackInfo& info);
typedef void (T::*InstanceSetterCallback)(const CallbackInfo& info, const Napi::Value& value);
typedef ClassPropertyDescriptor<T> PropertyDescriptor;
static Function DefineClass(Napi::Env env,
const char* utf8name,
const std::initializer_list<PropertyDescriptor>& properties,
void* data = nullptr);
static Function DefineClass(Napi::Env env,
const char* utf8name,
const std::vector<PropertyDescriptor>& properties,
void* data = nullptr);
static PropertyDescriptor StaticMethod(const char* utf8name,
StaticVoidMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
static PropertyDescriptor StaticMethod(const char* utf8name,
StaticMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
static PropertyDescriptor StaticAccessor(const char* utf8name,
StaticGetterCallback getter,
StaticSetterCallback setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
static PropertyDescriptor InstanceMethod(const char* utf8name,
InstanceVoidMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
static PropertyDescriptor InstanceMethod(const char* utf8name,
InstanceMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
static PropertyDescriptor InstanceAccessor(const char* utf8name,
InstanceGetterCallback getter,
InstanceSetterCallback setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);