napi-inl.h 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671
  1. #ifndef SRC_NAPI_INL_H_
  2. #define SRC_NAPI_INL_H_
  3. ////////////////////////////////////////////////////////////////////////////////
  4. // N-API C++ Wrapper Classes
  5. //
  6. // Inline header-only implementations for "N-API" ABI-stable C APIs for Node.js.
  7. ////////////////////////////////////////////////////////////////////////////////
  8. // Note: Do not include this file directly! Include "napi.h" instead.
  9. #include <cstring>
  10. #include <type_traits>
  11. namespace Napi {
  12. // Helpers to handle functions exposed from C++.
  13. namespace details {
  14. #ifdef NAPI_CPP_EXCEPTIONS
  15. #define NAPI_THROW(e) throw e
  16. // When C++ exceptions are enabled, Errors are thrown directly. There is no need
  17. // to return anything after the throw statement. The variadic parameter is an
  18. // optional return value that is ignored.
  19. #define NAPI_THROW_IF_FAILED(env, status, ...) \
  20. if ((status) != napi_ok) throw Error::New(env);
  21. #define NAPI_THROW_IF_FAILED_VOID(env, status) \
  22. if ((status) != napi_ok) throw Error::New(env);
  23. #else // NAPI_CPP_EXCEPTIONS
  24. #define NAPI_THROW(e) (e).ThrowAsJavaScriptException();
  25. // When C++ exceptions are disabled, Errors are thrown as JavaScript exceptions,
  26. // which are pending until the callback returns to JS. The variadic parameter
  27. // is an optional return value; usually it is an empty result.
  28. #define NAPI_THROW_IF_FAILED(env, status, ...) \
  29. if ((status) != napi_ok) { \
  30. Error::New(env).ThrowAsJavaScriptException(); \
  31. return __VA_ARGS__; \
  32. }
  33. // We need a _VOID version of this macro to avoid warnings resulting from
  34. // leaving the NAPI_THROW_IF_FAILED `...` argument empty.
  35. #define NAPI_THROW_IF_FAILED_VOID(env, status) \
  36. if ((status) != napi_ok) { \
  37. Error::New(env).ThrowAsJavaScriptException(); \
  38. return; \
  39. }
  40. #endif // NAPI_CPP_EXCEPTIONS
  41. #define NAPI_FATAL_IF_FAILED(status, location, message) \
  42. do { \
  43. if ((status) != napi_ok) { \
  44. Error::Fatal((location), (message)); \
  45. } \
  46. } while (0)
  47. // Attach a data item to an object and delete it when the object gets
  48. // garbage-collected.
  49. // TODO: Replace this code with `napi_add_finalizer()` whenever it becomes
  50. // available on all supported versions of Node.js.
  51. template <typename FreeType>
  52. static inline napi_status AttachData(napi_env env,
  53. napi_value obj,
  54. FreeType* data) {
  55. napi_value symbol, external;
  56. napi_status status = napi_create_symbol(env, nullptr, &symbol);
  57. if (status == napi_ok) {
  58. status = napi_create_external(env,
  59. data,
  60. [](napi_env /*env*/, void* data, void* /*hint*/) {
  61. delete static_cast<FreeType*>(data);
  62. },
  63. nullptr,
  64. &external);
  65. if (status == napi_ok) {
  66. napi_property_descriptor desc = {
  67. nullptr,
  68. symbol,
  69. nullptr,
  70. nullptr,
  71. nullptr,
  72. external,
  73. napi_default,
  74. nullptr
  75. };
  76. status = napi_define_properties(env, obj, 1, &desc);
  77. }
  78. }
  79. return status;
  80. }
  81. // For use in JS to C++ callback wrappers to catch any Napi::Error exceptions
  82. // and rethrow them as JavaScript exceptions before returning from the callback.
  83. template <typename Callable>
  84. inline napi_value WrapCallback(Callable callback) {
  85. #ifdef NAPI_CPP_EXCEPTIONS
  86. try {
  87. return callback();
  88. } catch (const Error& e) {
  89. e.ThrowAsJavaScriptException();
  90. return nullptr;
  91. }
  92. #else // NAPI_CPP_EXCEPTIONS
  93. // When C++ exceptions are disabled, errors are immediately thrown as JS
  94. // exceptions, so there is no need to catch and rethrow them here.
  95. return callback();
  96. #endif // NAPI_CPP_EXCEPTIONS
  97. }
  98. template <typename Callable, typename Return>
  99. struct CallbackData {
  100. static inline
  101. napi_value Wrapper(napi_env env, napi_callback_info info) {
  102. return details::WrapCallback([&] {
  103. CallbackInfo callbackInfo(env, info);
  104. CallbackData* callbackData =
  105. static_cast<CallbackData*>(callbackInfo.Data());
  106. callbackInfo.SetData(callbackData->data);
  107. return callbackData->callback(callbackInfo);
  108. });
  109. }
  110. Callable callback;
  111. void* data;
  112. };
  113. template <typename Callable>
  114. struct CallbackData<Callable, void> {
  115. static inline
  116. napi_value Wrapper(napi_env env, napi_callback_info info) {
  117. return details::WrapCallback([&] {
  118. CallbackInfo callbackInfo(env, info);
  119. CallbackData* callbackData =
  120. static_cast<CallbackData*>(callbackInfo.Data());
  121. callbackInfo.SetData(callbackData->data);
  122. callbackData->callback(callbackInfo);
  123. return nullptr;
  124. });
  125. }
  126. Callable callback;
  127. void* data;
  128. };
  129. template <typename T, typename Finalizer, typename Hint = void>
  130. struct FinalizeData {
  131. static inline
  132. void Wrapper(napi_env env, void* data, void* finalizeHint) {
  133. FinalizeData* finalizeData = static_cast<FinalizeData*>(finalizeHint);
  134. finalizeData->callback(Env(env), static_cast<T*>(data));
  135. delete finalizeData;
  136. }
  137. static inline
  138. void WrapperWithHint(napi_env env, void* data, void* finalizeHint) {
  139. FinalizeData* finalizeData = static_cast<FinalizeData*>(finalizeHint);
  140. finalizeData->callback(Env(env), static_cast<T*>(data), finalizeData->hint);
  141. delete finalizeData;
  142. }
  143. Finalizer callback;
  144. Hint* hint;
  145. };
  146. template <typename Getter, typename Setter>
  147. struct AccessorCallbackData {
  148. static inline
  149. napi_value GetterWrapper(napi_env env, napi_callback_info info) {
  150. return details::WrapCallback([&] {
  151. CallbackInfo callbackInfo(env, info);
  152. AccessorCallbackData* callbackData =
  153. static_cast<AccessorCallbackData*>(callbackInfo.Data());
  154. return callbackData->getterCallback(callbackInfo);
  155. });
  156. }
  157. static inline
  158. napi_value SetterWrapper(napi_env env, napi_callback_info info) {
  159. return details::WrapCallback([&] {
  160. CallbackInfo callbackInfo(env, info);
  161. AccessorCallbackData* callbackData =
  162. static_cast<AccessorCallbackData*>(callbackInfo.Data());
  163. callbackData->setterCallback(callbackInfo);
  164. return nullptr;
  165. });
  166. }
  167. Getter getterCallback;
  168. Setter setterCallback;
  169. };
  170. } // namespace details
  171. #ifndef NODE_ADDON_API_DISABLE_DEPRECATED
  172. # include "napi-inl.deprecated.h"
  173. #endif // !NODE_ADDON_API_DISABLE_DEPRECATED
  174. ////////////////////////////////////////////////////////////////////////////////
  175. // Module registration
  176. ////////////////////////////////////////////////////////////////////////////////
  177. #define NODE_API_MODULE(modname, regfunc) \
  178. napi_value __napi_ ## regfunc(napi_env env, \
  179. napi_value exports) { \
  180. return Napi::RegisterModule(env, exports, regfunc); \
  181. } \
  182. NAPI_MODULE(modname, __napi_ ## regfunc)
  183. // Adapt the NAPI_MODULE registration function:
  184. // - Wrap the arguments in NAPI wrappers.
  185. // - Catch any NAPI errors and rethrow as JS exceptions.
  186. inline napi_value RegisterModule(napi_env env,
  187. napi_value exports,
  188. ModuleRegisterCallback registerCallback) {
  189. return details::WrapCallback([&] {
  190. return napi_value(registerCallback(Napi::Env(env),
  191. Napi::Object(env, exports)));
  192. });
  193. }
  194. ////////////////////////////////////////////////////////////////////////////////
  195. // Env class
  196. ////////////////////////////////////////////////////////////////////////////////
  197. inline Env::Env(napi_env env) : _env(env) {
  198. }
  199. inline Env::operator napi_env() const {
  200. return _env;
  201. }
  202. inline Object Env::Global() const {
  203. napi_value value;
  204. napi_status status = napi_get_global(*this, &value);
  205. NAPI_THROW_IF_FAILED(*this, status, Object());
  206. return Object(*this, value);
  207. }
  208. inline Value Env::Undefined() const {
  209. napi_value value;
  210. napi_status status = napi_get_undefined(*this, &value);
  211. NAPI_THROW_IF_FAILED(*this, status, Value());
  212. return Value(*this, value);
  213. }
  214. inline Value Env::Null() const {
  215. napi_value value;
  216. napi_status status = napi_get_null(*this, &value);
  217. NAPI_THROW_IF_FAILED(*this, status, Value());
  218. return Value(*this, value);
  219. }
  220. inline bool Env::IsExceptionPending() const {
  221. bool result;
  222. napi_status status = napi_is_exception_pending(_env, &result);
  223. if (status != napi_ok) result = false; // Checking for a pending exception shouldn't throw.
  224. return result;
  225. }
  226. inline Error Env::GetAndClearPendingException() {
  227. napi_value value;
  228. napi_status status = napi_get_and_clear_last_exception(_env, &value);
  229. if (status != napi_ok) {
  230. // Don't throw another exception when failing to get the exception!
  231. return Error();
  232. }
  233. return Error(_env, value);
  234. }
  235. ////////////////////////////////////////////////////////////////////////////////
  236. // Value class
  237. ////////////////////////////////////////////////////////////////////////////////
  238. inline Value::Value() : _env(nullptr), _value(nullptr) {
  239. }
  240. inline Value::Value(napi_env env, napi_value value) : _env(env), _value(value) {
  241. }
  242. inline Value::operator napi_value() const {
  243. return _value;
  244. }
  245. inline bool Value::operator ==(const Value& other) const {
  246. return StrictEquals(other);
  247. }
  248. inline bool Value::operator !=(const Value& other) const {
  249. return !this->operator ==(other);
  250. }
  251. inline bool Value::StrictEquals(const Value& other) const {
  252. bool result;
  253. napi_status status = napi_strict_equals(_env, *this, other, &result);
  254. NAPI_THROW_IF_FAILED(_env, status, false);
  255. return result;
  256. }
  257. inline Napi::Env Value::Env() const {
  258. return Napi::Env(_env);
  259. }
  260. inline bool Value::IsEmpty() const {
  261. return _value == nullptr;
  262. }
  263. inline napi_valuetype Value::Type() const {
  264. if (_value == nullptr) {
  265. return napi_undefined;
  266. }
  267. napi_valuetype type;
  268. napi_status status = napi_typeof(_env, _value, &type);
  269. NAPI_THROW_IF_FAILED(_env, status, napi_undefined);
  270. return type;
  271. }
  272. inline bool Value::IsUndefined() const {
  273. return Type() == napi_undefined;
  274. }
  275. inline bool Value::IsNull() const {
  276. return Type() == napi_null;
  277. }
  278. inline bool Value::IsBoolean() const {
  279. return Type() == napi_boolean;
  280. }
  281. inline bool Value::IsNumber() const {
  282. return Type() == napi_number;
  283. }
  284. // currently experimental guard with version of NAPI_VERSION that it is
  285. // released in once it is no longer experimental
  286. #if (NAPI_VERSION > 2147483646)
  287. inline bool Value::IsBigInt() const {
  288. return Type() == napi_bigint;
  289. }
  290. #endif // NAPI_EXPERIMENTAL
  291. inline bool Value::IsString() const {
  292. return Type() == napi_string;
  293. }
  294. inline bool Value::IsSymbol() const {
  295. return Type() == napi_symbol;
  296. }
  297. inline bool Value::IsArray() const {
  298. if (_value == nullptr) {
  299. return false;
  300. }
  301. bool result;
  302. napi_status status = napi_is_array(_env, _value, &result);
  303. NAPI_THROW_IF_FAILED(_env, status, false);
  304. return result;
  305. }
  306. inline bool Value::IsArrayBuffer() const {
  307. if (_value == nullptr) {
  308. return false;
  309. }
  310. bool result;
  311. napi_status status = napi_is_arraybuffer(_env, _value, &result);
  312. NAPI_THROW_IF_FAILED(_env, status, false);
  313. return result;
  314. }
  315. inline bool Value::IsTypedArray() const {
  316. if (_value == nullptr) {
  317. return false;
  318. }
  319. bool result;
  320. napi_status status = napi_is_typedarray(_env, _value, &result);
  321. NAPI_THROW_IF_FAILED(_env, status, false);
  322. return result;
  323. }
  324. inline bool Value::IsObject() const {
  325. return Type() == napi_object || IsFunction();
  326. }
  327. inline bool Value::IsFunction() const {
  328. return Type() == napi_function;
  329. }
  330. inline bool Value::IsPromise() const {
  331. if (_value == nullptr) {
  332. return false;
  333. }
  334. bool result;
  335. napi_status status = napi_is_promise(_env, _value, &result);
  336. NAPI_THROW_IF_FAILED(_env, status, false);
  337. return result;
  338. }
  339. inline bool Value::IsDataView() const {
  340. if (_value == nullptr) {
  341. return false;
  342. }
  343. bool result;
  344. napi_status status = napi_is_dataview(_env, _value, &result);
  345. NAPI_THROW_IF_FAILED(_env, status, false);
  346. return result;
  347. }
  348. inline bool Value::IsBuffer() const {
  349. if (_value == nullptr) {
  350. return false;
  351. }
  352. bool result;
  353. napi_status status = napi_is_buffer(_env, _value, &result);
  354. NAPI_THROW_IF_FAILED(_env, status, false);
  355. return result;
  356. }
  357. inline bool Value::IsExternal() const {
  358. return Type() == napi_external;
  359. }
  360. template <typename T>
  361. inline T Value::As() const {
  362. return T(_env, _value);
  363. }
  364. inline Boolean Value::ToBoolean() const {
  365. napi_value result;
  366. napi_status status = napi_coerce_to_bool(_env, _value, &result);
  367. NAPI_THROW_IF_FAILED(_env, status, Boolean());
  368. return Boolean(_env, result);
  369. }
  370. inline Number Value::ToNumber() const {
  371. napi_value result;
  372. napi_status status = napi_coerce_to_number(_env, _value, &result);
  373. NAPI_THROW_IF_FAILED(_env, status, Number());
  374. return Number(_env, result);
  375. }
  376. inline String Value::ToString() const {
  377. napi_value result;
  378. napi_status status = napi_coerce_to_string(_env, _value, &result);
  379. NAPI_THROW_IF_FAILED(_env, status, String());
  380. return String(_env, result);
  381. }
  382. inline Object Value::ToObject() const {
  383. napi_value result;
  384. napi_status status = napi_coerce_to_object(_env, _value, &result);
  385. NAPI_THROW_IF_FAILED(_env, status, Object());
  386. return Object(_env, result);
  387. }
  388. ////////////////////////////////////////////////////////////////////////////////
  389. // Boolean class
  390. ////////////////////////////////////////////////////////////////////////////////
  391. inline Boolean Boolean::New(napi_env env, bool val) {
  392. napi_value value;
  393. napi_status status = napi_get_boolean(env, val, &value);
  394. NAPI_THROW_IF_FAILED(env, status, Boolean());
  395. return Boolean(env, value);
  396. }
  397. inline Boolean::Boolean() : Napi::Value() {
  398. }
  399. inline Boolean::Boolean(napi_env env, napi_value value) : Napi::Value(env, value) {
  400. }
  401. inline Boolean::operator bool() const {
  402. return Value();
  403. }
  404. inline bool Boolean::Value() const {
  405. bool result;
  406. napi_status status = napi_get_value_bool(_env, _value, &result);
  407. NAPI_THROW_IF_FAILED(_env, status, false);
  408. return result;
  409. }
  410. ////////////////////////////////////////////////////////////////////////////////
  411. // Number class
  412. ////////////////////////////////////////////////////////////////////////////////
  413. inline Number Number::New(napi_env env, double val) {
  414. napi_value value;
  415. napi_status status = napi_create_double(env, val, &value);
  416. NAPI_THROW_IF_FAILED(env, status, Number());
  417. return Number(env, value);
  418. }
  419. inline Number::Number() : Value() {
  420. }
  421. inline Number::Number(napi_env env, napi_value value) : Value(env, value) {
  422. }
  423. inline Number::operator int32_t() const {
  424. return Int32Value();
  425. }
  426. inline Number::operator uint32_t() const {
  427. return Uint32Value();
  428. }
  429. inline Number::operator int64_t() const {
  430. return Int64Value();
  431. }
  432. inline Number::operator float() const {
  433. return FloatValue();
  434. }
  435. inline Number::operator double() const {
  436. return DoubleValue();
  437. }
  438. inline int32_t Number::Int32Value() const {
  439. int32_t result;
  440. napi_status status = napi_get_value_int32(_env, _value, &result);
  441. NAPI_THROW_IF_FAILED(_env, status, 0);
  442. return result;
  443. }
  444. inline uint32_t Number::Uint32Value() const {
  445. uint32_t result;
  446. napi_status status = napi_get_value_uint32(_env, _value, &result);
  447. NAPI_THROW_IF_FAILED(_env, status, 0);
  448. return result;
  449. }
  450. inline int64_t Number::Int64Value() const {
  451. int64_t result;
  452. napi_status status = napi_get_value_int64(_env, _value, &result);
  453. NAPI_THROW_IF_FAILED(_env, status, 0);
  454. return result;
  455. }
  456. inline float Number::FloatValue() const {
  457. return static_cast<float>(DoubleValue());
  458. }
  459. inline double Number::DoubleValue() const {
  460. double result;
  461. napi_status status = napi_get_value_double(_env, _value, &result);
  462. NAPI_THROW_IF_FAILED(_env, status, 0);
  463. return result;
  464. }
  465. // currently experimental guard with version of NAPI_VERSION that it is
  466. // released in once it is no longer experimental
  467. #if (NAPI_VERSION > 2147483646)
  468. ////////////////////////////////////////////////////////////////////////////////
  469. // BigInt Class
  470. ////////////////////////////////////////////////////////////////////////////////
  471. inline BigInt BigInt::New(napi_env env, int64_t val) {
  472. napi_value value;
  473. napi_status status = napi_create_bigint_int64(env, val, &value);
  474. NAPI_THROW_IF_FAILED(env, status, BigInt());
  475. return BigInt(env, value);
  476. }
  477. inline BigInt BigInt::New(napi_env env, uint64_t val) {
  478. napi_value value;
  479. napi_status status = napi_create_bigint_uint64(env, val, &value);
  480. NAPI_THROW_IF_FAILED(env, status, BigInt());
  481. return BigInt(env, value);
  482. }
  483. inline BigInt BigInt::New(napi_env env, int sign_bit, size_t word_count, const uint64_t* words) {
  484. napi_value value;
  485. napi_status status = napi_create_bigint_words(env, sign_bit, word_count, words, &value);
  486. NAPI_THROW_IF_FAILED(env, status, BigInt());
  487. return BigInt(env, value);
  488. }
  489. inline BigInt::BigInt() : Value() {
  490. }
  491. inline BigInt::BigInt(napi_env env, napi_value value) : Value(env, value) {
  492. }
  493. inline int64_t BigInt::Int64Value(bool* lossless) const {
  494. int64_t result;
  495. napi_status status = napi_get_value_bigint_int64(
  496. _env, _value, &result, lossless);
  497. NAPI_THROW_IF_FAILED(_env, status, 0);
  498. return result;
  499. }
  500. inline uint64_t BigInt::Uint64Value(bool* lossless) const {
  501. uint64_t result;
  502. napi_status status = napi_get_value_bigint_uint64(
  503. _env, _value, &result, lossless);
  504. NAPI_THROW_IF_FAILED(_env, status, 0);
  505. return result;
  506. }
  507. inline size_t BigInt::WordCount() const {
  508. size_t word_count;
  509. napi_status status = napi_get_value_bigint_words(
  510. _env, _value, nullptr, &word_count, nullptr);
  511. NAPI_THROW_IF_FAILED(_env, status, 0);
  512. return word_count;
  513. }
  514. inline void BigInt::ToWords(int* sign_bit, size_t* word_count, uint64_t* words) {
  515. napi_status status = napi_get_value_bigint_words(
  516. _env, _value, sign_bit, word_count, words);
  517. NAPI_THROW_IF_FAILED_VOID(_env, status);
  518. }
  519. #endif // NAPI_EXPERIMENTAL
  520. ////////////////////////////////////////////////////////////////////////////////
  521. // Name class
  522. ////////////////////////////////////////////////////////////////////////////////
  523. inline Name::Name() : Value() {
  524. }
  525. inline Name::Name(napi_env env, napi_value value) : Value(env, value) {
  526. }
  527. ////////////////////////////////////////////////////////////////////////////////
  528. // String class
  529. ////////////////////////////////////////////////////////////////////////////////
  530. inline String String::New(napi_env env, const std::string& val) {
  531. return String::New(env, val.c_str(), val.size());
  532. }
  533. inline String String::New(napi_env env, const std::u16string& val) {
  534. return String::New(env, val.c_str(), val.size());
  535. }
  536. inline String String::New(napi_env env, const char* val) {
  537. napi_value value;
  538. napi_status status = napi_create_string_utf8(env, val, std::strlen(val), &value);
  539. NAPI_THROW_IF_FAILED(env, status, String());
  540. return String(env, value);
  541. }
  542. inline String String::New(napi_env env, const char16_t* val) {
  543. napi_value value;
  544. napi_status status = napi_create_string_utf16(env, val, std::u16string(val).size(), &value);
  545. NAPI_THROW_IF_FAILED(env, status, String());
  546. return String(env, value);
  547. }
  548. inline String String::New(napi_env env, const char* val, size_t length) {
  549. napi_value value;
  550. napi_status status = napi_create_string_utf8(env, val, length, &value);
  551. NAPI_THROW_IF_FAILED(env, status, String());
  552. return String(env, value);
  553. }
  554. inline String String::New(napi_env env, const char16_t* val, size_t length) {
  555. napi_value value;
  556. napi_status status = napi_create_string_utf16(env, val, length, &value);
  557. NAPI_THROW_IF_FAILED(env, status, String());
  558. return String(env, value);
  559. }
  560. inline String::String() : Name() {
  561. }
  562. inline String::String(napi_env env, napi_value value) : Name(env, value) {
  563. }
  564. inline String::operator std::string() const {
  565. return Utf8Value();
  566. }
  567. inline String::operator std::u16string() const {
  568. return Utf16Value();
  569. }
  570. inline std::string String::Utf8Value() const {
  571. size_t length;
  572. napi_status status = napi_get_value_string_utf8(_env, _value, nullptr, 0, &length);
  573. NAPI_THROW_IF_FAILED(_env, status, "");
  574. std::string value;
  575. value.reserve(length + 1);
  576. value.resize(length);
  577. status = napi_get_value_string_utf8(_env, _value, &value[0], value.capacity(), nullptr);
  578. NAPI_THROW_IF_FAILED(_env, status, "");
  579. return value;
  580. }
  581. inline std::u16string String::Utf16Value() const {
  582. size_t length;
  583. napi_status status = napi_get_value_string_utf16(_env, _value, nullptr, 0, &length);
  584. NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT(""));
  585. std::u16string value;
  586. value.reserve(length + 1);
  587. value.resize(length);
  588. status = napi_get_value_string_utf16(_env, _value, &value[0], value.capacity(), nullptr);
  589. NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT(""));
  590. return value;
  591. }
  592. ////////////////////////////////////////////////////////////////////////////////
  593. // Symbol class
  594. ////////////////////////////////////////////////////////////////////////////////
  595. inline Symbol Symbol::New(napi_env env, const char* description) {
  596. napi_value descriptionValue = description != nullptr ?
  597. String::New(env, description) : static_cast<napi_value>(nullptr);
  598. return Symbol::New(env, descriptionValue);
  599. }
  600. inline Symbol Symbol::New(napi_env env, const std::string& description) {
  601. napi_value descriptionValue = String::New(env, description);
  602. return Symbol::New(env, descriptionValue);
  603. }
  604. inline Symbol Symbol::New(napi_env env, String description) {
  605. napi_value descriptionValue = description;
  606. return Symbol::New(env, descriptionValue);
  607. }
  608. inline Symbol Symbol::New(napi_env env, napi_value description) {
  609. napi_value value;
  610. napi_status status = napi_create_symbol(env, description, &value);
  611. NAPI_THROW_IF_FAILED(env, status, Symbol());
  612. return Symbol(env, value);
  613. }
  614. inline Symbol Symbol::WellKnown(napi_env env, const std::string& name) {
  615. return Napi::Env(env).Global().Get("Symbol").As<Object>().Get(name).As<Symbol>();
  616. }
  617. inline Symbol::Symbol() : Name() {
  618. }
  619. inline Symbol::Symbol(napi_env env, napi_value value) : Name(env, value) {
  620. }
  621. ////////////////////////////////////////////////////////////////////////////////
  622. // Automagic value creation
  623. ////////////////////////////////////////////////////////////////////////////////
  624. namespace details {
  625. template <typename T>
  626. struct vf_number {
  627. static Number From(napi_env env, T value) {
  628. return Number::New(env, static_cast<double>(value));
  629. }
  630. };
  631. template<>
  632. struct vf_number<bool> {
  633. static Boolean From(napi_env env, bool value) {
  634. return Boolean::New(env, value);
  635. }
  636. };
  637. struct vf_utf8_charp {
  638. static String From(napi_env env, const char* value) {
  639. return String::New(env, value);
  640. }
  641. };
  642. struct vf_utf16_charp {
  643. static String From(napi_env env, const char16_t* value) {
  644. return String::New(env, value);
  645. }
  646. };
  647. struct vf_utf8_string {
  648. static String From(napi_env env, const std::string& value) {
  649. return String::New(env, value);
  650. }
  651. };
  652. struct vf_utf16_string {
  653. static String From(napi_env env, const std::u16string& value) {
  654. return String::New(env, value);
  655. }
  656. };
  657. template <typename T>
  658. struct vf_fallback {
  659. static Value From(napi_env env, const T& value) {
  660. return Value(env, value);
  661. }
  662. };
  663. template <typename...> struct disjunction : std::false_type {};
  664. template <typename B> struct disjunction<B> : B {};
  665. template <typename B, typename... Bs>
  666. struct disjunction<B, Bs...>
  667. : std::conditional<bool(B::value), B, disjunction<Bs...>>::type {};
  668. template <typename T>
  669. struct can_make_string
  670. : disjunction<typename std::is_convertible<T, const char *>::type,
  671. typename std::is_convertible<T, const char16_t *>::type,
  672. typename std::is_convertible<T, std::string>::type,
  673. typename std::is_convertible<T, std::u16string>::type> {};
  674. }
  675. template <typename T>
  676. Value Value::From(napi_env env, const T& value) {
  677. using Helper = typename std::conditional<
  678. std::is_integral<T>::value || std::is_floating_point<T>::value,
  679. details::vf_number<T>,
  680. typename std::conditional<
  681. details::can_make_string<T>::value,
  682. String,
  683. details::vf_fallback<T>
  684. >::type
  685. >::type;
  686. return Helper::From(env, value);
  687. }
  688. template <typename T>
  689. String String::From(napi_env env, const T& value) {
  690. struct Dummy {};
  691. using Helper = typename std::conditional<
  692. std::is_convertible<T, const char*>::value,
  693. details::vf_utf8_charp,
  694. typename std::conditional<
  695. std::is_convertible<T, const char16_t*>::value,
  696. details::vf_utf16_charp,
  697. typename std::conditional<
  698. std::is_convertible<T, std::string>::value,
  699. details::vf_utf8_string,
  700. typename std::conditional<
  701. std::is_convertible<T, std::u16string>::value,
  702. details::vf_utf16_string,
  703. Dummy
  704. >::type
  705. >::type
  706. >::type
  707. >::type;
  708. return Helper::From(env, value);
  709. }
  710. ////////////////////////////////////////////////////////////////////////////////
  711. // Object class
  712. ////////////////////////////////////////////////////////////////////////////////
  713. template <typename Key>
  714. inline Object::PropertyLValue<Key>::operator Value() const {
  715. return Object(_env, _object).Get(_key);
  716. }
  717. template <typename Key> template <typename ValueType>
  718. inline Object::PropertyLValue<Key>& Object::PropertyLValue<Key>::operator =(ValueType value) {
  719. Object(_env, _object).Set(_key, value);
  720. return *this;
  721. }
  722. template <typename Key>
  723. inline Object::PropertyLValue<Key>::PropertyLValue(Object object, Key key)
  724. : _env(object.Env()), _object(object), _key(key) {}
  725. inline Object Object::New(napi_env env) {
  726. napi_value value;
  727. napi_status status = napi_create_object(env, &value);
  728. NAPI_THROW_IF_FAILED(env, status, Object());
  729. return Object(env, value);
  730. }
  731. inline Object::Object() : Value() {
  732. }
  733. inline Object::Object(napi_env env, napi_value value) : Value(env, value) {
  734. }
  735. inline Object::PropertyLValue<std::string> Object::operator [](const char* utf8name) {
  736. return PropertyLValue<std::string>(*this, utf8name);
  737. }
  738. inline Object::PropertyLValue<std::string> Object::operator [](const std::string& utf8name) {
  739. return PropertyLValue<std::string>(*this, utf8name);
  740. }
  741. inline Object::PropertyLValue<uint32_t> Object::operator [](uint32_t index) {
  742. return PropertyLValue<uint32_t>(*this, index);
  743. }
  744. inline Value Object::operator [](const char* utf8name) const {
  745. return Get(utf8name);
  746. }
  747. inline Value Object::operator [](const std::string& utf8name) const {
  748. return Get(utf8name);
  749. }
  750. inline Value Object::operator [](uint32_t index) const {
  751. return Get(index);
  752. }
  753. inline bool Object::Has(napi_value key) const {
  754. bool result;
  755. napi_status status = napi_has_property(_env, _value, key, &result);
  756. NAPI_THROW_IF_FAILED(_env, status, false);
  757. return result;
  758. }
  759. inline bool Object::Has(Value key) const {
  760. bool result;
  761. napi_status status = napi_has_property(_env, _value, key, &result);
  762. NAPI_THROW_IF_FAILED(_env, status, false);
  763. return result;
  764. }
  765. inline bool Object::Has(const char* utf8name) const {
  766. bool result;
  767. napi_status status = napi_has_named_property(_env, _value, utf8name, &result);
  768. NAPI_THROW_IF_FAILED(_env, status, false);
  769. return result;
  770. }
  771. inline bool Object::Has(const std::string& utf8name) const {
  772. return Has(utf8name.c_str());
  773. }
  774. inline bool Object::HasOwnProperty(napi_value key) const {
  775. bool result;
  776. napi_status status = napi_has_own_property(_env, _value, key, &result);
  777. NAPI_THROW_IF_FAILED(_env, status, false);
  778. return result;
  779. }
  780. inline bool Object::HasOwnProperty(Value key) const {
  781. bool result;
  782. napi_status status = napi_has_own_property(_env, _value, key, &result);
  783. NAPI_THROW_IF_FAILED(_env, status, false);
  784. return result;
  785. }
  786. inline bool Object::HasOwnProperty(const char* utf8name) const {
  787. napi_value key;
  788. napi_status status = napi_create_string_utf8(_env, utf8name, std::strlen(utf8name), &key);
  789. NAPI_THROW_IF_FAILED(_env, status, false);
  790. return HasOwnProperty(key);
  791. }
  792. inline bool Object::HasOwnProperty(const std::string& utf8name) const {
  793. return HasOwnProperty(utf8name.c_str());
  794. }
  795. inline Value Object::Get(napi_value key) const {
  796. napi_value result;
  797. napi_status status = napi_get_property(_env, _value, key, &result);
  798. NAPI_THROW_IF_FAILED(_env, status, Value());
  799. return Value(_env, result);
  800. }
  801. inline Value Object::Get(Value key) const {
  802. napi_value result;
  803. napi_status status = napi_get_property(_env, _value, key, &result);
  804. NAPI_THROW_IF_FAILED(_env, status, Value());
  805. return Value(_env, result);
  806. }
  807. inline Value Object::Get(const char* utf8name) const {
  808. napi_value result;
  809. napi_status status = napi_get_named_property(_env, _value, utf8name, &result);
  810. NAPI_THROW_IF_FAILED(_env, status, Value());
  811. return Value(_env, result);
  812. }
  813. inline Value Object::Get(const std::string& utf8name) const {
  814. return Get(utf8name.c_str());
  815. }
  816. template <typename ValueType>
  817. inline void Object::Set(napi_value key, const ValueType& value) {
  818. napi_status status =
  819. napi_set_property(_env, _value, key, Value::From(_env, value));
  820. NAPI_THROW_IF_FAILED_VOID(_env, status);
  821. }
  822. template <typename ValueType>
  823. inline void Object::Set(Value key, const ValueType& value) {
  824. napi_status status =
  825. napi_set_property(_env, _value, key, Value::From(_env, value));
  826. NAPI_THROW_IF_FAILED_VOID(_env, status);
  827. }
  828. template <typename ValueType>
  829. inline void Object::Set(const char* utf8name, const ValueType& value) {
  830. napi_status status =
  831. napi_set_named_property(_env, _value, utf8name, Value::From(_env, value));
  832. NAPI_THROW_IF_FAILED_VOID(_env, status);
  833. }
  834. template <typename ValueType>
  835. inline void Object::Set(const std::string& utf8name, const ValueType& value) {
  836. Set(utf8name.c_str(), value);
  837. }
  838. inline bool Object::Delete(napi_value key) {
  839. bool result;
  840. napi_status status = napi_delete_property(_env, _value, key, &result);
  841. NAPI_THROW_IF_FAILED(_env, status, false);
  842. return result;
  843. }
  844. inline bool Object::Delete(Value key) {
  845. bool result;
  846. napi_status status = napi_delete_property(_env, _value, key, &result);
  847. NAPI_THROW_IF_FAILED(_env, status, false);
  848. return result;
  849. }
  850. inline bool Object::Delete(const char* utf8name) {
  851. return Delete(String::New(_env, utf8name));
  852. }
  853. inline bool Object::Delete(const std::string& utf8name) {
  854. return Delete(String::New(_env, utf8name));
  855. }
  856. inline bool Object::Has(uint32_t index) const {
  857. bool result;
  858. napi_status status = napi_has_element(_env, _value, index, &result);
  859. NAPI_THROW_IF_FAILED(_env, status, false);
  860. return result;
  861. }
  862. inline Value Object::Get(uint32_t index) const {
  863. napi_value value;
  864. napi_status status = napi_get_element(_env, _value, index, &value);
  865. NAPI_THROW_IF_FAILED(_env, status, Value());
  866. return Value(_env, value);
  867. }
  868. template <typename ValueType>
  869. inline void Object::Set(uint32_t index, const ValueType& value) {
  870. napi_status status =
  871. napi_set_element(_env, _value, index, Value::From(_env, value));
  872. NAPI_THROW_IF_FAILED_VOID(_env, status);
  873. }
  874. inline bool Object::Delete(uint32_t index) {
  875. bool result;
  876. napi_status status = napi_delete_element(_env, _value, index, &result);
  877. NAPI_THROW_IF_FAILED(_env, status, false);
  878. return result;
  879. }
  880. inline Array Object::GetPropertyNames() {
  881. napi_value result;
  882. napi_status status = napi_get_property_names(_env, _value, &result);
  883. NAPI_THROW_IF_FAILED(_env, status, Array());
  884. return Array(_env, result);
  885. }
  886. inline void Object::DefineProperty(const PropertyDescriptor& property) {
  887. napi_status status = napi_define_properties(_env, _value, 1,
  888. reinterpret_cast<const napi_property_descriptor*>(&property));
  889. NAPI_THROW_IF_FAILED_VOID(_env, status);
  890. }
  891. inline void Object::DefineProperties(const std::initializer_list<PropertyDescriptor>& properties) {
  892. napi_status status = napi_define_properties(_env, _value, properties.size(),
  893. reinterpret_cast<const napi_property_descriptor*>(properties.begin()));
  894. NAPI_THROW_IF_FAILED_VOID(_env, status);
  895. }
  896. inline void Object::DefineProperties(const std::vector<PropertyDescriptor>& properties) {
  897. napi_status status = napi_define_properties(_env, _value, properties.size(),
  898. reinterpret_cast<const napi_property_descriptor*>(properties.data()));
  899. NAPI_THROW_IF_FAILED_VOID(_env, status);
  900. }
  901. inline bool Object::InstanceOf(const Function& constructor) const {
  902. bool result;
  903. napi_status status = napi_instanceof(_env, _value, constructor, &result);
  904. NAPI_THROW_IF_FAILED(_env, status, false);
  905. return result;
  906. }
  907. ////////////////////////////////////////////////////////////////////////////////
  908. // External class
  909. ////////////////////////////////////////////////////////////////////////////////
  910. template <typename T>
  911. inline External<T> External<T>::New(napi_env env, T* data) {
  912. napi_value value;
  913. napi_status status = napi_create_external(env, data, nullptr, nullptr, &value);
  914. NAPI_THROW_IF_FAILED(env, status, External());
  915. return External(env, value);
  916. }
  917. template <typename T>
  918. template <typename Finalizer>
  919. inline External<T> External<T>::New(napi_env env,
  920. T* data,
  921. Finalizer finalizeCallback) {
  922. napi_value value;
  923. details::FinalizeData<T, Finalizer>* finalizeData =
  924. new details::FinalizeData<T, Finalizer>({ finalizeCallback, nullptr });
  925. napi_status status = napi_create_external(
  926. env,
  927. data,
  928. details::FinalizeData<T, Finalizer>::Wrapper,
  929. finalizeData,
  930. &value);
  931. if (status != napi_ok) {
  932. delete finalizeData;
  933. NAPI_THROW_IF_FAILED(env, status, External());
  934. }
  935. return External(env, value);
  936. }
  937. template <typename T>
  938. template <typename Finalizer, typename Hint>
  939. inline External<T> External<T>::New(napi_env env,
  940. T* data,
  941. Finalizer finalizeCallback,
  942. Hint* finalizeHint) {
  943. napi_value value;
  944. details::FinalizeData<T, Finalizer, Hint>* finalizeData =
  945. new details::FinalizeData<T, Finalizer, Hint>({ finalizeCallback, finalizeHint });
  946. napi_status status = napi_create_external(
  947. env,
  948. data,
  949. details::FinalizeData<T, Finalizer, Hint>::WrapperWithHint,
  950. finalizeData,
  951. &value);
  952. if (status != napi_ok) {
  953. delete finalizeData;
  954. NAPI_THROW_IF_FAILED(env, status, External());
  955. }
  956. return External(env, value);
  957. }
  958. template <typename T>
  959. inline External<T>::External() : Value() {
  960. }
  961. template <typename T>
  962. inline External<T>::External(napi_env env, napi_value value) : Value(env, value) {
  963. }
  964. template <typename T>
  965. inline T* External<T>::Data() const {
  966. void* data;
  967. napi_status status = napi_get_value_external(_env, _value, &data);
  968. NAPI_THROW_IF_FAILED(_env, status, nullptr);
  969. return reinterpret_cast<T*>(data);
  970. }
  971. ////////////////////////////////////////////////////////////////////////////////
  972. // Array class
  973. ////////////////////////////////////////////////////////////////////////////////
  974. inline Array Array::New(napi_env env) {
  975. napi_value value;
  976. napi_status status = napi_create_array(env, &value);
  977. NAPI_THROW_IF_FAILED(env, status, Array());
  978. return Array(env, value);
  979. }
  980. inline Array Array::New(napi_env env, size_t length) {
  981. napi_value value;
  982. napi_status status = napi_create_array_with_length(env, length, &value);
  983. NAPI_THROW_IF_FAILED(env, status, Array());
  984. return Array(env, value);
  985. }
  986. inline Array::Array() : Object() {
  987. }
  988. inline Array::Array(napi_env env, napi_value value) : Object(env, value) {
  989. }
  990. inline uint32_t Array::Length() const {
  991. uint32_t result;
  992. napi_status status = napi_get_array_length(_env, _value, &result);
  993. NAPI_THROW_IF_FAILED(_env, status, 0);
  994. return result;
  995. }
  996. ////////////////////////////////////////////////////////////////////////////////
  997. // ArrayBuffer class
  998. ////////////////////////////////////////////////////////////////////////////////
  999. inline ArrayBuffer ArrayBuffer::New(napi_env env, size_t byteLength) {
  1000. napi_value value;
  1001. void* data;
  1002. napi_status status = napi_create_arraybuffer(env, byteLength, &data, &value);
  1003. NAPI_THROW_IF_FAILED(env, status, ArrayBuffer());
  1004. return ArrayBuffer(env, value, data, byteLength);
  1005. }
  1006. inline ArrayBuffer ArrayBuffer::New(napi_env env,
  1007. void* externalData,
  1008. size_t byteLength) {
  1009. napi_value value;
  1010. napi_status status = napi_create_external_arraybuffer(
  1011. env, externalData, byteLength, nullptr, nullptr, &value);
  1012. NAPI_THROW_IF_FAILED(env, status, ArrayBuffer());
  1013. return ArrayBuffer(env, value, externalData, byteLength);
  1014. }
  1015. template <typename Finalizer>
  1016. inline ArrayBuffer ArrayBuffer::New(napi_env env,
  1017. void* externalData,
  1018. size_t byteLength,
  1019. Finalizer finalizeCallback) {
  1020. napi_value value;
  1021. details::FinalizeData<void, Finalizer>* finalizeData =
  1022. new details::FinalizeData<void, Finalizer>({ finalizeCallback, nullptr });
  1023. napi_status status = napi_create_external_arraybuffer(
  1024. env,
  1025. externalData,
  1026. byteLength,
  1027. details::FinalizeData<void, Finalizer>::Wrapper,
  1028. finalizeData,
  1029. &value);
  1030. if (status != napi_ok) {
  1031. delete finalizeData;
  1032. NAPI_THROW_IF_FAILED(env, status, ArrayBuffer());
  1033. }
  1034. return ArrayBuffer(env, value, externalData, byteLength);
  1035. }
  1036. template <typename Finalizer, typename Hint>
  1037. inline ArrayBuffer ArrayBuffer::New(napi_env env,
  1038. void* externalData,
  1039. size_t byteLength,
  1040. Finalizer finalizeCallback,
  1041. Hint* finalizeHint) {
  1042. napi_value value;
  1043. details::FinalizeData<void, Finalizer, Hint>* finalizeData =
  1044. new details::FinalizeData<void, Finalizer, Hint>({ finalizeCallback, finalizeHint });
  1045. napi_status status = napi_create_external_arraybuffer(
  1046. env,
  1047. externalData,
  1048. byteLength,
  1049. details::FinalizeData<void, Finalizer, Hint>::WrapperWithHint,
  1050. finalizeData,
  1051. &value);
  1052. if (status != napi_ok) {
  1053. delete finalizeData;
  1054. NAPI_THROW_IF_FAILED(env, status, ArrayBuffer());
  1055. }
  1056. return ArrayBuffer(env, value, externalData, byteLength);
  1057. }
  1058. inline ArrayBuffer::ArrayBuffer() : Object(), _data(nullptr), _length(0) {
  1059. }
  1060. inline ArrayBuffer::ArrayBuffer(napi_env env, napi_value value)
  1061. : Object(env, value), _data(nullptr), _length(0) {
  1062. }
  1063. inline ArrayBuffer::ArrayBuffer(napi_env env, napi_value value, void* data, size_t length)
  1064. : Object(env, value), _data(data), _length(length) {
  1065. }
  1066. inline void* ArrayBuffer::Data() {
  1067. EnsureInfo();
  1068. return _data;
  1069. }
  1070. inline size_t ArrayBuffer::ByteLength() {
  1071. EnsureInfo();
  1072. return _length;
  1073. }
  1074. inline void ArrayBuffer::EnsureInfo() const {
  1075. // The ArrayBuffer instance may have been constructed from a napi_value whose
  1076. // length/data are not yet known. Fetch and cache these values just once,
  1077. // since they can never change during the lifetime of the ArrayBuffer.
  1078. if (_data == nullptr) {
  1079. napi_status status = napi_get_arraybuffer_info(_env, _value, &_data, &_length);
  1080. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1081. }
  1082. }
  1083. ////////////////////////////////////////////////////////////////////////////////
  1084. // DataView class
  1085. ////////////////////////////////////////////////////////////////////////////////
  1086. inline DataView DataView::New(napi_env env,
  1087. Napi::ArrayBuffer arrayBuffer) {
  1088. return New(env, arrayBuffer, 0, arrayBuffer.ByteLength());
  1089. }
  1090. inline DataView DataView::New(napi_env env,
  1091. Napi::ArrayBuffer arrayBuffer,
  1092. size_t byteOffset) {
  1093. if (byteOffset > arrayBuffer.ByteLength()) {
  1094. NAPI_THROW(RangeError::New(env,
  1095. "Start offset is outside the bounds of the buffer"));
  1096. return DataView();
  1097. }
  1098. return New(env, arrayBuffer, byteOffset,
  1099. arrayBuffer.ByteLength() - byteOffset);
  1100. }
  1101. inline DataView DataView::New(napi_env env,
  1102. Napi::ArrayBuffer arrayBuffer,
  1103. size_t byteOffset,
  1104. size_t byteLength) {
  1105. if (byteOffset + byteLength > arrayBuffer.ByteLength()) {
  1106. NAPI_THROW(RangeError::New(env, "Invalid DataView length"));
  1107. return DataView();
  1108. }
  1109. napi_value value;
  1110. napi_status status = napi_create_dataview(
  1111. env, byteLength, arrayBuffer, byteOffset, &value);
  1112. NAPI_THROW_IF_FAILED(env, status, DataView());
  1113. return DataView(env, value);
  1114. }
  1115. inline DataView::DataView() : Object() {
  1116. }
  1117. inline DataView::DataView(napi_env env, napi_value value) : Object(env, value) {
  1118. napi_status status = napi_get_dataview_info(
  1119. _env,
  1120. _value /* dataView */,
  1121. &_length /* byteLength */,
  1122. &_data /* data */,
  1123. nullptr /* arrayBuffer */,
  1124. nullptr /* byteOffset */);
  1125. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1126. }
  1127. inline Napi::ArrayBuffer DataView::ArrayBuffer() const {
  1128. napi_value arrayBuffer;
  1129. napi_status status = napi_get_dataview_info(
  1130. _env,
  1131. _value /* dataView */,
  1132. nullptr /* byteLength */,
  1133. nullptr /* data */,
  1134. &arrayBuffer /* arrayBuffer */,
  1135. nullptr /* byteOffset */);
  1136. NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer());
  1137. return Napi::ArrayBuffer(_env, arrayBuffer);
  1138. }
  1139. inline size_t DataView::ByteOffset() const {
  1140. size_t byteOffset;
  1141. napi_status status = napi_get_dataview_info(
  1142. _env,
  1143. _value /* dataView */,
  1144. nullptr /* byteLength */,
  1145. nullptr /* data */,
  1146. nullptr /* arrayBuffer */,
  1147. &byteOffset /* byteOffset */);
  1148. NAPI_THROW_IF_FAILED(_env, status, 0);
  1149. return byteOffset;
  1150. }
  1151. inline size_t DataView::ByteLength() const {
  1152. return _length;
  1153. }
  1154. inline void* DataView::Data() const {
  1155. return _data;
  1156. }
  1157. inline float DataView::GetFloat32(size_t byteOffset) const {
  1158. return ReadData<float>(byteOffset);
  1159. }
  1160. inline double DataView::GetFloat64(size_t byteOffset) const {
  1161. return ReadData<double>(byteOffset);
  1162. }
  1163. inline int8_t DataView::GetInt8(size_t byteOffset) const {
  1164. return ReadData<int8_t>(byteOffset);
  1165. }
  1166. inline int16_t DataView::GetInt16(size_t byteOffset) const {
  1167. return ReadData<int16_t>(byteOffset);
  1168. }
  1169. inline int32_t DataView::GetInt32(size_t byteOffset) const {
  1170. return ReadData<int32_t>(byteOffset);
  1171. }
  1172. inline uint8_t DataView::GetUint8(size_t byteOffset) const {
  1173. return ReadData<uint8_t>(byteOffset);
  1174. }
  1175. inline uint16_t DataView::GetUint16(size_t byteOffset) const {
  1176. return ReadData<uint16_t>(byteOffset);
  1177. }
  1178. inline uint32_t DataView::GetUint32(size_t byteOffset) const {
  1179. return ReadData<uint32_t>(byteOffset);
  1180. }
  1181. inline void DataView::SetFloat32(size_t byteOffset, float value) const {
  1182. WriteData<float>(byteOffset, value);
  1183. }
  1184. inline void DataView::SetFloat64(size_t byteOffset, double value) const {
  1185. WriteData<double>(byteOffset, value);
  1186. }
  1187. inline void DataView::SetInt8(size_t byteOffset, int8_t value) const {
  1188. WriteData<int8_t>(byteOffset, value);
  1189. }
  1190. inline void DataView::SetInt16(size_t byteOffset, int16_t value) const {
  1191. WriteData<int16_t>(byteOffset, value);
  1192. }
  1193. inline void DataView::SetInt32(size_t byteOffset, int32_t value) const {
  1194. WriteData<int32_t>(byteOffset, value);
  1195. }
  1196. inline void DataView::SetUint8(size_t byteOffset, uint8_t value) const {
  1197. WriteData<uint8_t>(byteOffset, value);
  1198. }
  1199. inline void DataView::SetUint16(size_t byteOffset, uint16_t value) const {
  1200. WriteData<uint16_t>(byteOffset, value);
  1201. }
  1202. inline void DataView::SetUint32(size_t byteOffset, uint32_t value) const {
  1203. WriteData<uint32_t>(byteOffset, value);
  1204. }
  1205. template <typename T>
  1206. inline T DataView::ReadData(size_t byteOffset) const {
  1207. if (byteOffset + sizeof(T) > _length ||
  1208. byteOffset + sizeof(T) < byteOffset) { // overflow
  1209. NAPI_THROW(RangeError::New(_env,
  1210. "Offset is outside the bounds of the DataView"));
  1211. return 0;
  1212. }
  1213. return *reinterpret_cast<T*>(static_cast<uint8_t*>(_data) + byteOffset);
  1214. }
  1215. template <typename T>
  1216. inline void DataView::WriteData(size_t byteOffset, T value) const {
  1217. if (byteOffset + sizeof(T) > _length ||
  1218. byteOffset + sizeof(T) < byteOffset) { // overflow
  1219. NAPI_THROW(RangeError::New(_env,
  1220. "Offset is outside the bounds of the DataView"));
  1221. return;
  1222. }
  1223. *reinterpret_cast<T*>(static_cast<uint8_t*>(_data) + byteOffset) = value;
  1224. }
  1225. ////////////////////////////////////////////////////////////////////////////////
  1226. // TypedArray class
  1227. ////////////////////////////////////////////////////////////////////////////////
  1228. inline TypedArray::TypedArray()
  1229. : Object(), _type(TypedArray::unknown_array_type), _length(0) {
  1230. }
  1231. inline TypedArray::TypedArray(napi_env env, napi_value value)
  1232. : Object(env, value), _type(TypedArray::unknown_array_type), _length(0) {
  1233. }
  1234. inline TypedArray::TypedArray(napi_env env,
  1235. napi_value value,
  1236. napi_typedarray_type type,
  1237. size_t length)
  1238. : Object(env, value), _type(type), _length(length) {
  1239. }
  1240. inline napi_typedarray_type TypedArray::TypedArrayType() const {
  1241. if (_type == TypedArray::unknown_array_type) {
  1242. napi_status status = napi_get_typedarray_info(_env, _value,
  1243. &const_cast<TypedArray*>(this)->_type, &const_cast<TypedArray*>(this)->_length,
  1244. nullptr, nullptr, nullptr);
  1245. NAPI_THROW_IF_FAILED(_env, status, napi_int8_array);
  1246. }
  1247. return _type;
  1248. }
  1249. inline uint8_t TypedArray::ElementSize() const {
  1250. switch (TypedArrayType()) {
  1251. case napi_int8_array:
  1252. case napi_uint8_array:
  1253. case napi_uint8_clamped_array:
  1254. return 1;
  1255. case napi_int16_array:
  1256. case napi_uint16_array:
  1257. return 2;
  1258. case napi_int32_array:
  1259. case napi_uint32_array:
  1260. case napi_float32_array:
  1261. return 4;
  1262. case napi_float64_array:
  1263. return 8;
  1264. default:
  1265. return 0;
  1266. }
  1267. }
  1268. inline size_t TypedArray::ElementLength() const {
  1269. if (_type == TypedArray::unknown_array_type) {
  1270. napi_status status = napi_get_typedarray_info(_env, _value,
  1271. &const_cast<TypedArray*>(this)->_type, &const_cast<TypedArray*>(this)->_length,
  1272. nullptr, nullptr, nullptr);
  1273. NAPI_THROW_IF_FAILED(_env, status, 0);
  1274. }
  1275. return _length;
  1276. }
  1277. inline size_t TypedArray::ByteOffset() const {
  1278. size_t byteOffset;
  1279. napi_status status = napi_get_typedarray_info(
  1280. _env, _value, nullptr, nullptr, nullptr, nullptr, &byteOffset);
  1281. NAPI_THROW_IF_FAILED(_env, status, 0);
  1282. return byteOffset;
  1283. }
  1284. inline size_t TypedArray::ByteLength() const {
  1285. return ElementSize() * ElementLength();
  1286. }
  1287. inline Napi::ArrayBuffer TypedArray::ArrayBuffer() const {
  1288. napi_value arrayBuffer;
  1289. napi_status status = napi_get_typedarray_info(
  1290. _env, _value, nullptr, nullptr, nullptr, &arrayBuffer, nullptr);
  1291. NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer());
  1292. return Napi::ArrayBuffer(_env, arrayBuffer);
  1293. }
  1294. ////////////////////////////////////////////////////////////////////////////////
  1295. // TypedArrayOf<T> class
  1296. ////////////////////////////////////////////////////////////////////////////////
  1297. template <typename T>
  1298. inline TypedArrayOf<T> TypedArrayOf<T>::New(napi_env env,
  1299. size_t elementLength,
  1300. napi_typedarray_type type) {
  1301. Napi::ArrayBuffer arrayBuffer = Napi::ArrayBuffer::New(env, elementLength * sizeof (T));
  1302. return New(env, elementLength, arrayBuffer, 0, type);
  1303. }
  1304. template <typename T>
  1305. inline TypedArrayOf<T> TypedArrayOf<T>::New(napi_env env,
  1306. size_t elementLength,
  1307. Napi::ArrayBuffer arrayBuffer,
  1308. size_t bufferOffset,
  1309. napi_typedarray_type type) {
  1310. napi_value value;
  1311. napi_status status = napi_create_typedarray(
  1312. env, type, elementLength, arrayBuffer, bufferOffset, &value);
  1313. NAPI_THROW_IF_FAILED(env, status, TypedArrayOf<T>());
  1314. return TypedArrayOf<T>(
  1315. env, value, type, elementLength,
  1316. reinterpret_cast<T*>(reinterpret_cast<uint8_t*>(arrayBuffer.Data()) + bufferOffset));
  1317. }
  1318. template <typename T>
  1319. inline TypedArrayOf<T>::TypedArrayOf() : TypedArray(), _data(nullptr) {
  1320. }
  1321. template <typename T>
  1322. inline TypedArrayOf<T>::TypedArrayOf(napi_env env, napi_value value)
  1323. : TypedArray(env, value), _data(nullptr) {
  1324. napi_status status = napi_get_typedarray_info(
  1325. _env, _value, &_type, &_length, reinterpret_cast<void**>(&_data), nullptr, nullptr);
  1326. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1327. }
  1328. template <typename T>
  1329. inline TypedArrayOf<T>::TypedArrayOf(napi_env env,
  1330. napi_value value,
  1331. napi_typedarray_type type,
  1332. size_t length,
  1333. T* data)
  1334. : TypedArray(env, value, type, length), _data(data) {
  1335. if (!(type == TypedArrayTypeForPrimitiveType<T>() ||
  1336. (type == napi_uint8_clamped_array && std::is_same<T, uint8_t>::value))) {
  1337. NAPI_THROW(TypeError::New(env, "Array type must match the template parameter. "
  1338. "(Uint8 arrays may optionally have the \"clamped\" array type.)"));
  1339. }
  1340. }
  1341. template <typename T>
  1342. inline T& TypedArrayOf<T>::operator [](size_t index) {
  1343. return _data[index];
  1344. }
  1345. template <typename T>
  1346. inline const T& TypedArrayOf<T>::operator [](size_t index) const {
  1347. return _data[index];
  1348. }
  1349. template <typename T>
  1350. inline T* TypedArrayOf<T>::Data() {
  1351. return _data;
  1352. }
  1353. template <typename T>
  1354. inline const T* TypedArrayOf<T>::Data() const {
  1355. return _data;
  1356. }
  1357. ////////////////////////////////////////////////////////////////////////////////
  1358. // Function class
  1359. ////////////////////////////////////////////////////////////////////////////////
  1360. template <typename CbData>
  1361. static inline napi_status
  1362. CreateFunction(napi_env env,
  1363. const char* utf8name,
  1364. napi_callback cb,
  1365. CbData* data,
  1366. napi_value* result) {
  1367. napi_status status =
  1368. napi_create_function(env, utf8name, NAPI_AUTO_LENGTH, cb, data, result);
  1369. if (status == napi_ok) {
  1370. status = Napi::details::AttachData(env, *result, data);
  1371. }
  1372. return status;
  1373. }
  1374. template <typename Callable>
  1375. inline Function Function::New(napi_env env,
  1376. Callable cb,
  1377. const char* utf8name,
  1378. void* data) {
  1379. typedef decltype(cb(CallbackInfo(nullptr, nullptr))) ReturnType;
  1380. typedef details::CallbackData<Callable, ReturnType> CbData;
  1381. auto callbackData = new CbData({ cb, data });
  1382. napi_value value;
  1383. napi_status status = CreateFunction(env,
  1384. utf8name,
  1385. CbData::Wrapper,
  1386. callbackData,
  1387. &value);
  1388. NAPI_THROW_IF_FAILED(env, status, Function());
  1389. return Function(env, value);
  1390. }
  1391. template <typename Callable>
  1392. inline Function Function::New(napi_env env,
  1393. Callable cb,
  1394. const std::string& utf8name,
  1395. void* data) {
  1396. return New(env, cb, utf8name.c_str(), data);
  1397. }
  1398. inline Function::Function() : Object() {
  1399. }
  1400. inline Function::Function(napi_env env, napi_value value) : Object(env, value) {
  1401. }
  1402. inline Value Function::operator ()(const std::initializer_list<napi_value>& args) const {
  1403. return Call(Env().Undefined(), args);
  1404. }
  1405. inline Value Function::Call(const std::initializer_list<napi_value>& args) const {
  1406. return Call(Env().Undefined(), args);
  1407. }
  1408. inline Value Function::Call(const std::vector<napi_value>& args) const {
  1409. return Call(Env().Undefined(), args);
  1410. }
  1411. inline Value Function::Call(size_t argc, const napi_value* args) const {
  1412. return Call(Env().Undefined(), argc, args);
  1413. }
  1414. inline Value Function::Call(napi_value recv, const std::initializer_list<napi_value>& args) const {
  1415. return Call(recv, args.size(), args.begin());
  1416. }
  1417. inline Value Function::Call(napi_value recv, const std::vector<napi_value>& args) const {
  1418. return Call(recv, args.size(), args.data());
  1419. }
  1420. inline Value Function::Call(napi_value recv, size_t argc, const napi_value* args) const {
  1421. napi_value result;
  1422. napi_status status = napi_call_function(
  1423. _env, recv, _value, argc, args, &result);
  1424. NAPI_THROW_IF_FAILED(_env, status, Value());
  1425. return Value(_env, result);
  1426. }
  1427. inline Value Function::MakeCallback(
  1428. napi_value recv,
  1429. const std::initializer_list<napi_value>& args,
  1430. napi_async_context context) const {
  1431. return MakeCallback(recv, args.size(), args.begin(), context);
  1432. }
  1433. inline Value Function::MakeCallback(
  1434. napi_value recv,
  1435. const std::vector<napi_value>& args,
  1436. napi_async_context context) const {
  1437. return MakeCallback(recv, args.size(), args.data(), context);
  1438. }
  1439. inline Value Function::MakeCallback(
  1440. napi_value recv,
  1441. size_t argc,
  1442. const napi_value* args,
  1443. napi_async_context context) const {
  1444. napi_value result;
  1445. napi_status status = napi_make_callback(
  1446. _env, context, recv, _value, argc, args, &result);
  1447. NAPI_THROW_IF_FAILED(_env, status, Value());
  1448. return Value(_env, result);
  1449. }
  1450. inline Object Function::New(const std::initializer_list<napi_value>& args) const {
  1451. return New(args.size(), args.begin());
  1452. }
  1453. inline Object Function::New(const std::vector<napi_value>& args) const {
  1454. return New(args.size(), args.data());
  1455. }
  1456. inline Object Function::New(size_t argc, const napi_value* args) const {
  1457. napi_value result;
  1458. napi_status status = napi_new_instance(
  1459. _env, _value, argc, args, &result);
  1460. NAPI_THROW_IF_FAILED(_env, status, Object());
  1461. return Object(_env, result);
  1462. }
  1463. ////////////////////////////////////////////////////////////////////////////////
  1464. // Promise class
  1465. ////////////////////////////////////////////////////////////////////////////////
  1466. inline Promise::Deferred Promise::Deferred::New(napi_env env) {
  1467. return Promise::Deferred(env);
  1468. }
  1469. inline Promise::Deferred::Deferred(napi_env env) : _env(env) {
  1470. napi_status status = napi_create_promise(_env, &_deferred, &_promise);
  1471. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1472. }
  1473. inline Promise Promise::Deferred::Promise() const {
  1474. return Napi::Promise(_env, _promise);
  1475. }
  1476. inline Napi::Env Promise::Deferred::Env() const {
  1477. return Napi::Env(_env);
  1478. }
  1479. inline void Promise::Deferred::Resolve(napi_value value) const {
  1480. napi_status status = napi_resolve_deferred(_env, _deferred, value);
  1481. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1482. }
  1483. inline void Promise::Deferred::Reject(napi_value value) const {
  1484. napi_status status = napi_reject_deferred(_env, _deferred, value);
  1485. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1486. }
  1487. inline Promise::Promise(napi_env env, napi_value value) : Object(env, value) {
  1488. }
  1489. ////////////////////////////////////////////////////////////////////////////////
  1490. // Buffer<T> class
  1491. ////////////////////////////////////////////////////////////////////////////////
  1492. template <typename T>
  1493. inline Buffer<T> Buffer<T>::New(napi_env env, size_t length) {
  1494. napi_value value;
  1495. void* data;
  1496. napi_status status = napi_create_buffer(env, length * sizeof (T), &data, &value);
  1497. NAPI_THROW_IF_FAILED(env, status, Buffer<T>());
  1498. return Buffer(env, value, length, static_cast<T*>(data));
  1499. }
  1500. template <typename T>
  1501. inline Buffer<T> Buffer<T>::New(napi_env env, T* data, size_t length) {
  1502. napi_value value;
  1503. napi_status status = napi_create_external_buffer(
  1504. env, length * sizeof (T), data, nullptr, nullptr, &value);
  1505. NAPI_THROW_IF_FAILED(env, status, Buffer<T>());
  1506. return Buffer(env, value, length, data);
  1507. }
  1508. template <typename T>
  1509. template <typename Finalizer>
  1510. inline Buffer<T> Buffer<T>::New(napi_env env,
  1511. T* data,
  1512. size_t length,
  1513. Finalizer finalizeCallback) {
  1514. napi_value value;
  1515. details::FinalizeData<T, Finalizer>* finalizeData =
  1516. new details::FinalizeData<T, Finalizer>({ finalizeCallback, nullptr });
  1517. napi_status status = napi_create_external_buffer(
  1518. env,
  1519. length * sizeof (T),
  1520. data,
  1521. details::FinalizeData<T, Finalizer>::Wrapper,
  1522. finalizeData,
  1523. &value);
  1524. if (status != napi_ok) {
  1525. delete finalizeData;
  1526. NAPI_THROW_IF_FAILED(env, status, Buffer());
  1527. }
  1528. return Buffer(env, value, length, data);
  1529. }
  1530. template <typename T>
  1531. template <typename Finalizer, typename Hint>
  1532. inline Buffer<T> Buffer<T>::New(napi_env env,
  1533. T* data,
  1534. size_t length,
  1535. Finalizer finalizeCallback,
  1536. Hint* finalizeHint) {
  1537. napi_value value;
  1538. details::FinalizeData<T, Finalizer, Hint>* finalizeData =
  1539. new details::FinalizeData<T, Finalizer, Hint>({ finalizeCallback, finalizeHint });
  1540. napi_status status = napi_create_external_buffer(
  1541. env,
  1542. length * sizeof (T),
  1543. data,
  1544. details::FinalizeData<T, Finalizer, Hint>::WrapperWithHint,
  1545. finalizeData,
  1546. &value);
  1547. if (status != napi_ok) {
  1548. delete finalizeData;
  1549. NAPI_THROW_IF_FAILED(env, status, Buffer());
  1550. }
  1551. return Buffer(env, value, length, data);
  1552. }
  1553. template <typename T>
  1554. inline Buffer<T> Buffer<T>::Copy(napi_env env, const T* data, size_t length) {
  1555. napi_value value;
  1556. napi_status status = napi_create_buffer_copy(
  1557. env, length * sizeof (T), data, nullptr, &value);
  1558. NAPI_THROW_IF_FAILED(env, status, Buffer<T>());
  1559. return Buffer<T>(env, value);
  1560. }
  1561. template <typename T>
  1562. inline Buffer<T>::Buffer() : Uint8Array(), _length(0), _data(nullptr) {
  1563. }
  1564. template <typename T>
  1565. inline Buffer<T>::Buffer(napi_env env, napi_value value)
  1566. : Uint8Array(env, value), _length(0), _data(nullptr) {
  1567. }
  1568. template <typename T>
  1569. inline Buffer<T>::Buffer(napi_env env, napi_value value, size_t length, T* data)
  1570. : Uint8Array(env, value), _length(length), _data(data) {
  1571. }
  1572. template <typename T>
  1573. inline size_t Buffer<T>::Length() const {
  1574. EnsureInfo();
  1575. return _length;
  1576. }
  1577. template <typename T>
  1578. inline T* Buffer<T>::Data() const {
  1579. EnsureInfo();
  1580. return _data;
  1581. }
  1582. template <typename T>
  1583. inline void Buffer<T>::EnsureInfo() const {
  1584. // The Buffer instance may have been constructed from a napi_value whose
  1585. // length/data are not yet known. Fetch and cache these values just once,
  1586. // since they can never change during the lifetime of the Buffer.
  1587. if (_data == nullptr) {
  1588. size_t byteLength;
  1589. void* voidData;
  1590. napi_status status = napi_get_buffer_info(_env, _value, &voidData, &byteLength);
  1591. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1592. _length = byteLength / sizeof (T);
  1593. _data = static_cast<T*>(voidData);
  1594. }
  1595. }
  1596. ////////////////////////////////////////////////////////////////////////////////
  1597. // Error class
  1598. ////////////////////////////////////////////////////////////////////////////////
  1599. inline Error Error::New(napi_env env) {
  1600. napi_status status;
  1601. napi_value error = nullptr;
  1602. const napi_extended_error_info* info;
  1603. status = napi_get_last_error_info(env, &info);
  1604. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_last_error_info");
  1605. if (status == napi_ok) {
  1606. if (info->error_code == napi_pending_exception) {
  1607. status = napi_get_and_clear_last_exception(env, &error);
  1608. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_and_clear_last_exception");
  1609. }
  1610. else {
  1611. const char* error_message = info->error_message != nullptr ?
  1612. info->error_message : "Error in native callback";
  1613. bool isExceptionPending;
  1614. status = napi_is_exception_pending(env, &isExceptionPending);
  1615. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_is_exception_pending");
  1616. if (isExceptionPending) {
  1617. status = napi_get_and_clear_last_exception(env, &error);
  1618. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_and_clear_last_exception");
  1619. }
  1620. napi_value message;
  1621. status = napi_create_string_utf8(
  1622. env,
  1623. error_message,
  1624. std::strlen(error_message),
  1625. &message);
  1626. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_string_utf8");
  1627. if (status == napi_ok) {
  1628. switch (info->error_code) {
  1629. case napi_object_expected:
  1630. case napi_string_expected:
  1631. case napi_boolean_expected:
  1632. case napi_number_expected:
  1633. status = napi_create_type_error(env, nullptr, message, &error);
  1634. break;
  1635. default:
  1636. status = napi_create_error(env, nullptr, message, &error);
  1637. break;
  1638. }
  1639. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_error");
  1640. }
  1641. }
  1642. }
  1643. return Error(env, error);
  1644. }
  1645. inline Error Error::New(napi_env env, const char* message) {
  1646. return Error::New<Error>(env, message, std::strlen(message), napi_create_error);
  1647. }
  1648. inline Error Error::New(napi_env env, const std::string& message) {
  1649. return Error::New<Error>(env, message.c_str(), message.size(), napi_create_error);
  1650. }
  1651. inline NAPI_NO_RETURN void Error::Fatal(const char* location, const char* message) {
  1652. napi_fatal_error(location, NAPI_AUTO_LENGTH, message, NAPI_AUTO_LENGTH);
  1653. }
  1654. inline Error::Error() : ObjectReference() {
  1655. }
  1656. inline Error::Error(napi_env env, napi_value value) : ObjectReference(env, nullptr) {
  1657. if (value != nullptr) {
  1658. napi_status status = napi_create_reference(env, value, 1, &_ref);
  1659. // Avoid infinite recursion in the failure case.
  1660. // Don't try to construct & throw another Error instance.
  1661. NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_reference");
  1662. }
  1663. }
  1664. inline Error::Error(Error&& other) : ObjectReference(std::move(other)) {
  1665. }
  1666. inline Error& Error::operator =(Error&& other) {
  1667. static_cast<Reference<Object>*>(this)->operator=(std::move(other));
  1668. return *this;
  1669. }
  1670. inline Error::Error(const Error& other) : ObjectReference(other) {
  1671. }
  1672. inline Error& Error::operator =(Error& other) {
  1673. Reset();
  1674. _env = other.Env();
  1675. HandleScope scope(_env);
  1676. napi_value value = other.Value();
  1677. if (value != nullptr) {
  1678. napi_status status = napi_create_reference(_env, value, 1, &_ref);
  1679. NAPI_THROW_IF_FAILED(_env, status, *this);
  1680. }
  1681. return *this;
  1682. }
  1683. inline const std::string& Error::Message() const NAPI_NOEXCEPT {
  1684. if (_message.size() == 0 && _env != nullptr) {
  1685. #ifdef NAPI_CPP_EXCEPTIONS
  1686. try {
  1687. _message = Get("message").As<String>();
  1688. }
  1689. catch (...) {
  1690. // Catch all errors here, to include e.g. a std::bad_alloc from
  1691. // the std::string::operator=, because this method may not throw.
  1692. }
  1693. #else // NAPI_CPP_EXCEPTIONS
  1694. _message = Get("message").As<String>();
  1695. #endif // NAPI_CPP_EXCEPTIONS
  1696. }
  1697. return _message;
  1698. }
  1699. inline void Error::ThrowAsJavaScriptException() const {
  1700. HandleScope scope(_env);
  1701. if (!IsEmpty()) {
  1702. napi_status status = napi_throw(_env, Value());
  1703. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1704. }
  1705. }
  1706. #ifdef NAPI_CPP_EXCEPTIONS
  1707. inline const char* Error::what() const NAPI_NOEXCEPT {
  1708. return Message().c_str();
  1709. }
  1710. #endif // NAPI_CPP_EXCEPTIONS
  1711. template <typename TError>
  1712. inline TError Error::New(napi_env env,
  1713. const char* message,
  1714. size_t length,
  1715. create_error_fn create_error) {
  1716. napi_value str;
  1717. napi_status status = napi_create_string_utf8(env, message, length, &str);
  1718. NAPI_THROW_IF_FAILED(env, status, TError());
  1719. napi_value error;
  1720. status = create_error(env, nullptr, str, &error);
  1721. NAPI_THROW_IF_FAILED(env, status, TError());
  1722. return TError(env, error);
  1723. }
  1724. inline TypeError TypeError::New(napi_env env, const char* message) {
  1725. return Error::New<TypeError>(env, message, std::strlen(message), napi_create_type_error);
  1726. }
  1727. inline TypeError TypeError::New(napi_env env, const std::string& message) {
  1728. return Error::New<TypeError>(env, message.c_str(), message.size(), napi_create_type_error);
  1729. }
  1730. inline TypeError::TypeError() : Error() {
  1731. }
  1732. inline TypeError::TypeError(napi_env env, napi_value value) : Error(env, value) {
  1733. }
  1734. inline RangeError RangeError::New(napi_env env, const char* message) {
  1735. return Error::New<RangeError>(env, message, std::strlen(message), napi_create_range_error);
  1736. }
  1737. inline RangeError RangeError::New(napi_env env, const std::string& message) {
  1738. return Error::New<RangeError>(env, message.c_str(), message.size(), napi_create_range_error);
  1739. }
  1740. inline RangeError::RangeError() : Error() {
  1741. }
  1742. inline RangeError::RangeError(napi_env env, napi_value value) : Error(env, value) {
  1743. }
  1744. ////////////////////////////////////////////////////////////////////////////////
  1745. // Reference<T> class
  1746. ////////////////////////////////////////////////////////////////////////////////
  1747. template <typename T>
  1748. inline Reference<T> Reference<T>::New(const T& value, uint32_t initialRefcount) {
  1749. napi_env env = value.Env();
  1750. napi_value val = value;
  1751. if (val == nullptr) {
  1752. return Reference<T>(env, nullptr);
  1753. }
  1754. napi_ref ref;
  1755. napi_status status = napi_create_reference(env, value, initialRefcount, &ref);
  1756. NAPI_THROW_IF_FAILED(env, status, Reference<T>());
  1757. return Reference<T>(env, ref);
  1758. }
  1759. template <typename T>
  1760. inline Reference<T>::Reference() : _env(nullptr), _ref(nullptr), _suppressDestruct(false) {
  1761. }
  1762. template <typename T>
  1763. inline Reference<T>::Reference(napi_env env, napi_ref ref)
  1764. : _env(env), _ref(ref), _suppressDestruct(false) {
  1765. }
  1766. template <typename T>
  1767. inline Reference<T>::~Reference() {
  1768. if (_ref != nullptr) {
  1769. if (!_suppressDestruct) {
  1770. napi_delete_reference(_env, _ref);
  1771. }
  1772. _ref = nullptr;
  1773. }
  1774. }
  1775. template <typename T>
  1776. inline Reference<T>::Reference(Reference<T>&& other)
  1777. : _env(other._env), _ref(other._ref), _suppressDestruct(other._suppressDestruct) {
  1778. other._env = nullptr;
  1779. other._ref = nullptr;
  1780. other._suppressDestruct = false;
  1781. }
  1782. template <typename T>
  1783. inline Reference<T>& Reference<T>::operator =(Reference<T>&& other) {
  1784. Reset();
  1785. _env = other._env;
  1786. _ref = other._ref;
  1787. _suppressDestruct = other._suppressDestruct;
  1788. other._env = nullptr;
  1789. other._ref = nullptr;
  1790. other._suppressDestruct = false;
  1791. return *this;
  1792. }
  1793. template <typename T>
  1794. inline Reference<T>::Reference(const Reference<T>& other)
  1795. : _env(other._env), _ref(nullptr), _suppressDestruct(false) {
  1796. HandleScope scope(_env);
  1797. napi_value value = other.Value();
  1798. if (value != nullptr) {
  1799. // Copying is a limited scenario (currently only used for Error object) and always creates a
  1800. // strong reference to the given value even if the incoming reference is weak.
  1801. napi_status status = napi_create_reference(_env, value, 1, &_ref);
  1802. NAPI_FATAL_IF_FAILED(status, "Reference<T>::Reference", "napi_create_reference");
  1803. }
  1804. }
  1805. template <typename T>
  1806. inline Reference<T>::operator napi_ref() const {
  1807. return _ref;
  1808. }
  1809. template <typename T>
  1810. inline bool Reference<T>::operator ==(const Reference<T> &other) const {
  1811. HandleScope scope(_env);
  1812. return this->Value().StrictEquals(other.Value());
  1813. }
  1814. template <typename T>
  1815. inline bool Reference<T>::operator !=(const Reference<T> &other) const {
  1816. return !this->operator ==(other);
  1817. }
  1818. template <typename T>
  1819. inline Napi::Env Reference<T>::Env() const {
  1820. return Napi::Env(_env);
  1821. }
  1822. template <typename T>
  1823. inline bool Reference<T>::IsEmpty() const {
  1824. return _ref == nullptr;
  1825. }
  1826. template <typename T>
  1827. inline T Reference<T>::Value() const {
  1828. if (_ref == nullptr) {
  1829. return T(_env, nullptr);
  1830. }
  1831. napi_value value;
  1832. napi_status status = napi_get_reference_value(_env, _ref, &value);
  1833. NAPI_THROW_IF_FAILED(_env, status, T());
  1834. return T(_env, value);
  1835. }
  1836. template <typename T>
  1837. inline uint32_t Reference<T>::Ref() {
  1838. uint32_t result;
  1839. napi_status status = napi_reference_ref(_env, _ref, &result);
  1840. NAPI_THROW_IF_FAILED(_env, status, 1);
  1841. return result;
  1842. }
  1843. template <typename T>
  1844. inline uint32_t Reference<T>::Unref() {
  1845. uint32_t result;
  1846. napi_status status = napi_reference_unref(_env, _ref, &result);
  1847. NAPI_THROW_IF_FAILED(_env, status, 1);
  1848. return result;
  1849. }
  1850. template <typename T>
  1851. inline void Reference<T>::Reset() {
  1852. if (_ref != nullptr) {
  1853. napi_status status = napi_delete_reference(_env, _ref);
  1854. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1855. _ref = nullptr;
  1856. }
  1857. }
  1858. template <typename T>
  1859. inline void Reference<T>::Reset(const T& value, uint32_t refcount) {
  1860. Reset();
  1861. _env = value.Env();
  1862. napi_value val = value;
  1863. if (val != nullptr) {
  1864. napi_status status = napi_create_reference(_env, value, refcount, &_ref);
  1865. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1866. }
  1867. }
  1868. template <typename T>
  1869. inline void Reference<T>::SuppressDestruct() {
  1870. _suppressDestruct = true;
  1871. }
  1872. template <typename T>
  1873. inline Reference<T> Weak(T value) {
  1874. return Reference<T>::New(value, 0);
  1875. }
  1876. inline ObjectReference Weak(Object value) {
  1877. return Reference<Object>::New(value, 0);
  1878. }
  1879. inline FunctionReference Weak(Function value) {
  1880. return Reference<Function>::New(value, 0);
  1881. }
  1882. template <typename T>
  1883. inline Reference<T> Persistent(T value) {
  1884. return Reference<T>::New(value, 1);
  1885. }
  1886. inline ObjectReference Persistent(Object value) {
  1887. return Reference<Object>::New(value, 1);
  1888. }
  1889. inline FunctionReference Persistent(Function value) {
  1890. return Reference<Function>::New(value, 1);
  1891. }
  1892. ////////////////////////////////////////////////////////////////////////////////
  1893. // ObjectReference class
  1894. ////////////////////////////////////////////////////////////////////////////////
  1895. inline ObjectReference::ObjectReference(): Reference<Object>() {
  1896. }
  1897. inline ObjectReference::ObjectReference(napi_env env, napi_ref ref): Reference<Object>(env, ref) {
  1898. }
  1899. inline ObjectReference::ObjectReference(Reference<Object>&& other)
  1900. : Reference<Object>(std::move(other)) {
  1901. }
  1902. inline ObjectReference& ObjectReference::operator =(Reference<Object>&& other) {
  1903. static_cast<Reference<Object>*>(this)->operator=(std::move(other));
  1904. return *this;
  1905. }
  1906. inline ObjectReference::ObjectReference(ObjectReference&& other)
  1907. : Reference<Object>(std::move(other)) {
  1908. }
  1909. inline ObjectReference& ObjectReference::operator =(ObjectReference&& other) {
  1910. static_cast<Reference<Object>*>(this)->operator=(std::move(other));
  1911. return *this;
  1912. }
  1913. inline ObjectReference::ObjectReference(const ObjectReference& other)
  1914. : Reference<Object>(other) {
  1915. }
  1916. inline Napi::Value ObjectReference::Get(const char* utf8name) const {
  1917. EscapableHandleScope scope(_env);
  1918. return scope.Escape(Value().Get(utf8name));
  1919. }
  1920. inline Napi::Value ObjectReference::Get(const std::string& utf8name) const {
  1921. EscapableHandleScope scope(_env);
  1922. return scope.Escape(Value().Get(utf8name));
  1923. }
  1924. inline void ObjectReference::Set(const char* utf8name, napi_value value) {
  1925. HandleScope scope(_env);
  1926. Value().Set(utf8name, value);
  1927. }
  1928. inline void ObjectReference::Set(const char* utf8name, Napi::Value value) {
  1929. HandleScope scope(_env);
  1930. Value().Set(utf8name, value);
  1931. }
  1932. inline void ObjectReference::Set(const char* utf8name, const char* utf8value) {
  1933. HandleScope scope(_env);
  1934. Value().Set(utf8name, utf8value);
  1935. }
  1936. inline void ObjectReference::Set(const char* utf8name, bool boolValue) {
  1937. HandleScope scope(_env);
  1938. Value().Set(utf8name, boolValue);
  1939. }
  1940. inline void ObjectReference::Set(const char* utf8name, double numberValue) {
  1941. HandleScope scope(_env);
  1942. Value().Set(utf8name, numberValue);
  1943. }
  1944. inline void ObjectReference::Set(const std::string& utf8name, napi_value value) {
  1945. HandleScope scope(_env);
  1946. Value().Set(utf8name, value);
  1947. }
  1948. inline void ObjectReference::Set(const std::string& utf8name, Napi::Value value) {
  1949. HandleScope scope(_env);
  1950. Value().Set(utf8name, value);
  1951. }
  1952. inline void ObjectReference::Set(const std::string& utf8name, std::string& utf8value) {
  1953. HandleScope scope(_env);
  1954. Value().Set(utf8name, utf8value);
  1955. }
  1956. inline void ObjectReference::Set(const std::string& utf8name, bool boolValue) {
  1957. HandleScope scope(_env);
  1958. Value().Set(utf8name, boolValue);
  1959. }
  1960. inline void ObjectReference::Set(const std::string& utf8name, double numberValue) {
  1961. HandleScope scope(_env);
  1962. Value().Set(utf8name, numberValue);
  1963. }
  1964. inline Napi::Value ObjectReference::Get(uint32_t index) const {
  1965. EscapableHandleScope scope(_env);
  1966. return scope.Escape(Value().Get(index));
  1967. }
  1968. inline void ObjectReference::Set(uint32_t index, napi_value value) {
  1969. HandleScope scope(_env);
  1970. Value().Set(index, value);
  1971. }
  1972. inline void ObjectReference::Set(uint32_t index, Napi::Value value) {
  1973. HandleScope scope(_env);
  1974. Value().Set(index, value);
  1975. }
  1976. inline void ObjectReference::Set(uint32_t index, const char* utf8value) {
  1977. HandleScope scope(_env);
  1978. Value().Set(index, utf8value);
  1979. }
  1980. inline void ObjectReference::Set(uint32_t index, const std::string& utf8value) {
  1981. HandleScope scope(_env);
  1982. Value().Set(index, utf8value);
  1983. }
  1984. inline void ObjectReference::Set(uint32_t index, bool boolValue) {
  1985. HandleScope scope(_env);
  1986. Value().Set(index, boolValue);
  1987. }
  1988. inline void ObjectReference::Set(uint32_t index, double numberValue) {
  1989. HandleScope scope(_env);
  1990. Value().Set(index, numberValue);
  1991. }
  1992. ////////////////////////////////////////////////////////////////////////////////
  1993. // FunctionReference class
  1994. ////////////////////////////////////////////////////////////////////////////////
  1995. inline FunctionReference::FunctionReference(): Reference<Function>() {
  1996. }
  1997. inline FunctionReference::FunctionReference(napi_env env, napi_ref ref)
  1998. : Reference<Function>(env, ref) {
  1999. }
  2000. inline FunctionReference::FunctionReference(Reference<Function>&& other)
  2001. : Reference<Function>(std::move(other)) {
  2002. }
  2003. inline FunctionReference& FunctionReference::operator =(Reference<Function>&& other) {
  2004. static_cast<Reference<Function>*>(this)->operator=(std::move(other));
  2005. return *this;
  2006. }
  2007. inline FunctionReference::FunctionReference(FunctionReference&& other)
  2008. : Reference<Function>(std::move(other)) {
  2009. }
  2010. inline FunctionReference& FunctionReference::operator =(FunctionReference&& other) {
  2011. static_cast<Reference<Function>*>(this)->operator=(std::move(other));
  2012. return *this;
  2013. }
  2014. inline Napi::Value FunctionReference::operator ()(
  2015. const std::initializer_list<napi_value>& args) const {
  2016. EscapableHandleScope scope(_env);
  2017. return scope.Escape(Value()(args));
  2018. }
  2019. inline Napi::Value FunctionReference::Call(const std::initializer_list<napi_value>& args) const {
  2020. EscapableHandleScope scope(_env);
  2021. Napi::Value result = Value().Call(args);
  2022. if (scope.Env().IsExceptionPending()) {
  2023. return Value();
  2024. }
  2025. return scope.Escape(result);
  2026. }
  2027. inline Napi::Value FunctionReference::Call(const std::vector<napi_value>& args) const {
  2028. EscapableHandleScope scope(_env);
  2029. Napi::Value result = Value().Call(args);
  2030. if (scope.Env().IsExceptionPending()) {
  2031. return Value();
  2032. }
  2033. return scope.Escape(result);
  2034. }
  2035. inline Napi::Value FunctionReference::Call(
  2036. napi_value recv, const std::initializer_list<napi_value>& args) const {
  2037. EscapableHandleScope scope(_env);
  2038. Napi::Value result = Value().Call(recv, args);
  2039. if (scope.Env().IsExceptionPending()) {
  2040. return Value();
  2041. }
  2042. return scope.Escape(result);
  2043. }
  2044. inline Napi::Value FunctionReference::Call(
  2045. napi_value recv, const std::vector<napi_value>& args) const {
  2046. EscapableHandleScope scope(_env);
  2047. Napi::Value result = Value().Call(recv, args);
  2048. if (scope.Env().IsExceptionPending()) {
  2049. return Value();
  2050. }
  2051. return scope.Escape(result);
  2052. }
  2053. inline Napi::Value FunctionReference::Call(
  2054. napi_value recv, size_t argc, const napi_value* args) const {
  2055. EscapableHandleScope scope(_env);
  2056. Napi::Value result = Value().Call(recv, argc, args);
  2057. if (scope.Env().IsExceptionPending()) {
  2058. return Value();
  2059. }
  2060. return scope.Escape(result);
  2061. }
  2062. inline Napi::Value FunctionReference::MakeCallback(
  2063. napi_value recv,
  2064. const std::initializer_list<napi_value>& args,
  2065. napi_async_context context) const {
  2066. EscapableHandleScope scope(_env);
  2067. Napi::Value result = Value().MakeCallback(recv, args, context);
  2068. if (scope.Env().IsExceptionPending()) {
  2069. return Value();
  2070. }
  2071. return scope.Escape(result);
  2072. }
  2073. inline Napi::Value FunctionReference::MakeCallback(
  2074. napi_value recv,
  2075. const std::vector<napi_value>& args,
  2076. napi_async_context context) const {
  2077. EscapableHandleScope scope(_env);
  2078. Napi::Value result = Value().MakeCallback(recv, args, context);
  2079. if (scope.Env().IsExceptionPending()) {
  2080. return Value();
  2081. }
  2082. return scope.Escape(result);
  2083. }
  2084. inline Napi::Value FunctionReference::MakeCallback(
  2085. napi_value recv,
  2086. size_t argc,
  2087. const napi_value* args,
  2088. napi_async_context context) const {
  2089. EscapableHandleScope scope(_env);
  2090. Napi::Value result = Value().MakeCallback(recv, argc, args, context);
  2091. if (scope.Env().IsExceptionPending()) {
  2092. return Value();
  2093. }
  2094. return scope.Escape(result);
  2095. }
  2096. inline Object FunctionReference::New(const std::initializer_list<napi_value>& args) const {
  2097. EscapableHandleScope scope(_env);
  2098. return scope.Escape(Value().New(args)).As<Object>();
  2099. }
  2100. inline Object FunctionReference::New(const std::vector<napi_value>& args) const {
  2101. EscapableHandleScope scope(_env);
  2102. return scope.Escape(Value().New(args)).As<Object>();
  2103. }
  2104. ////////////////////////////////////////////////////////////////////////////////
  2105. // CallbackInfo class
  2106. ////////////////////////////////////////////////////////////////////////////////
  2107. inline CallbackInfo::CallbackInfo(napi_env env, napi_callback_info info)
  2108. : _env(env), _info(info), _this(nullptr), _dynamicArgs(nullptr), _data(nullptr) {
  2109. _argc = _staticArgCount;
  2110. _argv = _staticArgs;
  2111. napi_status status = napi_get_cb_info(env, info, &_argc, _argv, &_this, &_data);
  2112. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2113. if (_argc > _staticArgCount) {
  2114. // Use either a fixed-size array (on the stack) or a dynamically-allocated
  2115. // array (on the heap) depending on the number of args.
  2116. _dynamicArgs = new napi_value[_argc];
  2117. _argv = _dynamicArgs;
  2118. status = napi_get_cb_info(env, info, &_argc, _argv, nullptr, nullptr);
  2119. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2120. }
  2121. }
  2122. inline CallbackInfo::~CallbackInfo() {
  2123. if (_dynamicArgs != nullptr) {
  2124. delete[] _dynamicArgs;
  2125. }
  2126. }
  2127. inline Value CallbackInfo::NewTarget() const {
  2128. napi_value newTarget;
  2129. napi_status status = napi_get_new_target(_env, _info, &newTarget);
  2130. NAPI_THROW_IF_FAILED(_env, status, Value());
  2131. return Value(_env, newTarget);
  2132. }
  2133. inline bool CallbackInfo::IsConstructCall() const {
  2134. return !NewTarget().IsEmpty();
  2135. }
  2136. inline Napi::Env CallbackInfo::Env() const {
  2137. return Napi::Env(_env);
  2138. }
  2139. inline size_t CallbackInfo::Length() const {
  2140. return _argc;
  2141. }
  2142. inline const Value CallbackInfo::operator [](size_t index) const {
  2143. return index < _argc ? Value(_env, _argv[index]) : Env().Undefined();
  2144. }
  2145. inline Value CallbackInfo::This() const {
  2146. if (_this == nullptr) {
  2147. return Env().Undefined();
  2148. }
  2149. return Object(_env, _this);
  2150. }
  2151. inline void* CallbackInfo::Data() const {
  2152. return _data;
  2153. }
  2154. inline void CallbackInfo::SetData(void* data) {
  2155. _data = data;
  2156. }
  2157. ////////////////////////////////////////////////////////////////////////////////
  2158. // PropertyDescriptor class
  2159. ////////////////////////////////////////////////////////////////////////////////
  2160. template <typename Getter>
  2161. inline PropertyDescriptor
  2162. PropertyDescriptor::Accessor(Napi::Env env,
  2163. Napi::Object object,
  2164. const char* utf8name,
  2165. Getter getter,
  2166. napi_property_attributes attributes,
  2167. void* /*data*/) {
  2168. typedef details::CallbackData<Getter, Napi::Value> CbData;
  2169. auto callbackData = new CbData({ getter, nullptr });
  2170. napi_status status = AttachData(env, object, callbackData);
  2171. NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  2172. return PropertyDescriptor({
  2173. utf8name,
  2174. nullptr,
  2175. nullptr,
  2176. CbData::Wrapper,
  2177. nullptr,
  2178. nullptr,
  2179. attributes,
  2180. callbackData
  2181. });
  2182. }
  2183. template <typename Getter>
  2184. inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env,
  2185. Napi::Object object,
  2186. const std::string& utf8name,
  2187. Getter getter,
  2188. napi_property_attributes attributes,
  2189. void* data) {
  2190. return Accessor(env, object, utf8name.c_str(), getter, attributes, data);
  2191. }
  2192. template <typename Getter>
  2193. inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env,
  2194. Napi::Object object,
  2195. Name name,
  2196. Getter getter,
  2197. napi_property_attributes attributes,
  2198. void* /*data*/) {
  2199. typedef details::CallbackData<Getter, Napi::Value> CbData;
  2200. auto callbackData = new CbData({ getter, nullptr });
  2201. napi_status status = AttachData(env, object, callbackData);
  2202. NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  2203. return PropertyDescriptor({
  2204. nullptr,
  2205. name,
  2206. nullptr,
  2207. CbData::Wrapper,
  2208. nullptr,
  2209. nullptr,
  2210. attributes,
  2211. callbackData
  2212. });
  2213. }
  2214. template <typename Getter, typename Setter>
  2215. inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env,
  2216. Napi::Object object,
  2217. const char* utf8name,
  2218. Getter getter,
  2219. Setter setter,
  2220. napi_property_attributes attributes,
  2221. void* /*data*/) {
  2222. typedef details::AccessorCallbackData<Getter, Setter> CbData;
  2223. auto callbackData = new CbData({ getter, setter });
  2224. napi_status status = AttachData(env, object, callbackData);
  2225. NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  2226. return PropertyDescriptor({
  2227. utf8name,
  2228. nullptr,
  2229. nullptr,
  2230. CbData::GetterWrapper,
  2231. CbData::SetterWrapper,
  2232. nullptr,
  2233. attributes,
  2234. callbackData
  2235. });
  2236. }
  2237. template <typename Getter, typename Setter>
  2238. inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env,
  2239. Napi::Object object,
  2240. const std::string& utf8name,
  2241. Getter getter,
  2242. Setter setter,
  2243. napi_property_attributes attributes,
  2244. void* data) {
  2245. return Accessor(env, object, utf8name.c_str(), getter, setter, attributes, data);
  2246. }
  2247. template <typename Getter, typename Setter>
  2248. inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env,
  2249. Napi::Object object,
  2250. Name name,
  2251. Getter getter,
  2252. Setter setter,
  2253. napi_property_attributes attributes,
  2254. void* /*data*/) {
  2255. typedef details::AccessorCallbackData<Getter, Setter> CbData;
  2256. auto callbackData = new CbData({ getter, setter });
  2257. napi_status status = AttachData(env, object, callbackData);
  2258. NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  2259. return PropertyDescriptor({
  2260. nullptr,
  2261. name,
  2262. nullptr,
  2263. CbData::GetterWrapper,
  2264. CbData::SetterWrapper,
  2265. nullptr,
  2266. attributes,
  2267. callbackData
  2268. });
  2269. }
  2270. template <typename Callable>
  2271. inline PropertyDescriptor PropertyDescriptor::Function(Napi::Env env,
  2272. Napi::Object /*object*/,
  2273. const char* utf8name,
  2274. Callable cb,
  2275. napi_property_attributes attributes,
  2276. void* data) {
  2277. return PropertyDescriptor({
  2278. utf8name,
  2279. nullptr,
  2280. nullptr,
  2281. nullptr,
  2282. nullptr,
  2283. Napi::Function::New(env, cb, utf8name, data),
  2284. attributes,
  2285. nullptr
  2286. });
  2287. }
  2288. template <typename Callable>
  2289. inline PropertyDescriptor PropertyDescriptor::Function(Napi::Env env,
  2290. Napi::Object object,
  2291. const std::string& utf8name,
  2292. Callable cb,
  2293. napi_property_attributes attributes,
  2294. void* data) {
  2295. return Function(env, object, utf8name.c_str(), cb, attributes, data);
  2296. }
  2297. template <typename Callable>
  2298. inline PropertyDescriptor PropertyDescriptor::Function(Napi::Env env,
  2299. Napi::Object /*object*/,
  2300. Name name,
  2301. Callable cb,
  2302. napi_property_attributes attributes,
  2303. void* data) {
  2304. return PropertyDescriptor({
  2305. nullptr,
  2306. name,
  2307. nullptr,
  2308. nullptr,
  2309. nullptr,
  2310. Napi::Function::New(env, cb, nullptr, data),
  2311. attributes,
  2312. nullptr
  2313. });
  2314. }
  2315. inline PropertyDescriptor PropertyDescriptor::Value(const char* utf8name,
  2316. napi_value value,
  2317. napi_property_attributes attributes) {
  2318. return PropertyDescriptor({
  2319. utf8name, nullptr, nullptr, nullptr, nullptr, value, attributes, nullptr
  2320. });
  2321. }
  2322. inline PropertyDescriptor PropertyDescriptor::Value(const std::string& utf8name,
  2323. napi_value value,
  2324. napi_property_attributes attributes) {
  2325. return Value(utf8name.c_str(), value, attributes);
  2326. }
  2327. inline PropertyDescriptor PropertyDescriptor::Value(napi_value name,
  2328. napi_value value,
  2329. napi_property_attributes attributes) {
  2330. return PropertyDescriptor({
  2331. nullptr, name, nullptr, nullptr, nullptr, value, attributes, nullptr
  2332. });
  2333. }
  2334. inline PropertyDescriptor PropertyDescriptor::Value(Name name,
  2335. Napi::Value value,
  2336. napi_property_attributes attributes) {
  2337. napi_value nameValue = name;
  2338. napi_value valueValue = value;
  2339. return PropertyDescriptor::Value(nameValue, valueValue, attributes);
  2340. }
  2341. inline PropertyDescriptor::PropertyDescriptor(napi_property_descriptor desc)
  2342. : _desc(desc) {
  2343. }
  2344. inline PropertyDescriptor::operator napi_property_descriptor&() {
  2345. return _desc;
  2346. }
  2347. inline PropertyDescriptor::operator const napi_property_descriptor&() const {
  2348. return _desc;
  2349. }
  2350. ////////////////////////////////////////////////////////////////////////////////
  2351. // ObjectWrap<T> class
  2352. ////////////////////////////////////////////////////////////////////////////////
  2353. template <typename T>
  2354. inline ObjectWrap<T>::ObjectWrap(const Napi::CallbackInfo& callbackInfo) {
  2355. napi_env env = callbackInfo.Env();
  2356. napi_value wrapper = callbackInfo.This();
  2357. napi_status status;
  2358. napi_ref ref;
  2359. T* instance = static_cast<T*>(this);
  2360. status = napi_wrap(env, wrapper, instance, FinalizeCallback, nullptr, &ref);
  2361. NAPI_THROW_IF_FAILED_VOID(env, status);
  2362. Reference<Object>* instanceRef = instance;
  2363. *instanceRef = Reference<Object>(env, ref);
  2364. }
  2365. template<typename T>
  2366. inline T* ObjectWrap<T>::Unwrap(Object wrapper) {
  2367. T* unwrapped;
  2368. napi_status status = napi_unwrap(wrapper.Env(), wrapper, reinterpret_cast<void**>(&unwrapped));
  2369. NAPI_THROW_IF_FAILED(wrapper.Env(), status, nullptr);
  2370. return unwrapped;
  2371. }
  2372. template <typename T>
  2373. inline Function
  2374. ObjectWrap<T>::DefineClass(Napi::Env env,
  2375. const char* utf8name,
  2376. const size_t props_count,
  2377. const napi_property_descriptor* descriptors,
  2378. void* data) {
  2379. napi_status status;
  2380. std::vector<napi_property_descriptor> props(props_count);
  2381. // We copy the descriptors to a local array because before defining the class
  2382. // we must replace static method property descriptors with value property
  2383. // descriptors such that the value is a function-valued `napi_value` created
  2384. // with `CreateFunction()`.
  2385. //
  2386. // This replacement could be made for instance methods as well, but V8 aborts
  2387. // if we do that, because it expects methods defined on the prototype template
  2388. // to have `FunctionTemplate`s.
  2389. for (size_t index = 0; index < props_count; index++) {
  2390. props[index] = descriptors[index];
  2391. napi_property_descriptor* prop = &props[index];
  2392. if (prop->method == T::StaticMethodCallbackWrapper) {
  2393. status = CreateFunction(env,
  2394. utf8name,
  2395. prop->method,
  2396. static_cast<StaticMethodCallbackData*>(prop->data),
  2397. &(prop->value));
  2398. NAPI_THROW_IF_FAILED(env, status, Function());
  2399. prop->method = nullptr;
  2400. prop->data = nullptr;
  2401. } else if (prop->method == T::StaticVoidMethodCallbackWrapper) {
  2402. status = CreateFunction(env,
  2403. utf8name,
  2404. prop->method,
  2405. static_cast<StaticVoidMethodCallbackData*>(prop->data),
  2406. &(prop->value));
  2407. NAPI_THROW_IF_FAILED(env, status, Function());
  2408. prop->method = nullptr;
  2409. prop->data = nullptr;
  2410. }
  2411. }
  2412. napi_value value;
  2413. status = napi_define_class(env,
  2414. utf8name,
  2415. NAPI_AUTO_LENGTH,
  2416. T::ConstructorCallbackWrapper,
  2417. data,
  2418. props_count,
  2419. props.data(),
  2420. &value);
  2421. NAPI_THROW_IF_FAILED(env, status, Function());
  2422. // After defining the class we iterate once more over the property descriptors
  2423. // and attach the data associated with accessors and instance methods to the
  2424. // newly created JavaScript class.
  2425. for (size_t idx = 0; idx < props_count; idx++) {
  2426. const napi_property_descriptor* prop = &props[idx];
  2427. if (prop->getter == T::StaticGetterCallbackWrapper ||
  2428. prop->setter == T::StaticSetterCallbackWrapper) {
  2429. status = Napi::details::AttachData(env,
  2430. value,
  2431. static_cast<StaticAccessorCallbackData*>(prop->data));
  2432. NAPI_THROW_IF_FAILED(env, status, Function());
  2433. } else if (prop->getter == T::InstanceGetterCallbackWrapper ||
  2434. prop->setter == T::InstanceSetterCallbackWrapper) {
  2435. status = Napi::details::AttachData(env,
  2436. value,
  2437. static_cast<InstanceAccessorCallbackData*>(prop->data));
  2438. NAPI_THROW_IF_FAILED(env, status, Function());
  2439. } else if (prop->method != nullptr && !(prop->attributes & napi_static)) {
  2440. if (prop->method == T::InstanceVoidMethodCallbackWrapper) {
  2441. status = Napi::details::AttachData(env,
  2442. value,
  2443. static_cast<InstanceVoidMethodCallbackData*>(prop->data));
  2444. NAPI_THROW_IF_FAILED(env, status, Function());
  2445. } else if (prop->method == T::InstanceMethodCallbackWrapper) {
  2446. status = Napi::details::AttachData(env,
  2447. value,
  2448. static_cast<InstanceMethodCallbackData*>(prop->data));
  2449. NAPI_THROW_IF_FAILED(env, status, Function());
  2450. }
  2451. }
  2452. }
  2453. return Function(env, value);
  2454. }
  2455. template <typename T>
  2456. inline Function ObjectWrap<T>::DefineClass(
  2457. Napi::Env env,
  2458. const char* utf8name,
  2459. const std::initializer_list<ClassPropertyDescriptor<T>>& properties,
  2460. void* data) {
  2461. return DefineClass(env,
  2462. utf8name,
  2463. properties.size(),
  2464. reinterpret_cast<const napi_property_descriptor*>(properties.begin()),
  2465. data);
  2466. }
  2467. template <typename T>
  2468. inline Function ObjectWrap<T>::DefineClass(
  2469. Napi::Env env,
  2470. const char* utf8name,
  2471. const std::vector<ClassPropertyDescriptor<T>>& properties,
  2472. void* data) {
  2473. return DefineClass(env,
  2474. utf8name,
  2475. properties.size(),
  2476. reinterpret_cast<const napi_property_descriptor*>(properties.data()),
  2477. data);
  2478. }
  2479. template <typename T>
  2480. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  2481. const char* utf8name,
  2482. StaticVoidMethodCallback method,
  2483. napi_property_attributes attributes,
  2484. void* data) {
  2485. StaticVoidMethodCallbackData* callbackData = new StaticVoidMethodCallbackData({ method, data });
  2486. napi_property_descriptor desc = napi_property_descriptor();
  2487. desc.utf8name = utf8name;
  2488. desc.method = T::StaticVoidMethodCallbackWrapper;
  2489. desc.data = callbackData;
  2490. desc.attributes = static_cast<napi_property_attributes>(attributes | napi_static);
  2491. return desc;
  2492. }
  2493. template <typename T>
  2494. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  2495. const char* utf8name,
  2496. StaticMethodCallback method,
  2497. napi_property_attributes attributes,
  2498. void* data) {
  2499. StaticMethodCallbackData* callbackData = new StaticMethodCallbackData({ method, data });
  2500. napi_property_descriptor desc = napi_property_descriptor();
  2501. desc.utf8name = utf8name;
  2502. desc.method = T::StaticMethodCallbackWrapper;
  2503. desc.data = callbackData;
  2504. desc.attributes = static_cast<napi_property_attributes>(attributes | napi_static);
  2505. return desc;
  2506. }
  2507. template <typename T>
  2508. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  2509. Symbol name,
  2510. StaticVoidMethodCallback method,
  2511. napi_property_attributes attributes,
  2512. void* data) {
  2513. StaticVoidMethodCallbackData* callbackData = new StaticVoidMethodCallbackData({ method, data });
  2514. napi_property_descriptor desc = napi_property_descriptor();
  2515. desc.name = name;
  2516. desc.method = T::StaticVoidMethodCallbackWrapper;
  2517. desc.data = callbackData;
  2518. desc.attributes = static_cast<napi_property_attributes>(attributes | napi_static);
  2519. return desc;
  2520. }
  2521. template <typename T>
  2522. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  2523. Symbol name,
  2524. StaticMethodCallback method,
  2525. napi_property_attributes attributes,
  2526. void* data) {
  2527. StaticMethodCallbackData* callbackData = new StaticMethodCallbackData({ method, data });
  2528. napi_property_descriptor desc = napi_property_descriptor();
  2529. desc.name = name;
  2530. desc.method = T::StaticMethodCallbackWrapper;
  2531. desc.data = callbackData;
  2532. desc.attributes = static_cast<napi_property_attributes>(attributes | napi_static);
  2533. return desc;
  2534. }
  2535. template <typename T>
  2536. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticAccessor(
  2537. const char* utf8name,
  2538. StaticGetterCallback getter,
  2539. StaticSetterCallback setter,
  2540. napi_property_attributes attributes,
  2541. void* data) {
  2542. StaticAccessorCallbackData* callbackData =
  2543. new StaticAccessorCallbackData({ getter, setter, data });
  2544. napi_property_descriptor desc = napi_property_descriptor();
  2545. desc.utf8name = utf8name;
  2546. desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr;
  2547. desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr;
  2548. desc.data = callbackData;
  2549. desc.attributes = static_cast<napi_property_attributes>(attributes | napi_static);
  2550. return desc;
  2551. }
  2552. template <typename T>
  2553. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticAccessor(
  2554. Symbol name,
  2555. StaticGetterCallback getter,
  2556. StaticSetterCallback setter,
  2557. napi_property_attributes attributes,
  2558. void* data) {
  2559. StaticAccessorCallbackData* callbackData =
  2560. new StaticAccessorCallbackData({ getter, setter, data });
  2561. napi_property_descriptor desc = napi_property_descriptor();
  2562. desc.name = name;
  2563. desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr;
  2564. desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr;
  2565. desc.data = callbackData;
  2566. desc.attributes = static_cast<napi_property_attributes>(attributes | napi_static);
  2567. return desc;
  2568. }
  2569. template <typename T>
  2570. inline ClassPropertyDescriptor<T> ObjectWrap<T>::InstanceMethod(
  2571. const char* utf8name,
  2572. InstanceVoidMethodCallback method,
  2573. napi_property_attributes attributes,
  2574. void* data) {
  2575. InstanceVoidMethodCallbackData* callbackData =
  2576. new InstanceVoidMethodCallbackData({ method, data});
  2577. napi_property_descriptor desc = napi_property_descriptor();
  2578. desc.utf8name = utf8name;
  2579. desc.method = T::InstanceVoidMethodCallbackWrapper;
  2580. desc.data = callbackData;
  2581. desc.attributes = attributes;
  2582. return desc;
  2583. }
  2584. template <typename T>
  2585. inline ClassPropertyDescriptor<T> ObjectWrap<T>::InstanceMethod(
  2586. const char* utf8name,
  2587. InstanceMethodCallback method,
  2588. napi_property_attributes attributes,
  2589. void* data) {
  2590. InstanceMethodCallbackData* callbackData = new InstanceMethodCallbackData({ method, data });
  2591. napi_property_descriptor desc = napi_property_descriptor();
  2592. desc.utf8name = utf8name;
  2593. desc.method = T::InstanceMethodCallbackWrapper;
  2594. desc.data = callbackData;
  2595. desc.attributes = attributes;
  2596. return desc;
  2597. }
  2598. template <typename T>
  2599. inline ClassPropertyDescriptor<T> ObjectWrap<T>::InstanceMethod(
  2600. Symbol name,
  2601. InstanceVoidMethodCallback method,
  2602. napi_property_attributes attributes,
  2603. void* data) {
  2604. InstanceVoidMethodCallbackData* callbackData =
  2605. new InstanceVoidMethodCallbackData({ method, data});
  2606. napi_property_descriptor desc = napi_property_descriptor();
  2607. desc.name = name;
  2608. desc.method = T::InstanceVoidMethodCallbackWrapper;
  2609. desc.data = callbackData;
  2610. desc.attributes = attributes;
  2611. return desc;
  2612. }
  2613. template <typename T>
  2614. inline ClassPropertyDescriptor<T> ObjectWrap<T>::InstanceMethod(
  2615. Symbol name,
  2616. InstanceMethodCallback method,
  2617. napi_property_attributes attributes,
  2618. void* data) {
  2619. InstanceMethodCallbackData* callbackData = new InstanceMethodCallbackData({ method, data });
  2620. napi_property_descriptor desc = napi_property_descriptor();
  2621. desc.name = name;
  2622. desc.method = T::InstanceMethodCallbackWrapper;
  2623. desc.data = callbackData;
  2624. desc.attributes = attributes;
  2625. return desc;
  2626. }
  2627. template <typename T>
  2628. inline ClassPropertyDescriptor<T> ObjectWrap<T>::InstanceAccessor(
  2629. const char* utf8name,
  2630. InstanceGetterCallback getter,
  2631. InstanceSetterCallback setter,
  2632. napi_property_attributes attributes,
  2633. void* data) {
  2634. InstanceAccessorCallbackData* callbackData =
  2635. new InstanceAccessorCallbackData({ getter, setter, data });
  2636. napi_property_descriptor desc = napi_property_descriptor();
  2637. desc.utf8name = utf8name;
  2638. desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr;
  2639. desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr;
  2640. desc.data = callbackData;
  2641. desc.attributes = attributes;
  2642. return desc;
  2643. }
  2644. template <typename T>
  2645. inline ClassPropertyDescriptor<T> ObjectWrap<T>::InstanceAccessor(
  2646. Symbol name,
  2647. InstanceGetterCallback getter,
  2648. InstanceSetterCallback setter,
  2649. napi_property_attributes attributes,
  2650. void* data) {
  2651. InstanceAccessorCallbackData* callbackData =
  2652. new InstanceAccessorCallbackData({ getter, setter, data });
  2653. napi_property_descriptor desc = napi_property_descriptor();
  2654. desc.name = name;
  2655. desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr;
  2656. desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr;
  2657. desc.data = callbackData;
  2658. desc.attributes = attributes;
  2659. return desc;
  2660. }
  2661. template <typename T>
  2662. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticValue(const char* utf8name,
  2663. Napi::Value value, napi_property_attributes attributes) {
  2664. napi_property_descriptor desc = napi_property_descriptor();
  2665. desc.utf8name = utf8name;
  2666. desc.value = value;
  2667. desc.attributes = static_cast<napi_property_attributes>(attributes | napi_static);
  2668. return desc;
  2669. }
  2670. template <typename T>
  2671. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticValue(Symbol name,
  2672. Napi::Value value, napi_property_attributes attributes) {
  2673. napi_property_descriptor desc = napi_property_descriptor();
  2674. desc.name = name;
  2675. desc.value = value;
  2676. desc.attributes = static_cast<napi_property_attributes>(attributes | napi_static);
  2677. return desc;
  2678. }
  2679. template <typename T>
  2680. inline ClassPropertyDescriptor<T> ObjectWrap<T>::InstanceValue(
  2681. const char* utf8name,
  2682. Napi::Value value,
  2683. napi_property_attributes attributes) {
  2684. napi_property_descriptor desc = napi_property_descriptor();
  2685. desc.utf8name = utf8name;
  2686. desc.value = value;
  2687. desc.attributes = attributes;
  2688. return desc;
  2689. }
  2690. template <typename T>
  2691. inline ClassPropertyDescriptor<T> ObjectWrap<T>::InstanceValue(
  2692. Symbol name,
  2693. Napi::Value value,
  2694. napi_property_attributes attributes) {
  2695. napi_property_descriptor desc = napi_property_descriptor();
  2696. desc.name = name;
  2697. desc.value = value;
  2698. desc.attributes = attributes;
  2699. return desc;
  2700. }
  2701. template <typename T>
  2702. inline napi_value ObjectWrap<T>::ConstructorCallbackWrapper(
  2703. napi_env env,
  2704. napi_callback_info info) {
  2705. napi_value new_target;
  2706. napi_status status = napi_get_new_target(env, info, &new_target);
  2707. if (status != napi_ok) return nullptr;
  2708. bool isConstructCall = (new_target != nullptr);
  2709. if (!isConstructCall) {
  2710. napi_throw_type_error(env, nullptr, "Class constructors cannot be invoked without 'new'");
  2711. return nullptr;
  2712. }
  2713. T* instance;
  2714. napi_value wrapper = details::WrapCallback([&] {
  2715. CallbackInfo callbackInfo(env, info);
  2716. instance = new T(callbackInfo);
  2717. return callbackInfo.This();
  2718. });
  2719. return wrapper;
  2720. }
  2721. template <typename T>
  2722. inline napi_value ObjectWrap<T>::StaticVoidMethodCallbackWrapper(
  2723. napi_env env,
  2724. napi_callback_info info) {
  2725. return details::WrapCallback([&] {
  2726. CallbackInfo callbackInfo(env, info);
  2727. StaticVoidMethodCallbackData* callbackData =
  2728. reinterpret_cast<StaticVoidMethodCallbackData*>(callbackInfo.Data());
  2729. callbackInfo.SetData(callbackData->data);
  2730. callbackData->callback(callbackInfo);
  2731. return nullptr;
  2732. });
  2733. }
  2734. template <typename T>
  2735. inline napi_value ObjectWrap<T>::StaticMethodCallbackWrapper(
  2736. napi_env env,
  2737. napi_callback_info info) {
  2738. return details::WrapCallback([&] {
  2739. CallbackInfo callbackInfo(env, info);
  2740. StaticMethodCallbackData* callbackData =
  2741. reinterpret_cast<StaticMethodCallbackData*>(callbackInfo.Data());
  2742. callbackInfo.SetData(callbackData->data);
  2743. return callbackData->callback(callbackInfo);
  2744. });
  2745. }
  2746. template <typename T>
  2747. inline napi_value ObjectWrap<T>::StaticGetterCallbackWrapper(
  2748. napi_env env,
  2749. napi_callback_info info) {
  2750. return details::WrapCallback([&] {
  2751. CallbackInfo callbackInfo(env, info);
  2752. StaticAccessorCallbackData* callbackData =
  2753. reinterpret_cast<StaticAccessorCallbackData*>(callbackInfo.Data());
  2754. callbackInfo.SetData(callbackData->data);
  2755. return callbackData->getterCallback(callbackInfo);
  2756. });
  2757. }
  2758. template <typename T>
  2759. inline napi_value ObjectWrap<T>::StaticSetterCallbackWrapper(
  2760. napi_env env,
  2761. napi_callback_info info) {
  2762. return details::WrapCallback([&] {
  2763. CallbackInfo callbackInfo(env, info);
  2764. StaticAccessorCallbackData* callbackData =
  2765. reinterpret_cast<StaticAccessorCallbackData*>(callbackInfo.Data());
  2766. callbackInfo.SetData(callbackData->data);
  2767. callbackData->setterCallback(callbackInfo, callbackInfo[0]);
  2768. return nullptr;
  2769. });
  2770. }
  2771. template <typename T>
  2772. inline napi_value ObjectWrap<T>::InstanceVoidMethodCallbackWrapper(
  2773. napi_env env,
  2774. napi_callback_info info) {
  2775. return details::WrapCallback([&] {
  2776. CallbackInfo callbackInfo(env, info);
  2777. InstanceVoidMethodCallbackData* callbackData =
  2778. reinterpret_cast<InstanceVoidMethodCallbackData*>(callbackInfo.Data());
  2779. callbackInfo.SetData(callbackData->data);
  2780. T* instance = Unwrap(callbackInfo.This().As<Object>());
  2781. auto cb = callbackData->callback;
  2782. (instance->*cb)(callbackInfo);
  2783. return nullptr;
  2784. });
  2785. }
  2786. template <typename T>
  2787. inline napi_value ObjectWrap<T>::InstanceMethodCallbackWrapper(
  2788. napi_env env,
  2789. napi_callback_info info) {
  2790. return details::WrapCallback([&] {
  2791. CallbackInfo callbackInfo(env, info);
  2792. InstanceMethodCallbackData* callbackData =
  2793. reinterpret_cast<InstanceMethodCallbackData*>(callbackInfo.Data());
  2794. callbackInfo.SetData(callbackData->data);
  2795. T* instance = Unwrap(callbackInfo.This().As<Object>());
  2796. auto cb = callbackData->callback;
  2797. return (instance->*cb)(callbackInfo);
  2798. });
  2799. }
  2800. template <typename T>
  2801. inline napi_value ObjectWrap<T>::InstanceGetterCallbackWrapper(
  2802. napi_env env,
  2803. napi_callback_info info) {
  2804. return details::WrapCallback([&] {
  2805. CallbackInfo callbackInfo(env, info);
  2806. InstanceAccessorCallbackData* callbackData =
  2807. reinterpret_cast<InstanceAccessorCallbackData*>(callbackInfo.Data());
  2808. callbackInfo.SetData(callbackData->data);
  2809. T* instance = Unwrap(callbackInfo.This().As<Object>());
  2810. auto cb = callbackData->getterCallback;
  2811. return (instance->*cb)(callbackInfo);
  2812. });
  2813. }
  2814. template <typename T>
  2815. inline napi_value ObjectWrap<T>::InstanceSetterCallbackWrapper(
  2816. napi_env env,
  2817. napi_callback_info info) {
  2818. return details::WrapCallback([&] {
  2819. CallbackInfo callbackInfo(env, info);
  2820. InstanceAccessorCallbackData* callbackData =
  2821. reinterpret_cast<InstanceAccessorCallbackData*>(callbackInfo.Data());
  2822. callbackInfo.SetData(callbackData->data);
  2823. T* instance = Unwrap(callbackInfo.This().As<Object>());
  2824. auto cb = callbackData->setterCallback;
  2825. (instance->*cb)(callbackInfo, callbackInfo[0]);
  2826. return nullptr;
  2827. });
  2828. }
  2829. template <typename T>
  2830. inline void ObjectWrap<T>::FinalizeCallback(napi_env /*env*/, void* data, void* /*hint*/) {
  2831. T* instance = reinterpret_cast<T*>(data);
  2832. delete instance;
  2833. }
  2834. ////////////////////////////////////////////////////////////////////////////////
  2835. // HandleScope class
  2836. ////////////////////////////////////////////////////////////////////////////////
  2837. inline HandleScope::HandleScope(napi_env env, napi_handle_scope scope)
  2838. : _env(env), _scope(scope) {
  2839. }
  2840. inline HandleScope::HandleScope(Napi::Env env) : _env(env) {
  2841. napi_status status = napi_open_handle_scope(_env, &_scope);
  2842. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2843. }
  2844. inline HandleScope::~HandleScope() {
  2845. napi_close_handle_scope(_env, _scope);
  2846. }
  2847. inline HandleScope::operator napi_handle_scope() const {
  2848. return _scope;
  2849. }
  2850. inline Napi::Env HandleScope::Env() const {
  2851. return Napi::Env(_env);
  2852. }
  2853. ////////////////////////////////////////////////////////////////////////////////
  2854. // EscapableHandleScope class
  2855. ////////////////////////////////////////////////////////////////////////////////
  2856. inline EscapableHandleScope::EscapableHandleScope(
  2857. napi_env env, napi_escapable_handle_scope scope) : _env(env), _scope(scope) {
  2858. }
  2859. inline EscapableHandleScope::EscapableHandleScope(Napi::Env env) : _env(env) {
  2860. napi_status status = napi_open_escapable_handle_scope(_env, &_scope);
  2861. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2862. }
  2863. inline EscapableHandleScope::~EscapableHandleScope() {
  2864. napi_close_escapable_handle_scope(_env, _scope);
  2865. }
  2866. inline EscapableHandleScope::operator napi_escapable_handle_scope() const {
  2867. return _scope;
  2868. }
  2869. inline Napi::Env EscapableHandleScope::Env() const {
  2870. return Napi::Env(_env);
  2871. }
  2872. inline Value EscapableHandleScope::Escape(napi_value escapee) {
  2873. napi_value result;
  2874. napi_status status = napi_escape_handle(_env, _scope, escapee, &result);
  2875. NAPI_THROW_IF_FAILED(_env, status, Value());
  2876. return Value(_env, result);
  2877. }
  2878. #if (NAPI_VERSION > 2)
  2879. ////////////////////////////////////////////////////////////////////////////////
  2880. // CallbackScope class
  2881. ////////////////////////////////////////////////////////////////////////////////
  2882. inline CallbackScope::CallbackScope(
  2883. napi_env env, napi_callback_scope scope) : _env(env), _scope(scope) {
  2884. }
  2885. inline CallbackScope::CallbackScope(napi_env env, napi_async_context context)
  2886. : _env(env) {
  2887. napi_status status = napi_open_callback_scope(
  2888. _env, Object::New(env), context, &_scope);
  2889. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2890. }
  2891. inline CallbackScope::~CallbackScope() {
  2892. napi_close_callback_scope(_env, _scope);
  2893. }
  2894. inline CallbackScope::operator napi_callback_scope() const {
  2895. return _scope;
  2896. }
  2897. inline Napi::Env CallbackScope::Env() const {
  2898. return Napi::Env(_env);
  2899. }
  2900. #endif
  2901. ////////////////////////////////////////////////////////////////////////////////
  2902. // AsyncContext class
  2903. ////////////////////////////////////////////////////////////////////////////////
  2904. inline AsyncContext::AsyncContext(napi_env env, const char* resource_name)
  2905. : AsyncContext(env, resource_name, Object::New(env)) {
  2906. }
  2907. inline AsyncContext::AsyncContext(napi_env env,
  2908. const char* resource_name,
  2909. const Object& resource)
  2910. : _env(env),
  2911. _context(nullptr) {
  2912. napi_value resource_id;
  2913. napi_status status = napi_create_string_utf8(
  2914. _env, resource_name, NAPI_AUTO_LENGTH, &resource_id);
  2915. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2916. status = napi_async_init(_env, resource, resource_id, &_context);
  2917. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2918. }
  2919. inline AsyncContext::~AsyncContext() {
  2920. if (_context != nullptr) {
  2921. napi_async_destroy(_env, _context);
  2922. _context = nullptr;
  2923. }
  2924. }
  2925. inline AsyncContext::AsyncContext(AsyncContext&& other) {
  2926. _env = other._env;
  2927. other._env = nullptr;
  2928. _context = other._context;
  2929. other._context = nullptr;
  2930. }
  2931. inline AsyncContext& AsyncContext::operator =(AsyncContext&& other) {
  2932. _env = other._env;
  2933. other._env = nullptr;
  2934. _context = other._context;
  2935. other._context = nullptr;
  2936. return *this;
  2937. }
  2938. inline AsyncContext::operator napi_async_context() const {
  2939. return _context;
  2940. }
  2941. ////////////////////////////////////////////////////////////////////////////////
  2942. // AsyncWorker class
  2943. ////////////////////////////////////////////////////////////////////////////////
  2944. inline AsyncWorker::AsyncWorker(const Function& callback)
  2945. : AsyncWorker(callback, "generic") {
  2946. }
  2947. inline AsyncWorker::AsyncWorker(const Function& callback,
  2948. const char* resource_name)
  2949. : AsyncWorker(callback, resource_name, Object::New(callback.Env())) {
  2950. }
  2951. inline AsyncWorker::AsyncWorker(const Function& callback,
  2952. const char* resource_name,
  2953. const Object& resource)
  2954. : AsyncWorker(Object::New(callback.Env()),
  2955. callback,
  2956. resource_name,
  2957. resource) {
  2958. }
  2959. inline AsyncWorker::AsyncWorker(const Object& receiver,
  2960. const Function& callback)
  2961. : AsyncWorker(receiver, callback, "generic") {
  2962. }
  2963. inline AsyncWorker::AsyncWorker(const Object& receiver,
  2964. const Function& callback,
  2965. const char* resource_name)
  2966. : AsyncWorker(receiver,
  2967. callback,
  2968. resource_name,
  2969. Object::New(callback.Env())) {
  2970. }
  2971. inline AsyncWorker::AsyncWorker(const Object& receiver,
  2972. const Function& callback,
  2973. const char* resource_name,
  2974. const Object& resource)
  2975. : _env(callback.Env()),
  2976. _receiver(Napi::Persistent(receiver)),
  2977. _callback(Napi::Persistent(callback)) {
  2978. napi_value resource_id;
  2979. napi_status status = napi_create_string_latin1(
  2980. _env, resource_name, NAPI_AUTO_LENGTH, &resource_id);
  2981. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2982. status = napi_create_async_work(_env, resource, resource_id, OnExecute,
  2983. OnWorkComplete, this, &_work);
  2984. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2985. }
  2986. inline AsyncWorker::~AsyncWorker() {
  2987. if (_work != nullptr) {
  2988. napi_delete_async_work(_env, _work);
  2989. _work = nullptr;
  2990. }
  2991. }
  2992. inline AsyncWorker::AsyncWorker(AsyncWorker&& other) {
  2993. _env = other._env;
  2994. other._env = nullptr;
  2995. _work = other._work;
  2996. other._work = nullptr;
  2997. _receiver = std::move(other._receiver);
  2998. _callback = std::move(other._callback);
  2999. _error = std::move(other._error);
  3000. }
  3001. inline AsyncWorker& AsyncWorker::operator =(AsyncWorker&& other) {
  3002. _env = other._env;
  3003. other._env = nullptr;
  3004. _work = other._work;
  3005. other._work = nullptr;
  3006. _receiver = std::move(other._receiver);
  3007. _callback = std::move(other._callback);
  3008. _error = std::move(other._error);
  3009. return *this;
  3010. }
  3011. inline AsyncWorker::operator napi_async_work() const {
  3012. return _work;
  3013. }
  3014. inline Napi::Env AsyncWorker::Env() const {
  3015. return Napi::Env(_env);
  3016. }
  3017. inline void AsyncWorker::Queue() {
  3018. napi_status status = napi_queue_async_work(_env, _work);
  3019. NAPI_THROW_IF_FAILED_VOID(_env, status);
  3020. }
  3021. inline void AsyncWorker::Cancel() {
  3022. napi_status status = napi_cancel_async_work(_env, _work);
  3023. NAPI_THROW_IF_FAILED_VOID(_env, status);
  3024. }
  3025. inline ObjectReference& AsyncWorker::Receiver() {
  3026. return _receiver;
  3027. }
  3028. inline FunctionReference& AsyncWorker::Callback() {
  3029. return _callback;
  3030. }
  3031. inline void AsyncWorker::OnOK() {
  3032. _callback.Call(_receiver.Value(), std::initializer_list<napi_value>{});
  3033. }
  3034. inline void AsyncWorker::OnError(const Error& e) {
  3035. _callback.Call(_receiver.Value(), std::initializer_list<napi_value>{ e.Value() });
  3036. }
  3037. inline void AsyncWorker::SetError(const std::string& error) {
  3038. _error = error;
  3039. }
  3040. inline void AsyncWorker::OnExecute(napi_env /*env*/, void* this_pointer) {
  3041. AsyncWorker* self = static_cast<AsyncWorker*>(this_pointer);
  3042. #ifdef NAPI_CPP_EXCEPTIONS
  3043. try {
  3044. self->Execute();
  3045. } catch (const std::exception& e) {
  3046. self->SetError(e.what());
  3047. }
  3048. #else // NAPI_CPP_EXCEPTIONS
  3049. self->Execute();
  3050. #endif // NAPI_CPP_EXCEPTIONS
  3051. }
  3052. inline void AsyncWorker::OnWorkComplete(
  3053. napi_env /*env*/, napi_status status, void* this_pointer) {
  3054. AsyncWorker* self = static_cast<AsyncWorker*>(this_pointer);
  3055. if (status != napi_cancelled) {
  3056. HandleScope scope(self->_env);
  3057. details::WrapCallback([&] {
  3058. if (self->_error.size() == 0) {
  3059. self->OnOK();
  3060. }
  3061. else {
  3062. self->OnError(Error::New(self->_env, self->_error));
  3063. }
  3064. return nullptr;
  3065. });
  3066. }
  3067. delete self;
  3068. }
  3069. ////////////////////////////////////////////////////////////////////////////////
  3070. // Memory Management class
  3071. ////////////////////////////////////////////////////////////////////////////////
  3072. inline int64_t MemoryManagement::AdjustExternalMemory(Env env, int64_t change_in_bytes) {
  3073. int64_t result;
  3074. napi_status status = napi_adjust_external_memory(env, change_in_bytes, &result);
  3075. NAPI_THROW_IF_FAILED(env, status, 0);
  3076. return result;
  3077. }
  3078. ////////////////////////////////////////////////////////////////////////////////
  3079. // Version Management class
  3080. ////////////////////////////////////////////////////////////////////////////////
  3081. inline uint32_t VersionManagement::GetNapiVersion(Env env) {
  3082. uint32_t result;
  3083. napi_status status = napi_get_version(env, &result);
  3084. NAPI_THROW_IF_FAILED(env, status, 0);
  3085. return result;
  3086. }
  3087. inline const napi_node_version* VersionManagement::GetNodeVersion(Env env) {
  3088. const napi_node_version* result;
  3089. napi_status status = napi_get_node_version(env, &result);
  3090. NAPI_THROW_IF_FAILED(env, status, 0);
  3091. return result;
  3092. }
  3093. // These macros shouldn't be useful in user code.
  3094. #undef NAPI_THROW
  3095. #undef NAPI_THROW_IF_FAILED
  3096. } // namespace Napi
  3097. #endif // SRC_NAPI_INL_H_