napi-inl.h 129 KB

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