-
Notifications
You must be signed in to change notification settings - Fork 459
/
napi.h
3295 lines (2822 loc) · 116 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_
#ifndef NAPI_HAS_THREADS
#if !defined(__wasm__) || (defined(__EMSCRIPTEN_PTHREADS__) || \
(defined(__wasi__) && defined(_REENTRANT)))
#define NAPI_HAS_THREADS 1
#else
#define NAPI_HAS_THREADS 0
#endif
#endif
#include <node_api.h>
#include <functional>
#include <initializer_list>
#include <memory>
#if NAPI_HAS_THREADS
#include <mutex>
#endif // NAPI_HAS_THREADS
#include <string>
#include <vector>
// VS2015 RTM has bugs with constexpr, so require min of VS2015 Update 3 (known
// good version)
#if !defined(_MSC_VER) || _MSC_FULL_VER >= 190024210
#define NAPI_HAS_CONSTEXPR 1
#endif
// VS2013 does not support char16_t literal strings, so we'll work around it
// using wchar_t strings and casting them. This is safe as long as the character
// sizes are the same.
#if defined(_MSC_VER) && _MSC_VER <= 1800
static_assert(sizeof(char16_t) == sizeof(wchar_t),
"Size mismatch between char16_t and wchar_t");
#define NAPI_WIDE_TEXT(x) reinterpret_cast<char16_t*>(L##x)
#else
#define NAPI_WIDE_TEXT(x) u##x
#endif
// Backwards-compatibility to handle the rename of this macro definition, in
// case they are used within userland code.
#ifdef NAPI_CPP_EXCEPTIONS
#define NODE_ADDON_API_CPP_EXCEPTIONS
#endif
#if defined(NODE_ADDON_API_CPP_EXCEPTIONS) && !defined(NAPI_CPP_EXCEPTIONS)
#define NAPI_CPP_EXCEPTIONS
#endif
#ifdef NAPI_DISABLE_CPP_EXCEPTIONS
#define NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS
#endif
#if defined(NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS) && \
!defined(NAPI_DISABLE_CPP_EXCEPTIONS)
#define NAPI_DISABLE_CPP_EXCEPTIONS
#endif
// If C++ exceptions are not explicitly enabled or disabled, enable them
// if exceptions were enabled in the compiler settings.
#if !defined(NODE_ADDON_API_CPP_EXCEPTIONS) && \
!defined(NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS)
#if defined(_CPPUNWIND) || defined(__EXCEPTIONS)
#define NODE_ADDON_API_CPP_EXCEPTIONS
#else
#error Exception support not detected. \
Define either NODE_ADDON_API_CPP_EXCEPTIONS or NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS.
#endif
#endif
// If C++ NODE_ADDON_API_CPP_EXCEPTIONS are enabled, NODE_ADDON_API_ENABLE_MAYBE
// should not be set
#if defined(NODE_ADDON_API_CPP_EXCEPTIONS) && \
defined(NODE_ADDON_API_ENABLE_MAYBE)
#error NODE_ADDON_API_ENABLE_MAYBE should not be set when \
NODE_ADDON_API_CPP_EXCEPTIONS is defined.
#endif
#ifdef _NOEXCEPT
#define NAPI_NOEXCEPT _NOEXCEPT
#else
#define NAPI_NOEXCEPT noexcept
#endif
#ifdef NODE_ADDON_API_CPP_EXCEPTIONS
// When C++ exceptions are enabled, Errors are thrown directly. There is no need
// to return anything after the throw statements. The variadic parameter is an
// optional return value that is ignored.
// We need _VOID versions of the macros to avoid warnings resulting from
// leaving the NAPI_THROW_* `...` argument empty.
#define NAPI_THROW(e, ...) throw e
#define NAPI_THROW_VOID(e) throw e
#define NAPI_THROW_IF_FAILED(env, status, ...) \
if ((status) != napi_ok) throw Napi::Error::New(env);
#define NAPI_THROW_IF_FAILED_VOID(env, status) \
if ((status) != napi_ok) throw Napi::Error::New(env);
#else // NODE_ADDON_API_CPP_EXCEPTIONS
// When C++ exceptions are disabled, Errors are thrown as JavaScript exceptions,
// which are pending until the callback returns to JS. The variadic parameter
// is an optional return value; usually it is an empty result.
// We need _VOID versions of the macros to avoid warnings resulting from
// leaving the NAPI_THROW_* `...` argument empty.
#define NAPI_THROW(e, ...) \
do { \
(e).ThrowAsJavaScriptException(); \
return __VA_ARGS__; \
} while (0)
#define NAPI_THROW_VOID(e) \
do { \
(e).ThrowAsJavaScriptException(); \
return; \
} while (0)
#define NAPI_THROW_IF_FAILED(env, status, ...) \
if ((status) != napi_ok) { \
Napi::Error::New(env).ThrowAsJavaScriptException(); \
return __VA_ARGS__; \
}
#define NAPI_THROW_IF_FAILED_VOID(env, status) \
if ((status) != napi_ok) { \
Napi::Error::New(env).ThrowAsJavaScriptException(); \
return; \
}
#endif // NODE_ADDON_API_CPP_EXCEPTIONS
#ifdef NODE_ADDON_API_ENABLE_MAYBE
#define NAPI_MAYBE_THROW_IF_FAILED(env, status, type) \
NAPI_THROW_IF_FAILED(env, status, Napi::Nothing<type>())
#define NAPI_RETURN_OR_THROW_IF_FAILED(env, status, result, type) \
NAPI_MAYBE_THROW_IF_FAILED(env, status, type); \
return Napi::Just<type>(result);
#else
#define NAPI_MAYBE_THROW_IF_FAILED(env, status, type) \
NAPI_THROW_IF_FAILED(env, status, type())
#define NAPI_RETURN_OR_THROW_IF_FAILED(env, status, result, type) \
NAPI_MAYBE_THROW_IF_FAILED(env, status, type); \
return result;
#endif
#define NAPI_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete;
#define NAPI_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete;
#define NAPI_DISALLOW_ASSIGN_COPY(CLASS) \
NAPI_DISALLOW_ASSIGN(CLASS) \
NAPI_DISALLOW_COPY(CLASS)
#define NAPI_CHECK(condition, location, message) \
do { \
if (!(condition)) { \
Napi::Error::Fatal((location), (message)); \
} \
} while (0)
// Internal check helper. Be careful that the formatted message length should be
// max 255 size and null terminated.
#define NAPI_INTERNAL_CHECK(expr, location, ...) \
do { \
if (!(expr)) { \
std::string msg = Napi::details::StringFormat(__VA_ARGS__); \
Napi::Error::Fatal(location, msg.c_str()); \
} \
} while (0)
#define NAPI_INTERNAL_CHECK_EQ(actual, expected, value_format, location) \
do { \
auto actual_value = (actual); \
NAPI_INTERNAL_CHECK(actual_value == (expected), \
location, \
"Expected " #actual " to be equal to " #expected \
", but got " value_format ".", \
actual_value); \
} while (0)
#define NAPI_FATAL_IF_FAILED(status, location, message) \
NAPI_CHECK((status) == napi_ok, location, message)
////////////////////////////////////////////////////////////////////////////////
/// Node-API C++ Wrapper Classes
///
/// These classes wrap the "Node-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 {
#ifdef NAPI_CPP_CUSTOM_NAMESPACE
// NAPI_CPP_CUSTOM_NAMESPACE can be #define'd per-addon to avoid symbol
// conflicts between different instances of node-addon-api
// First dummy definition of the namespace to make sure that Napi::(name) still
// refers to the right things inside this file.
namespace NAPI_CPP_CUSTOM_NAMESPACE {}
using namespace NAPI_CPP_CUSTOM_NAMESPACE;
namespace NAPI_CPP_CUSTOM_NAMESPACE {
#endif
// Forward declarations
class Env;
class Value;
class Boolean;
class Number;
#if NAPI_VERSION > 5
class BigInt;
#endif // NAPI_VERSION > 5
#if (NAPI_VERSION > 4)
class Date;
#endif
class String;
class Object;
class Array;
class ArrayBuffer;
class Function;
class Error;
class PropertyDescriptor;
class CallbackInfo;
class TypedArray;
template <typename T>
class TypedArrayOf;
using Int8Array =
TypedArrayOf<int8_t>; ///< Typed-array of signed 8-bit integers
using Uint8Array =
TypedArrayOf<uint8_t>; ///< Typed-array of unsigned 8-bit integers
using Int16Array =
TypedArrayOf<int16_t>; ///< Typed-array of signed 16-bit integers
using Uint16Array =
TypedArrayOf<uint16_t>; ///< Typed-array of unsigned 16-bit integers
using Int32Array =
TypedArrayOf<int32_t>; ///< Typed-array of signed 32-bit integers
using Uint32Array =
TypedArrayOf<uint32_t>; ///< Typed-array of unsigned 32-bit integers
using Float32Array =
TypedArrayOf<float>; ///< Typed-array of 32-bit floating-point values
using Float64Array =
TypedArrayOf<double>; ///< Typed-array of 64-bit floating-point values
#if NAPI_VERSION > 5
using BigInt64Array =
TypedArrayOf<int64_t>; ///< Typed array of signed 64-bit integers
using BigUint64Array =
TypedArrayOf<uint64_t>; ///< Typed array of unsigned 64-bit integers
#endif // NAPI_VERSION > 5
/// Defines the signature of a Node-API C++ module's registration callback
/// (init) function.
using ModuleRegisterCallback = Object (*)(Env env, Object exports);
class MemoryManagement;
/// A simple Maybe type, representing an object which may or may not have a
/// value.
///
/// If an API method returns a Maybe<>, the API method can potentially fail
/// either because an exception is thrown, or because an exception is pending,
/// e.g. because a previous API call threw an exception that hasn't been
/// caught yet. In that case, a "Nothing" value is returned.
template <class T>
class Maybe {
public:
bool IsNothing() const;
bool IsJust() const;
/// Short-hand for Unwrap(), which doesn't return a value. Could be used
/// where the actual value of the Maybe is not needed like Object::Set.
/// If this Maybe is nothing (empty), node-addon-api will crash the
/// process.
void Check() const;
/// Return the value of type T contained in the Maybe. If this Maybe is
/// nothing (empty), node-addon-api will crash the process.
T Unwrap() const;
/// Return the value of type T contained in the Maybe, or using a default
/// value if this Maybe is nothing (empty).
T UnwrapOr(const T& default_value) const;
/// Converts this Maybe to a value of type T in the out. If this Maybe is
/// nothing (empty), `false` is returned and `out` is left untouched.
bool UnwrapTo(T* out) const;
bool operator==(const Maybe& other) const;
bool operator!=(const Maybe& other) const;
private:
Maybe();
explicit Maybe(const T& t);
bool _has_value;
T _value;
template <class U>
friend Maybe<U> Nothing();
template <class U>
friend Maybe<U> Just(const U& u);
};
template <class T>
inline Maybe<T> Nothing();
template <class T>
inline Maybe<T> Just(const T& t);
#if defined(NODE_ADDON_API_ENABLE_MAYBE)
template <typename T>
using MaybeOrValue = Maybe<T>;
#else
template <typename T>
using MaybeOrValue = T;
#endif
#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER
using node_addon_api_basic_env = node_api_nogc_env;
using node_addon_api_basic_finalize = node_api_nogc_finalize;
#else
using node_addon_api_basic_env = napi_env;
using node_addon_api_basic_finalize = napi_finalize;
#endif
/// Environment for Node-API values and operations.
///
/// All Node-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 Node-API values or other
/// Node-API operations within the callback. (Many methods infer the
/// environment from the `this` instance that the method is called on.)
///
/// Multiple environments may co-exist in a single process or a thread.
///
/// In the V8 JavaScript engine, a Node-API environment approximately
/// corresponds to an Isolate.
class BasicEnv {
private:
node_addon_api_basic_env _env;
#if NAPI_VERSION > 5
template <typename T>
static void DefaultFini(Env, T* data);
template <typename DataType, typename HintType>
static void DefaultFiniWithHint(Env, DataType* data, HintType* hint);
#endif // NAPI_VERSION > 5
public:
BasicEnv(node_addon_api_basic_env env);
operator node_addon_api_basic_env() const;
// Without these operator overloads, the error:
//
// Use of overloaded operator '==' is ambiguous (with operand types
// 'Napi::Env' and 'Napi::Env')
//
// ... occurs when comparing foo.Env() == bar.Env() or foo.Env() == nullptr
bool operator==(const BasicEnv& other) const {
return _env == other._env;
};
bool operator==(std::nullptr_t /*other*/) const {
return _env == nullptr;
};
#if NAPI_VERSION > 2
template <typename Hook, typename Arg = void>
class CleanupHook;
template <typename Hook>
CleanupHook<Hook> AddCleanupHook(Hook hook);
template <typename Hook, typename Arg>
CleanupHook<Hook, Arg> AddCleanupHook(Hook hook, Arg* arg);
#endif // NAPI_VERSION > 2
#if NAPI_VERSION > 5
template <typename T>
T* GetInstanceData() const;
template <typename T>
using Finalizer = void (*)(Env, T*);
template <typename T, Finalizer<T> fini = BasicEnv::DefaultFini<T>>
void SetInstanceData(T* data) const;
template <typename DataType, typename HintType>
using FinalizerWithHint = void (*)(Env, DataType*, HintType*);
template <typename DataType,
typename HintType,
FinalizerWithHint<DataType, HintType> fini =
BasicEnv::DefaultFiniWithHint<DataType, HintType>>
void SetInstanceData(DataType* data, HintType* hint) const;
#endif // NAPI_VERSION > 5
#if NAPI_VERSION > 2
template <typename Hook, typename Arg>
class CleanupHook {
public:
CleanupHook();
CleanupHook(BasicEnv env, Hook hook, Arg* arg);
CleanupHook(BasicEnv env, Hook hook);
bool Remove(BasicEnv env);
bool IsEmpty() const;
private:
static inline void Wrapper(void* data) NAPI_NOEXCEPT;
static inline void WrapperWithArg(void* data) NAPI_NOEXCEPT;
void (*wrapper)(void* arg);
struct CleanupData {
Hook hook;
Arg* arg;
} * data;
};
#endif // NAPI_VERSION > 2
#if NAPI_VERSION > 8
const char* GetModuleFileName() const;
#endif // NAPI_VERSION > 8
#ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER
template <typename FinalizerType>
inline void PostFinalizer(FinalizerType finalizeCallback) const;
template <typename FinalizerType, typename T>
inline void PostFinalizer(FinalizerType finalizeCallback, T* data) const;
template <typename FinalizerType, typename T, typename Hint>
inline void PostFinalizer(FinalizerType finalizeCallback,
T* data,
Hint* finalizeHint) const;
#endif // NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER
friend class Env;
};
class Env : public BasicEnv {
public:
Env(napi_env env);
operator napi_env() const;
Object Global() const;
Value Undefined() const;
Value Null() const;
bool IsExceptionPending() const;
Error GetAndClearPendingException() const;
MaybeOrValue<Value> RunScript(const char* utf8script) const;
MaybeOrValue<Value> RunScript(const std::string& utf8script) const;
MaybeOrValue<Value> RunScript(String script) const;
};
/// 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 Node-API value primitive.
/// Creates a JS value from a C++ primitive.
///
/// `value` may be any of:
/// - bool
/// - Any integer type
/// - Any floating point type
/// - const char* (encoded using UTF-8, null-terminated)
/// - const char16_t* (encoded using UTF-16-LE, null-terminated)
/// - std::string (encoded using UTF-8)
/// - std::u16string
/// - napi::Value
/// - napi_value
template <typename T>
static Value From(napi_env env, const T& value);
static void CheckCast(napi_env env, napi_value value);
/// Converts to a Node-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;
/// Checks if the value is empty (uninitialized).
///
/// An empty value is invalid, and most attempts to perform an operation on an
/// empty value will result in an exception. Note an empty value is distinct
/// from JavaScript `null` or `undefined`, which are valid values.
///
/// When C++ exceptions are disabled at compile time, a method with a `Value`
/// return type may return an empty value to indicate a pending exception. So
/// when not using C++ exceptions, callers should check whether the value is
/// empty before attempting to use it.
bool IsEmpty() 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.
#if NAPI_VERSION > 5
bool IsBigInt() const; ///< Tests if a value is a JavaScript bigint.
#endif // NAPI_VERSION > 5
#if (NAPI_VERSION > 4)
bool IsDate() const; ///< Tests if a value is a JavaScript date.
#endif
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 IsPromise() const; ///< Tests if a value is a JavaScript promise.
bool IsDataView() const; ///< Tests if a value is a JavaScript data view.
bool IsBuffer() const; ///< Tests if a value is a Node buffer.
bool IsExternal() const; ///< Tests if a value is a pointer to external data.
/// 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`.
///
/// If `NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` is defined, this method
/// asserts that the actual type is the expected type.
template <typename T>
T As() const;
// Unsafe Value::As(), should be avoided.
template <typename T>
T UnsafeAs() const;
MaybeOrValue<Boolean> ToBoolean()
const; ///< Coerces a value to a JavaScript boolean.
MaybeOrValue<Number> ToNumber()
const; ///< Coerces a value to a JavaScript number.
MaybeOrValue<String> ToString()
const; ///< Coerces a value to a JavaScript string.
MaybeOrValue<Object> ToObject()
const; ///< Coerces a value to a JavaScript object.
protected:
/// !cond INTERNAL
napi_env _env;
napi_value _value;
/// !endcond
};
/// A JavaScript boolean value.
class Boolean : public Value {
public:
static Boolean New(napi_env env, ///< Node-API environment
bool value ///< Boolean value
);
static void CheckCast(napi_env env, napi_value value);
Boolean(); ///< Creates a new _empty_ Boolean instance.
Boolean(napi_env env,
napi_value value); ///< Wraps a Node-API value primitive.
operator bool() const; ///< Converts a Boolean value to a boolean primitive.
bool Value() const; ///< Converts a Boolean value to a boolean primitive.
};
/// A JavaScript number value.
class Number : public Value {
public:
static Number New(napi_env env, ///< Node-API environment
double value ///< Number value
);
static void CheckCast(napi_env env, napi_value value);
Number(); ///< Creates a new _empty_ Number instance.
Number(napi_env env,
napi_value value); ///< Wraps a Node-API value primitive.
operator int32_t()
const; ///< Converts a Number value to a 32-bit signed integer value.
operator uint32_t()
const; ///< Converts a Number value to a 32-bit unsigned integer value.
operator int64_t()
const; ///< Converts a Number value to a 64-bit signed integer value.
operator float()
const; ///< Converts a Number value to a 32-bit floating-point value.
operator double()
const; ///< Converts a Number value to a 64-bit floating-point value.
int32_t Int32Value()
const; ///< Converts a Number value to a 32-bit signed integer value.
uint32_t Uint32Value()
const; ///< Converts a Number value to a 32-bit unsigned integer value.
int64_t Int64Value()
const; ///< Converts a Number value to a 64-bit signed integer value.
float FloatValue()
const; ///< Converts a Number value to a 32-bit floating-point value.
double DoubleValue()
const; ///< Converts a Number value to a 64-bit floating-point value.
};
#if NAPI_VERSION > 5
/// A JavaScript bigint value.
class BigInt : public Value {
public:
static BigInt New(napi_env env, ///< Node-API environment
int64_t value ///< Number value
);
static BigInt New(napi_env env, ///< Node-API environment
uint64_t value ///< Number value
);
/// Creates a new BigInt object using a specified sign bit and a
/// specified list of digits/words.
/// The resulting number is calculated as:
/// (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...)
static BigInt New(napi_env env, ///< Node-API environment
int sign_bit, ///< Sign bit. 1 if negative.
size_t word_count, ///< Number of words in array
const uint64_t* words ///< Array of words
);
static void CheckCast(napi_env env, napi_value value);
BigInt(); ///< Creates a new _empty_ BigInt instance.
BigInt(napi_env env,
napi_value value); ///< Wraps a Node-API value primitive.
int64_t Int64Value(bool* lossless)
const; ///< Converts a BigInt value to a 64-bit signed integer value.
uint64_t Uint64Value(bool* lossless)
const; ///< Converts a BigInt value to a 64-bit unsigned integer value.
size_t WordCount() const; ///< The number of 64-bit words needed to store
///< the result of ToWords().
/// Writes the contents of this BigInt to a specified memory location.
/// `sign_bit` must be provided and will be set to 1 if this BigInt is
/// negative.
/// `*word_count` has to be initialized to the length of the `words` array.
/// Upon return, it will be set to the actual number of words that would
/// be needed to store this BigInt (i.e. the return value of `WordCount()`).
void ToWords(int* sign_bit, size_t* word_count, uint64_t* words);
};
#endif // NAPI_VERSION > 5
#if (NAPI_VERSION > 4)
/// A JavaScript date value.
class Date : public Value {
public:
/// Creates a new Date value from a double primitive.
static Date New(napi_env env, ///< Node-API environment
double value ///< Number value
);
static void CheckCast(napi_env env, napi_value value);
Date(); ///< Creates a new _empty_ Date instance.
Date(napi_env env, napi_value value); ///< Wraps a Node-API value primitive.
operator double() const; ///< Converts a Date value to double primitive
double ValueOf() const; ///< Converts a Date value to a double primitive.
};
#endif
/// A JavaScript string or symbol value (that can be used as a property name).
class Name : public Value {
public:
static void CheckCast(napi_env env, napi_value value);
Name(); ///< Creates a new _empty_ Name instance.
Name(napi_env env,
napi_value value); ///< Wraps a Node-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, ///< Node-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, ///< Node-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, ///< Node-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, ///< Node-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, ///< Node-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, ///< Node-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
);
/// Creates a new String based on the original object's type.
///
/// `value` may be any of:
/// - const char* (encoded using UTF-8, null-terminated)
/// - const char16_t* (encoded using UTF-16-LE, null-terminated)
/// - std::string (encoded using UTF-8)
/// - std::u16string
template <typename T>
static String From(napi_env env, const T& value);
static void CheckCast(napi_env env, napi_value value);
String(); ///< Creates a new _empty_ String instance.
String(napi_env env,
napi_value value); ///< Wraps a Node-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.
};
/// A JavaScript symbol value.
class Symbol : public Name {
public:
/// Creates a new Symbol value with an optional description.
static Symbol New(
napi_env env, ///< Node-API environment
const char* description =
nullptr ///< Optional UTF-8 encoded null-terminated C string
/// describing the symbol
);
/// Creates a new Symbol value with a description.
static Symbol New(
napi_env env, ///< Node-API environment
const std::string&
description ///< UTF-8 encoded C++ string describing the symbol
);
/// Creates a new Symbol value with a description.
static Symbol New(napi_env env, ///< Node-API environment
String description ///< String value describing the symbol
);
/// Creates a new Symbol value with a description.
static Symbol New(
napi_env env, ///< Node-API environment
napi_value description ///< String value describing the symbol
);
/// Get a public Symbol (e.g. Symbol.iterator).
static MaybeOrValue<Symbol> WellKnown(napi_env, const std::string& name);
// Create a symbol in the global registry, UTF-8 Encoded cpp string
static MaybeOrValue<Symbol> For(napi_env env, const std::string& description);
// Create a symbol in the global registry, C style string (null terminated)
static MaybeOrValue<Symbol> For(napi_env env, const char* description);
// Create a symbol in the global registry, String value describing the symbol
static MaybeOrValue<Symbol> For(napi_env env, String description);
// Create a symbol in the global registry, napi_value describing the symbol
static MaybeOrValue<Symbol> For(napi_env env, napi_value description);
static void CheckCast(napi_env env, napi_value value);
Symbol(); ///< Creates a new _empty_ Symbol instance.
Symbol(napi_env env,
napi_value value); ///< Wraps a Node-API value primitive.
};
class TypeTaggable : public Value {
public:
#if NAPI_VERSION >= 8
void TypeTag(const napi_type_tag* type_tag) const;
bool CheckTypeTag(const napi_type_tag* type_tag) const;
#endif // NAPI_VERSION >= 8
protected:
TypeTaggable();
TypeTaggable(napi_env env, napi_value value);
};
/// A JavaScript object value.
class Object : public TypeTaggable {
public:
/// Enables property and element assignments using indexing syntax.
///
/// This is a convenient helper to get and set object properties. As
/// getting and setting object properties may throw with JavaScript
/// exceptions, it is notable that these operations may fail.
/// When NODE_ADDON_API_ENABLE_MAYBE is defined, the process will abort
/// on JavaScript exceptions.
///
/// Example:
///
/// Napi::Value propertyValue = object1['A'];
/// object2['A'] = propertyValue;
/// Napi::Value elementValue = array[0];
/// array[1] = elementValue;
template <typename Key>
class PropertyLValue {
public:
/// Converts an L-value to a value.
operator Value() const;
/// Assigns a value to the property. The type of value can be
/// anything supported by `Object::Set`.
template <typename ValueType>
PropertyLValue& operator=(ValueType value);
private:
PropertyLValue() = delete;
PropertyLValue(Object object, Key key);
napi_env _env;
napi_value _object;
Key _key;
friend class Napi::Object;
};
/// Creates a new Object value.
static Object New(napi_env env ///< Node-API environment
);
static void CheckCast(napi_env env, napi_value value);
Object(); ///< Creates a new _empty_ Object instance.
Object(napi_env env,
napi_value value); ///< Wraps a Node-API value primitive.
/// Gets or sets a named property.
PropertyLValue<std::string> operator[](
const char* utf8name ///< UTF-8 encoded null-terminated property name
);
/// Gets or sets a named property.
PropertyLValue<std::string> operator[](
const std::string& utf8name ///< UTF-8 encoded property name
);
/// Gets or sets an indexed property or array element.
PropertyLValue<uint32_t> operator[](
uint32_t index /// Property / element index
);
/// Gets or sets an indexed property or array element.
PropertyLValue<Value> operator[](Value index /// Property / element index
) const;
/// Gets a named property.
MaybeOrValue<Value> operator[](
const char* utf8name ///< UTF-8 encoded null-terminated property name
) const;
/// Gets a named property.
MaybeOrValue<Value> operator[](
const std::string& utf8name ///< UTF-8 encoded property name
) const;
/// Gets an indexed property or array element.
MaybeOrValue<Value> operator[](uint32_t index ///< Property / element index
) const;
/// Checks whether a property is present.
MaybeOrValue<bool> Has(napi_value key ///< Property key primitive
) const;
/// Checks whether a property is present.
MaybeOrValue<bool> Has(Value key ///< Property key
) const;
/// Checks whether a named property is present.
MaybeOrValue<bool> Has(
const char* utf8name ///< UTF-8 encoded null-terminated property name
) const;
/// Checks whether a named property is present.
MaybeOrValue<bool> Has(
const std::string& utf8name ///< UTF-8 encoded property name
) const;
/// Checks whether a own property is present.
MaybeOrValue<bool> HasOwnProperty(napi_value key ///< Property key primitive
) const;
/// Checks whether a own property is present.
MaybeOrValue<bool> HasOwnProperty(Value key ///< Property key
) const;
/// Checks whether a own property is present.
MaybeOrValue<bool> HasOwnProperty(
const char* utf8name ///< UTF-8 encoded null-terminated property name
) const;
/// Checks whether a own property is present.
MaybeOrValue<bool> HasOwnProperty(
const std::string& utf8name ///< UTF-8 encoded property name
) const;
/// Gets a property.
MaybeOrValue<Value> Get(napi_value key ///< Property key primitive
) const;
/// Gets a property.
MaybeOrValue<Value> Get(Value key ///< Property key
) const;
/// Gets a named property.
MaybeOrValue<Value> Get(
const char* utf8name ///< UTF-8 encoded null-terminated property name
) const;
/// Gets a named property.
MaybeOrValue<Value> Get(
const std::string& utf8name ///< UTF-8 encoded property name
) const;
/// Sets a property.
template <typename ValueType>
MaybeOrValue<bool> Set(napi_value key, ///< Property key primitive
const ValueType& value ///< Property value primitive
) const;
/// Sets a property.
template <typename ValueType>
MaybeOrValue<bool> Set(Value key, ///< Property key
const ValueType& value ///< Property value
) const;
/// Sets a named property.
template <typename ValueType>
MaybeOrValue<bool> Set(
const char* utf8name, ///< UTF-8 encoded null-terminated property name
const ValueType& value) const;
/// Sets a named property.
template <typename ValueType>
MaybeOrValue<bool> Set(
const std::string& utf8name, ///< UTF-8 encoded property name
const ValueType& value ///< Property value primitive
) const;
/// Delete property.
MaybeOrValue<bool> Delete(napi_value key ///< Property key primitive
) const;
/// Delete property.
MaybeOrValue<bool> Delete(Value key ///< Property key