Brunobkr/llama.cpp_AlgMor24_github
ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.
03k
1#ifndef SRC_NAPI_H_2#define SRC_NAPI_H_3 4#ifndef NAPI_HAS_THREADS5#if !defined(__wasm__) || (defined(__EMSCRIPTEN_PTHREADS__) || \6 (defined(__wasi__) && defined(_REENTRANT)))7#define NAPI_HAS_THREADS 18#else9#define NAPI_HAS_THREADS 010#endif11#endif12 13#include <node_api.h>14#include <functional>15#include <initializer_list>16#include <memory>17#if NAPI_HAS_THREADS18#include <mutex>19#endif // NAPI_HAS_THREADS20#include <string>21#include <vector>22 23// VS2015 RTM has bugs with constexpr, so require min of VS2015 Update 3 (known24// good version)25#if !defined(_MSC_VER) || _MSC_FULL_VER >= 19002421026#define NAPI_HAS_CONSTEXPR 127#endif28 29// VS2013 does not support char16_t literal strings, so we'll work around it30// using wchar_t strings and casting them. This is safe as long as the character31// sizes are the same.32#if defined(_MSC_VER) && _MSC_VER <= 180033static_assert(sizeof(char16_t) == sizeof(wchar_t),34 "Size mismatch between char16_t and wchar_t");35#define NAPI_WIDE_TEXT(x) reinterpret_cast<char16_t*>(L##x)36#else37#define NAPI_WIDE_TEXT(x) u##x38#endif39 40// If C++ exceptions are not explicitly enabled or disabled, enable them41// if exceptions were enabled in the compiler settings.42#if !defined(NAPI_CPP_EXCEPTIONS) && !defined(NAPI_DISABLE_CPP_EXCEPTIONS)43#if defined(_CPPUNWIND) || defined(__EXCEPTIONS)44#define NAPI_CPP_EXCEPTIONS45#else46#error Exception support not detected. \47 Define either NAPI_CPP_EXCEPTIONS or NAPI_DISABLE_CPP_EXCEPTIONS.48#endif49#endif50 51// If C++ NAPI_CPP_EXCEPTIONS are enabled, NODE_ADDON_API_ENABLE_MAYBE should52// not be set53#if defined(NAPI_CPP_EXCEPTIONS) && defined(NODE_ADDON_API_ENABLE_MAYBE)54#error NODE_ADDON_API_ENABLE_MAYBE should not be set when \55 NAPI_CPP_EXCEPTIONS is defined.56#endif57 58#ifdef _NOEXCEPT59#define NAPI_NOEXCEPT _NOEXCEPT60#else61#define NAPI_NOEXCEPT noexcept62#endif63 64#ifdef NAPI_CPP_EXCEPTIONS65 66// When C++ exceptions are enabled, Errors are thrown directly. There is no need67// to return anything after the throw statements. The variadic parameter is an68// optional return value that is ignored.69// We need _VOID versions of the macros to avoid warnings resulting from70// leaving the NAPI_THROW_* `...` argument empty.71 72#define NAPI_THROW(e, ...) throw e73#define NAPI_THROW_VOID(e) throw e74 75#define NAPI_THROW_IF_FAILED(env, status, ...) \76 if ((status) != napi_ok) throw Napi::Error::New(env);77 78#define NAPI_THROW_IF_FAILED_VOID(env, status) \79 if ((status) != napi_ok) throw Napi::Error::New(env);80 81#else // NAPI_CPP_EXCEPTIONS82 83// When C++ exceptions are disabled, Errors are thrown as JavaScript exceptions,84// which are pending until the callback returns to JS. The variadic parameter85// is an optional return value; usually it is an empty result.86// We need _VOID versions of the macros to avoid warnings resulting from87// leaving the NAPI_THROW_* `...` argument empty.88 89#define NAPI_THROW(e, ...) \90 do { \91 (e).ThrowAsJavaScriptException(); \92 return __VA_ARGS__; \93 } while (0)94 95#define NAPI_THROW_VOID(e) \96 do { \97 (e).ThrowAsJavaScriptException(); \98 return; \99 } while (0)100 101#define NAPI_THROW_IF_FAILED(env, status, ...) \102 if ((status) != napi_ok) { \103 Napi::Error::New(env).ThrowAsJavaScriptException(); \104 return __VA_ARGS__; \105 }106 107#define NAPI_THROW_IF_FAILED_VOID(env, status) \108 if ((status) != napi_ok) { \109 Napi::Error::New(env).ThrowAsJavaScriptException(); \110 return; \111 }112 113#endif // NAPI_CPP_EXCEPTIONS114 115#ifdef NODE_ADDON_API_ENABLE_MAYBE116#define NAPI_MAYBE_THROW_IF_FAILED(env, status, type) \117 NAPI_THROW_IF_FAILED(env, status, Napi::Nothing<type>())118 119#define NAPI_RETURN_OR_THROW_IF_FAILED(env, status, result, type) \120 NAPI_MAYBE_THROW_IF_FAILED(env, status, type); \121 return Napi::Just<type>(result);122#else123#define NAPI_MAYBE_THROW_IF_FAILED(env, status, type) \124 NAPI_THROW_IF_FAILED(env, status, type())125 126#define NAPI_RETURN_OR_THROW_IF_FAILED(env, status, result, type) \127 NAPI_MAYBE_THROW_IF_FAILED(env, status, type); \128 return result;129#endif130 131#define NAPI_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete;132#define NAPI_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete;133 134#define NAPI_DISALLOW_ASSIGN_COPY(CLASS) \135 NAPI_DISALLOW_ASSIGN(CLASS) \136 NAPI_DISALLOW_COPY(CLASS)137 138#define NAPI_CHECK(condition, location, message) \139 do { \140 if (!(condition)) { \141 Napi::Error::Fatal((location), (message)); \142 } \143 } while (0)144 145#define NAPI_FATAL_IF_FAILED(status, location, message) \146 NAPI_CHECK((status) == napi_ok, location, message)147 148////////////////////////////////////////////////////////////////////////////////149/// Node-API C++ Wrapper Classes150///151/// These classes wrap the "Node-API" ABI-stable C APIs for Node.js, providing a152/// C++ object model and C++ exception-handling semantics with low overhead.153/// The wrappers are all header-only so that they do not affect the ABI.154////////////////////////////////////////////////////////////////////////////////155namespace Napi {156 157#ifdef NAPI_CPP_CUSTOM_NAMESPACE158// NAPI_CPP_CUSTOM_NAMESPACE can be #define'd per-addon to avoid symbol159// conflicts between different instances of node-addon-api160 161// First dummy definition of the namespace to make sure that Napi::(name) still162// refers to the right things inside this file.163namespace NAPI_CPP_CUSTOM_NAMESPACE {}164using namespace NAPI_CPP_CUSTOM_NAMESPACE;165 166namespace NAPI_CPP_CUSTOM_NAMESPACE {167#endif168 169// Forward declarations170class Env;171class Value;172class Boolean;173class Number;174#if NAPI_VERSION > 5175class BigInt;176#endif // NAPI_VERSION > 5177#if (NAPI_VERSION > 4)178class Date;179#endif180class String;181class Object;182class Array;183class ArrayBuffer;184class Function;185class Error;186class PropertyDescriptor;187class CallbackInfo;188class TypedArray;189template <typename T>190class TypedArrayOf;191 192using Int8Array =193 TypedArrayOf<int8_t>; ///< Typed-array of signed 8-bit integers194using Uint8Array =195 TypedArrayOf<uint8_t>; ///< Typed-array of unsigned 8-bit integers196using Int16Array =197 TypedArrayOf<int16_t>; ///< Typed-array of signed 16-bit integers198using Uint16Array =199 TypedArrayOf<uint16_t>; ///< Typed-array of unsigned 16-bit integers200using Int32Array =201 TypedArrayOf<int32_t>; ///< Typed-array of signed 32-bit integers202using Uint32Array =203 TypedArrayOf<uint32_t>; ///< Typed-array of unsigned 32-bit integers204using Float32Array =205 TypedArrayOf<float>; ///< Typed-array of 32-bit floating-point values206using Float64Array =207 TypedArrayOf<double>; ///< Typed-array of 64-bit floating-point values208#if NAPI_VERSION > 5209using BigInt64Array =210 TypedArrayOf<int64_t>; ///< Typed array of signed 64-bit integers211using BigUint64Array =212 TypedArrayOf<uint64_t>; ///< Typed array of unsigned 64-bit integers213#endif // NAPI_VERSION > 5214 215/// Defines the signature of a Node-API C++ module's registration callback216/// (init) function.217using ModuleRegisterCallback = Object (*)(Env env, Object exports);218 219class MemoryManagement;220 221/// A simple Maybe type, representing an object which may or may not have a222/// value.223///224/// If an API method returns a Maybe<>, the API method can potentially fail225/// either because an exception is thrown, or because an exception is pending,226/// e.g. because a previous API call threw an exception that hasn't been227/// caught yet. In that case, a "Nothing" value is returned.228template <class T>229class Maybe {230 public:231 bool IsNothing() const;232 bool IsJust() const;233 234 /// Short-hand for Unwrap(), which doesn't return a value. Could be used235 /// where the actual value of the Maybe is not needed like Object::Set.236 /// If this Maybe is nothing (empty), node-addon-api will crash the237 /// process.238 void Check() const;239 240 /// Return the value of type T contained in the Maybe. If this Maybe is241 /// nothing (empty), node-addon-api will crash the process.242 T Unwrap() const;243 244 /// Return the value of type T contained in the Maybe, or using a default245 /// value if this Maybe is nothing (empty).246 T UnwrapOr(const T& default_value) const;247 248 /// Converts this Maybe to a value of type T in the out. If this Maybe is249 /// nothing (empty), `false` is returned and `out` is left untouched.250 bool UnwrapTo(T* out) const;251 252 bool operator==(const Maybe& other) const;253 bool operator!=(const Maybe& other) const;254 255 private:256 Maybe();257 explicit Maybe(const T& t);258 259 bool _has_value;260 T _value;261 262 template <class U>263 friend Maybe<U> Nothing();264 template <class U>265 friend Maybe<U> Just(const U& u);266};267 268template <class T>269inline Maybe<T> Nothing();270 271template <class T>272inline Maybe<T> Just(const T& t);273 274#if defined(NODE_ADDON_API_ENABLE_MAYBE)275template <typename T>276using MaybeOrValue = Maybe<T>;277#else278template <typename T>279using MaybeOrValue = T;280#endif281 282/// Environment for Node-API values and operations.283///284/// All Node-API values and operations must be associated with an environment.285/// An environment instance is always provided to callback functions; that286/// environment must then be used for any creation of Node-API values or other287/// Node-API operations within the callback. (Many methods infer the288/// environment from the `this` instance that the method is called on.)289///290/// In the future, multiple environments per process may be supported,291/// although current implementations only support one environment per process.292///293/// In the V8 JavaScript engine, a Node-API environment approximately294/// corresponds to an Isolate.295class Env {296 private:297 napi_env _env;298#if NAPI_VERSION > 5299 template <typename T>300 static void DefaultFini(Env, T* data);301 template <typename DataType, typename HintType>302 static void DefaultFiniWithHint(Env, DataType* data, HintType* hint);303#endif // NAPI_VERSION > 5304 public:305 Env(napi_env env);306 307 operator napi_env() const;308 309 Object Global() const;310 Value Undefined() const;311 Value Null() const;312 313 bool IsExceptionPending() const;314 Error GetAndClearPendingException() const;315 316 MaybeOrValue<Value> RunScript(const char* utf8script) const;317 MaybeOrValue<Value> RunScript(const std::string& utf8script) const;318 MaybeOrValue<Value> RunScript(String script) const;319 320#if NAPI_VERSION > 2321 template <typename Hook, typename Arg = void>322 class CleanupHook;323 324 template <typename Hook>325 CleanupHook<Hook> AddCleanupHook(Hook hook);326 327 template <typename Hook, typename Arg>328 CleanupHook<Hook, Arg> AddCleanupHook(Hook hook, Arg* arg);329#endif // NAPI_VERSION > 2330 331#if NAPI_VERSION > 5332 template <typename T>333 T* GetInstanceData() const;334 335 template <typename T>336 using Finalizer = void (*)(Env, T*);337 template <typename T, Finalizer<T> fini = Env::DefaultFini<T>>338 void SetInstanceData(T* data) const;339 340 template <typename DataType, typename HintType>341 using FinalizerWithHint = void (*)(Env, DataType*, HintType*);342 template <typename DataType,343 typename HintType,344 FinalizerWithHint<DataType, HintType> fini =345 Env::DefaultFiniWithHint<DataType, HintType>>346 void SetInstanceData(DataType* data, HintType* hint) const;347#endif // NAPI_VERSION > 5348 349#if NAPI_VERSION > 2350 template <typename Hook, typename Arg>351 class CleanupHook {352 public:353 CleanupHook();354 CleanupHook(Env env, Hook hook, Arg* arg);355 CleanupHook(Env env, Hook hook);356 bool Remove(Env env);357 bool IsEmpty() const;358 359 private:360 static inline void Wrapper(void* data) NAPI_NOEXCEPT;361 static inline void WrapperWithArg(void* data) NAPI_NOEXCEPT;362 363 void (*wrapper)(void* arg);364 struct CleanupData {365 Hook hook;366 Arg* arg;367 } * data;368 };369#endif // NAPI_VERSION > 2370 371#if NAPI_VERSION > 8372 const char* GetModuleFileName() const;373#endif // NAPI_VERSION > 8374};375 376/// A JavaScript value of unknown type.377///378/// For type-specific operations, convert to one of the Value subclasses using a379/// `To*` or `As()` method. The `To*` methods do type coercion; the `As()`380/// method does not.381///382/// Napi::Value value = ...383/// if (!value.IsString()) throw Napi::TypeError::New(env, "Invalid384/// arg..."); Napi::String str = value.As<Napi::String>(); // Cast to a385/// string value386///387/// Napi::Value anotherValue = ...388/// bool isTruthy = anotherValue.ToBoolean(); // Coerce to a boolean value389class Value {390 public:391 Value(); ///< Creates a new _empty_ Value instance.392 Value(napi_env env,393 napi_value value); ///< Wraps a Node-API value primitive.394 395 /// Creates a JS value from a C++ primitive.396 ///397 /// `value` may be any of:398 /// - bool399 /// - Any integer type400 /// - Any floating point type401 /// - const char* (encoded using UTF-8, null-terminated)402 /// - const char16_t* (encoded using UTF-16-LE, null-terminated)403 /// - std::string (encoded using UTF-8)404 /// - std::u16string405 /// - napi::Value406 /// - napi_value407 template <typename T>408 static Value From(napi_env env, const T& value);409 410 /// Converts to a Node-API value primitive.411 ///412 /// If the instance is _empty_, this returns `nullptr`.413 operator napi_value() const;414 415 /// Tests if this value strictly equals another value.416 bool operator==(const Value& other) const;417 418 /// Tests if this value does not strictly equal another value.419 bool operator!=(const Value& other) const;420 421 /// Tests if this value strictly equals another value.422 bool StrictEquals(const Value& other) const;423 424 /// Gets the environment the value is associated with.425 Napi::Env Env() const;426 427 /// Checks if the value is empty (uninitialized).428 ///429 /// An empty value is invalid, and most attempts to perform an operation on an430 /// empty value will result in an exception. Note an empty value is distinct431 /// from JavaScript `null` or `undefined`, which are valid values.432 ///433 /// When C++ exceptions are disabled at compile time, a method with a `Value`434 /// return type may return an empty value to indicate a pending exception. So435 /// when not using C++ exceptions, callers should check whether the value is436 /// empty before attempting to use it.437 bool IsEmpty() const;438 439 napi_valuetype Type() const; ///< Gets the type of the value.440 441 bool IsUndefined()442 const; ///< Tests if a value is an undefined JavaScript value.443 bool IsNull() const; ///< Tests if a value is a null JavaScript value.444 bool IsBoolean() const; ///< Tests if a value is a JavaScript boolean.445 bool IsNumber() const; ///< Tests if a value is a JavaScript number.446#if NAPI_VERSION > 5447 bool IsBigInt() const; ///< Tests if a value is a JavaScript bigint.448#endif // NAPI_VERSION > 5449#if (NAPI_VERSION > 4)450 bool IsDate() const; ///< Tests if a value is a JavaScript date.451#endif452 bool IsString() const; ///< Tests if a value is a JavaScript string.453 bool IsSymbol() const; ///< Tests if a value is a JavaScript symbol.454 bool IsArray() const; ///< Tests if a value is a JavaScript array.455 bool IsArrayBuffer()456 const; ///< Tests if a value is a JavaScript array buffer.457 bool IsTypedArray() const; ///< Tests if a value is a JavaScript typed array.458 bool IsObject() const; ///< Tests if a value is a JavaScript object.459 bool IsFunction() const; ///< Tests if a value is a JavaScript function.460 bool IsPromise() const; ///< Tests if a value is a JavaScript promise.461 bool IsDataView() const; ///< Tests if a value is a JavaScript data view.462 bool IsBuffer() const; ///< Tests if a value is a Node buffer.463 bool IsExternal() const; ///< Tests if a value is a pointer to external data.464 465 /// Casts to another type of `Napi::Value`, when the actual type is known or466 /// assumed.467 ///468 /// This conversion does NOT coerce the type. Calling any methods469 /// inappropriate for the actual value type will throw `Napi::Error`.470 ///471 /// If `NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` is defined, this method472 /// asserts that the actual type is the expected type.473 template <typename T>474 T As() const;475 476 MaybeOrValue<Boolean> ToBoolean()477 const; ///< Coerces a value to a JavaScript boolean.478 MaybeOrValue<Number> ToNumber()479 const; ///< Coerces a value to a JavaScript number.480 MaybeOrValue<String> ToString()481 const; ///< Coerces a value to a JavaScript string.482 MaybeOrValue<Object> ToObject()483 const; ///< Coerces a value to a JavaScript object.484 485 protected:486 /// !cond INTERNAL487 napi_env _env;488 napi_value _value;489 /// !endcond490};491 492/// A JavaScript boolean value.493class Boolean : public Value {494 public:495 static Boolean New(napi_env env, ///< Node-API environment496 bool value ///< Boolean value497 );498 499 static void CheckCast(napi_env env, napi_value value);500 501 Boolean(); ///< Creates a new _empty_ Boolean instance.502 Boolean(napi_env env,503 napi_value value); ///< Wraps a Node-API value primitive.504 505 operator bool() const; ///< Converts a Boolean value to a boolean primitive.506 bool Value() const; ///< Converts a Boolean value to a boolean primitive.507};508 509/// A JavaScript number value.510class Number : public Value {511 public:512 static Number New(napi_env env, ///< Node-API environment513 double value ///< Number value514 );515 516 static void CheckCast(napi_env env, napi_value value);517 518 Number(); ///< Creates a new _empty_ Number instance.519 Number(napi_env env,520 napi_value value); ///< Wraps a Node-API value primitive.521 522 operator int32_t()523 const; ///< Converts a Number value to a 32-bit signed integer value.524 operator uint32_t()525 const; ///< Converts a Number value to a 32-bit unsigned integer value.526 operator int64_t()527 const; ///< Converts a Number value to a 64-bit signed integer value.528 operator float()529 const; ///< Converts a Number value to a 32-bit floating-point value.530 operator double()531 const; ///< Converts a Number value to a 64-bit floating-point value.532 533 int32_t Int32Value()534 const; ///< Converts a Number value to a 32-bit signed integer value.535 uint32_t Uint32Value()536 const; ///< Converts a Number value to a 32-bit unsigned integer value.537 int64_t Int64Value()538 const; ///< Converts a Number value to a 64-bit signed integer value.539 float FloatValue()540 const; ///< Converts a Number value to a 32-bit floating-point value.541 double DoubleValue()542 const; ///< Converts a Number value to a 64-bit floating-point value.543};544 545#if NAPI_VERSION > 5546/// A JavaScript bigint value.547class BigInt : public Value {548 public:549 static BigInt New(napi_env env, ///< Node-API environment550 int64_t value ///< Number value551 );552 static BigInt New(napi_env env, ///< Node-API environment553 uint64_t value ///< Number value554 );555 556 /// Creates a new BigInt object using a specified sign bit and a557 /// specified list of digits/words.558 /// The resulting number is calculated as:559 /// (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...)560 static BigInt New(napi_env env, ///< Node-API environment561 int sign_bit, ///< Sign bit. 1 if negative.562 size_t word_count, ///< Number of words in array563 const uint64_t* words ///< Array of words564 );565 566 static void CheckCast(napi_env env, napi_value value);567 568 BigInt(); ///< Creates a new _empty_ BigInt instance.569 BigInt(napi_env env,570 napi_value value); ///< Wraps a Node-API value primitive.571 572 int64_t Int64Value(bool* lossless)573 const; ///< Converts a BigInt value to a 64-bit signed integer value.574 uint64_t Uint64Value(bool* lossless)575 const; ///< Converts a BigInt value to a 64-bit unsigned integer value.576 577 size_t WordCount() const; ///< The number of 64-bit words needed to store578 ///< the result of ToWords().579 580 /// Writes the contents of this BigInt to a specified memory location.581 /// `sign_bit` must be provided and will be set to 1 if this BigInt is582 /// negative.583 /// `*word_count` has to be initialized to the length of the `words` array.584 /// Upon return, it will be set to the actual number of words that would585 /// be needed to store this BigInt (i.e. the return value of `WordCount()`).586 void ToWords(int* sign_bit, size_t* word_count, uint64_t* words);587};588#endif // NAPI_VERSION > 5589 590#if (NAPI_VERSION > 4)591/// A JavaScript date value.592class Date : public Value {593 public:594 /// Creates a new Date value from a double primitive.595 static Date New(napi_env env, ///< Node-API environment596 double value ///< Number value597 );598 599 static void CheckCast(napi_env env, napi_value value);600 601 Date(); ///< Creates a new _empty_ Date instance.602 Date(napi_env env, napi_value value); ///< Wraps a Node-API value primitive.603 operator double() const; ///< Converts a Date value to double primitive604 605 double ValueOf() const; ///< Converts a Date value to a double primitive.606};607#endif608 609/// A JavaScript string or symbol value (that can be used as a property name).610class Name : public Value {611 public:612 static void CheckCast(napi_env env, napi_value value);613 614 Name(); ///< Creates a new _empty_ Name instance.615 Name(napi_env env,616 napi_value value); ///< Wraps a Node-API value primitive.617};618 619/// A JavaScript string value.620class String : public Name {621 public:622 /// Creates a new String value from a UTF-8 encoded C++ string.623 static String New(napi_env env, ///< Node-API environment624 const std::string& value ///< UTF-8 encoded C++ string625 );626 627 /// Creates a new String value from a UTF-16 encoded C++ string.628 static String New(napi_env env, ///< Node-API environment629 const std::u16string& value ///< UTF-16 encoded C++ string630 );631 632 /// Creates a new String value from a UTF-8 encoded C string.633 static String New(634 napi_env env, ///< Node-API environment635 const char* value ///< UTF-8 encoded null-terminated C string636 );637 638 /// Creates a new String value from a UTF-16 encoded C string.639 static String New(640 napi_env env, ///< Node-API environment641 const char16_t* value ///< UTF-16 encoded null-terminated C string642 );643 644 /// Creates a new String value from a UTF-8 encoded C string with specified645 /// length.646 static String New(napi_env env, ///< Node-API environment647 const char* value, ///< UTF-8 encoded C string (not648 ///< necessarily null-terminated)649 size_t length ///< length of the string in bytes650 );651 652 /// Creates a new String value from a UTF-16 encoded C string with specified653 /// length.654 static String New(655 napi_env env, ///< Node-API environment656 const char16_t* value, ///< UTF-16 encoded C string (not necessarily657 ///< null-terminated)658 size_t length ///< Length of the string in 2-byte code units659 );660 661 /// Creates a new String based on the original object's type.662 ///663 /// `value` may be any of:664 /// - const char* (encoded using UTF-8, null-terminated)665 /// - const char16_t* (encoded using UTF-16-LE, null-terminated)666 /// - std::string (encoded using UTF-8)667 /// - std::u16string668 template <typename T>669 static String From(napi_env env, const T& value);670 671 static void CheckCast(napi_env env, napi_value value);672 673 String(); ///< Creates a new _empty_ String instance.674 String(napi_env env,675 napi_value value); ///< Wraps a Node-API value primitive.676 677 operator std::string()678 const; ///< Converts a String value to a UTF-8 encoded C++ string.679 operator std::u16string()680 const; ///< Converts a String value to a UTF-16 encoded C++ string.681 std::string Utf8Value()682 const; ///< Converts a String value to a UTF-8 encoded C++ string.683 std::u16string Utf16Value()684 const; ///< Converts a String value to a UTF-16 encoded C++ string.685};686 687/// A JavaScript symbol value.688class Symbol : public Name {689 public:690 /// Creates a new Symbol value with an optional description.691 static Symbol New(692 napi_env env, ///< Node-API environment693 const char* description =694 nullptr ///< Optional UTF-8 encoded null-terminated C string695 /// describing the symbol696 );697 698 /// Creates a new Symbol value with a description.699 static Symbol New(700 napi_env env, ///< Node-API environment701 const std::string&702 description ///< UTF-8 encoded C++ string describing the symbol703 );704 705 /// Creates a new Symbol value with a description.706 static Symbol New(napi_env env, ///< Node-API environment707 String description ///< String value describing the symbol708 );709 710 /// Creates a new Symbol value with a description.711 static Symbol New(712 napi_env env, ///< Node-API environment713 napi_value description ///< String value describing the symbol714 );715 716 /// Get a public Symbol (e.g. Symbol.iterator).717 static MaybeOrValue<Symbol> WellKnown(napi_env, const std::string& name);718 719 // Create a symbol in the global registry, UTF-8 Encoded cpp string720 static MaybeOrValue<Symbol> For(napi_env env, const std::string& description);721 722 // Create a symbol in the global registry, C style string (null terminated)723 static MaybeOrValue<Symbol> For(napi_env env, const char* description);724 725 // Create a symbol in the global registry, String value describing the symbol726 static MaybeOrValue<Symbol> For(napi_env env, String description);727 728 // Create a symbol in the global registry, napi_value describing the symbol729 static MaybeOrValue<Symbol> For(napi_env env, napi_value description);730 731 static void CheckCast(napi_env env, napi_value value);732 733 Symbol(); ///< Creates a new _empty_ Symbol instance.734 Symbol(napi_env env,735 napi_value value); ///< Wraps a Node-API value primitive.736};737 738class TypeTaggable : public Value {739 public:740#if NAPI_VERSION >= 8741 void TypeTag(const napi_type_tag* type_tag) const;742 bool CheckTypeTag(const napi_type_tag* type_tag) const;743#endif // NAPI_VERSION >= 8744 protected:745 TypeTaggable();746 TypeTaggable(napi_env env, napi_value value);747};748 749/// A JavaScript object value.750class Object : public TypeTaggable {751 public:752 /// Enables property and element assignments using indexing syntax.753 ///754 /// This is a convenient helper to get and set object properties. As755 /// getting and setting object properties may throw with JavaScript756 /// exceptions, it is notable that these operations may fail.757 /// When NODE_ADDON_API_ENABLE_MAYBE is defined, the process will abort758 /// on JavaScript exceptions.759 ///760 /// Example:761 ///762 /// Napi::Value propertyValue = object1['A'];763 /// object2['A'] = propertyValue;764 /// Napi::Value elementValue = array[0];765 /// array[1] = elementValue;766 template <typename Key>767 class PropertyLValue {768 public:769 /// Converts an L-value to a value.770 operator Value() const;771 772 /// Assigns a value to the property. The type of value can be773 /// anything supported by `Object::Set`.774 template <typename ValueType>775 PropertyLValue& operator=(ValueType value);776 777 private:778 PropertyLValue() = delete;779 PropertyLValue(Object object, Key key);780 napi_env _env;781 napi_value _object;782 Key _key;783 784 friend class Napi::Object;785 };786 787 /// Creates a new Object value.788 static Object New(napi_env env ///< Node-API environment789 );790 791 static void CheckCast(napi_env env, napi_value value);792 793 Object(); ///< Creates a new _empty_ Object instance.794 Object(napi_env env,795 napi_value value); ///< Wraps a Node-API value primitive.796 797 /// Gets or sets a named property.798 PropertyLValue<std::string> operator[](799 const char* utf8name ///< UTF-8 encoded null-terminated property name800 );801 802 /// Gets or sets a named property.803 PropertyLValue<std::string> operator[](804 const std::string& utf8name ///< UTF-8 encoded property name805 );806 807 /// Gets or sets an indexed property or array element.808 PropertyLValue<uint32_t> operator[](809 uint32_t index /// Property / element index810 );811 812 /// Gets or sets an indexed property or array element.813 PropertyLValue<Value> operator[](Value index /// Property / element index814 ) const;815 816 /// Gets a named property.817 MaybeOrValue<Value> operator[](818 const char* utf8name ///< UTF-8 encoded null-terminated property name819 ) const;820 821 /// Gets a named property.822 MaybeOrValue<Value> operator[](823 const std::string& utf8name ///< UTF-8 encoded property name824 ) const;825 826 /// Gets an indexed property or array element.827 MaybeOrValue<Value> operator[](uint32_t index ///< Property / element index828 ) const;829 830 /// Checks whether a property is present.831 MaybeOrValue<bool> Has(napi_value key ///< Property key primitive832 ) const;833 834 /// Checks whether a property is present.835 MaybeOrValue<bool> Has(Value key ///< Property key836 ) const;837 838 /// Checks whether a named property is present.839 MaybeOrValue<bool> Has(840 const char* utf8name ///< UTF-8 encoded null-terminated property name841 ) const;842 843 /// Checks whether a named property is present.844 MaybeOrValue<bool> Has(845 const std::string& utf8name ///< UTF-8 encoded property name846 ) const;847 848 /// Checks whether a own property is present.849 MaybeOrValue<bool> HasOwnProperty(napi_value key ///< Property key primitive850 ) const;851 852 /// Checks whether a own property is present.853 MaybeOrValue<bool> HasOwnProperty(Value key ///< Property key854 ) const;855 856 /// Checks whether a own property is present.857 MaybeOrValue<bool> HasOwnProperty(858 const char* utf8name ///< UTF-8 encoded null-terminated property name859 ) const;860 861 /// Checks whether a own property is present.862 MaybeOrValue<bool> HasOwnProperty(863 const std::string& utf8name ///< UTF-8 encoded property name864 ) const;865 866 /// Gets a property.867 MaybeOrValue<Value> Get(napi_value key ///< Property key primitive868 ) const;869 870 /// Gets a property.871 MaybeOrValue<Value> Get(Value key ///< Property key872 ) const;873 874 /// Gets a named property.875 MaybeOrValue<Value> Get(876 const char* utf8name ///< UTF-8 encoded null-terminated property name877 ) const;878 879 /// Gets a named property.880 MaybeOrValue<Value> Get(881 const std::string& utf8name ///< UTF-8 encoded property name882 ) const;883 884 /// Sets a property.885 template <typename ValueType>886 MaybeOrValue<bool> Set(napi_value key, ///< Property key primitive887 const ValueType& value ///< Property value primitive888 ) const;889 890 /// Sets a property.891 template <typename ValueType>892 MaybeOrValue<bool> Set(Value key, ///< Property key893 const ValueType& value ///< Property value894 ) const;895 896 /// Sets a named property.897 template <typename ValueType>898 MaybeOrValue<bool> Set(899 const char* utf8name, ///< UTF-8 encoded null-terminated property name900 const ValueType& value) const;901 902 /// Sets a named property.903 template <typename ValueType>904 MaybeOrValue<bool> Set(905 const std::string& utf8name, ///< UTF-8 encoded property name906 const ValueType& value ///< Property value primitive907 ) const;908 909 /// Delete property.910 MaybeOrValue<bool> Delete(napi_value key ///< Property key primitive911 ) const;912 913 /// Delete property.914 MaybeOrValue<bool> Delete(Value key ///< Property key915 ) const;916 917 /// Delete property.918 MaybeOrValue<bool> Delete(919 const char* utf8name ///< UTF-8 encoded null-terminated property name920 ) const;921 922 /// Delete property.923 MaybeOrValue<bool> Delete(924 const std::string& utf8name ///< UTF-8 encoded property name925 ) const;926 927 /// Checks whether an indexed property is present.928 MaybeOrValue<bool> Has(uint32_t index ///< Property / element index929 ) const;930 931 /// Gets an indexed property or array element.932 MaybeOrValue<Value> Get(uint32_t index ///< Property / element index933 ) const;934 935 /// Sets an indexed property or array element.936 template <typename ValueType>937 MaybeOrValue<bool> Set(uint32_t index, ///< Property / element index938 const ValueType& value ///< Property value primitive939 ) const;940 941 /// Deletes an indexed property or array element.942 MaybeOrValue<bool> Delete(uint32_t index ///< Property / element index943 ) const;944 945 /// This operation can fail in case of Proxy.[[OwnPropertyKeys]] and946 /// Proxy.[[GetOwnProperty]] calling into JavaScript. See:947 /// -948 /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys949 /// -950 /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p951 MaybeOrValue<Array> GetPropertyNames() const; ///< Get all property names952 953 /// Defines a property on the object.954 ///955 /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling956 /// into JavaScript. See957 /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc958 MaybeOrValue<bool> DefineProperty(959 const PropertyDescriptor&960 property ///< Descriptor for the property to be defined961 ) const;962 963 /// Defines properties on the object.964 ///965 /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling966 /// into JavaScript. See967 /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc968 MaybeOrValue<bool> DefineProperties(969 const std::initializer_list<PropertyDescriptor>& properties970 ///< List of descriptors for the properties to be defined971 ) const;972 973 /// Defines properties on the object.974 ///975 /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling976 /// into JavaScript. See977 /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc978 MaybeOrValue<bool> DefineProperties(979 const std::vector<PropertyDescriptor>& properties980 ///< Vector of descriptors for the properties to be defined981 ) const;982 983 /// Checks if an object is an instance created by a constructor function.984 ///985 /// This is equivalent to the JavaScript `instanceof` operator.986 ///987 /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into988 /// JavaScript.989 /// See990 /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof991 MaybeOrValue<bool> InstanceOf(992 const Function& constructor ///< Constructor function993 ) const;994 995 template <typename Finalizer, typename T>996 inline void AddFinalizer(Finalizer finalizeCallback, T* data) const;997 998 template <typename Finalizer, typename T, typename Hint>999 inline void AddFinalizer(Finalizer finalizeCallback,1000 T* data,1001 Hint* finalizeHint) const;1002 1003#ifdef NAPI_CPP_EXCEPTIONS1004 class const_iterator;1005 1006 inline const_iterator begin() const;1007 1008 inline const_iterator end() const;1009 1010 class iterator;1011 1012 inline iterator begin();1013 1014 inline iterator end();1015#endif // NAPI_CPP_EXCEPTIONS1016 1017#if NAPI_VERSION >= 81018 /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into1019 /// JavaScript.1020 /// See1021 /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof1022 MaybeOrValue<bool> Freeze() const;1023 /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into1024 /// JavaScript.1025 /// See1026 /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof1027 MaybeOrValue<bool> Seal() const;1028#endif // NAPI_VERSION >= 81029};1030 1031template <typename T>1032class External : public TypeTaggable {1033 public:1034 static External New(napi_env env, T* data);1035 1036 // Finalizer must implement `void operator()(Env env, T* data)`.1037 template <typename Finalizer>1038 static External New(napi_env env, T* data, Finalizer finalizeCallback);1039 // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`.1040 template <typename Finalizer, typename Hint>1041 static External New(napi_env env,1042 T* data,1043 Finalizer finalizeCallback,1044 Hint* finalizeHint);1045 1046 static void CheckCast(napi_env env, napi_value value);1047 1048 External();1049 External(napi_env env, napi_value value);1050 1051 T* Data() const;1052};1053 1054class Array : public Object {1055 public:1056 static Array New(napi_env env);1057 static Array New(napi_env env, size_t length);1058 1059 static void CheckCast(napi_env env, napi_value value);1060 1061 Array();1062 Array(napi_env env, napi_value value);1063 1064 uint32_t Length() const;1065};1066 1067#ifdef NAPI_CPP_EXCEPTIONS1068class Object::const_iterator {1069 private:1070 enum class Type { BEGIN, END };1071 1072 inline const_iterator(const Object* object, const Type type);1073 1074 public:1075 inline const_iterator& operator++();1076 1077 inline bool operator==(const const_iterator& other) const;1078 1079 inline bool operator!=(const const_iterator& other) const;1080 1081 inline const std::pair<Value, Object::PropertyLValue<Value>> operator*()1082 const;1083 1084 private:1085 const Napi::Object* _object;1086 Array _keys;1087 uint32_t _index;1088 1089 friend class Object;1090};1091 1092class Object::iterator {1093 private:1094 enum class Type { BEGIN, END };1095 1096 inline iterator(Object* object, const Type type);1097 1098 public:1099 inline iterator& operator++();1100 1101 inline bool operator==(const iterator& other) const;1102 1103 inline bool operator!=(const iterator& other) const;1104 1105 inline std::pair<Value, Object::PropertyLValue<Value>> operator*();1106 1107 private:1108 Napi::Object* _object;1109 Array _keys;1110 uint32_t _index;1111 1112 friend class Object;1113};1114#endif // NAPI_CPP_EXCEPTIONS1115 1116/// A JavaScript array buffer value.1117class ArrayBuffer : public Object {1118 public:1119 /// Creates a new ArrayBuffer instance over a new automatically-allocated1120 /// buffer.1121 static ArrayBuffer New(1122 napi_env env, ///< Node-API environment1123 size_t byteLength ///< Length of the buffer to be allocated, in bytes1124 );1125 1126#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED1127 /// Creates a new ArrayBuffer instance, using an external buffer with1128 /// specified byte length.1129 static ArrayBuffer New(1130 napi_env env, ///< Node-API environment1131 void* externalData, ///< Pointer to the external buffer to be used by1132 ///< the array1133 size_t byteLength ///< Length of the external buffer to be used by the1134 ///< array, in bytes1135 );1136 1137 /// Creates a new ArrayBuffer instance, using an external buffer with1138 /// specified byte length.1139 template <typename Finalizer>1140 static ArrayBuffer New(1141 napi_env env, ///< Node-API environment1142 void* externalData, ///< Pointer to the external buffer to be used by1143 ///< the array1144 size_t byteLength, ///< Length of the external buffer to be used by the1145 ///< array,1146 /// in bytes1147 Finalizer finalizeCallback ///< Function to be called when the array1148 ///< buffer is destroyed;1149 /// must implement `void operator()(Env env,1150 /// void* externalData)`1151 );1152 1153 /// Creates a new ArrayBuffer instance, using an external buffer with1154 /// specified byte length.1155 template <typename Finalizer, typename Hint>1156 static ArrayBuffer New(1157 napi_env env, ///< Node-API environment1158 void* externalData, ///< Pointer to the external buffer to be used by1159 ///< the array1160 size_t byteLength, ///< Length of the external buffer to be used by the1161 ///< array,1162 /// in bytes1163 Finalizer finalizeCallback, ///< Function to be called when the array1164 ///< buffer is destroyed;1165 /// must implement `void operator()(Env1166 /// env, void* externalData, Hint* hint)`1167 Hint* finalizeHint ///< Hint (second parameter) to be passed to the1168 ///< finalize callback1169 );1170#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED1171 1172 static void CheckCast(napi_env env, napi_value value);1173 1174 ArrayBuffer(); ///< Creates a new _empty_ ArrayBuffer instance.1175 ArrayBuffer(napi_env env,1176 napi_value value); ///< Wraps a Node-API value primitive.1177 1178 void* Data(); ///< Gets a pointer to the data buffer.1179 size_t ByteLength(); ///< Gets the length of the array buffer in bytes.1180 1181#if NAPI_VERSION >= 71182 bool IsDetached() const;1183 void Detach();1184#endif // NAPI_VERSION >= 71185};1186 1187/// A JavaScript typed-array value with unknown array type.1188///1189/// For type-specific operations, cast to a `TypedArrayOf<T>` instance using the1190/// `As()` method:1191///1192/// Napi::TypedArray array = ...1193/// if (t.TypedArrayType() == napi_int32_array) {1194/// Napi::Int32Array int32Array = t.As<Napi::Int32Array>();1195/// }1196class TypedArray : public Object {1197 public:1198 static void CheckCast(napi_env env, napi_value value);1199 1200 TypedArray(); ///< Creates a new _empty_ TypedArray instance.