napi-inl.h 203 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303
  1. #ifndef SRC_NAPI_INL_H_
  2. #define SRC_NAPI_INL_H_
  3. ////////////////////////////////////////////////////////////////////////////////
  4. // Node-API C++ Wrapper Classes
  5. //
  6. // Inline header-only implementations for "Node-API" ABI-stable C APIs for
  7. // Node.js.
  8. ////////////////////////////////////////////////////////////////////////////////
  9. // Note: Do not include this file directly! Include "napi.h" instead.
  10. #include <algorithm>
  11. #include <cstring>
  12. #include <mutex>
  13. #include <type_traits>
  14. #include <utility>
  15. namespace Napi {
  16. #ifdef NAPI_CPP_CUSTOM_NAMESPACE
  17. namespace NAPI_CPP_CUSTOM_NAMESPACE {
  18. #endif
  19. // Helpers to handle functions exposed from C++.
  20. namespace details {
  21. // Attach a data item to an object and delete it when the object gets
  22. // garbage-collected.
  23. // TODO: Replace this code with `napi_add_finalizer()` whenever it becomes
  24. // available on all supported versions of Node.js.
  25. template <typename FreeType>
  26. inline napi_status AttachData(napi_env env,
  27. napi_value obj,
  28. FreeType* data,
  29. napi_finalize finalizer = nullptr,
  30. void* hint = nullptr) {
  31. napi_status status;
  32. if (finalizer == nullptr) {
  33. finalizer = [](napi_env /*env*/, void* data, void* /*hint*/) {
  34. delete static_cast<FreeType*>(data);
  35. };
  36. }
  37. #if (NAPI_VERSION < 5)
  38. napi_value symbol, external;
  39. status = napi_create_symbol(env, nullptr, &symbol);
  40. if (status == napi_ok) {
  41. status = napi_create_external(env, data, finalizer, hint, &external);
  42. if (status == napi_ok) {
  43. napi_property_descriptor desc = {nullptr,
  44. symbol,
  45. nullptr,
  46. nullptr,
  47. nullptr,
  48. external,
  49. napi_default,
  50. nullptr};
  51. status = napi_define_properties(env, obj, 1, &desc);
  52. }
  53. }
  54. #else // NAPI_VERSION >= 5
  55. status = napi_add_finalizer(env, obj, data, finalizer, hint, nullptr);
  56. #endif
  57. return status;
  58. }
  59. // For use in JS to C++ callback wrappers to catch any Napi::Error exceptions
  60. // and rethrow them as JavaScript exceptions before returning from the callback.
  61. template <typename Callable>
  62. inline napi_value WrapCallback(Callable callback) {
  63. #ifdef NAPI_CPP_EXCEPTIONS
  64. try {
  65. return callback();
  66. } catch (const Error& e) {
  67. e.ThrowAsJavaScriptException();
  68. return nullptr;
  69. }
  70. #else // NAPI_CPP_EXCEPTIONS
  71. // When C++ exceptions are disabled, errors are immediately thrown as JS
  72. // exceptions, so there is no need to catch and rethrow them here.
  73. return callback();
  74. #endif // NAPI_CPP_EXCEPTIONS
  75. }
  76. // For use in JS to C++ void callback wrappers to catch any Napi::Error
  77. // exceptions and rethrow them as JavaScript exceptions before returning from
  78. // the callback.
  79. template <typename Callable>
  80. inline void WrapVoidCallback(Callable callback) {
  81. #ifdef NAPI_CPP_EXCEPTIONS
  82. try {
  83. callback();
  84. } catch (const Error& e) {
  85. e.ThrowAsJavaScriptException();
  86. }
  87. #else // NAPI_CPP_EXCEPTIONS
  88. // When C++ exceptions are disabled, errors are immediately thrown as JS
  89. // exceptions, so there is no need to catch and rethrow them here.
  90. callback();
  91. #endif // NAPI_CPP_EXCEPTIONS
  92. }
  93. template <typename Callable, typename Return>
  94. struct CallbackData {
  95. static inline napi_value Wrapper(napi_env env, napi_callback_info info) {
  96. return details::WrapCallback([&] {
  97. CallbackInfo callbackInfo(env, info);
  98. CallbackData* callbackData =
  99. static_cast<CallbackData*>(callbackInfo.Data());
  100. callbackInfo.SetData(callbackData->data);
  101. return callbackData->callback(callbackInfo);
  102. });
  103. }
  104. Callable callback;
  105. void* data;
  106. };
  107. template <typename Callable>
  108. struct CallbackData<Callable, void> {
  109. static inline napi_value Wrapper(napi_env env, napi_callback_info info) {
  110. return details::WrapCallback([&] {
  111. CallbackInfo callbackInfo(env, info);
  112. CallbackData* callbackData =
  113. static_cast<CallbackData*>(callbackInfo.Data());
  114. callbackInfo.SetData(callbackData->data);
  115. callbackData->callback(callbackInfo);
  116. return nullptr;
  117. });
  118. }
  119. Callable callback;
  120. void* data;
  121. };
  122. template <void (*Callback)(const CallbackInfo& info)>
  123. napi_value TemplatedVoidCallback(napi_env env,
  124. napi_callback_info info) NAPI_NOEXCEPT {
  125. return details::WrapCallback([&] {
  126. CallbackInfo cbInfo(env, info);
  127. Callback(cbInfo);
  128. return nullptr;
  129. });
  130. }
  131. template <Napi::Value (*Callback)(const CallbackInfo& info)>
  132. napi_value TemplatedCallback(napi_env env,
  133. napi_callback_info info) NAPI_NOEXCEPT {
  134. return details::WrapCallback([&] {
  135. CallbackInfo cbInfo(env, info);
  136. return Callback(cbInfo);
  137. });
  138. }
  139. template <typename T,
  140. Napi::Value (T::*UnwrapCallback)(const CallbackInfo& info)>
  141. napi_value TemplatedInstanceCallback(napi_env env,
  142. napi_callback_info info) NAPI_NOEXCEPT {
  143. return details::WrapCallback([&] {
  144. CallbackInfo cbInfo(env, info);
  145. T* instance = T::Unwrap(cbInfo.This().As<Object>());
  146. return (instance->*UnwrapCallback)(cbInfo);
  147. });
  148. }
  149. template <typename T, void (T::*UnwrapCallback)(const CallbackInfo& info)>
  150. napi_value TemplatedInstanceVoidCallback(napi_env env, napi_callback_info info)
  151. NAPI_NOEXCEPT {
  152. return details::WrapCallback([&] {
  153. CallbackInfo cbInfo(env, info);
  154. T* instance = T::Unwrap(cbInfo.This().As<Object>());
  155. (instance->*UnwrapCallback)(cbInfo);
  156. return nullptr;
  157. });
  158. }
  159. template <typename T, typename Finalizer, typename Hint = void>
  160. struct FinalizeData {
  161. static inline void Wrapper(napi_env env,
  162. void* data,
  163. void* finalizeHint) NAPI_NOEXCEPT {
  164. WrapVoidCallback([&] {
  165. FinalizeData* finalizeData = static_cast<FinalizeData*>(finalizeHint);
  166. finalizeData->callback(Env(env), static_cast<T*>(data));
  167. delete finalizeData;
  168. });
  169. }
  170. static inline void WrapperWithHint(napi_env env,
  171. void* data,
  172. void* finalizeHint) NAPI_NOEXCEPT {
  173. WrapVoidCallback([&] {
  174. FinalizeData* finalizeData = static_cast<FinalizeData*>(finalizeHint);
  175. finalizeData->callback(
  176. Env(env), static_cast<T*>(data), finalizeData->hint);
  177. delete finalizeData;
  178. });
  179. }
  180. Finalizer callback;
  181. Hint* hint;
  182. };
  183. #if (NAPI_VERSION > 3 && !defined(__wasm32__))
  184. template <typename ContextType = void,
  185. typename Finalizer = std::function<void(Env, void*, ContextType*)>,
  186. typename FinalizerDataType = void>
  187. struct ThreadSafeFinalize {
  188. static inline void Wrapper(napi_env env,
  189. void* rawFinalizeData,
  190. void* /* rawContext */) {
  191. if (rawFinalizeData == nullptr) return;
  192. ThreadSafeFinalize* finalizeData =
  193. static_cast<ThreadSafeFinalize*>(rawFinalizeData);
  194. finalizeData->callback(Env(env));
  195. delete finalizeData;
  196. }
  197. static inline void FinalizeWrapperWithData(napi_env env,
  198. void* rawFinalizeData,
  199. void* /* rawContext */) {
  200. if (rawFinalizeData == nullptr) return;
  201. ThreadSafeFinalize* finalizeData =
  202. static_cast<ThreadSafeFinalize*>(rawFinalizeData);
  203. finalizeData->callback(Env(env), finalizeData->data);
  204. delete finalizeData;
  205. }
  206. static inline void FinalizeWrapperWithContext(napi_env env,
  207. void* rawFinalizeData,
  208. void* rawContext) {
  209. if (rawFinalizeData == nullptr) return;
  210. ThreadSafeFinalize* finalizeData =
  211. static_cast<ThreadSafeFinalize*>(rawFinalizeData);
  212. finalizeData->callback(Env(env), static_cast<ContextType*>(rawContext));
  213. delete finalizeData;
  214. }
  215. static inline void FinalizeFinalizeWrapperWithDataAndContext(
  216. napi_env env, void* rawFinalizeData, void* rawContext) {
  217. if (rawFinalizeData == nullptr) return;
  218. ThreadSafeFinalize* finalizeData =
  219. static_cast<ThreadSafeFinalize*>(rawFinalizeData);
  220. finalizeData->callback(
  221. Env(env), finalizeData->data, static_cast<ContextType*>(rawContext));
  222. delete finalizeData;
  223. }
  224. FinalizerDataType* data;
  225. Finalizer callback;
  226. };
  227. template <typename ContextType, typename DataType, typename CallJs, CallJs call>
  228. inline typename std::enable_if<call != static_cast<CallJs>(nullptr)>::type
  229. CallJsWrapper(napi_env env, napi_value jsCallback, void* context, void* data) {
  230. call(env,
  231. Function(env, jsCallback),
  232. static_cast<ContextType*>(context),
  233. static_cast<DataType*>(data));
  234. }
  235. template <typename ContextType, typename DataType, typename CallJs, CallJs call>
  236. inline typename std::enable_if<call == static_cast<CallJs>(nullptr)>::type
  237. CallJsWrapper(napi_env env,
  238. napi_value jsCallback,
  239. void* /*context*/,
  240. void* /*data*/) {
  241. if (jsCallback != nullptr) {
  242. Function(env, jsCallback).Call(0, nullptr);
  243. }
  244. }
  245. #if NAPI_VERSION > 4
  246. template <typename CallbackType, typename TSFN>
  247. napi_value DefaultCallbackWrapper(napi_env /*env*/, std::nullptr_t /*cb*/) {
  248. return nullptr;
  249. }
  250. template <typename CallbackType, typename TSFN>
  251. napi_value DefaultCallbackWrapper(napi_env /*env*/, Napi::Function cb) {
  252. return cb;
  253. }
  254. #else
  255. template <typename CallbackType, typename TSFN>
  256. napi_value DefaultCallbackWrapper(napi_env env, Napi::Function cb) {
  257. if (cb.IsEmpty()) {
  258. return TSFN::EmptyFunctionFactory(env);
  259. }
  260. return cb;
  261. }
  262. #endif // NAPI_VERSION > 4
  263. #endif // NAPI_VERSION > 3 && !defined(__wasm32__)
  264. template <typename Getter, typename Setter>
  265. struct AccessorCallbackData {
  266. static inline napi_value GetterWrapper(napi_env env,
  267. napi_callback_info info) {
  268. return details::WrapCallback([&] {
  269. CallbackInfo callbackInfo(env, info);
  270. AccessorCallbackData* callbackData =
  271. static_cast<AccessorCallbackData*>(callbackInfo.Data());
  272. callbackInfo.SetData(callbackData->data);
  273. return callbackData->getterCallback(callbackInfo);
  274. });
  275. }
  276. static inline napi_value SetterWrapper(napi_env env,
  277. napi_callback_info info) {
  278. return details::WrapCallback([&] {
  279. CallbackInfo callbackInfo(env, info);
  280. AccessorCallbackData* callbackData =
  281. static_cast<AccessorCallbackData*>(callbackInfo.Data());
  282. callbackInfo.SetData(callbackData->data);
  283. callbackData->setterCallback(callbackInfo);
  284. return nullptr;
  285. });
  286. }
  287. Getter getterCallback;
  288. Setter setterCallback;
  289. void* data;
  290. };
  291. } // namespace details
  292. #ifndef NODE_ADDON_API_DISABLE_DEPRECATED
  293. #include "napi-inl.deprecated.h"
  294. #endif // !NODE_ADDON_API_DISABLE_DEPRECATED
  295. ////////////////////////////////////////////////////////////////////////////////
  296. // Module registration
  297. ////////////////////////////////////////////////////////////////////////////////
  298. // Register an add-on based on an initializer function.
  299. #define NODE_API_MODULE(modname, regfunc) \
  300. static napi_value __napi_##regfunc(napi_env env, napi_value exports) { \
  301. return Napi::RegisterModule(env, exports, regfunc); \
  302. } \
  303. NAPI_MODULE(modname, __napi_##regfunc)
  304. // Register an add-on based on a subclass of `Addon<T>` with a custom Node.js
  305. // module name.
  306. #define NODE_API_NAMED_ADDON(modname, classname) \
  307. static napi_value __napi_##classname(napi_env env, napi_value exports) { \
  308. return Napi::RegisterModule(env, exports, &classname::Init); \
  309. } \
  310. NAPI_MODULE(modname, __napi_##classname)
  311. // Register an add-on based on a subclass of `Addon<T>` with the Node.js module
  312. // name given by node-gyp from the `target_name` in binding.gyp.
  313. #define NODE_API_ADDON(classname) \
  314. NODE_API_NAMED_ADDON(NODE_GYP_MODULE_NAME, classname)
  315. // Adapt the NAPI_MODULE registration function:
  316. // - Wrap the arguments in NAPI wrappers.
  317. // - Catch any NAPI errors and rethrow as JS exceptions.
  318. inline napi_value RegisterModule(napi_env env,
  319. napi_value exports,
  320. ModuleRegisterCallback registerCallback) {
  321. return details::WrapCallback([&] {
  322. return napi_value(
  323. registerCallback(Napi::Env(env), Napi::Object(env, exports)));
  324. });
  325. }
  326. ////////////////////////////////////////////////////////////////////////////////
  327. // Maybe class
  328. ////////////////////////////////////////////////////////////////////////////////
  329. template <class T>
  330. bool Maybe<T>::IsNothing() const {
  331. return !_has_value;
  332. }
  333. template <class T>
  334. bool Maybe<T>::IsJust() const {
  335. return _has_value;
  336. }
  337. template <class T>
  338. void Maybe<T>::Check() const {
  339. NAPI_CHECK(IsJust(), "Napi::Maybe::Check", "Maybe value is Nothing.");
  340. }
  341. template <class T>
  342. T Maybe<T>::Unwrap() const {
  343. NAPI_CHECK(IsJust(), "Napi::Maybe::Unwrap", "Maybe value is Nothing.");
  344. return _value;
  345. }
  346. template <class T>
  347. T Maybe<T>::UnwrapOr(const T& default_value) const {
  348. return _has_value ? _value : default_value;
  349. }
  350. template <class T>
  351. bool Maybe<T>::UnwrapTo(T* out) const {
  352. if (IsJust()) {
  353. *out = _value;
  354. return true;
  355. };
  356. return false;
  357. }
  358. template <class T>
  359. bool Maybe<T>::operator==(const Maybe& other) const {
  360. return (IsJust() == other.IsJust()) &&
  361. (!IsJust() || Unwrap() == other.Unwrap());
  362. }
  363. template <class T>
  364. bool Maybe<T>::operator!=(const Maybe& other) const {
  365. return !operator==(other);
  366. }
  367. template <class T>
  368. Maybe<T>::Maybe() : _has_value(false) {}
  369. template <class T>
  370. Maybe<T>::Maybe(const T& t) : _has_value(true), _value(t) {}
  371. template <class T>
  372. inline Maybe<T> Nothing() {
  373. return Maybe<T>();
  374. }
  375. template <class T>
  376. inline Maybe<T> Just(const T& t) {
  377. return Maybe<T>(t);
  378. }
  379. ////////////////////////////////////////////////////////////////////////////////
  380. // Env class
  381. ////////////////////////////////////////////////////////////////////////////////
  382. inline Env::Env(napi_env env) : _env(env) {}
  383. inline Env::operator napi_env() const {
  384. return _env;
  385. }
  386. inline Object Env::Global() const {
  387. napi_value value;
  388. napi_status status = napi_get_global(*this, &value);
  389. NAPI_THROW_IF_FAILED(*this, status, Object());
  390. return Object(*this, value);
  391. }
  392. inline Value Env::Undefined() const {
  393. napi_value value;
  394. napi_status status = napi_get_undefined(*this, &value);
  395. NAPI_THROW_IF_FAILED(*this, status, Value());
  396. return Value(*this, value);
  397. }
  398. inline Value Env::Null() const {
  399. napi_value value;
  400. napi_status status = napi_get_null(*this, &value);
  401. NAPI_THROW_IF_FAILED(*this, status, Value());
  402. return Value(*this, value);
  403. }
  404. inline bool Env::IsExceptionPending() const {
  405. bool result;
  406. napi_status status = napi_is_exception_pending(_env, &result);
  407. if (status != napi_ok)
  408. result = false; // Checking for a pending exception shouldn't throw.
  409. return result;
  410. }
  411. inline Error Env::GetAndClearPendingException() const {
  412. napi_value value;
  413. napi_status status = napi_get_and_clear_last_exception(_env, &value);
  414. if (status != napi_ok) {
  415. // Don't throw another exception when failing to get the exception!
  416. return Error();
  417. }
  418. return Error(_env, value);
  419. }
  420. inline MaybeOrValue<Value> Env::RunScript(const char* utf8script) const {
  421. String script = String::New(_env, utf8script);
  422. return RunScript(script);
  423. }
  424. inline MaybeOrValue<Value> Env::RunScript(const std::string& utf8script) const {
  425. return RunScript(utf8script.c_str());
  426. }
  427. inline MaybeOrValue<Value> Env::RunScript(String script) const {
  428. napi_value result;
  429. napi_status status = napi_run_script(_env, script, &result);
  430. NAPI_RETURN_OR_THROW_IF_FAILED(
  431. _env, status, Napi::Value(_env, result), Napi::Value);
  432. }
  433. #if NAPI_VERSION > 2
  434. template <typename Hook, typename Arg>
  435. void Env::CleanupHook<Hook, Arg>::Wrapper(void* data) NAPI_NOEXCEPT {
  436. auto* cleanupData =
  437. static_cast<typename Napi::Env::CleanupHook<Hook, Arg>::CleanupData*>(
  438. data);
  439. cleanupData->hook();
  440. delete cleanupData;
  441. }
  442. template <typename Hook, typename Arg>
  443. void Env::CleanupHook<Hook, Arg>::WrapperWithArg(void* data) NAPI_NOEXCEPT {
  444. auto* cleanupData =
  445. static_cast<typename Napi::Env::CleanupHook<Hook, Arg>::CleanupData*>(
  446. data);
  447. cleanupData->hook(static_cast<Arg*>(cleanupData->arg));
  448. delete cleanupData;
  449. }
  450. #endif // NAPI_VERSION > 2
  451. #if NAPI_VERSION > 5
  452. template <typename T, Env::Finalizer<T> fini>
  453. inline void Env::SetInstanceData(T* data) const {
  454. napi_status status = napi_set_instance_data(
  455. _env,
  456. data,
  457. [](napi_env env, void* data, void*) { fini(env, static_cast<T*>(data)); },
  458. nullptr);
  459. NAPI_THROW_IF_FAILED_VOID(_env, status);
  460. }
  461. template <typename DataType,
  462. typename HintType,
  463. Napi::Env::FinalizerWithHint<DataType, HintType> fini>
  464. inline void Env::SetInstanceData(DataType* data, HintType* hint) const {
  465. napi_status status = napi_set_instance_data(
  466. _env,
  467. data,
  468. [](napi_env env, void* data, void* hint) {
  469. fini(env, static_cast<DataType*>(data), static_cast<HintType*>(hint));
  470. },
  471. hint);
  472. NAPI_THROW_IF_FAILED_VOID(_env, status);
  473. }
  474. template <typename T>
  475. inline T* Env::GetInstanceData() const {
  476. void* data = nullptr;
  477. napi_status status = napi_get_instance_data(_env, &data);
  478. NAPI_THROW_IF_FAILED(_env, status, nullptr);
  479. return static_cast<T*>(data);
  480. }
  481. template <typename T>
  482. void Env::DefaultFini(Env, T* data) {
  483. delete data;
  484. }
  485. template <typename DataType, typename HintType>
  486. void Env::DefaultFiniWithHint(Env, DataType* data, HintType*) {
  487. delete data;
  488. }
  489. #endif // NAPI_VERSION > 5
  490. ////////////////////////////////////////////////////////////////////////////////
  491. // Value class
  492. ////////////////////////////////////////////////////////////////////////////////
  493. inline Value::Value() : _env(nullptr), _value(nullptr) {}
  494. inline Value::Value(napi_env env, napi_value value)
  495. : _env(env), _value(value) {}
  496. inline Value::operator napi_value() const {
  497. return _value;
  498. }
  499. inline bool Value::operator==(const Value& other) const {
  500. return StrictEquals(other);
  501. }
  502. inline bool Value::operator!=(const Value& other) const {
  503. return !this->operator==(other);
  504. }
  505. inline bool Value::StrictEquals(const Value& other) const {
  506. bool result;
  507. napi_status status = napi_strict_equals(_env, *this, other, &result);
  508. NAPI_THROW_IF_FAILED(_env, status, false);
  509. return result;
  510. }
  511. inline Napi::Env Value::Env() const {
  512. return Napi::Env(_env);
  513. }
  514. inline bool Value::IsEmpty() const {
  515. return _value == nullptr;
  516. }
  517. inline napi_valuetype Value::Type() const {
  518. if (IsEmpty()) {
  519. return napi_undefined;
  520. }
  521. napi_valuetype type;
  522. napi_status status = napi_typeof(_env, _value, &type);
  523. NAPI_THROW_IF_FAILED(_env, status, napi_undefined);
  524. return type;
  525. }
  526. inline bool Value::IsUndefined() const {
  527. return Type() == napi_undefined;
  528. }
  529. inline bool Value::IsNull() const {
  530. return Type() == napi_null;
  531. }
  532. inline bool Value::IsBoolean() const {
  533. return Type() == napi_boolean;
  534. }
  535. inline bool Value::IsNumber() const {
  536. return Type() == napi_number;
  537. }
  538. #if NAPI_VERSION > 5
  539. inline bool Value::IsBigInt() const {
  540. return Type() == napi_bigint;
  541. }
  542. #endif // NAPI_VERSION > 5
  543. #if (NAPI_VERSION > 4)
  544. inline bool Value::IsDate() const {
  545. if (IsEmpty()) {
  546. return false;
  547. }
  548. bool result;
  549. napi_status status = napi_is_date(_env, _value, &result);
  550. NAPI_THROW_IF_FAILED(_env, status, false);
  551. return result;
  552. }
  553. #endif
  554. inline bool Value::IsString() const {
  555. return Type() == napi_string;
  556. }
  557. inline bool Value::IsSymbol() const {
  558. return Type() == napi_symbol;
  559. }
  560. inline bool Value::IsArray() const {
  561. if (IsEmpty()) {
  562. return false;
  563. }
  564. bool result;
  565. napi_status status = napi_is_array(_env, _value, &result);
  566. NAPI_THROW_IF_FAILED(_env, status, false);
  567. return result;
  568. }
  569. inline bool Value::IsArrayBuffer() const {
  570. if (IsEmpty()) {
  571. return false;
  572. }
  573. bool result;
  574. napi_status status = napi_is_arraybuffer(_env, _value, &result);
  575. NAPI_THROW_IF_FAILED(_env, status, false);
  576. return result;
  577. }
  578. inline bool Value::IsTypedArray() const {
  579. if (IsEmpty()) {
  580. return false;
  581. }
  582. bool result;
  583. napi_status status = napi_is_typedarray(_env, _value, &result);
  584. NAPI_THROW_IF_FAILED(_env, status, false);
  585. return result;
  586. }
  587. inline bool Value::IsObject() const {
  588. return Type() == napi_object || IsFunction();
  589. }
  590. inline bool Value::IsFunction() const {
  591. return Type() == napi_function;
  592. }
  593. inline bool Value::IsPromise() const {
  594. if (IsEmpty()) {
  595. return false;
  596. }
  597. bool result;
  598. napi_status status = napi_is_promise(_env, _value, &result);
  599. NAPI_THROW_IF_FAILED(_env, status, false);
  600. return result;
  601. }
  602. inline bool Value::IsDataView() const {
  603. if (IsEmpty()) {
  604. return false;
  605. }
  606. bool result;
  607. napi_status status = napi_is_dataview(_env, _value, &result);
  608. NAPI_THROW_IF_FAILED(_env, status, false);
  609. return result;
  610. }
  611. inline bool Value::IsBuffer() const {
  612. if (IsEmpty()) {
  613. return false;
  614. }
  615. bool result;
  616. napi_status status = napi_is_buffer(_env, _value, &result);
  617. NAPI_THROW_IF_FAILED(_env, status, false);
  618. return result;
  619. }
  620. inline bool Value::IsExternal() const {
  621. return Type() == napi_external;
  622. }
  623. template <typename T>
  624. inline T Value::As() const {
  625. return T(_env, _value);
  626. }
  627. inline MaybeOrValue<Boolean> Value::ToBoolean() const {
  628. napi_value result;
  629. napi_status status = napi_coerce_to_bool(_env, _value, &result);
  630. NAPI_RETURN_OR_THROW_IF_FAILED(
  631. _env, status, Napi::Boolean(_env, result), Napi::Boolean);
  632. }
  633. inline MaybeOrValue<Number> Value::ToNumber() const {
  634. napi_value result;
  635. napi_status status = napi_coerce_to_number(_env, _value, &result);
  636. NAPI_RETURN_OR_THROW_IF_FAILED(
  637. _env, status, Napi::Number(_env, result), Napi::Number);
  638. }
  639. inline MaybeOrValue<String> Value::ToString() const {
  640. napi_value result;
  641. napi_status status = napi_coerce_to_string(_env, _value, &result);
  642. NAPI_RETURN_OR_THROW_IF_FAILED(
  643. _env, status, Napi::String(_env, result), Napi::String);
  644. }
  645. inline MaybeOrValue<Object> Value::ToObject() const {
  646. napi_value result;
  647. napi_status status = napi_coerce_to_object(_env, _value, &result);
  648. NAPI_RETURN_OR_THROW_IF_FAILED(
  649. _env, status, Napi::Object(_env, result), Napi::Object);
  650. }
  651. ////////////////////////////////////////////////////////////////////////////////
  652. // Boolean class
  653. ////////////////////////////////////////////////////////////////////////////////
  654. inline Boolean Boolean::New(napi_env env, bool val) {
  655. napi_value value;
  656. napi_status status = napi_get_boolean(env, val, &value);
  657. NAPI_THROW_IF_FAILED(env, status, Boolean());
  658. return Boolean(env, value);
  659. }
  660. inline Boolean::Boolean() : Napi::Value() {}
  661. inline Boolean::Boolean(napi_env env, napi_value value)
  662. : Napi::Value(env, value) {}
  663. inline Boolean::operator bool() const {
  664. return Value();
  665. }
  666. inline bool Boolean::Value() const {
  667. bool result;
  668. napi_status status = napi_get_value_bool(_env, _value, &result);
  669. NAPI_THROW_IF_FAILED(_env, status, false);
  670. return result;
  671. }
  672. ////////////////////////////////////////////////////////////////////////////////
  673. // Number class
  674. ////////////////////////////////////////////////////////////////////////////////
  675. inline Number Number::New(napi_env env, double val) {
  676. napi_value value;
  677. napi_status status = napi_create_double(env, val, &value);
  678. NAPI_THROW_IF_FAILED(env, status, Number());
  679. return Number(env, value);
  680. }
  681. inline Number::Number() : Value() {}
  682. inline Number::Number(napi_env env, napi_value value) : Value(env, value) {}
  683. inline Number::operator int32_t() const {
  684. return Int32Value();
  685. }
  686. inline Number::operator uint32_t() const {
  687. return Uint32Value();
  688. }
  689. inline Number::operator int64_t() const {
  690. return Int64Value();
  691. }
  692. inline Number::operator float() const {
  693. return FloatValue();
  694. }
  695. inline Number::operator double() const {
  696. return DoubleValue();
  697. }
  698. inline int32_t Number::Int32Value() const {
  699. int32_t result;
  700. napi_status status = napi_get_value_int32(_env, _value, &result);
  701. NAPI_THROW_IF_FAILED(_env, status, 0);
  702. return result;
  703. }
  704. inline uint32_t Number::Uint32Value() const {
  705. uint32_t result;
  706. napi_status status = napi_get_value_uint32(_env, _value, &result);
  707. NAPI_THROW_IF_FAILED(_env, status, 0);
  708. return result;
  709. }
  710. inline int64_t Number::Int64Value() const {
  711. int64_t result;
  712. napi_status status = napi_get_value_int64(_env, _value, &result);
  713. NAPI_THROW_IF_FAILED(_env, status, 0);
  714. return result;
  715. }
  716. inline float Number::FloatValue() const {
  717. return static_cast<float>(DoubleValue());
  718. }
  719. inline double Number::DoubleValue() const {
  720. double result;
  721. napi_status status = napi_get_value_double(_env, _value, &result);
  722. NAPI_THROW_IF_FAILED(_env, status, 0);
  723. return result;
  724. }
  725. #if NAPI_VERSION > 5
  726. ////////////////////////////////////////////////////////////////////////////////
  727. // BigInt Class
  728. ////////////////////////////////////////////////////////////////////////////////
  729. inline BigInt BigInt::New(napi_env env, int64_t val) {
  730. napi_value value;
  731. napi_status status = napi_create_bigint_int64(env, val, &value);
  732. NAPI_THROW_IF_FAILED(env, status, BigInt());
  733. return BigInt(env, value);
  734. }
  735. inline BigInt BigInt::New(napi_env env, uint64_t val) {
  736. napi_value value;
  737. napi_status status = napi_create_bigint_uint64(env, val, &value);
  738. NAPI_THROW_IF_FAILED(env, status, BigInt());
  739. return BigInt(env, value);
  740. }
  741. inline BigInt BigInt::New(napi_env env,
  742. int sign_bit,
  743. size_t word_count,
  744. const uint64_t* words) {
  745. napi_value value;
  746. napi_status status =
  747. napi_create_bigint_words(env, sign_bit, word_count, words, &value);
  748. NAPI_THROW_IF_FAILED(env, status, BigInt());
  749. return BigInt(env, value);
  750. }
  751. inline BigInt::BigInt() : Value() {}
  752. inline BigInt::BigInt(napi_env env, napi_value value) : Value(env, value) {}
  753. inline int64_t BigInt::Int64Value(bool* lossless) const {
  754. int64_t result;
  755. napi_status status =
  756. napi_get_value_bigint_int64(_env, _value, &result, lossless);
  757. NAPI_THROW_IF_FAILED(_env, status, 0);
  758. return result;
  759. }
  760. inline uint64_t BigInt::Uint64Value(bool* lossless) const {
  761. uint64_t result;
  762. napi_status status =
  763. napi_get_value_bigint_uint64(_env, _value, &result, lossless);
  764. NAPI_THROW_IF_FAILED(_env, status, 0);
  765. return result;
  766. }
  767. inline size_t BigInt::WordCount() const {
  768. size_t word_count;
  769. napi_status status =
  770. napi_get_value_bigint_words(_env, _value, nullptr, &word_count, nullptr);
  771. NAPI_THROW_IF_FAILED(_env, status, 0);
  772. return word_count;
  773. }
  774. inline void BigInt::ToWords(int* sign_bit,
  775. size_t* word_count,
  776. uint64_t* words) {
  777. napi_status status =
  778. napi_get_value_bigint_words(_env, _value, sign_bit, word_count, words);
  779. NAPI_THROW_IF_FAILED_VOID(_env, status);
  780. }
  781. #endif // NAPI_VERSION > 5
  782. #if (NAPI_VERSION > 4)
  783. ////////////////////////////////////////////////////////////////////////////////
  784. // Date Class
  785. ////////////////////////////////////////////////////////////////////////////////
  786. inline Date Date::New(napi_env env, double val) {
  787. napi_value value;
  788. napi_status status = napi_create_date(env, val, &value);
  789. NAPI_THROW_IF_FAILED(env, status, Date());
  790. return Date(env, value);
  791. }
  792. inline Date::Date() : Value() {}
  793. inline Date::Date(napi_env env, napi_value value) : Value(env, value) {}
  794. inline Date::operator double() const {
  795. return ValueOf();
  796. }
  797. inline double Date::ValueOf() const {
  798. double result;
  799. napi_status status = napi_get_date_value(_env, _value, &result);
  800. NAPI_THROW_IF_FAILED(_env, status, 0);
  801. return result;
  802. }
  803. #endif
  804. ////////////////////////////////////////////////////////////////////////////////
  805. // Name class
  806. ////////////////////////////////////////////////////////////////////////////////
  807. inline Name::Name() : Value() {}
  808. inline Name::Name(napi_env env, napi_value value) : Value(env, value) {}
  809. ////////////////////////////////////////////////////////////////////////////////
  810. // String class
  811. ////////////////////////////////////////////////////////////////////////////////
  812. inline String String::New(napi_env env, const std::string& val) {
  813. return String::New(env, val.c_str(), val.size());
  814. }
  815. inline String String::New(napi_env env, const std::u16string& val) {
  816. return String::New(env, val.c_str(), val.size());
  817. }
  818. inline String String::New(napi_env env, const char* val) {
  819. // TODO(@gabrielschulhof) Remove if-statement when core's error handling is
  820. // available in all supported versions.
  821. if (val == nullptr) {
  822. // Throw an error that looks like it came from core.
  823. NAPI_THROW_IF_FAILED(env, napi_invalid_arg, String());
  824. }
  825. napi_value value;
  826. napi_status status =
  827. napi_create_string_utf8(env, val, std::strlen(val), &value);
  828. NAPI_THROW_IF_FAILED(env, status, String());
  829. return String(env, value);
  830. }
  831. inline String String::New(napi_env env, const char16_t* val) {
  832. napi_value value;
  833. // TODO(@gabrielschulhof) Remove if-statement when core's error handling is
  834. // available in all supported versions.
  835. if (val == nullptr) {
  836. // Throw an error that looks like it came from core.
  837. NAPI_THROW_IF_FAILED(env, napi_invalid_arg, String());
  838. }
  839. napi_status status =
  840. napi_create_string_utf16(env, val, std::u16string(val).size(), &value);
  841. NAPI_THROW_IF_FAILED(env, status, String());
  842. return String(env, value);
  843. }
  844. inline String String::New(napi_env env, const char* val, size_t length) {
  845. napi_value value;
  846. napi_status status = napi_create_string_utf8(env, val, length, &value);
  847. NAPI_THROW_IF_FAILED(env, status, String());
  848. return String(env, value);
  849. }
  850. inline String String::New(napi_env env, const char16_t* val, size_t length) {
  851. napi_value value;
  852. napi_status status = napi_create_string_utf16(env, val, length, &value);
  853. NAPI_THROW_IF_FAILED(env, status, String());
  854. return String(env, value);
  855. }
  856. inline String::String() : Name() {}
  857. inline String::String(napi_env env, napi_value value) : Name(env, value) {}
  858. inline String::operator std::string() const {
  859. return Utf8Value();
  860. }
  861. inline String::operator std::u16string() const {
  862. return Utf16Value();
  863. }
  864. inline std::string String::Utf8Value() const {
  865. size_t length;
  866. napi_status status =
  867. napi_get_value_string_utf8(_env, _value, nullptr, 0, &length);
  868. NAPI_THROW_IF_FAILED(_env, status, "");
  869. std::string value;
  870. value.reserve(length + 1);
  871. value.resize(length);
  872. status = napi_get_value_string_utf8(
  873. _env, _value, &value[0], value.capacity(), nullptr);
  874. NAPI_THROW_IF_FAILED(_env, status, "");
  875. return value;
  876. }
  877. inline std::u16string String::Utf16Value() const {
  878. size_t length;
  879. napi_status status =
  880. napi_get_value_string_utf16(_env, _value, nullptr, 0, &length);
  881. NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT(""));
  882. std::u16string value;
  883. value.reserve(length + 1);
  884. value.resize(length);
  885. status = napi_get_value_string_utf16(
  886. _env, _value, &value[0], value.capacity(), nullptr);
  887. NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT(""));
  888. return value;
  889. }
  890. ////////////////////////////////////////////////////////////////////////////////
  891. // Symbol class
  892. ////////////////////////////////////////////////////////////////////////////////
  893. inline Symbol Symbol::New(napi_env env, const char* description) {
  894. napi_value descriptionValue = description != nullptr
  895. ? String::New(env, description)
  896. : static_cast<napi_value>(nullptr);
  897. return Symbol::New(env, descriptionValue);
  898. }
  899. inline Symbol Symbol::New(napi_env env, const std::string& description) {
  900. napi_value descriptionValue = String::New(env, description);
  901. return Symbol::New(env, descriptionValue);
  902. }
  903. inline Symbol Symbol::New(napi_env env, String description) {
  904. napi_value descriptionValue = description;
  905. return Symbol::New(env, descriptionValue);
  906. }
  907. inline Symbol Symbol::New(napi_env env, napi_value description) {
  908. napi_value value;
  909. napi_status status = napi_create_symbol(env, description, &value);
  910. NAPI_THROW_IF_FAILED(env, status, Symbol());
  911. return Symbol(env, value);
  912. }
  913. inline MaybeOrValue<Symbol> Symbol::WellKnown(napi_env env,
  914. const std::string& name) {
  915. #if defined(NODE_ADDON_API_ENABLE_MAYBE)
  916. Value symbol_obj;
  917. Value symbol_value;
  918. if (Napi::Env(env).Global().Get("Symbol").UnwrapTo(&symbol_obj) &&
  919. symbol_obj.As<Object>().Get(name).UnwrapTo(&symbol_value)) {
  920. return Just<Symbol>(symbol_value.As<Symbol>());
  921. }
  922. return Nothing<Symbol>();
  923. #else
  924. return Napi::Env(env)
  925. .Global()
  926. .Get("Symbol")
  927. .As<Object>()
  928. .Get(name)
  929. .As<Symbol>();
  930. #endif
  931. }
  932. inline MaybeOrValue<Symbol> Symbol::For(napi_env env,
  933. const std::string& description) {
  934. napi_value descriptionValue = String::New(env, description);
  935. return Symbol::For(env, descriptionValue);
  936. }
  937. inline MaybeOrValue<Symbol> Symbol::For(napi_env env, const char* description) {
  938. napi_value descriptionValue = String::New(env, description);
  939. return Symbol::For(env, descriptionValue);
  940. }
  941. inline MaybeOrValue<Symbol> Symbol::For(napi_env env, String description) {
  942. return Symbol::For(env, static_cast<napi_value>(description));
  943. }
  944. inline MaybeOrValue<Symbol> Symbol::For(napi_env env, napi_value description) {
  945. #if defined(NODE_ADDON_API_ENABLE_MAYBE)
  946. Value symbol_obj;
  947. Value symbol_for_value;
  948. Value symbol_value;
  949. if (Napi::Env(env).Global().Get("Symbol").UnwrapTo(&symbol_obj) &&
  950. symbol_obj.As<Object>().Get("for").UnwrapTo(&symbol_for_value) &&
  951. symbol_for_value.As<Function>()
  952. .Call(symbol_obj, {description})
  953. .UnwrapTo(&symbol_value)) {
  954. return Just<Symbol>(symbol_value.As<Symbol>());
  955. }
  956. return Nothing<Symbol>();
  957. #else
  958. Object symbol_obj = Napi::Env(env).Global().Get("Symbol").As<Object>();
  959. return symbol_obj.Get("for")
  960. .As<Function>()
  961. .Call(symbol_obj, {description})
  962. .As<Symbol>();
  963. #endif
  964. }
  965. inline Symbol::Symbol() : Name() {}
  966. inline Symbol::Symbol(napi_env env, napi_value value) : Name(env, value) {}
  967. ////////////////////////////////////////////////////////////////////////////////
  968. // Automagic value creation
  969. ////////////////////////////////////////////////////////////////////////////////
  970. namespace details {
  971. template <typename T>
  972. struct vf_number {
  973. static Number From(napi_env env, T value) {
  974. return Number::New(env, static_cast<double>(value));
  975. }
  976. };
  977. template <>
  978. struct vf_number<bool> {
  979. static Boolean From(napi_env env, bool value) {
  980. return Boolean::New(env, value);
  981. }
  982. };
  983. struct vf_utf8_charp {
  984. static String From(napi_env env, const char* value) {
  985. return String::New(env, value);
  986. }
  987. };
  988. struct vf_utf16_charp {
  989. static String From(napi_env env, const char16_t* value) {
  990. return String::New(env, value);
  991. }
  992. };
  993. struct vf_utf8_string {
  994. static String From(napi_env env, const std::string& value) {
  995. return String::New(env, value);
  996. }
  997. };
  998. struct vf_utf16_string {
  999. static String From(napi_env env, const std::u16string& value) {
  1000. return String::New(env, value);
  1001. }
  1002. };
  1003. template <typename T>
  1004. struct vf_fallback {
  1005. static Value From(napi_env env, const T& value) { return Value(env, value); }
  1006. };
  1007. template <typename...>
  1008. struct disjunction : std::false_type {};
  1009. template <typename B>
  1010. struct disjunction<B> : B {};
  1011. template <typename B, typename... Bs>
  1012. struct disjunction<B, Bs...>
  1013. : std::conditional<bool(B::value), B, disjunction<Bs...>>::type {};
  1014. template <typename T>
  1015. struct can_make_string
  1016. : disjunction<typename std::is_convertible<T, const char*>::type,
  1017. typename std::is_convertible<T, const char16_t*>::type,
  1018. typename std::is_convertible<T, std::string>::type,
  1019. typename std::is_convertible<T, std::u16string>::type> {};
  1020. } // namespace details
  1021. template <typename T>
  1022. Value Value::From(napi_env env, const T& value) {
  1023. using Helper = typename std::conditional<
  1024. std::is_integral<T>::value || std::is_floating_point<T>::value,
  1025. details::vf_number<T>,
  1026. typename std::conditional<details::can_make_string<T>::value,
  1027. String,
  1028. details::vf_fallback<T>>::type>::type;
  1029. return Helper::From(env, value);
  1030. }
  1031. template <typename T>
  1032. String String::From(napi_env env, const T& value) {
  1033. struct Dummy {};
  1034. using Helper = typename std::conditional<
  1035. std::is_convertible<T, const char*>::value,
  1036. details::vf_utf8_charp,
  1037. typename std::conditional<
  1038. std::is_convertible<T, const char16_t*>::value,
  1039. details::vf_utf16_charp,
  1040. typename std::conditional<
  1041. std::is_convertible<T, std::string>::value,
  1042. details::vf_utf8_string,
  1043. typename std::conditional<
  1044. std::is_convertible<T, std::u16string>::value,
  1045. details::vf_utf16_string,
  1046. Dummy>::type>::type>::type>::type;
  1047. return Helper::From(env, value);
  1048. }
  1049. ////////////////////////////////////////////////////////////////////////////////
  1050. // Object class
  1051. ////////////////////////////////////////////////////////////////////////////////
  1052. template <typename Key>
  1053. inline Object::PropertyLValue<Key>::operator Value() const {
  1054. MaybeOrValue<Value> val = Object(_env, _object).Get(_key);
  1055. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  1056. return val.Unwrap();
  1057. #else
  1058. return val;
  1059. #endif
  1060. }
  1061. template <typename Key>
  1062. template <typename ValueType>
  1063. inline Object::PropertyLValue<Key>& Object::PropertyLValue<Key>::operator=(
  1064. ValueType value) {
  1065. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  1066. MaybeOrValue<bool> result =
  1067. #endif
  1068. Object(_env, _object).Set(_key, value);
  1069. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  1070. result.Unwrap();
  1071. #endif
  1072. return *this;
  1073. }
  1074. template <typename Key>
  1075. inline Object::PropertyLValue<Key>::PropertyLValue(Object object, Key key)
  1076. : _env(object.Env()), _object(object), _key(key) {}
  1077. inline Object Object::New(napi_env env) {
  1078. napi_value value;
  1079. napi_status status = napi_create_object(env, &value);
  1080. NAPI_THROW_IF_FAILED(env, status, Object());
  1081. return Object(env, value);
  1082. }
  1083. inline Object::Object() : Value() {}
  1084. inline Object::Object(napi_env env, napi_value value) : Value(env, value) {}
  1085. inline Object::PropertyLValue<std::string> Object::operator[](
  1086. const char* utf8name) {
  1087. return PropertyLValue<std::string>(*this, utf8name);
  1088. }
  1089. inline Object::PropertyLValue<std::string> Object::operator[](
  1090. const std::string& utf8name) {
  1091. return PropertyLValue<std::string>(*this, utf8name);
  1092. }
  1093. inline Object::PropertyLValue<uint32_t> Object::operator[](uint32_t index) {
  1094. return PropertyLValue<uint32_t>(*this, index);
  1095. }
  1096. inline Object::PropertyLValue<Value> Object::operator[](Value index) const {
  1097. return PropertyLValue<Value>(*this, index);
  1098. }
  1099. inline MaybeOrValue<Value> Object::operator[](const char* utf8name) const {
  1100. return Get(utf8name);
  1101. }
  1102. inline MaybeOrValue<Value> Object::operator[](
  1103. const std::string& utf8name) const {
  1104. return Get(utf8name);
  1105. }
  1106. inline MaybeOrValue<Value> Object::operator[](uint32_t index) const {
  1107. return Get(index);
  1108. }
  1109. inline MaybeOrValue<bool> Object::Has(napi_value key) const {
  1110. bool result;
  1111. napi_status status = napi_has_property(_env, _value, key, &result);
  1112. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1113. }
  1114. inline MaybeOrValue<bool> Object::Has(Value key) const {
  1115. bool result;
  1116. napi_status status = napi_has_property(_env, _value, key, &result);
  1117. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1118. }
  1119. inline MaybeOrValue<bool> Object::Has(const char* utf8name) const {
  1120. bool result;
  1121. napi_status status = napi_has_named_property(_env, _value, utf8name, &result);
  1122. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1123. }
  1124. inline MaybeOrValue<bool> Object::Has(const std::string& utf8name) const {
  1125. return Has(utf8name.c_str());
  1126. }
  1127. inline MaybeOrValue<bool> Object::HasOwnProperty(napi_value key) const {
  1128. bool result;
  1129. napi_status status = napi_has_own_property(_env, _value, key, &result);
  1130. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1131. }
  1132. inline MaybeOrValue<bool> Object::HasOwnProperty(Value key) const {
  1133. bool result;
  1134. napi_status status = napi_has_own_property(_env, _value, key, &result);
  1135. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1136. }
  1137. inline MaybeOrValue<bool> Object::HasOwnProperty(const char* utf8name) const {
  1138. napi_value key;
  1139. napi_status status =
  1140. napi_create_string_utf8(_env, utf8name, std::strlen(utf8name), &key);
  1141. NAPI_MAYBE_THROW_IF_FAILED(_env, status, bool);
  1142. return HasOwnProperty(key);
  1143. }
  1144. inline MaybeOrValue<bool> Object::HasOwnProperty(
  1145. const std::string& utf8name) const {
  1146. return HasOwnProperty(utf8name.c_str());
  1147. }
  1148. inline MaybeOrValue<Value> Object::Get(napi_value key) const {
  1149. napi_value result;
  1150. napi_status status = napi_get_property(_env, _value, key, &result);
  1151. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value);
  1152. }
  1153. inline MaybeOrValue<Value> Object::Get(Value key) const {
  1154. napi_value result;
  1155. napi_status status = napi_get_property(_env, _value, key, &result);
  1156. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value);
  1157. }
  1158. inline MaybeOrValue<Value> Object::Get(const char* utf8name) const {
  1159. napi_value result;
  1160. napi_status status = napi_get_named_property(_env, _value, utf8name, &result);
  1161. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value);
  1162. }
  1163. inline MaybeOrValue<Value> Object::Get(const std::string& utf8name) const {
  1164. return Get(utf8name.c_str());
  1165. }
  1166. template <typename ValueType>
  1167. inline MaybeOrValue<bool> Object::Set(napi_value key,
  1168. const ValueType& value) const {
  1169. napi_status status =
  1170. napi_set_property(_env, _value, key, Value::From(_env, value));
  1171. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1172. }
  1173. template <typename ValueType>
  1174. inline MaybeOrValue<bool> Object::Set(Value key, const ValueType& value) const {
  1175. napi_status status =
  1176. napi_set_property(_env, _value, key, Value::From(_env, value));
  1177. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1178. }
  1179. template <typename ValueType>
  1180. inline MaybeOrValue<bool> Object::Set(const char* utf8name,
  1181. const ValueType& value) const {
  1182. napi_status status =
  1183. napi_set_named_property(_env, _value, utf8name, Value::From(_env, value));
  1184. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1185. }
  1186. template <typename ValueType>
  1187. inline MaybeOrValue<bool> Object::Set(const std::string& utf8name,
  1188. const ValueType& value) const {
  1189. return Set(utf8name.c_str(), value);
  1190. }
  1191. inline MaybeOrValue<bool> Object::Delete(napi_value key) const {
  1192. bool result;
  1193. napi_status status = napi_delete_property(_env, _value, key, &result);
  1194. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1195. }
  1196. inline MaybeOrValue<bool> Object::Delete(Value key) const {
  1197. bool result;
  1198. napi_status status = napi_delete_property(_env, _value, key, &result);
  1199. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1200. }
  1201. inline MaybeOrValue<bool> Object::Delete(const char* utf8name) const {
  1202. return Delete(String::New(_env, utf8name));
  1203. }
  1204. inline MaybeOrValue<bool> Object::Delete(const std::string& utf8name) const {
  1205. return Delete(String::New(_env, utf8name));
  1206. }
  1207. inline MaybeOrValue<bool> Object::Has(uint32_t index) const {
  1208. bool result;
  1209. napi_status status = napi_has_element(_env, _value, index, &result);
  1210. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1211. }
  1212. inline MaybeOrValue<Value> Object::Get(uint32_t index) const {
  1213. napi_value value;
  1214. napi_status status = napi_get_element(_env, _value, index, &value);
  1215. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, value), Value);
  1216. }
  1217. template <typename ValueType>
  1218. inline MaybeOrValue<bool> Object::Set(uint32_t index,
  1219. const ValueType& value) const {
  1220. napi_status status =
  1221. napi_set_element(_env, _value, index, Value::From(_env, value));
  1222. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1223. }
  1224. inline MaybeOrValue<bool> Object::Delete(uint32_t index) const {
  1225. bool result;
  1226. napi_status status = napi_delete_element(_env, _value, index, &result);
  1227. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1228. }
  1229. inline MaybeOrValue<Array> Object::GetPropertyNames() const {
  1230. napi_value result;
  1231. napi_status status = napi_get_property_names(_env, _value, &result);
  1232. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Array(_env, result), Array);
  1233. }
  1234. inline MaybeOrValue<bool> Object::DefineProperty(
  1235. const PropertyDescriptor& property) const {
  1236. napi_status status = napi_define_properties(
  1237. _env,
  1238. _value,
  1239. 1,
  1240. reinterpret_cast<const napi_property_descriptor*>(&property));
  1241. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1242. }
  1243. inline MaybeOrValue<bool> Object::DefineProperties(
  1244. const std::initializer_list<PropertyDescriptor>& properties) const {
  1245. napi_status status = napi_define_properties(
  1246. _env,
  1247. _value,
  1248. properties.size(),
  1249. reinterpret_cast<const napi_property_descriptor*>(properties.begin()));
  1250. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1251. }
  1252. inline MaybeOrValue<bool> Object::DefineProperties(
  1253. const std::vector<PropertyDescriptor>& properties) const {
  1254. napi_status status = napi_define_properties(
  1255. _env,
  1256. _value,
  1257. properties.size(),
  1258. reinterpret_cast<const napi_property_descriptor*>(properties.data()));
  1259. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1260. }
  1261. inline MaybeOrValue<bool> Object::InstanceOf(
  1262. const Function& constructor) const {
  1263. bool result;
  1264. napi_status status = napi_instanceof(_env, _value, constructor, &result);
  1265. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1266. }
  1267. template <typename Finalizer, typename T>
  1268. inline void Object::AddFinalizer(Finalizer finalizeCallback, T* data) const {
  1269. details::FinalizeData<T, Finalizer>* finalizeData =
  1270. new details::FinalizeData<T, Finalizer>(
  1271. {std::move(finalizeCallback), nullptr});
  1272. napi_status status =
  1273. details::AttachData(_env,
  1274. *this,
  1275. data,
  1276. details::FinalizeData<T, Finalizer>::Wrapper,
  1277. finalizeData);
  1278. if (status != napi_ok) {
  1279. delete finalizeData;
  1280. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1281. }
  1282. }
  1283. template <typename Finalizer, typename T, typename Hint>
  1284. inline void Object::AddFinalizer(Finalizer finalizeCallback,
  1285. T* data,
  1286. Hint* finalizeHint) const {
  1287. details::FinalizeData<T, Finalizer, Hint>* finalizeData =
  1288. new details::FinalizeData<T, Finalizer, Hint>(
  1289. {std::move(finalizeCallback), finalizeHint});
  1290. napi_status status = details::AttachData(
  1291. _env,
  1292. *this,
  1293. data,
  1294. details::FinalizeData<T, Finalizer, Hint>::WrapperWithHint,
  1295. finalizeData);
  1296. if (status != napi_ok) {
  1297. delete finalizeData;
  1298. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1299. }
  1300. }
  1301. #ifdef NAPI_CPP_EXCEPTIONS
  1302. inline Object::const_iterator::const_iterator(const Object* object,
  1303. const Type type) {
  1304. _object = object;
  1305. _keys = object->GetPropertyNames();
  1306. _index = type == Type::BEGIN ? 0 : _keys.Length();
  1307. }
  1308. inline Object::const_iterator Napi::Object::begin() const {
  1309. const_iterator it(this, Object::const_iterator::Type::BEGIN);
  1310. return it;
  1311. }
  1312. inline Object::const_iterator Napi::Object::end() const {
  1313. const_iterator it(this, Object::const_iterator::Type::END);
  1314. return it;
  1315. }
  1316. inline Object::const_iterator& Object::const_iterator::operator++() {
  1317. ++_index;
  1318. return *this;
  1319. }
  1320. inline bool Object::const_iterator::operator==(
  1321. const const_iterator& other) const {
  1322. return _index == other._index;
  1323. }
  1324. inline bool Object::const_iterator::operator!=(
  1325. const const_iterator& other) const {
  1326. return _index != other._index;
  1327. }
  1328. inline const std::pair<Value, Object::PropertyLValue<Value>>
  1329. Object::const_iterator::operator*() const {
  1330. const Value key = _keys[_index];
  1331. const PropertyLValue<Value> value = (*_object)[key];
  1332. return {key, value};
  1333. }
  1334. inline Object::iterator::iterator(Object* object, const Type type) {
  1335. _object = object;
  1336. _keys = object->GetPropertyNames();
  1337. _index = type == Type::BEGIN ? 0 : _keys.Length();
  1338. }
  1339. inline Object::iterator Napi::Object::begin() {
  1340. iterator it(this, Object::iterator::Type::BEGIN);
  1341. return it;
  1342. }
  1343. inline Object::iterator Napi::Object::end() {
  1344. iterator it(this, Object::iterator::Type::END);
  1345. return it;
  1346. }
  1347. inline Object::iterator& Object::iterator::operator++() {
  1348. ++_index;
  1349. return *this;
  1350. }
  1351. inline bool Object::iterator::operator==(const iterator& other) const {
  1352. return _index == other._index;
  1353. }
  1354. inline bool Object::iterator::operator!=(const iterator& other) const {
  1355. return _index != other._index;
  1356. }
  1357. inline std::pair<Value, Object::PropertyLValue<Value>>
  1358. Object::iterator::operator*() {
  1359. Value key = _keys[_index];
  1360. PropertyLValue<Value> value = (*_object)[key];
  1361. return {key, value};
  1362. }
  1363. #endif // NAPI_CPP_EXCEPTIONS
  1364. #if NAPI_VERSION >= 8
  1365. inline MaybeOrValue<bool> Object::Freeze() const {
  1366. napi_status status = napi_object_freeze(_env, _value);
  1367. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1368. }
  1369. inline MaybeOrValue<bool> Object::Seal() const {
  1370. napi_status status = napi_object_seal(_env, _value);
  1371. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1372. }
  1373. #endif // NAPI_VERSION >= 8
  1374. ////////////////////////////////////////////////////////////////////////////////
  1375. // External class
  1376. ////////////////////////////////////////////////////////////////////////////////
  1377. template <typename T>
  1378. inline External<T> External<T>::New(napi_env env, T* data) {
  1379. napi_value value;
  1380. napi_status status =
  1381. napi_create_external(env, data, nullptr, nullptr, &value);
  1382. NAPI_THROW_IF_FAILED(env, status, External());
  1383. return External(env, value);
  1384. }
  1385. template <typename T>
  1386. template <typename Finalizer>
  1387. inline External<T> External<T>::New(napi_env env,
  1388. T* data,
  1389. Finalizer finalizeCallback) {
  1390. napi_value value;
  1391. details::FinalizeData<T, Finalizer>* finalizeData =
  1392. new details::FinalizeData<T, Finalizer>(
  1393. {std::move(finalizeCallback), nullptr});
  1394. napi_status status =
  1395. napi_create_external(env,
  1396. data,
  1397. details::FinalizeData<T, Finalizer>::Wrapper,
  1398. finalizeData,
  1399. &value);
  1400. if (status != napi_ok) {
  1401. delete finalizeData;
  1402. NAPI_THROW_IF_FAILED(env, status, External());
  1403. }
  1404. return External(env, value);
  1405. }
  1406. template <typename T>
  1407. template <typename Finalizer, typename Hint>
  1408. inline External<T> External<T>::New(napi_env env,
  1409. T* data,
  1410. Finalizer finalizeCallback,
  1411. Hint* finalizeHint) {
  1412. napi_value value;
  1413. details::FinalizeData<T, Finalizer, Hint>* finalizeData =
  1414. new details::FinalizeData<T, Finalizer, Hint>(
  1415. {std::move(finalizeCallback), finalizeHint});
  1416. napi_status status = napi_create_external(
  1417. env,
  1418. data,
  1419. details::FinalizeData<T, Finalizer, Hint>::WrapperWithHint,
  1420. finalizeData,
  1421. &value);
  1422. if (status != napi_ok) {
  1423. delete finalizeData;
  1424. NAPI_THROW_IF_FAILED(env, status, External());
  1425. }
  1426. return External(env, value);
  1427. }
  1428. template <typename T>
  1429. inline External<T>::External() : Value() {}
  1430. template <typename T>
  1431. inline External<T>::External(napi_env env, napi_value value)
  1432. : Value(env, value) {}
  1433. template <typename T>
  1434. inline T* External<T>::Data() const {
  1435. void* data;
  1436. napi_status status = napi_get_value_external(_env, _value, &data);
  1437. NAPI_THROW_IF_FAILED(_env, status, nullptr);
  1438. return reinterpret_cast<T*>(data);
  1439. }
  1440. ////////////////////////////////////////////////////////////////////////////////
  1441. // Array class
  1442. ////////////////////////////////////////////////////////////////////////////////
  1443. inline Array Array::New(napi_env env) {
  1444. napi_value value;
  1445. napi_status status = napi_create_array(env, &value);
  1446. NAPI_THROW_IF_FAILED(env, status, Array());
  1447. return Array(env, value);
  1448. }
  1449. inline Array Array::New(napi_env env, size_t length) {
  1450. napi_value value;
  1451. napi_status status = napi_create_array_with_length(env, length, &value);
  1452. NAPI_THROW_IF_FAILED(env, status, Array());
  1453. return Array(env, value);
  1454. }
  1455. inline Array::Array() : Object() {}
  1456. inline Array::Array(napi_env env, napi_value value) : Object(env, value) {}
  1457. inline uint32_t Array::Length() const {
  1458. uint32_t result;
  1459. napi_status status = napi_get_array_length(_env, _value, &result);
  1460. NAPI_THROW_IF_FAILED(_env, status, 0);
  1461. return result;
  1462. }
  1463. ////////////////////////////////////////////////////////////////////////////////
  1464. // ArrayBuffer class
  1465. ////////////////////////////////////////////////////////////////////////////////
  1466. inline ArrayBuffer ArrayBuffer::New(napi_env env, size_t byteLength) {
  1467. napi_value value;
  1468. void* data;
  1469. napi_status status = napi_create_arraybuffer(env, byteLength, &data, &value);
  1470. NAPI_THROW_IF_FAILED(env, status, ArrayBuffer());
  1471. return ArrayBuffer(env, value);
  1472. }
  1473. inline ArrayBuffer ArrayBuffer::New(napi_env env,
  1474. void* externalData,
  1475. size_t byteLength) {
  1476. napi_value value;
  1477. napi_status status = napi_create_external_arraybuffer(
  1478. env, externalData, byteLength, nullptr, nullptr, &value);
  1479. NAPI_THROW_IF_FAILED(env, status, ArrayBuffer());
  1480. return ArrayBuffer(env, value);
  1481. }
  1482. template <typename Finalizer>
  1483. inline ArrayBuffer ArrayBuffer::New(napi_env env,
  1484. void* externalData,
  1485. size_t byteLength,
  1486. Finalizer finalizeCallback) {
  1487. napi_value value;
  1488. details::FinalizeData<void, Finalizer>* finalizeData =
  1489. new details::FinalizeData<void, Finalizer>(
  1490. {std::move(finalizeCallback), nullptr});
  1491. napi_status status = napi_create_external_arraybuffer(
  1492. env,
  1493. externalData,
  1494. byteLength,
  1495. details::FinalizeData<void, Finalizer>::Wrapper,
  1496. finalizeData,
  1497. &value);
  1498. if (status != napi_ok) {
  1499. delete finalizeData;
  1500. NAPI_THROW_IF_FAILED(env, status, ArrayBuffer());
  1501. }
  1502. return ArrayBuffer(env, value);
  1503. }
  1504. template <typename Finalizer, typename Hint>
  1505. inline ArrayBuffer ArrayBuffer::New(napi_env env,
  1506. void* externalData,
  1507. size_t byteLength,
  1508. Finalizer finalizeCallback,
  1509. Hint* finalizeHint) {
  1510. napi_value value;
  1511. details::FinalizeData<void, Finalizer, Hint>* finalizeData =
  1512. new details::FinalizeData<void, Finalizer, Hint>(
  1513. {std::move(finalizeCallback), finalizeHint});
  1514. napi_status status = napi_create_external_arraybuffer(
  1515. env,
  1516. externalData,
  1517. byteLength,
  1518. details::FinalizeData<void, Finalizer, Hint>::WrapperWithHint,
  1519. finalizeData,
  1520. &value);
  1521. if (status != napi_ok) {
  1522. delete finalizeData;
  1523. NAPI_THROW_IF_FAILED(env, status, ArrayBuffer());
  1524. }
  1525. return ArrayBuffer(env, value);
  1526. }
  1527. inline ArrayBuffer::ArrayBuffer() : Object() {}
  1528. inline ArrayBuffer::ArrayBuffer(napi_env env, napi_value value)
  1529. : Object(env, value) {}
  1530. inline void* ArrayBuffer::Data() {
  1531. void* data;
  1532. napi_status status = napi_get_arraybuffer_info(_env, _value, &data, nullptr);
  1533. NAPI_THROW_IF_FAILED(_env, status, nullptr);
  1534. return data;
  1535. }
  1536. inline size_t ArrayBuffer::ByteLength() {
  1537. size_t length;
  1538. napi_status status =
  1539. napi_get_arraybuffer_info(_env, _value, nullptr, &length);
  1540. NAPI_THROW_IF_FAILED(_env, status, 0);
  1541. return length;
  1542. }
  1543. #if NAPI_VERSION >= 7
  1544. inline bool ArrayBuffer::IsDetached() const {
  1545. bool detached;
  1546. napi_status status = napi_is_detached_arraybuffer(_env, _value, &detached);
  1547. NAPI_THROW_IF_FAILED(_env, status, false);
  1548. return detached;
  1549. }
  1550. inline void ArrayBuffer::Detach() {
  1551. napi_status status = napi_detach_arraybuffer(_env, _value);
  1552. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1553. }
  1554. #endif // NAPI_VERSION >= 7
  1555. ////////////////////////////////////////////////////////////////////////////////
  1556. // DataView class
  1557. ////////////////////////////////////////////////////////////////////////////////
  1558. inline DataView DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer) {
  1559. return New(env, arrayBuffer, 0, arrayBuffer.ByteLength());
  1560. }
  1561. inline DataView DataView::New(napi_env env,
  1562. Napi::ArrayBuffer arrayBuffer,
  1563. size_t byteOffset) {
  1564. if (byteOffset > arrayBuffer.ByteLength()) {
  1565. NAPI_THROW(RangeError::New(
  1566. env, "Start offset is outside the bounds of the buffer"),
  1567. DataView());
  1568. }
  1569. return New(
  1570. env, arrayBuffer, byteOffset, arrayBuffer.ByteLength() - byteOffset);
  1571. }
  1572. inline DataView DataView::New(napi_env env,
  1573. Napi::ArrayBuffer arrayBuffer,
  1574. size_t byteOffset,
  1575. size_t byteLength) {
  1576. if (byteOffset + byteLength > arrayBuffer.ByteLength()) {
  1577. NAPI_THROW(RangeError::New(env, "Invalid DataView length"), DataView());
  1578. }
  1579. napi_value value;
  1580. napi_status status =
  1581. napi_create_dataview(env, byteLength, arrayBuffer, byteOffset, &value);
  1582. NAPI_THROW_IF_FAILED(env, status, DataView());
  1583. return DataView(env, value);
  1584. }
  1585. inline DataView::DataView() : Object() {}
  1586. inline DataView::DataView(napi_env env, napi_value value) : Object(env, value) {
  1587. napi_status status = napi_get_dataview_info(_env,
  1588. _value /* dataView */,
  1589. &_length /* byteLength */,
  1590. &_data /* data */,
  1591. nullptr /* arrayBuffer */,
  1592. nullptr /* byteOffset */);
  1593. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1594. }
  1595. inline Napi::ArrayBuffer DataView::ArrayBuffer() const {
  1596. napi_value arrayBuffer;
  1597. napi_status status = napi_get_dataview_info(_env,
  1598. _value /* dataView */,
  1599. nullptr /* byteLength */,
  1600. nullptr /* data */,
  1601. &arrayBuffer /* arrayBuffer */,
  1602. nullptr /* byteOffset */);
  1603. NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer());
  1604. return Napi::ArrayBuffer(_env, arrayBuffer);
  1605. }
  1606. inline size_t DataView::ByteOffset() const {
  1607. size_t byteOffset;
  1608. napi_status status = napi_get_dataview_info(_env,
  1609. _value /* dataView */,
  1610. nullptr /* byteLength */,
  1611. nullptr /* data */,
  1612. nullptr /* arrayBuffer */,
  1613. &byteOffset /* byteOffset */);
  1614. NAPI_THROW_IF_FAILED(_env, status, 0);
  1615. return byteOffset;
  1616. }
  1617. inline size_t DataView::ByteLength() const {
  1618. return _length;
  1619. }
  1620. inline void* DataView::Data() const {
  1621. return _data;
  1622. }
  1623. inline float DataView::GetFloat32(size_t byteOffset) const {
  1624. return ReadData<float>(byteOffset);
  1625. }
  1626. inline double DataView::GetFloat64(size_t byteOffset) const {
  1627. return ReadData<double>(byteOffset);
  1628. }
  1629. inline int8_t DataView::GetInt8(size_t byteOffset) const {
  1630. return ReadData<int8_t>(byteOffset);
  1631. }
  1632. inline int16_t DataView::GetInt16(size_t byteOffset) const {
  1633. return ReadData<int16_t>(byteOffset);
  1634. }
  1635. inline int32_t DataView::GetInt32(size_t byteOffset) const {
  1636. return ReadData<int32_t>(byteOffset);
  1637. }
  1638. inline uint8_t DataView::GetUint8(size_t byteOffset) const {
  1639. return ReadData<uint8_t>(byteOffset);
  1640. }
  1641. inline uint16_t DataView::GetUint16(size_t byteOffset) const {
  1642. return ReadData<uint16_t>(byteOffset);
  1643. }
  1644. inline uint32_t DataView::GetUint32(size_t byteOffset) const {
  1645. return ReadData<uint32_t>(byteOffset);
  1646. }
  1647. inline void DataView::SetFloat32(size_t byteOffset, float value) const {
  1648. WriteData<float>(byteOffset, value);
  1649. }
  1650. inline void DataView::SetFloat64(size_t byteOffset, double value) const {
  1651. WriteData<double>(byteOffset, value);
  1652. }
  1653. inline void DataView::SetInt8(size_t byteOffset, int8_t value) const {
  1654. WriteData<int8_t>(byteOffset, value);
  1655. }
  1656. inline void DataView::SetInt16(size_t byteOffset, int16_t value) const {
  1657. WriteData<int16_t>(byteOffset, value);
  1658. }
  1659. inline void DataView::SetInt32(size_t byteOffset, int32_t value) const {
  1660. WriteData<int32_t>(byteOffset, value);
  1661. }
  1662. inline void DataView::SetUint8(size_t byteOffset, uint8_t value) const {
  1663. WriteData<uint8_t>(byteOffset, value);
  1664. }
  1665. inline void DataView::SetUint16(size_t byteOffset, uint16_t value) const {
  1666. WriteData<uint16_t>(byteOffset, value);
  1667. }
  1668. inline void DataView::SetUint32(size_t byteOffset, uint32_t value) const {
  1669. WriteData<uint32_t>(byteOffset, value);
  1670. }
  1671. template <typename T>
  1672. inline T DataView::ReadData(size_t byteOffset) const {
  1673. if (byteOffset + sizeof(T) > _length ||
  1674. byteOffset + sizeof(T) < byteOffset) { // overflow
  1675. NAPI_THROW(
  1676. RangeError::New(_env, "Offset is outside the bounds of the DataView"),
  1677. 0);
  1678. }
  1679. return *reinterpret_cast<T*>(static_cast<uint8_t*>(_data) + byteOffset);
  1680. }
  1681. template <typename T>
  1682. inline void DataView::WriteData(size_t byteOffset, T value) const {
  1683. if (byteOffset + sizeof(T) > _length ||
  1684. byteOffset + sizeof(T) < byteOffset) { // overflow
  1685. NAPI_THROW_VOID(
  1686. RangeError::New(_env, "Offset is outside the bounds of the DataView"));
  1687. }
  1688. *reinterpret_cast<T*>(static_cast<uint8_t*>(_data) + byteOffset) = value;
  1689. }
  1690. ////////////////////////////////////////////////////////////////////////////////
  1691. // TypedArray class
  1692. ////////////////////////////////////////////////////////////////////////////////
  1693. inline TypedArray::TypedArray()
  1694. : Object(), _type(napi_typedarray_type::napi_int8_array), _length(0) {}
  1695. inline TypedArray::TypedArray(napi_env env, napi_value value)
  1696. : Object(env, value),
  1697. _type(napi_typedarray_type::napi_int8_array),
  1698. _length(0) {
  1699. if (value != nullptr) {
  1700. napi_status status =
  1701. napi_get_typedarray_info(_env,
  1702. _value,
  1703. &const_cast<TypedArray*>(this)->_type,
  1704. &const_cast<TypedArray*>(this)->_length,
  1705. nullptr,
  1706. nullptr,
  1707. nullptr);
  1708. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1709. }
  1710. }
  1711. inline TypedArray::TypedArray(napi_env env,
  1712. napi_value value,
  1713. napi_typedarray_type type,
  1714. size_t length)
  1715. : Object(env, value), _type(type), _length(length) {}
  1716. inline napi_typedarray_type TypedArray::TypedArrayType() const {
  1717. return _type;
  1718. }
  1719. inline uint8_t TypedArray::ElementSize() const {
  1720. switch (_type) {
  1721. case napi_int8_array:
  1722. case napi_uint8_array:
  1723. case napi_uint8_clamped_array:
  1724. return 1;
  1725. case napi_int16_array:
  1726. case napi_uint16_array:
  1727. return 2;
  1728. case napi_int32_array:
  1729. case napi_uint32_array:
  1730. case napi_float32_array:
  1731. return 4;
  1732. case napi_float64_array:
  1733. #if (NAPI_VERSION > 5)
  1734. case napi_bigint64_array:
  1735. case napi_biguint64_array:
  1736. #endif // (NAPI_VERSION > 5)
  1737. return 8;
  1738. default:
  1739. return 0;
  1740. }
  1741. }
  1742. inline size_t TypedArray::ElementLength() const {
  1743. return _length;
  1744. }
  1745. inline size_t TypedArray::ByteOffset() const {
  1746. size_t byteOffset;
  1747. napi_status status = napi_get_typedarray_info(
  1748. _env, _value, nullptr, nullptr, nullptr, nullptr, &byteOffset);
  1749. NAPI_THROW_IF_FAILED(_env, status, 0);
  1750. return byteOffset;
  1751. }
  1752. inline size_t TypedArray::ByteLength() const {
  1753. return ElementSize() * ElementLength();
  1754. }
  1755. inline Napi::ArrayBuffer TypedArray::ArrayBuffer() const {
  1756. napi_value arrayBuffer;
  1757. napi_status status = napi_get_typedarray_info(
  1758. _env, _value, nullptr, nullptr, nullptr, &arrayBuffer, nullptr);
  1759. NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer());
  1760. return Napi::ArrayBuffer(_env, arrayBuffer);
  1761. }
  1762. ////////////////////////////////////////////////////////////////////////////////
  1763. // TypedArrayOf<T> class
  1764. ////////////////////////////////////////////////////////////////////////////////
  1765. template <typename T>
  1766. inline TypedArrayOf<T> TypedArrayOf<T>::New(napi_env env,
  1767. size_t elementLength,
  1768. napi_typedarray_type type) {
  1769. Napi::ArrayBuffer arrayBuffer =
  1770. Napi::ArrayBuffer::New(env, elementLength * sizeof(T));
  1771. return New(env, elementLength, arrayBuffer, 0, type);
  1772. }
  1773. template <typename T>
  1774. inline TypedArrayOf<T> TypedArrayOf<T>::New(napi_env env,
  1775. size_t elementLength,
  1776. Napi::ArrayBuffer arrayBuffer,
  1777. size_t bufferOffset,
  1778. napi_typedarray_type type) {
  1779. napi_value value;
  1780. napi_status status = napi_create_typedarray(
  1781. env, type, elementLength, arrayBuffer, bufferOffset, &value);
  1782. NAPI_THROW_IF_FAILED(env, status, TypedArrayOf<T>());
  1783. return TypedArrayOf<T>(
  1784. env,
  1785. value,
  1786. type,
  1787. elementLength,
  1788. reinterpret_cast<T*>(reinterpret_cast<uint8_t*>(arrayBuffer.Data()) +
  1789. bufferOffset));
  1790. }
  1791. template <typename T>
  1792. inline TypedArrayOf<T>::TypedArrayOf() : TypedArray(), _data(nullptr) {}
  1793. template <typename T>
  1794. inline TypedArrayOf<T>::TypedArrayOf(napi_env env, napi_value value)
  1795. : TypedArray(env, value), _data(nullptr) {
  1796. napi_status status = napi_ok;
  1797. if (value != nullptr) {
  1798. void* data = nullptr;
  1799. status = napi_get_typedarray_info(
  1800. _env, _value, &_type, &_length, &data, nullptr, nullptr);
  1801. _data = static_cast<T*>(data);
  1802. } else {
  1803. _type = TypedArrayTypeForPrimitiveType<T>();
  1804. _length = 0;
  1805. }
  1806. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1807. }
  1808. template <typename T>
  1809. inline TypedArrayOf<T>::TypedArrayOf(napi_env env,
  1810. napi_value value,
  1811. napi_typedarray_type type,
  1812. size_t length,
  1813. T* data)
  1814. : TypedArray(env, value, type, length), _data(data) {
  1815. if (!(type == TypedArrayTypeForPrimitiveType<T>() ||
  1816. (type == napi_uint8_clamped_array &&
  1817. std::is_same<T, uint8_t>::value))) {
  1818. NAPI_THROW_VOID(TypeError::New(
  1819. env,
  1820. "Array type must match the template parameter. "
  1821. "(Uint8 arrays may optionally have the \"clamped\" array type.)"));
  1822. }
  1823. }
  1824. template <typename T>
  1825. inline T& TypedArrayOf<T>::operator[](size_t index) {
  1826. return _data[index];
  1827. }
  1828. template <typename T>
  1829. inline const T& TypedArrayOf<T>::operator[](size_t index) const {
  1830. return _data[index];
  1831. }
  1832. template <typename T>
  1833. inline T* TypedArrayOf<T>::Data() {
  1834. return _data;
  1835. }
  1836. template <typename T>
  1837. inline const T* TypedArrayOf<T>::Data() const {
  1838. return _data;
  1839. }
  1840. ////////////////////////////////////////////////////////////////////////////////
  1841. // Function class
  1842. ////////////////////////////////////////////////////////////////////////////////
  1843. template <typename CbData>
  1844. inline napi_status CreateFunction(napi_env env,
  1845. const char* utf8name,
  1846. napi_callback cb,
  1847. CbData* data,
  1848. napi_value* result) {
  1849. napi_status status =
  1850. napi_create_function(env, utf8name, NAPI_AUTO_LENGTH, cb, data, result);
  1851. if (status == napi_ok) {
  1852. status = Napi::details::AttachData(env, *result, data);
  1853. }
  1854. return status;
  1855. }
  1856. template <Function::VoidCallback cb>
  1857. inline Function Function::New(napi_env env, const char* utf8name, void* data) {
  1858. napi_value result = nullptr;
  1859. napi_status status = napi_create_function(env,
  1860. utf8name,
  1861. NAPI_AUTO_LENGTH,
  1862. details::TemplatedVoidCallback<cb>,
  1863. data,
  1864. &result);
  1865. NAPI_THROW_IF_FAILED(env, status, Function());
  1866. return Function(env, result);
  1867. }
  1868. template <Function::Callback cb>
  1869. inline Function Function::New(napi_env env, const char* utf8name, void* data) {
  1870. napi_value result = nullptr;
  1871. napi_status status = napi_create_function(env,
  1872. utf8name,
  1873. NAPI_AUTO_LENGTH,
  1874. details::TemplatedCallback<cb>,
  1875. data,
  1876. &result);
  1877. NAPI_THROW_IF_FAILED(env, status, Function());
  1878. return Function(env, result);
  1879. }
  1880. template <Function::VoidCallback cb>
  1881. inline Function Function::New(napi_env env,
  1882. const std::string& utf8name,
  1883. void* data) {
  1884. return Function::New<cb>(env, utf8name.c_str(), data);
  1885. }
  1886. template <Function::Callback cb>
  1887. inline Function Function::New(napi_env env,
  1888. const std::string& utf8name,
  1889. void* data) {
  1890. return Function::New<cb>(env, utf8name.c_str(), data);
  1891. }
  1892. template <typename Callable>
  1893. inline Function Function::New(napi_env env,
  1894. Callable cb,
  1895. const char* utf8name,
  1896. void* data) {
  1897. using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr)));
  1898. using CbData = details::CallbackData<Callable, ReturnType>;
  1899. auto callbackData = new CbData{std::move(cb), data};
  1900. napi_value value;
  1901. napi_status status =
  1902. CreateFunction(env, utf8name, CbData::Wrapper, callbackData, &value);
  1903. if (status != napi_ok) {
  1904. delete callbackData;
  1905. NAPI_THROW_IF_FAILED(env, status, Function());
  1906. }
  1907. return Function(env, value);
  1908. }
  1909. template <typename Callable>
  1910. inline Function Function::New(napi_env env,
  1911. Callable cb,
  1912. const std::string& utf8name,
  1913. void* data) {
  1914. return New(env, cb, utf8name.c_str(), data);
  1915. }
  1916. inline Function::Function() : Object() {}
  1917. inline Function::Function(napi_env env, napi_value value)
  1918. : Object(env, value) {}
  1919. inline MaybeOrValue<Value> Function::operator()(
  1920. const std::initializer_list<napi_value>& args) const {
  1921. return Call(Env().Undefined(), args);
  1922. }
  1923. inline MaybeOrValue<Value> Function::Call(
  1924. const std::initializer_list<napi_value>& args) const {
  1925. return Call(Env().Undefined(), args);
  1926. }
  1927. inline MaybeOrValue<Value> Function::Call(
  1928. const std::vector<napi_value>& args) const {
  1929. return Call(Env().Undefined(), args);
  1930. }
  1931. inline MaybeOrValue<Value> Function::Call(
  1932. const std::vector<Value>& args) const {
  1933. return Call(Env().Undefined(), args);
  1934. }
  1935. inline MaybeOrValue<Value> Function::Call(size_t argc,
  1936. const napi_value* args) const {
  1937. return Call(Env().Undefined(), argc, args);
  1938. }
  1939. inline MaybeOrValue<Value> Function::Call(
  1940. napi_value recv, const std::initializer_list<napi_value>& args) const {
  1941. return Call(recv, args.size(), args.begin());
  1942. }
  1943. inline MaybeOrValue<Value> Function::Call(
  1944. napi_value recv, const std::vector<napi_value>& args) const {
  1945. return Call(recv, args.size(), args.data());
  1946. }
  1947. inline MaybeOrValue<Value> Function::Call(
  1948. napi_value recv, const std::vector<Value>& args) const {
  1949. const size_t argc = args.size();
  1950. const size_t stackArgsCount = 6;
  1951. napi_value stackArgs[stackArgsCount];
  1952. std::vector<napi_value> heapArgs;
  1953. napi_value* argv;
  1954. if (argc <= stackArgsCount) {
  1955. argv = stackArgs;
  1956. } else {
  1957. heapArgs.resize(argc);
  1958. argv = heapArgs.data();
  1959. }
  1960. for (size_t index = 0; index < argc; index++) {
  1961. argv[index] = static_cast<napi_value>(args[index]);
  1962. }
  1963. return Call(recv, argc, argv);
  1964. }
  1965. inline MaybeOrValue<Value> Function::Call(napi_value recv,
  1966. size_t argc,
  1967. const napi_value* args) const {
  1968. napi_value result;
  1969. napi_status status =
  1970. napi_call_function(_env, recv, _value, argc, args, &result);
  1971. NAPI_RETURN_OR_THROW_IF_FAILED(
  1972. _env, status, Napi::Value(_env, result), Napi::Value);
  1973. }
  1974. inline MaybeOrValue<Value> Function::MakeCallback(
  1975. napi_value recv,
  1976. const std::initializer_list<napi_value>& args,
  1977. napi_async_context context) const {
  1978. return MakeCallback(recv, args.size(), args.begin(), context);
  1979. }
  1980. inline MaybeOrValue<Value> Function::MakeCallback(
  1981. napi_value recv,
  1982. const std::vector<napi_value>& args,
  1983. napi_async_context context) const {
  1984. return MakeCallback(recv, args.size(), args.data(), context);
  1985. }
  1986. inline MaybeOrValue<Value> Function::MakeCallback(
  1987. napi_value recv,
  1988. size_t argc,
  1989. const napi_value* args,
  1990. napi_async_context context) const {
  1991. napi_value result;
  1992. napi_status status =
  1993. napi_make_callback(_env, context, recv, _value, argc, args, &result);
  1994. NAPI_RETURN_OR_THROW_IF_FAILED(
  1995. _env, status, Napi::Value(_env, result), Napi::Value);
  1996. }
  1997. inline MaybeOrValue<Object> Function::New(
  1998. const std::initializer_list<napi_value>& args) const {
  1999. return New(args.size(), args.begin());
  2000. }
  2001. inline MaybeOrValue<Object> Function::New(
  2002. const std::vector<napi_value>& args) const {
  2003. return New(args.size(), args.data());
  2004. }
  2005. inline MaybeOrValue<Object> Function::New(size_t argc,
  2006. const napi_value* args) const {
  2007. napi_value result;
  2008. napi_status status = napi_new_instance(_env, _value, argc, args, &result);
  2009. NAPI_RETURN_OR_THROW_IF_FAILED(
  2010. _env, status, Napi::Object(_env, result), Napi::Object);
  2011. }
  2012. ////////////////////////////////////////////////////////////////////////////////
  2013. // Promise class
  2014. ////////////////////////////////////////////////////////////////////////////////
  2015. inline Promise::Deferred Promise::Deferred::New(napi_env env) {
  2016. return Promise::Deferred(env);
  2017. }
  2018. inline Promise::Deferred::Deferred(napi_env env) : _env(env) {
  2019. napi_status status = napi_create_promise(_env, &_deferred, &_promise);
  2020. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2021. }
  2022. inline Promise Promise::Deferred::Promise() const {
  2023. return Napi::Promise(_env, _promise);
  2024. }
  2025. inline Napi::Env Promise::Deferred::Env() const {
  2026. return Napi::Env(_env);
  2027. }
  2028. inline void Promise::Deferred::Resolve(napi_value value) const {
  2029. napi_status status = napi_resolve_deferred(_env, _deferred, value);
  2030. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2031. }
  2032. inline void Promise::Deferred::Reject(napi_value value) const {
  2033. napi_status status = napi_reject_deferred(_env, _deferred, value);
  2034. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2035. }
  2036. inline Promise::Promise(napi_env env, napi_value value) : Object(env, value) {}
  2037. ////////////////////////////////////////////////////////////////////////////////
  2038. // Buffer<T> class
  2039. ////////////////////////////////////////////////////////////////////////////////
  2040. template <typename T>
  2041. inline Buffer<T> Buffer<T>::New(napi_env env, size_t length) {
  2042. napi_value value;
  2043. void* data;
  2044. napi_status status =
  2045. napi_create_buffer(env, length * sizeof(T), &data, &value);
  2046. NAPI_THROW_IF_FAILED(env, status, Buffer<T>());
  2047. return Buffer(env, value, length, static_cast<T*>(data));
  2048. }
  2049. template <typename T>
  2050. inline Buffer<T> Buffer<T>::New(napi_env env, T* data, size_t length) {
  2051. napi_value value;
  2052. napi_status status = napi_create_external_buffer(
  2053. env, length * sizeof(T), data, nullptr, nullptr, &value);
  2054. NAPI_THROW_IF_FAILED(env, status, Buffer<T>());
  2055. return Buffer(env, value, length, data);
  2056. }
  2057. template <typename T>
  2058. template <typename Finalizer>
  2059. inline Buffer<T> Buffer<T>::New(napi_env env,
  2060. T* data,
  2061. size_t length,
  2062. Finalizer finalizeCallback) {
  2063. napi_value value;
  2064. details::FinalizeData<T, Finalizer>* finalizeData =
  2065. new details::FinalizeData<T, Finalizer>(
  2066. {std::move(finalizeCallback), nullptr});
  2067. napi_status status =
  2068. napi_create_external_buffer(env,
  2069. length * sizeof(T),
  2070. data,
  2071. details::FinalizeData<T, Finalizer>::Wrapper,
  2072. finalizeData,
  2073. &value);
  2074. if (status != napi_ok) {
  2075. delete finalizeData;
  2076. NAPI_THROW_IF_FAILED(env, status, Buffer());
  2077. }
  2078. return Buffer(env, value, length, data);
  2079. }
  2080. template <typename T>
  2081. template <typename Finalizer, typename Hint>
  2082. inline Buffer<T> Buffer<T>::New(napi_env env,
  2083. T* data,
  2084. size_t length,
  2085. Finalizer finalizeCallback,
  2086. Hint* finalizeHint) {
  2087. napi_value value;
  2088. details::FinalizeData<T, Finalizer, Hint>* finalizeData =
  2089. new details::FinalizeData<T, Finalizer, Hint>(
  2090. {std::move(finalizeCallback), finalizeHint});
  2091. napi_status status = napi_create_external_buffer(
  2092. env,
  2093. length * sizeof(T),
  2094. data,
  2095. details::FinalizeData<T, Finalizer, Hint>::WrapperWithHint,
  2096. finalizeData,
  2097. &value);
  2098. if (status != napi_ok) {
  2099. delete finalizeData;
  2100. NAPI_THROW_IF_FAILED(env, status, Buffer());
  2101. }
  2102. return Buffer(env, value, length, data);
  2103. }
  2104. template <typename T>
  2105. inline Buffer<T> Buffer<T>::Copy(napi_env env, const T* data, size_t length) {
  2106. napi_value value;
  2107. napi_status status =
  2108. napi_create_buffer_copy(env, length * sizeof(T), data, nullptr, &value);
  2109. NAPI_THROW_IF_FAILED(env, status, Buffer<T>());
  2110. return Buffer<T>(env, value);
  2111. }
  2112. template <typename T>
  2113. inline Buffer<T>::Buffer() : Uint8Array(), _length(0), _data(nullptr) {}
  2114. template <typename T>
  2115. inline Buffer<T>::Buffer(napi_env env, napi_value value)
  2116. : Uint8Array(env, value), _length(0), _data(nullptr) {}
  2117. template <typename T>
  2118. inline Buffer<T>::Buffer(napi_env env, napi_value value, size_t length, T* data)
  2119. : Uint8Array(env, value), _length(length), _data(data) {}
  2120. template <typename T>
  2121. inline size_t Buffer<T>::Length() const {
  2122. EnsureInfo();
  2123. return _length;
  2124. }
  2125. template <typename T>
  2126. inline T* Buffer<T>::Data() const {
  2127. EnsureInfo();
  2128. return _data;
  2129. }
  2130. template <typename T>
  2131. inline void Buffer<T>::EnsureInfo() const {
  2132. // The Buffer instance may have been constructed from a napi_value whose
  2133. // length/data are not yet known. Fetch and cache these values just once,
  2134. // since they can never change during the lifetime of the Buffer.
  2135. if (_data == nullptr) {
  2136. size_t byteLength;
  2137. void* voidData;
  2138. napi_status status =
  2139. napi_get_buffer_info(_env, _value, &voidData, &byteLength);
  2140. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2141. _length = byteLength / sizeof(T);
  2142. _data = static_cast<T*>(voidData);
  2143. }
  2144. }
  2145. ////////////////////////////////////////////////////////////////////////////////
  2146. // Error class
  2147. ////////////////////////////////////////////////////////////////////////////////
  2148. inline Error Error::New(napi_env env) {
  2149. napi_status status;
  2150. napi_value error = nullptr;
  2151. bool is_exception_pending;
  2152. napi_extended_error_info last_error_info_copy;
  2153. {
  2154. // We must retrieve the last error info before doing anything else because
  2155. // doing anything else will replace the last error info.
  2156. const napi_extended_error_info* last_error_info;
  2157. status = napi_get_last_error_info(env, &last_error_info);
  2158. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_last_error_info");
  2159. // All fields of the `napi_extended_error_info` structure gets reset in
  2160. // subsequent Node-API function calls on the same `env`. This includes a
  2161. // call to `napi_is_exception_pending()`. So here it is necessary to make a
  2162. // copy of the information as the `error_code` field is used later on.
  2163. memcpy(&last_error_info_copy,
  2164. last_error_info,
  2165. sizeof(napi_extended_error_info));
  2166. }
  2167. status = napi_is_exception_pending(env, &is_exception_pending);
  2168. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_is_exception_pending");
  2169. // A pending exception takes precedence over any internal error status.
  2170. if (is_exception_pending) {
  2171. status = napi_get_and_clear_last_exception(env, &error);
  2172. NAPI_FATAL_IF_FAILED(
  2173. status, "Error::New", "napi_get_and_clear_last_exception");
  2174. } else {
  2175. const char* error_message = last_error_info_copy.error_message != nullptr
  2176. ? last_error_info_copy.error_message
  2177. : "Error in native callback";
  2178. napi_value message;
  2179. status = napi_create_string_utf8(
  2180. env, error_message, std::strlen(error_message), &message);
  2181. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_string_utf8");
  2182. switch (last_error_info_copy.error_code) {
  2183. case napi_object_expected:
  2184. case napi_string_expected:
  2185. case napi_boolean_expected:
  2186. case napi_number_expected:
  2187. status = napi_create_type_error(env, nullptr, message, &error);
  2188. break;
  2189. default:
  2190. status = napi_create_error(env, nullptr, message, &error);
  2191. break;
  2192. }
  2193. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_error");
  2194. }
  2195. return Error(env, error);
  2196. }
  2197. inline Error Error::New(napi_env env, const char* message) {
  2198. return Error::New<Error>(
  2199. env, message, std::strlen(message), napi_create_error);
  2200. }
  2201. inline Error Error::New(napi_env env, const std::string& message) {
  2202. return Error::New<Error>(
  2203. env, message.c_str(), message.size(), napi_create_error);
  2204. }
  2205. inline NAPI_NO_RETURN void Error::Fatal(const char* location,
  2206. const char* message) {
  2207. napi_fatal_error(location, NAPI_AUTO_LENGTH, message, NAPI_AUTO_LENGTH);
  2208. }
  2209. inline Error::Error() : ObjectReference() {}
  2210. inline Error::Error(napi_env env, napi_value value)
  2211. : ObjectReference(env, nullptr) {
  2212. if (value != nullptr) {
  2213. // Attempting to create a reference on the error object.
  2214. // If it's not a Object/Function/Symbol, this call will return an error
  2215. // status.
  2216. napi_status status = napi_create_reference(env, value, 1, &_ref);
  2217. if (status != napi_ok) {
  2218. napi_value wrappedErrorObj;
  2219. // Create an error object
  2220. status = napi_create_object(env, &wrappedErrorObj);
  2221. NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_object");
  2222. // property flag that we attach to show the error object is wrapped
  2223. napi_property_descriptor wrapObjFlag = {
  2224. ERROR_WRAP_VALUE(), // Unique GUID identifier since Symbol isn't a
  2225. // viable option
  2226. nullptr,
  2227. nullptr,
  2228. nullptr,
  2229. nullptr,
  2230. Value::From(env, value),
  2231. napi_enumerable,
  2232. nullptr};
  2233. status = napi_define_properties(env, wrappedErrorObj, 1, &wrapObjFlag);
  2234. NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_define_properties");
  2235. // Create a reference on the newly wrapped object
  2236. status = napi_create_reference(env, wrappedErrorObj, 1, &_ref);
  2237. }
  2238. // Avoid infinite recursion in the failure case.
  2239. NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_reference");
  2240. }
  2241. }
  2242. inline Object Error::Value() const {
  2243. if (_ref == nullptr) {
  2244. return Object(_env, nullptr);
  2245. }
  2246. napi_value refValue;
  2247. napi_status status = napi_get_reference_value(_env, _ref, &refValue);
  2248. NAPI_THROW_IF_FAILED(_env, status, Object());
  2249. napi_valuetype type;
  2250. status = napi_typeof(_env, refValue, &type);
  2251. NAPI_THROW_IF_FAILED(_env, status, Object());
  2252. // If refValue isn't a symbol, then we proceed to whether the refValue has the
  2253. // wrapped error flag
  2254. if (type != napi_symbol) {
  2255. // We are checking if the object is wrapped
  2256. bool isWrappedObject = false;
  2257. status = napi_has_property(_env,
  2258. refValue,
  2259. String::From(_env, ERROR_WRAP_VALUE()),
  2260. &isWrappedObject);
  2261. // Don't care about status
  2262. if (isWrappedObject) {
  2263. napi_value unwrappedValue;
  2264. status = napi_get_property(_env,
  2265. refValue,
  2266. String::From(_env, ERROR_WRAP_VALUE()),
  2267. &unwrappedValue);
  2268. NAPI_THROW_IF_FAILED(_env, status, Object());
  2269. return Object(_env, unwrappedValue);
  2270. }
  2271. }
  2272. return Object(_env, refValue);
  2273. }
  2274. inline Error::Error(Error&& other) : ObjectReference(std::move(other)) {}
  2275. inline Error& Error::operator=(Error&& other) {
  2276. static_cast<Reference<Object>*>(this)->operator=(std::move(other));
  2277. return *this;
  2278. }
  2279. inline Error::Error(const Error& other) : ObjectReference(other) {}
  2280. inline Error& Error::operator=(const Error& other) {
  2281. Reset();
  2282. _env = other.Env();
  2283. HandleScope scope(_env);
  2284. napi_value value = other.Value();
  2285. if (value != nullptr) {
  2286. napi_status status = napi_create_reference(_env, value, 1, &_ref);
  2287. NAPI_THROW_IF_FAILED(_env, status, *this);
  2288. }
  2289. return *this;
  2290. }
  2291. inline const std::string& Error::Message() const NAPI_NOEXCEPT {
  2292. if (_message.size() == 0 && _env != nullptr) {
  2293. #ifdef NAPI_CPP_EXCEPTIONS
  2294. try {
  2295. _message = Get("message").As<String>();
  2296. } catch (...) {
  2297. // Catch all errors here, to include e.g. a std::bad_alloc from
  2298. // the std::string::operator=, because this method may not throw.
  2299. }
  2300. #else // NAPI_CPP_EXCEPTIONS
  2301. #if defined(NODE_ADDON_API_ENABLE_MAYBE)
  2302. Napi::Value message_val;
  2303. if (Get("message").UnwrapTo(&message_val)) {
  2304. _message = message_val.As<String>();
  2305. }
  2306. #else
  2307. _message = Get("message").As<String>();
  2308. #endif
  2309. #endif // NAPI_CPP_EXCEPTIONS
  2310. }
  2311. return _message;
  2312. }
  2313. // we created an object on the &_ref
  2314. inline void Error::ThrowAsJavaScriptException() const {
  2315. HandleScope scope(_env);
  2316. if (!IsEmpty()) {
  2317. #ifdef NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS
  2318. bool pendingException = false;
  2319. // check if there is already a pending exception. If so don't try to throw a
  2320. // new one as that is not allowed/possible
  2321. napi_status status = napi_is_exception_pending(_env, &pendingException);
  2322. if ((status != napi_ok) ||
  2323. ((status == napi_ok) && (pendingException == false))) {
  2324. // We intentionally don't use `NAPI_THROW_*` macros here to ensure
  2325. // that there is no possible recursion as `ThrowAsJavaScriptException`
  2326. // is part of `NAPI_THROW_*` macro definition for noexcept.
  2327. status = napi_throw(_env, Value());
  2328. if (status == napi_pending_exception) {
  2329. // The environment must be terminating as we checked earlier and there
  2330. // was no pending exception. In this case continuing will result
  2331. // in a fatal error and there is nothing the author has done incorrectly
  2332. // in their code that is worth flagging through a fatal error
  2333. return;
  2334. }
  2335. } else {
  2336. status = napi_pending_exception;
  2337. }
  2338. #else
  2339. // We intentionally don't use `NAPI_THROW_*` macros here to ensure
  2340. // that there is no possible recursion as `ThrowAsJavaScriptException`
  2341. // is part of `NAPI_THROW_*` macro definition for noexcept.
  2342. napi_status status = napi_throw(_env, Value());
  2343. #endif
  2344. #ifdef NAPI_CPP_EXCEPTIONS
  2345. if (status != napi_ok) {
  2346. throw Error::New(_env);
  2347. }
  2348. #else // NAPI_CPP_EXCEPTIONS
  2349. NAPI_FATAL_IF_FAILED(
  2350. status, "Error::ThrowAsJavaScriptException", "napi_throw");
  2351. #endif // NAPI_CPP_EXCEPTIONS
  2352. }
  2353. }
  2354. #ifdef NAPI_CPP_EXCEPTIONS
  2355. inline const char* Error::what() const NAPI_NOEXCEPT {
  2356. return Message().c_str();
  2357. }
  2358. #endif // NAPI_CPP_EXCEPTIONS
  2359. inline const char* Error::ERROR_WRAP_VALUE() NAPI_NOEXCEPT {
  2360. return "4bda9e7e-4913-4dbc-95de-891cbf66598e-errorVal";
  2361. }
  2362. template <typename TError>
  2363. inline TError Error::New(napi_env env,
  2364. const char* message,
  2365. size_t length,
  2366. create_error_fn create_error) {
  2367. napi_value str;
  2368. napi_status status = napi_create_string_utf8(env, message, length, &str);
  2369. NAPI_THROW_IF_FAILED(env, status, TError());
  2370. napi_value error;
  2371. status = create_error(env, nullptr, str, &error);
  2372. NAPI_THROW_IF_FAILED(env, status, TError());
  2373. return TError(env, error);
  2374. }
  2375. inline TypeError TypeError::New(napi_env env, const char* message) {
  2376. return Error::New<TypeError>(
  2377. env, message, std::strlen(message), napi_create_type_error);
  2378. }
  2379. inline TypeError TypeError::New(napi_env env, const std::string& message) {
  2380. return Error::New<TypeError>(
  2381. env, message.c_str(), message.size(), napi_create_type_error);
  2382. }
  2383. inline TypeError::TypeError() : Error() {}
  2384. inline TypeError::TypeError(napi_env env, napi_value value)
  2385. : Error(env, value) {}
  2386. inline RangeError RangeError::New(napi_env env, const char* message) {
  2387. return Error::New<RangeError>(
  2388. env, message, std::strlen(message), napi_create_range_error);
  2389. }
  2390. inline RangeError RangeError::New(napi_env env, const std::string& message) {
  2391. return Error::New<RangeError>(
  2392. env, message.c_str(), message.size(), napi_create_range_error);
  2393. }
  2394. inline RangeError::RangeError() : Error() {}
  2395. inline RangeError::RangeError(napi_env env, napi_value value)
  2396. : Error(env, value) {}
  2397. ////////////////////////////////////////////////////////////////////////////////
  2398. // Reference<T> class
  2399. ////////////////////////////////////////////////////////////////////////////////
  2400. template <typename T>
  2401. inline Reference<T> Reference<T>::New(const T& value,
  2402. uint32_t initialRefcount) {
  2403. napi_env env = value.Env();
  2404. napi_value val = value;
  2405. if (val == nullptr) {
  2406. return Reference<T>(env, nullptr);
  2407. }
  2408. napi_ref ref;
  2409. napi_status status = napi_create_reference(env, value, initialRefcount, &ref);
  2410. NAPI_THROW_IF_FAILED(env, status, Reference<T>());
  2411. return Reference<T>(env, ref);
  2412. }
  2413. template <typename T>
  2414. inline Reference<T>::Reference()
  2415. : _env(nullptr), _ref(nullptr), _suppressDestruct(false) {}
  2416. template <typename T>
  2417. inline Reference<T>::Reference(napi_env env, napi_ref ref)
  2418. : _env(env), _ref(ref), _suppressDestruct(false) {}
  2419. template <typename T>
  2420. inline Reference<T>::~Reference() {
  2421. if (_ref != nullptr) {
  2422. if (!_suppressDestruct) {
  2423. napi_delete_reference(_env, _ref);
  2424. }
  2425. _ref = nullptr;
  2426. }
  2427. }
  2428. template <typename T>
  2429. inline Reference<T>::Reference(Reference<T>&& other)
  2430. : _env(other._env),
  2431. _ref(other._ref),
  2432. _suppressDestruct(other._suppressDestruct) {
  2433. other._env = nullptr;
  2434. other._ref = nullptr;
  2435. other._suppressDestruct = false;
  2436. }
  2437. template <typename T>
  2438. inline Reference<T>& Reference<T>::operator=(Reference<T>&& other) {
  2439. Reset();
  2440. _env = other._env;
  2441. _ref = other._ref;
  2442. _suppressDestruct = other._suppressDestruct;
  2443. other._env = nullptr;
  2444. other._ref = nullptr;
  2445. other._suppressDestruct = false;
  2446. return *this;
  2447. }
  2448. template <typename T>
  2449. inline Reference<T>::Reference(const Reference<T>& other)
  2450. : _env(other._env), _ref(nullptr), _suppressDestruct(false) {
  2451. HandleScope scope(_env);
  2452. napi_value value = other.Value();
  2453. if (value != nullptr) {
  2454. // Copying is a limited scenario (currently only used for Error object) and
  2455. // always creates a strong reference to the given value even if the incoming
  2456. // reference is weak.
  2457. napi_status status = napi_create_reference(_env, value, 1, &_ref);
  2458. NAPI_FATAL_IF_FAILED(
  2459. status, "Reference<T>::Reference", "napi_create_reference");
  2460. }
  2461. }
  2462. template <typename T>
  2463. inline Reference<T>::operator napi_ref() const {
  2464. return _ref;
  2465. }
  2466. template <typename T>
  2467. inline bool Reference<T>::operator==(const Reference<T>& other) const {
  2468. HandleScope scope(_env);
  2469. return this->Value().StrictEquals(other.Value());
  2470. }
  2471. template <typename T>
  2472. inline bool Reference<T>::operator!=(const Reference<T>& other) const {
  2473. return !this->operator==(other);
  2474. }
  2475. template <typename T>
  2476. inline Napi::Env Reference<T>::Env() const {
  2477. return Napi::Env(_env);
  2478. }
  2479. template <typename T>
  2480. inline bool Reference<T>::IsEmpty() const {
  2481. return _ref == nullptr;
  2482. }
  2483. template <typename T>
  2484. inline T Reference<T>::Value() const {
  2485. if (_ref == nullptr) {
  2486. return T(_env, nullptr);
  2487. }
  2488. napi_value value;
  2489. napi_status status = napi_get_reference_value(_env, _ref, &value);
  2490. NAPI_THROW_IF_FAILED(_env, status, T());
  2491. return T(_env, value);
  2492. }
  2493. template <typename T>
  2494. inline uint32_t Reference<T>::Ref() const {
  2495. uint32_t result;
  2496. napi_status status = napi_reference_ref(_env, _ref, &result);
  2497. NAPI_THROW_IF_FAILED(_env, status, 0);
  2498. return result;
  2499. }
  2500. template <typename T>
  2501. inline uint32_t Reference<T>::Unref() const {
  2502. uint32_t result;
  2503. napi_status status = napi_reference_unref(_env, _ref, &result);
  2504. NAPI_THROW_IF_FAILED(_env, status, 0);
  2505. return result;
  2506. }
  2507. template <typename T>
  2508. inline void Reference<T>::Reset() {
  2509. if (_ref != nullptr) {
  2510. napi_status status = napi_delete_reference(_env, _ref);
  2511. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2512. _ref = nullptr;
  2513. }
  2514. }
  2515. template <typename T>
  2516. inline void Reference<T>::Reset(const T& value, uint32_t refcount) {
  2517. Reset();
  2518. _env = value.Env();
  2519. napi_value val = value;
  2520. if (val != nullptr) {
  2521. napi_status status = napi_create_reference(_env, value, refcount, &_ref);
  2522. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2523. }
  2524. }
  2525. template <typename T>
  2526. inline void Reference<T>::SuppressDestruct() {
  2527. _suppressDestruct = true;
  2528. }
  2529. template <typename T>
  2530. inline Reference<T> Weak(T value) {
  2531. return Reference<T>::New(value, 0);
  2532. }
  2533. inline ObjectReference Weak(Object value) {
  2534. return Reference<Object>::New(value, 0);
  2535. }
  2536. inline FunctionReference Weak(Function value) {
  2537. return Reference<Function>::New(value, 0);
  2538. }
  2539. template <typename T>
  2540. inline Reference<T> Persistent(T value) {
  2541. return Reference<T>::New(value, 1);
  2542. }
  2543. inline ObjectReference Persistent(Object value) {
  2544. return Reference<Object>::New(value, 1);
  2545. }
  2546. inline FunctionReference Persistent(Function value) {
  2547. return Reference<Function>::New(value, 1);
  2548. }
  2549. ////////////////////////////////////////////////////////////////////////////////
  2550. // ObjectReference class
  2551. ////////////////////////////////////////////////////////////////////////////////
  2552. inline ObjectReference::ObjectReference() : Reference<Object>() {}
  2553. inline ObjectReference::ObjectReference(napi_env env, napi_ref ref)
  2554. : Reference<Object>(env, ref) {}
  2555. inline ObjectReference::ObjectReference(Reference<Object>&& other)
  2556. : Reference<Object>(std::move(other)) {}
  2557. inline ObjectReference& ObjectReference::operator=(Reference<Object>&& other) {
  2558. static_cast<Reference<Object>*>(this)->operator=(std::move(other));
  2559. return *this;
  2560. }
  2561. inline ObjectReference::ObjectReference(ObjectReference&& other)
  2562. : Reference<Object>(std::move(other)) {}
  2563. inline ObjectReference& ObjectReference::operator=(ObjectReference&& other) {
  2564. static_cast<Reference<Object>*>(this)->operator=(std::move(other));
  2565. return *this;
  2566. }
  2567. inline ObjectReference::ObjectReference(const ObjectReference& other)
  2568. : Reference<Object>(other) {}
  2569. inline MaybeOrValue<Napi::Value> ObjectReference::Get(
  2570. const char* utf8name) const {
  2571. EscapableHandleScope scope(_env);
  2572. MaybeOrValue<Napi::Value> result = Value().Get(utf8name);
  2573. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2574. if (result.IsJust()) {
  2575. return Just(scope.Escape(result.Unwrap()));
  2576. }
  2577. return result;
  2578. #else
  2579. if (scope.Env().IsExceptionPending()) {
  2580. return Value();
  2581. }
  2582. return scope.Escape(result);
  2583. #endif
  2584. }
  2585. inline MaybeOrValue<Napi::Value> ObjectReference::Get(
  2586. const std::string& utf8name) const {
  2587. EscapableHandleScope scope(_env);
  2588. MaybeOrValue<Napi::Value> result = Value().Get(utf8name);
  2589. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2590. if (result.IsJust()) {
  2591. return Just(scope.Escape(result.Unwrap()));
  2592. }
  2593. return result;
  2594. #else
  2595. if (scope.Env().IsExceptionPending()) {
  2596. return Value();
  2597. }
  2598. return scope.Escape(result);
  2599. #endif
  2600. }
  2601. inline MaybeOrValue<bool> ObjectReference::Set(const char* utf8name,
  2602. napi_value value) const {
  2603. HandleScope scope(_env);
  2604. return Value().Set(utf8name, value);
  2605. }
  2606. inline MaybeOrValue<bool> ObjectReference::Set(const char* utf8name,
  2607. Napi::Value value) const {
  2608. HandleScope scope(_env);
  2609. return Value().Set(utf8name, value);
  2610. }
  2611. inline MaybeOrValue<bool> ObjectReference::Set(const char* utf8name,
  2612. const char* utf8value) const {
  2613. HandleScope scope(_env);
  2614. return Value().Set(utf8name, utf8value);
  2615. }
  2616. inline MaybeOrValue<bool> ObjectReference::Set(const char* utf8name,
  2617. bool boolValue) const {
  2618. HandleScope scope(_env);
  2619. return Value().Set(utf8name, boolValue);
  2620. }
  2621. inline MaybeOrValue<bool> ObjectReference::Set(const char* utf8name,
  2622. double numberValue) const {
  2623. HandleScope scope(_env);
  2624. return Value().Set(utf8name, numberValue);
  2625. }
  2626. inline MaybeOrValue<bool> ObjectReference::Set(const std::string& utf8name,
  2627. napi_value value) const {
  2628. HandleScope scope(_env);
  2629. return Value().Set(utf8name, value);
  2630. }
  2631. inline MaybeOrValue<bool> ObjectReference::Set(const std::string& utf8name,
  2632. Napi::Value value) const {
  2633. HandleScope scope(_env);
  2634. return Value().Set(utf8name, value);
  2635. }
  2636. inline MaybeOrValue<bool> ObjectReference::Set(const std::string& utf8name,
  2637. std::string& utf8value) const {
  2638. HandleScope scope(_env);
  2639. return Value().Set(utf8name, utf8value);
  2640. }
  2641. inline MaybeOrValue<bool> ObjectReference::Set(const std::string& utf8name,
  2642. bool boolValue) const {
  2643. HandleScope scope(_env);
  2644. return Value().Set(utf8name, boolValue);
  2645. }
  2646. inline MaybeOrValue<bool> ObjectReference::Set(const std::string& utf8name,
  2647. double numberValue) const {
  2648. HandleScope scope(_env);
  2649. return Value().Set(utf8name, numberValue);
  2650. }
  2651. inline MaybeOrValue<Napi::Value> ObjectReference::Get(uint32_t index) const {
  2652. EscapableHandleScope scope(_env);
  2653. MaybeOrValue<Napi::Value> result = Value().Get(index);
  2654. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2655. if (result.IsJust()) {
  2656. return Just(scope.Escape(result.Unwrap()));
  2657. }
  2658. return result;
  2659. #else
  2660. if (scope.Env().IsExceptionPending()) {
  2661. return Value();
  2662. }
  2663. return scope.Escape(result);
  2664. #endif
  2665. }
  2666. inline MaybeOrValue<bool> ObjectReference::Set(uint32_t index,
  2667. napi_value value) const {
  2668. HandleScope scope(_env);
  2669. return Value().Set(index, value);
  2670. }
  2671. inline MaybeOrValue<bool> ObjectReference::Set(uint32_t index,
  2672. Napi::Value value) const {
  2673. HandleScope scope(_env);
  2674. return Value().Set(index, value);
  2675. }
  2676. inline MaybeOrValue<bool> ObjectReference::Set(uint32_t index,
  2677. const char* utf8value) const {
  2678. HandleScope scope(_env);
  2679. return Value().Set(index, utf8value);
  2680. }
  2681. inline MaybeOrValue<bool> ObjectReference::Set(
  2682. uint32_t index, const std::string& utf8value) const {
  2683. HandleScope scope(_env);
  2684. return Value().Set(index, utf8value);
  2685. }
  2686. inline MaybeOrValue<bool> ObjectReference::Set(uint32_t index,
  2687. bool boolValue) const {
  2688. HandleScope scope(_env);
  2689. return Value().Set(index, boolValue);
  2690. }
  2691. inline MaybeOrValue<bool> ObjectReference::Set(uint32_t index,
  2692. double numberValue) const {
  2693. HandleScope scope(_env);
  2694. return Value().Set(index, numberValue);
  2695. }
  2696. ////////////////////////////////////////////////////////////////////////////////
  2697. // FunctionReference class
  2698. ////////////////////////////////////////////////////////////////////////////////
  2699. inline FunctionReference::FunctionReference() : Reference<Function>() {}
  2700. inline FunctionReference::FunctionReference(napi_env env, napi_ref ref)
  2701. : Reference<Function>(env, ref) {}
  2702. inline FunctionReference::FunctionReference(Reference<Function>&& other)
  2703. : Reference<Function>(std::move(other)) {}
  2704. inline FunctionReference& FunctionReference::operator=(
  2705. Reference<Function>&& other) {
  2706. static_cast<Reference<Function>*>(this)->operator=(std::move(other));
  2707. return *this;
  2708. }
  2709. inline FunctionReference::FunctionReference(FunctionReference&& other)
  2710. : Reference<Function>(std::move(other)) {}
  2711. inline FunctionReference& FunctionReference::operator=(
  2712. FunctionReference&& other) {
  2713. static_cast<Reference<Function>*>(this)->operator=(std::move(other));
  2714. return *this;
  2715. }
  2716. inline MaybeOrValue<Napi::Value> FunctionReference::operator()(
  2717. const std::initializer_list<napi_value>& args) const {
  2718. EscapableHandleScope scope(_env);
  2719. MaybeOrValue<Napi::Value> result = Value()(args);
  2720. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2721. if (result.IsJust()) {
  2722. return Just(scope.Escape(result.Unwrap()));
  2723. }
  2724. return result;
  2725. #else
  2726. if (scope.Env().IsExceptionPending()) {
  2727. return Value();
  2728. }
  2729. return scope.Escape(result);
  2730. #endif
  2731. }
  2732. inline MaybeOrValue<Napi::Value> FunctionReference::Call(
  2733. const std::initializer_list<napi_value>& args) const {
  2734. EscapableHandleScope scope(_env);
  2735. MaybeOrValue<Napi::Value> result = Value().Call(args);
  2736. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2737. if (result.IsJust()) {
  2738. return Just(scope.Escape(result.Unwrap()));
  2739. }
  2740. return result;
  2741. #else
  2742. if (scope.Env().IsExceptionPending()) {
  2743. return Value();
  2744. }
  2745. return scope.Escape(result);
  2746. #endif
  2747. }
  2748. inline MaybeOrValue<Napi::Value> FunctionReference::Call(
  2749. const std::vector<napi_value>& args) const {
  2750. EscapableHandleScope scope(_env);
  2751. MaybeOrValue<Napi::Value> result = Value().Call(args);
  2752. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2753. if (result.IsJust()) {
  2754. return Just(scope.Escape(result.Unwrap()));
  2755. }
  2756. return result;
  2757. #else
  2758. if (scope.Env().IsExceptionPending()) {
  2759. return Value();
  2760. }
  2761. return scope.Escape(result);
  2762. #endif
  2763. }
  2764. inline MaybeOrValue<Napi::Value> FunctionReference::Call(
  2765. napi_value recv, const std::initializer_list<napi_value>& args) const {
  2766. EscapableHandleScope scope(_env);
  2767. MaybeOrValue<Napi::Value> result = Value().Call(recv, args);
  2768. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2769. if (result.IsJust()) {
  2770. return Just(scope.Escape(result.Unwrap()));
  2771. }
  2772. return result;
  2773. #else
  2774. if (scope.Env().IsExceptionPending()) {
  2775. return Value();
  2776. }
  2777. return scope.Escape(result);
  2778. #endif
  2779. }
  2780. inline MaybeOrValue<Napi::Value> FunctionReference::Call(
  2781. napi_value recv, const std::vector<napi_value>& args) const {
  2782. EscapableHandleScope scope(_env);
  2783. MaybeOrValue<Napi::Value> result = Value().Call(recv, args);
  2784. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2785. if (result.IsJust()) {
  2786. return Just(scope.Escape(result.Unwrap()));
  2787. }
  2788. return result;
  2789. #else
  2790. if (scope.Env().IsExceptionPending()) {
  2791. return Value();
  2792. }
  2793. return scope.Escape(result);
  2794. #endif
  2795. }
  2796. inline MaybeOrValue<Napi::Value> FunctionReference::Call(
  2797. napi_value recv, size_t argc, const napi_value* args) const {
  2798. EscapableHandleScope scope(_env);
  2799. MaybeOrValue<Napi::Value> result = Value().Call(recv, argc, args);
  2800. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2801. if (result.IsJust()) {
  2802. return Just(scope.Escape(result.Unwrap()));
  2803. }
  2804. return result;
  2805. #else
  2806. if (scope.Env().IsExceptionPending()) {
  2807. return Value();
  2808. }
  2809. return scope.Escape(result);
  2810. #endif
  2811. }
  2812. inline MaybeOrValue<Napi::Value> FunctionReference::MakeCallback(
  2813. napi_value recv,
  2814. const std::initializer_list<napi_value>& args,
  2815. napi_async_context context) const {
  2816. EscapableHandleScope scope(_env);
  2817. MaybeOrValue<Napi::Value> result = Value().MakeCallback(recv, args, context);
  2818. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2819. if (result.IsJust()) {
  2820. return Just(scope.Escape(result.Unwrap()));
  2821. }
  2822. return result;
  2823. #else
  2824. if (scope.Env().IsExceptionPending()) {
  2825. return Value();
  2826. }
  2827. return scope.Escape(result);
  2828. #endif
  2829. }
  2830. inline MaybeOrValue<Napi::Value> FunctionReference::MakeCallback(
  2831. napi_value recv,
  2832. const std::vector<napi_value>& args,
  2833. napi_async_context context) const {
  2834. EscapableHandleScope scope(_env);
  2835. MaybeOrValue<Napi::Value> result = Value().MakeCallback(recv, args, context);
  2836. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2837. if (result.IsJust()) {
  2838. return Just(scope.Escape(result.Unwrap()));
  2839. }
  2840. return result;
  2841. #else
  2842. if (scope.Env().IsExceptionPending()) {
  2843. return Value();
  2844. }
  2845. return scope.Escape(result);
  2846. #endif
  2847. }
  2848. inline MaybeOrValue<Napi::Value> FunctionReference::MakeCallback(
  2849. napi_value recv,
  2850. size_t argc,
  2851. const napi_value* args,
  2852. napi_async_context context) const {
  2853. EscapableHandleScope scope(_env);
  2854. MaybeOrValue<Napi::Value> result =
  2855. Value().MakeCallback(recv, argc, args, context);
  2856. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2857. if (result.IsJust()) {
  2858. return Just(scope.Escape(result.Unwrap()));
  2859. }
  2860. return result;
  2861. #else
  2862. if (scope.Env().IsExceptionPending()) {
  2863. return Value();
  2864. }
  2865. return scope.Escape(result);
  2866. #endif
  2867. }
  2868. inline MaybeOrValue<Object> FunctionReference::New(
  2869. const std::initializer_list<napi_value>& args) const {
  2870. EscapableHandleScope scope(_env);
  2871. MaybeOrValue<Object> result = Value().New(args);
  2872. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2873. if (result.IsJust()) {
  2874. return Just(scope.Escape(result.Unwrap()).As<Object>());
  2875. }
  2876. return result;
  2877. #else
  2878. if (scope.Env().IsExceptionPending()) {
  2879. return Object();
  2880. }
  2881. return scope.Escape(result).As<Object>();
  2882. #endif
  2883. }
  2884. inline MaybeOrValue<Object> FunctionReference::New(
  2885. const std::vector<napi_value>& args) const {
  2886. EscapableHandleScope scope(_env);
  2887. MaybeOrValue<Object> result = Value().New(args);
  2888. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2889. if (result.IsJust()) {
  2890. return Just(scope.Escape(result.Unwrap()).As<Object>());
  2891. }
  2892. return result;
  2893. #else
  2894. if (scope.Env().IsExceptionPending()) {
  2895. return Object();
  2896. }
  2897. return scope.Escape(result).As<Object>();
  2898. #endif
  2899. }
  2900. ////////////////////////////////////////////////////////////////////////////////
  2901. // CallbackInfo class
  2902. ////////////////////////////////////////////////////////////////////////////////
  2903. inline CallbackInfo::CallbackInfo(napi_env env, napi_callback_info info)
  2904. : _env(env),
  2905. _info(info),
  2906. _this(nullptr),
  2907. _dynamicArgs(nullptr),
  2908. _data(nullptr) {
  2909. _argc = _staticArgCount;
  2910. _argv = _staticArgs;
  2911. napi_status status =
  2912. napi_get_cb_info(env, info, &_argc, _argv, &_this, &_data);
  2913. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2914. if (_argc > _staticArgCount) {
  2915. // Use either a fixed-size array (on the stack) or a dynamically-allocated
  2916. // array (on the heap) depending on the number of args.
  2917. _dynamicArgs = new napi_value[_argc];
  2918. _argv = _dynamicArgs;
  2919. status = napi_get_cb_info(env, info, &_argc, _argv, nullptr, nullptr);
  2920. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2921. }
  2922. }
  2923. inline CallbackInfo::~CallbackInfo() {
  2924. if (_dynamicArgs != nullptr) {
  2925. delete[] _dynamicArgs;
  2926. }
  2927. }
  2928. inline CallbackInfo::operator napi_callback_info() const {
  2929. return _info;
  2930. }
  2931. inline Value CallbackInfo::NewTarget() const {
  2932. napi_value newTarget;
  2933. napi_status status = napi_get_new_target(_env, _info, &newTarget);
  2934. NAPI_THROW_IF_FAILED(_env, status, Value());
  2935. return Value(_env, newTarget);
  2936. }
  2937. inline bool CallbackInfo::IsConstructCall() const {
  2938. return !NewTarget().IsEmpty();
  2939. }
  2940. inline Napi::Env CallbackInfo::Env() const {
  2941. return Napi::Env(_env);
  2942. }
  2943. inline size_t CallbackInfo::Length() const {
  2944. return _argc;
  2945. }
  2946. inline const Value CallbackInfo::operator[](size_t index) const {
  2947. return index < _argc ? Value(_env, _argv[index]) : Env().Undefined();
  2948. }
  2949. inline Value CallbackInfo::This() const {
  2950. if (_this == nullptr) {
  2951. return Env().Undefined();
  2952. }
  2953. return Object(_env, _this);
  2954. }
  2955. inline void* CallbackInfo::Data() const {
  2956. return _data;
  2957. }
  2958. inline void CallbackInfo::SetData(void* data) {
  2959. _data = data;
  2960. }
  2961. ////////////////////////////////////////////////////////////////////////////////
  2962. // PropertyDescriptor class
  2963. ////////////////////////////////////////////////////////////////////////////////
  2964. template <typename PropertyDescriptor::GetterCallback Getter>
  2965. PropertyDescriptor PropertyDescriptor::Accessor(
  2966. const char* utf8name, napi_property_attributes attributes, void* data) {
  2967. napi_property_descriptor desc = napi_property_descriptor();
  2968. desc.utf8name = utf8name;
  2969. desc.getter = details::TemplatedCallback<Getter>;
  2970. desc.attributes = attributes;
  2971. desc.data = data;
  2972. return desc;
  2973. }
  2974. template <typename PropertyDescriptor::GetterCallback Getter>
  2975. PropertyDescriptor PropertyDescriptor::Accessor(
  2976. const std::string& utf8name,
  2977. napi_property_attributes attributes,
  2978. void* data) {
  2979. return Accessor<Getter>(utf8name.c_str(), attributes, data);
  2980. }
  2981. template <typename PropertyDescriptor::GetterCallback Getter>
  2982. PropertyDescriptor PropertyDescriptor::Accessor(
  2983. Name name, napi_property_attributes attributes, void* data) {
  2984. napi_property_descriptor desc = napi_property_descriptor();
  2985. desc.name = name;
  2986. desc.getter = details::TemplatedCallback<Getter>;
  2987. desc.attributes = attributes;
  2988. desc.data = data;
  2989. return desc;
  2990. }
  2991. template <typename PropertyDescriptor::GetterCallback Getter,
  2992. typename PropertyDescriptor::SetterCallback Setter>
  2993. PropertyDescriptor PropertyDescriptor::Accessor(
  2994. const char* utf8name, napi_property_attributes attributes, void* data) {
  2995. napi_property_descriptor desc = napi_property_descriptor();
  2996. desc.utf8name = utf8name;
  2997. desc.getter = details::TemplatedCallback<Getter>;
  2998. desc.setter = details::TemplatedVoidCallback<Setter>;
  2999. desc.attributes = attributes;
  3000. desc.data = data;
  3001. return desc;
  3002. }
  3003. template <typename PropertyDescriptor::GetterCallback Getter,
  3004. typename PropertyDescriptor::SetterCallback Setter>
  3005. PropertyDescriptor PropertyDescriptor::Accessor(
  3006. const std::string& utf8name,
  3007. napi_property_attributes attributes,
  3008. void* data) {
  3009. return Accessor<Getter, Setter>(utf8name.c_str(), attributes, data);
  3010. }
  3011. template <typename PropertyDescriptor::GetterCallback Getter,
  3012. typename PropertyDescriptor::SetterCallback Setter>
  3013. PropertyDescriptor PropertyDescriptor::Accessor(
  3014. Name name, napi_property_attributes attributes, void* data) {
  3015. napi_property_descriptor desc = napi_property_descriptor();
  3016. desc.name = name;
  3017. desc.getter = details::TemplatedCallback<Getter>;
  3018. desc.setter = details::TemplatedVoidCallback<Setter>;
  3019. desc.attributes = attributes;
  3020. desc.data = data;
  3021. return desc;
  3022. }
  3023. template <typename Getter>
  3024. inline PropertyDescriptor PropertyDescriptor::Accessor(
  3025. Napi::Env env,
  3026. Napi::Object object,
  3027. const char* utf8name,
  3028. Getter getter,
  3029. napi_property_attributes attributes,
  3030. void* data) {
  3031. using CbData = details::CallbackData<Getter, Napi::Value>;
  3032. auto callbackData = new CbData({getter, data});
  3033. napi_status status = AttachData(env, object, callbackData);
  3034. if (status != napi_ok) {
  3035. delete callbackData;
  3036. NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  3037. }
  3038. return PropertyDescriptor({utf8name,
  3039. nullptr,
  3040. nullptr,
  3041. CbData::Wrapper,
  3042. nullptr,
  3043. nullptr,
  3044. attributes,
  3045. callbackData});
  3046. }
  3047. template <typename Getter>
  3048. inline PropertyDescriptor PropertyDescriptor::Accessor(
  3049. Napi::Env env,
  3050. Napi::Object object,
  3051. const std::string& utf8name,
  3052. Getter getter,
  3053. napi_property_attributes attributes,
  3054. void* data) {
  3055. return Accessor(env, object, utf8name.c_str(), getter, attributes, data);
  3056. }
  3057. template <typename Getter>
  3058. inline PropertyDescriptor PropertyDescriptor::Accessor(
  3059. Napi::Env env,
  3060. Napi::Object object,
  3061. Name name,
  3062. Getter getter,
  3063. napi_property_attributes attributes,
  3064. void* data) {
  3065. using CbData = details::CallbackData<Getter, Napi::Value>;
  3066. auto callbackData = new CbData({getter, data});
  3067. napi_status status = AttachData(env, object, callbackData);
  3068. if (status != napi_ok) {
  3069. delete callbackData;
  3070. NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  3071. }
  3072. return PropertyDescriptor({nullptr,
  3073. name,
  3074. nullptr,
  3075. CbData::Wrapper,
  3076. nullptr,
  3077. nullptr,
  3078. attributes,
  3079. callbackData});
  3080. }
  3081. template <typename Getter, typename Setter>
  3082. inline PropertyDescriptor PropertyDescriptor::Accessor(
  3083. Napi::Env env,
  3084. Napi::Object object,
  3085. const char* utf8name,
  3086. Getter getter,
  3087. Setter setter,
  3088. napi_property_attributes attributes,
  3089. void* data) {
  3090. using CbData = details::AccessorCallbackData<Getter, Setter>;
  3091. auto callbackData = new CbData({getter, setter, data});
  3092. napi_status status = AttachData(env, object, callbackData);
  3093. if (status != napi_ok) {
  3094. delete callbackData;
  3095. NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  3096. }
  3097. return PropertyDescriptor({utf8name,
  3098. nullptr,
  3099. nullptr,
  3100. CbData::GetterWrapper,
  3101. CbData::SetterWrapper,
  3102. nullptr,
  3103. attributes,
  3104. callbackData});
  3105. }
  3106. template <typename Getter, typename Setter>
  3107. inline PropertyDescriptor PropertyDescriptor::Accessor(
  3108. Napi::Env env,
  3109. Napi::Object object,
  3110. const std::string& utf8name,
  3111. Getter getter,
  3112. Setter setter,
  3113. napi_property_attributes attributes,
  3114. void* data) {
  3115. return Accessor(
  3116. env, object, utf8name.c_str(), getter, setter, attributes, data);
  3117. }
  3118. template <typename Getter, typename Setter>
  3119. inline PropertyDescriptor PropertyDescriptor::Accessor(
  3120. Napi::Env env,
  3121. Napi::Object object,
  3122. Name name,
  3123. Getter getter,
  3124. Setter setter,
  3125. napi_property_attributes attributes,
  3126. void* data) {
  3127. using CbData = details::AccessorCallbackData<Getter, Setter>;
  3128. auto callbackData = new CbData({getter, setter, data});
  3129. napi_status status = AttachData(env, object, callbackData);
  3130. if (status != napi_ok) {
  3131. delete callbackData;
  3132. NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  3133. }
  3134. return PropertyDescriptor({nullptr,
  3135. name,
  3136. nullptr,
  3137. CbData::GetterWrapper,
  3138. CbData::SetterWrapper,
  3139. nullptr,
  3140. attributes,
  3141. callbackData});
  3142. }
  3143. template <typename Callable>
  3144. inline PropertyDescriptor PropertyDescriptor::Function(
  3145. Napi::Env env,
  3146. Napi::Object /*object*/,
  3147. const char* utf8name,
  3148. Callable cb,
  3149. napi_property_attributes attributes,
  3150. void* data) {
  3151. return PropertyDescriptor({utf8name,
  3152. nullptr,
  3153. nullptr,
  3154. nullptr,
  3155. nullptr,
  3156. Napi::Function::New(env, cb, utf8name, data),
  3157. attributes,
  3158. nullptr});
  3159. }
  3160. template <typename Callable>
  3161. inline PropertyDescriptor PropertyDescriptor::Function(
  3162. Napi::Env env,
  3163. Napi::Object object,
  3164. const std::string& utf8name,
  3165. Callable cb,
  3166. napi_property_attributes attributes,
  3167. void* data) {
  3168. return Function(env, object, utf8name.c_str(), cb, attributes, data);
  3169. }
  3170. template <typename Callable>
  3171. inline PropertyDescriptor PropertyDescriptor::Function(
  3172. Napi::Env env,
  3173. Napi::Object /*object*/,
  3174. Name name,
  3175. Callable cb,
  3176. napi_property_attributes attributes,
  3177. void* data) {
  3178. return PropertyDescriptor({nullptr,
  3179. name,
  3180. nullptr,
  3181. nullptr,
  3182. nullptr,
  3183. Napi::Function::New(env, cb, nullptr, data),
  3184. attributes,
  3185. nullptr});
  3186. }
  3187. inline PropertyDescriptor PropertyDescriptor::Value(
  3188. const char* utf8name,
  3189. napi_value value,
  3190. napi_property_attributes attributes) {
  3191. return PropertyDescriptor({utf8name,
  3192. nullptr,
  3193. nullptr,
  3194. nullptr,
  3195. nullptr,
  3196. value,
  3197. attributes,
  3198. nullptr});
  3199. }
  3200. inline PropertyDescriptor PropertyDescriptor::Value(
  3201. const std::string& utf8name,
  3202. napi_value value,
  3203. napi_property_attributes attributes) {
  3204. return Value(utf8name.c_str(), value, attributes);
  3205. }
  3206. inline PropertyDescriptor PropertyDescriptor::Value(
  3207. napi_value name, napi_value value, napi_property_attributes attributes) {
  3208. return PropertyDescriptor(
  3209. {nullptr, name, nullptr, nullptr, nullptr, value, attributes, nullptr});
  3210. }
  3211. inline PropertyDescriptor PropertyDescriptor::Value(
  3212. Name name, Napi::Value value, napi_property_attributes attributes) {
  3213. napi_value nameValue = name;
  3214. napi_value valueValue = value;
  3215. return PropertyDescriptor::Value(nameValue, valueValue, attributes);
  3216. }
  3217. inline PropertyDescriptor::PropertyDescriptor(napi_property_descriptor desc)
  3218. : _desc(desc) {}
  3219. inline PropertyDescriptor::operator napi_property_descriptor&() {
  3220. return _desc;
  3221. }
  3222. inline PropertyDescriptor::operator const napi_property_descriptor&() const {
  3223. return _desc;
  3224. }
  3225. ////////////////////////////////////////////////////////////////////////////////
  3226. // InstanceWrap<T> class
  3227. ////////////////////////////////////////////////////////////////////////////////
  3228. template <typename T>
  3229. inline void InstanceWrap<T>::AttachPropData(
  3230. napi_env env, napi_value value, const napi_property_descriptor* prop) {
  3231. napi_status status;
  3232. if (!(prop->attributes & napi_static)) {
  3233. if (prop->method == T::InstanceVoidMethodCallbackWrapper) {
  3234. status = Napi::details::AttachData(
  3235. env, value, static_cast<InstanceVoidMethodCallbackData*>(prop->data));
  3236. NAPI_THROW_IF_FAILED_VOID(env, status);
  3237. } else if (prop->method == T::InstanceMethodCallbackWrapper) {
  3238. status = Napi::details::AttachData(
  3239. env, value, static_cast<InstanceMethodCallbackData*>(prop->data));
  3240. NAPI_THROW_IF_FAILED_VOID(env, status);
  3241. } else if (prop->getter == T::InstanceGetterCallbackWrapper ||
  3242. prop->setter == T::InstanceSetterCallbackWrapper) {
  3243. status = Napi::details::AttachData(
  3244. env, value, static_cast<InstanceAccessorCallbackData*>(prop->data));
  3245. NAPI_THROW_IF_FAILED_VOID(env, status);
  3246. }
  3247. }
  3248. }
  3249. template <typename T>
  3250. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3251. const char* utf8name,
  3252. InstanceVoidMethodCallback method,
  3253. napi_property_attributes attributes,
  3254. void* data) {
  3255. InstanceVoidMethodCallbackData* callbackData =
  3256. new InstanceVoidMethodCallbackData({method, data});
  3257. napi_property_descriptor desc = napi_property_descriptor();
  3258. desc.utf8name = utf8name;
  3259. desc.method = T::InstanceVoidMethodCallbackWrapper;
  3260. desc.data = callbackData;
  3261. desc.attributes = attributes;
  3262. return desc;
  3263. }
  3264. template <typename T>
  3265. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3266. const char* utf8name,
  3267. InstanceMethodCallback method,
  3268. napi_property_attributes attributes,
  3269. void* data) {
  3270. InstanceMethodCallbackData* callbackData =
  3271. new InstanceMethodCallbackData({method, data});
  3272. napi_property_descriptor desc = napi_property_descriptor();
  3273. desc.utf8name = utf8name;
  3274. desc.method = T::InstanceMethodCallbackWrapper;
  3275. desc.data = callbackData;
  3276. desc.attributes = attributes;
  3277. return desc;
  3278. }
  3279. template <typename T>
  3280. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3281. Symbol name,
  3282. InstanceVoidMethodCallback method,
  3283. napi_property_attributes attributes,
  3284. void* data) {
  3285. InstanceVoidMethodCallbackData* callbackData =
  3286. new InstanceVoidMethodCallbackData({method, data});
  3287. napi_property_descriptor desc = napi_property_descriptor();
  3288. desc.name = name;
  3289. desc.method = T::InstanceVoidMethodCallbackWrapper;
  3290. desc.data = callbackData;
  3291. desc.attributes = attributes;
  3292. return desc;
  3293. }
  3294. template <typename T>
  3295. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3296. Symbol name,
  3297. InstanceMethodCallback method,
  3298. napi_property_attributes attributes,
  3299. void* data) {
  3300. InstanceMethodCallbackData* callbackData =
  3301. new InstanceMethodCallbackData({method, data});
  3302. napi_property_descriptor desc = napi_property_descriptor();
  3303. desc.name = name;
  3304. desc.method = T::InstanceMethodCallbackWrapper;
  3305. desc.data = callbackData;
  3306. desc.attributes = attributes;
  3307. return desc;
  3308. }
  3309. template <typename T>
  3310. template <typename InstanceWrap<T>::InstanceVoidMethodCallback method>
  3311. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3312. const char* utf8name, napi_property_attributes attributes, void* data) {
  3313. napi_property_descriptor desc = napi_property_descriptor();
  3314. desc.utf8name = utf8name;
  3315. desc.method = details::TemplatedInstanceVoidCallback<T, method>;
  3316. desc.data = data;
  3317. desc.attributes = attributes;
  3318. return desc;
  3319. }
  3320. template <typename T>
  3321. template <typename InstanceWrap<T>::InstanceMethodCallback method>
  3322. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3323. const char* utf8name, napi_property_attributes attributes, void* data) {
  3324. napi_property_descriptor desc = napi_property_descriptor();
  3325. desc.utf8name = utf8name;
  3326. desc.method = details::TemplatedInstanceCallback<T, method>;
  3327. desc.data = data;
  3328. desc.attributes = attributes;
  3329. return desc;
  3330. }
  3331. template <typename T>
  3332. template <typename InstanceWrap<T>::InstanceVoidMethodCallback method>
  3333. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3334. Symbol name, napi_property_attributes attributes, void* data) {
  3335. napi_property_descriptor desc = napi_property_descriptor();
  3336. desc.name = name;
  3337. desc.method = details::TemplatedInstanceVoidCallback<T, method>;
  3338. desc.data = data;
  3339. desc.attributes = attributes;
  3340. return desc;
  3341. }
  3342. template <typename T>
  3343. template <typename InstanceWrap<T>::InstanceMethodCallback method>
  3344. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3345. Symbol name, napi_property_attributes attributes, void* data) {
  3346. napi_property_descriptor desc = napi_property_descriptor();
  3347. desc.name = name;
  3348. desc.method = details::TemplatedInstanceCallback<T, method>;
  3349. desc.data = data;
  3350. desc.attributes = attributes;
  3351. return desc;
  3352. }
  3353. template <typename T>
  3354. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceAccessor(
  3355. const char* utf8name,
  3356. InstanceGetterCallback getter,
  3357. InstanceSetterCallback setter,
  3358. napi_property_attributes attributes,
  3359. void* data) {
  3360. InstanceAccessorCallbackData* callbackData =
  3361. new InstanceAccessorCallbackData({getter, setter, data});
  3362. napi_property_descriptor desc = napi_property_descriptor();
  3363. desc.utf8name = utf8name;
  3364. desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr;
  3365. desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr;
  3366. desc.data = callbackData;
  3367. desc.attributes = attributes;
  3368. return desc;
  3369. }
  3370. template <typename T>
  3371. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceAccessor(
  3372. Symbol name,
  3373. InstanceGetterCallback getter,
  3374. InstanceSetterCallback setter,
  3375. napi_property_attributes attributes,
  3376. void* data) {
  3377. InstanceAccessorCallbackData* callbackData =
  3378. new InstanceAccessorCallbackData({getter, setter, data});
  3379. napi_property_descriptor desc = napi_property_descriptor();
  3380. desc.name = name;
  3381. desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr;
  3382. desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr;
  3383. desc.data = callbackData;
  3384. desc.attributes = attributes;
  3385. return desc;
  3386. }
  3387. template <typename T>
  3388. template <typename InstanceWrap<T>::InstanceGetterCallback getter,
  3389. typename InstanceWrap<T>::InstanceSetterCallback setter>
  3390. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceAccessor(
  3391. const char* utf8name, napi_property_attributes attributes, void* data) {
  3392. napi_property_descriptor desc = napi_property_descriptor();
  3393. desc.utf8name = utf8name;
  3394. desc.getter = details::TemplatedInstanceCallback<T, getter>;
  3395. desc.setter = This::WrapSetter(This::SetterTag<setter>());
  3396. desc.data = data;
  3397. desc.attributes = attributes;
  3398. return desc;
  3399. }
  3400. template <typename T>
  3401. template <typename InstanceWrap<T>::InstanceGetterCallback getter,
  3402. typename InstanceWrap<T>::InstanceSetterCallback setter>
  3403. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceAccessor(
  3404. Symbol name, napi_property_attributes attributes, void* data) {
  3405. napi_property_descriptor desc = napi_property_descriptor();
  3406. desc.name = name;
  3407. desc.getter = details::TemplatedInstanceCallback<T, getter>;
  3408. desc.setter = This::WrapSetter(This::SetterTag<setter>());
  3409. desc.data = data;
  3410. desc.attributes = attributes;
  3411. return desc;
  3412. }
  3413. template <typename T>
  3414. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceValue(
  3415. const char* utf8name,
  3416. Napi::Value value,
  3417. napi_property_attributes attributes) {
  3418. napi_property_descriptor desc = napi_property_descriptor();
  3419. desc.utf8name = utf8name;
  3420. desc.value = value;
  3421. desc.attributes = attributes;
  3422. return desc;
  3423. }
  3424. template <typename T>
  3425. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceValue(
  3426. Symbol name, Napi::Value value, napi_property_attributes attributes) {
  3427. napi_property_descriptor desc = napi_property_descriptor();
  3428. desc.name = name;
  3429. desc.value = value;
  3430. desc.attributes = attributes;
  3431. return desc;
  3432. }
  3433. template <typename T>
  3434. inline napi_value InstanceWrap<T>::InstanceVoidMethodCallbackWrapper(
  3435. napi_env env, napi_callback_info info) {
  3436. return details::WrapCallback([&] {
  3437. CallbackInfo callbackInfo(env, info);
  3438. InstanceVoidMethodCallbackData* callbackData =
  3439. reinterpret_cast<InstanceVoidMethodCallbackData*>(callbackInfo.Data());
  3440. callbackInfo.SetData(callbackData->data);
  3441. T* instance = T::Unwrap(callbackInfo.This().As<Object>());
  3442. auto cb = callbackData->callback;
  3443. (instance->*cb)(callbackInfo);
  3444. return nullptr;
  3445. });
  3446. }
  3447. template <typename T>
  3448. inline napi_value InstanceWrap<T>::InstanceMethodCallbackWrapper(
  3449. napi_env env, napi_callback_info info) {
  3450. return details::WrapCallback([&] {
  3451. CallbackInfo callbackInfo(env, info);
  3452. InstanceMethodCallbackData* callbackData =
  3453. reinterpret_cast<InstanceMethodCallbackData*>(callbackInfo.Data());
  3454. callbackInfo.SetData(callbackData->data);
  3455. T* instance = T::Unwrap(callbackInfo.This().As<Object>());
  3456. auto cb = callbackData->callback;
  3457. return (instance->*cb)(callbackInfo);
  3458. });
  3459. }
  3460. template <typename T>
  3461. inline napi_value InstanceWrap<T>::InstanceGetterCallbackWrapper(
  3462. napi_env env, napi_callback_info info) {
  3463. return details::WrapCallback([&] {
  3464. CallbackInfo callbackInfo(env, info);
  3465. InstanceAccessorCallbackData* callbackData =
  3466. reinterpret_cast<InstanceAccessorCallbackData*>(callbackInfo.Data());
  3467. callbackInfo.SetData(callbackData->data);
  3468. T* instance = T::Unwrap(callbackInfo.This().As<Object>());
  3469. auto cb = callbackData->getterCallback;
  3470. return (instance->*cb)(callbackInfo);
  3471. });
  3472. }
  3473. template <typename T>
  3474. inline napi_value InstanceWrap<T>::InstanceSetterCallbackWrapper(
  3475. napi_env env, napi_callback_info info) {
  3476. return details::WrapCallback([&] {
  3477. CallbackInfo callbackInfo(env, info);
  3478. InstanceAccessorCallbackData* callbackData =
  3479. reinterpret_cast<InstanceAccessorCallbackData*>(callbackInfo.Data());
  3480. callbackInfo.SetData(callbackData->data);
  3481. T* instance = T::Unwrap(callbackInfo.This().As<Object>());
  3482. auto cb = callbackData->setterCallback;
  3483. (instance->*cb)(callbackInfo, callbackInfo[0]);
  3484. return nullptr;
  3485. });
  3486. }
  3487. template <typename T>
  3488. template <typename InstanceWrap<T>::InstanceSetterCallback method>
  3489. inline napi_value InstanceWrap<T>::WrappedMethod(
  3490. napi_env env, napi_callback_info info) NAPI_NOEXCEPT {
  3491. return details::WrapCallback([&] {
  3492. const CallbackInfo cbInfo(env, info);
  3493. T* instance = T::Unwrap(cbInfo.This().As<Object>());
  3494. (instance->*method)(cbInfo, cbInfo[0]);
  3495. return nullptr;
  3496. });
  3497. }
  3498. ////////////////////////////////////////////////////////////////////////////////
  3499. // ObjectWrap<T> class
  3500. ////////////////////////////////////////////////////////////////////////////////
  3501. template <typename T>
  3502. inline ObjectWrap<T>::ObjectWrap(const Napi::CallbackInfo& callbackInfo) {
  3503. napi_env env = callbackInfo.Env();
  3504. napi_value wrapper = callbackInfo.This();
  3505. napi_status status;
  3506. napi_ref ref;
  3507. T* instance = static_cast<T*>(this);
  3508. status = napi_wrap(env, wrapper, instance, FinalizeCallback, nullptr, &ref);
  3509. NAPI_THROW_IF_FAILED_VOID(env, status);
  3510. Reference<Object>* instanceRef = instance;
  3511. *instanceRef = Reference<Object>(env, ref);
  3512. }
  3513. template <typename T>
  3514. inline ObjectWrap<T>::~ObjectWrap() {
  3515. // If the JS object still exists at this point, remove the finalizer added
  3516. // through `napi_wrap()`.
  3517. if (!IsEmpty()) {
  3518. Object object = Value();
  3519. // It is not valid to call `napi_remove_wrap()` with an empty `object`.
  3520. // This happens e.g. during garbage collection.
  3521. if (!object.IsEmpty() && _construction_failed) {
  3522. napi_remove_wrap(Env(), object, nullptr);
  3523. }
  3524. }
  3525. }
  3526. template <typename T>
  3527. inline T* ObjectWrap<T>::Unwrap(Object wrapper) {
  3528. void* unwrapped;
  3529. napi_status status = napi_unwrap(wrapper.Env(), wrapper, &unwrapped);
  3530. NAPI_THROW_IF_FAILED(wrapper.Env(), status, nullptr);
  3531. return static_cast<T*>(unwrapped);
  3532. }
  3533. template <typename T>
  3534. inline Function ObjectWrap<T>::DefineClass(
  3535. Napi::Env env,
  3536. const char* utf8name,
  3537. const size_t props_count,
  3538. const napi_property_descriptor* descriptors,
  3539. void* data) {
  3540. napi_status status;
  3541. std::vector<napi_property_descriptor> props(props_count);
  3542. // We copy the descriptors to a local array because before defining the class
  3543. // we must replace static method property descriptors with value property
  3544. // descriptors such that the value is a function-valued `napi_value` created
  3545. // with `CreateFunction()`.
  3546. //
  3547. // This replacement could be made for instance methods as well, but V8 aborts
  3548. // if we do that, because it expects methods defined on the prototype template
  3549. // to have `FunctionTemplate`s.
  3550. for (size_t index = 0; index < props_count; index++) {
  3551. props[index] = descriptors[index];
  3552. napi_property_descriptor* prop = &props[index];
  3553. if (prop->method == T::StaticMethodCallbackWrapper) {
  3554. status =
  3555. CreateFunction(env,
  3556. utf8name,
  3557. prop->method,
  3558. static_cast<StaticMethodCallbackData*>(prop->data),
  3559. &(prop->value));
  3560. NAPI_THROW_IF_FAILED(env, status, Function());
  3561. prop->method = nullptr;
  3562. prop->data = nullptr;
  3563. } else if (prop->method == T::StaticVoidMethodCallbackWrapper) {
  3564. status =
  3565. CreateFunction(env,
  3566. utf8name,
  3567. prop->method,
  3568. static_cast<StaticVoidMethodCallbackData*>(prop->data),
  3569. &(prop->value));
  3570. NAPI_THROW_IF_FAILED(env, status, Function());
  3571. prop->method = nullptr;
  3572. prop->data = nullptr;
  3573. }
  3574. }
  3575. napi_value value;
  3576. status = napi_define_class(env,
  3577. utf8name,
  3578. NAPI_AUTO_LENGTH,
  3579. T::ConstructorCallbackWrapper,
  3580. data,
  3581. props_count,
  3582. props.data(),
  3583. &value);
  3584. NAPI_THROW_IF_FAILED(env, status, Function());
  3585. // After defining the class we iterate once more over the property descriptors
  3586. // and attach the data associated with accessors and instance methods to the
  3587. // newly created JavaScript class.
  3588. for (size_t idx = 0; idx < props_count; idx++) {
  3589. const napi_property_descriptor* prop = &props[idx];
  3590. if (prop->getter == T::StaticGetterCallbackWrapper ||
  3591. prop->setter == T::StaticSetterCallbackWrapper) {
  3592. status = Napi::details::AttachData(
  3593. env, value, static_cast<StaticAccessorCallbackData*>(prop->data));
  3594. NAPI_THROW_IF_FAILED(env, status, Function());
  3595. } else {
  3596. // InstanceWrap<T>::AttachPropData is responsible for attaching the data
  3597. // of instance methods and accessors.
  3598. T::AttachPropData(env, value, prop);
  3599. }
  3600. }
  3601. return Function(env, value);
  3602. }
  3603. template <typename T>
  3604. inline Function ObjectWrap<T>::DefineClass(
  3605. Napi::Env env,
  3606. const char* utf8name,
  3607. const std::initializer_list<ClassPropertyDescriptor<T>>& properties,
  3608. void* data) {
  3609. return DefineClass(
  3610. env,
  3611. utf8name,
  3612. properties.size(),
  3613. reinterpret_cast<const napi_property_descriptor*>(properties.begin()),
  3614. data);
  3615. }
  3616. template <typename T>
  3617. inline Function ObjectWrap<T>::DefineClass(
  3618. Napi::Env env,
  3619. const char* utf8name,
  3620. const std::vector<ClassPropertyDescriptor<T>>& properties,
  3621. void* data) {
  3622. return DefineClass(
  3623. env,
  3624. utf8name,
  3625. properties.size(),
  3626. reinterpret_cast<const napi_property_descriptor*>(properties.data()),
  3627. data);
  3628. }
  3629. template <typename T>
  3630. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3631. const char* utf8name,
  3632. StaticVoidMethodCallback method,
  3633. napi_property_attributes attributes,
  3634. void* data) {
  3635. StaticVoidMethodCallbackData* callbackData =
  3636. new StaticVoidMethodCallbackData({method, data});
  3637. napi_property_descriptor desc = napi_property_descriptor();
  3638. desc.utf8name = utf8name;
  3639. desc.method = T::StaticVoidMethodCallbackWrapper;
  3640. desc.data = callbackData;
  3641. desc.attributes =
  3642. static_cast<napi_property_attributes>(attributes | napi_static);
  3643. return desc;
  3644. }
  3645. template <typename T>
  3646. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3647. const char* utf8name,
  3648. StaticMethodCallback method,
  3649. napi_property_attributes attributes,
  3650. void* data) {
  3651. StaticMethodCallbackData* callbackData =
  3652. new StaticMethodCallbackData({method, data});
  3653. napi_property_descriptor desc = napi_property_descriptor();
  3654. desc.utf8name = utf8name;
  3655. desc.method = T::StaticMethodCallbackWrapper;
  3656. desc.data = callbackData;
  3657. desc.attributes =
  3658. static_cast<napi_property_attributes>(attributes | napi_static);
  3659. return desc;
  3660. }
  3661. template <typename T>
  3662. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3663. Symbol name,
  3664. StaticVoidMethodCallback method,
  3665. napi_property_attributes attributes,
  3666. void* data) {
  3667. StaticVoidMethodCallbackData* callbackData =
  3668. new StaticVoidMethodCallbackData({method, data});
  3669. napi_property_descriptor desc = napi_property_descriptor();
  3670. desc.name = name;
  3671. desc.method = T::StaticVoidMethodCallbackWrapper;
  3672. desc.data = callbackData;
  3673. desc.attributes =
  3674. static_cast<napi_property_attributes>(attributes | napi_static);
  3675. return desc;
  3676. }
  3677. template <typename T>
  3678. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3679. Symbol name,
  3680. StaticMethodCallback method,
  3681. napi_property_attributes attributes,
  3682. void* data) {
  3683. StaticMethodCallbackData* callbackData =
  3684. new StaticMethodCallbackData({method, data});
  3685. napi_property_descriptor desc = napi_property_descriptor();
  3686. desc.name = name;
  3687. desc.method = T::StaticMethodCallbackWrapper;
  3688. desc.data = callbackData;
  3689. desc.attributes =
  3690. static_cast<napi_property_attributes>(attributes | napi_static);
  3691. return desc;
  3692. }
  3693. template <typename T>
  3694. template <typename ObjectWrap<T>::StaticVoidMethodCallback method>
  3695. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3696. const char* utf8name, napi_property_attributes attributes, void* data) {
  3697. napi_property_descriptor desc = napi_property_descriptor();
  3698. desc.utf8name = utf8name;
  3699. desc.method = details::TemplatedVoidCallback<method>;
  3700. desc.data = data;
  3701. desc.attributes =
  3702. static_cast<napi_property_attributes>(attributes | napi_static);
  3703. return desc;
  3704. }
  3705. template <typename T>
  3706. template <typename ObjectWrap<T>::StaticVoidMethodCallback method>
  3707. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3708. Symbol name, napi_property_attributes attributes, void* data) {
  3709. napi_property_descriptor desc = napi_property_descriptor();
  3710. desc.name = name;
  3711. desc.method = details::TemplatedVoidCallback<method>;
  3712. desc.data = data;
  3713. desc.attributes =
  3714. static_cast<napi_property_attributes>(attributes | napi_static);
  3715. return desc;
  3716. }
  3717. template <typename T>
  3718. template <typename ObjectWrap<T>::StaticMethodCallback method>
  3719. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3720. const char* utf8name, napi_property_attributes attributes, void* data) {
  3721. napi_property_descriptor desc = napi_property_descriptor();
  3722. desc.utf8name = utf8name;
  3723. desc.method = details::TemplatedCallback<method>;
  3724. desc.data = data;
  3725. desc.attributes =
  3726. static_cast<napi_property_attributes>(attributes | napi_static);
  3727. return desc;
  3728. }
  3729. template <typename T>
  3730. template <typename ObjectWrap<T>::StaticMethodCallback method>
  3731. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3732. Symbol name, napi_property_attributes attributes, void* data) {
  3733. napi_property_descriptor desc = napi_property_descriptor();
  3734. desc.name = name;
  3735. desc.method = details::TemplatedCallback<method>;
  3736. desc.data = data;
  3737. desc.attributes =
  3738. static_cast<napi_property_attributes>(attributes | napi_static);
  3739. return desc;
  3740. }
  3741. template <typename T>
  3742. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticAccessor(
  3743. const char* utf8name,
  3744. StaticGetterCallback getter,
  3745. StaticSetterCallback setter,
  3746. napi_property_attributes attributes,
  3747. void* data) {
  3748. StaticAccessorCallbackData* callbackData =
  3749. new StaticAccessorCallbackData({getter, setter, data});
  3750. napi_property_descriptor desc = napi_property_descriptor();
  3751. desc.utf8name = utf8name;
  3752. desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr;
  3753. desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr;
  3754. desc.data = callbackData;
  3755. desc.attributes =
  3756. static_cast<napi_property_attributes>(attributes | napi_static);
  3757. return desc;
  3758. }
  3759. template <typename T>
  3760. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticAccessor(
  3761. Symbol name,
  3762. StaticGetterCallback getter,
  3763. StaticSetterCallback setter,
  3764. napi_property_attributes attributes,
  3765. void* data) {
  3766. StaticAccessorCallbackData* callbackData =
  3767. new StaticAccessorCallbackData({getter, setter, data});
  3768. napi_property_descriptor desc = napi_property_descriptor();
  3769. desc.name = name;
  3770. desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr;
  3771. desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr;
  3772. desc.data = callbackData;
  3773. desc.attributes =
  3774. static_cast<napi_property_attributes>(attributes | napi_static);
  3775. return desc;
  3776. }
  3777. template <typename T>
  3778. template <typename ObjectWrap<T>::StaticGetterCallback getter,
  3779. typename ObjectWrap<T>::StaticSetterCallback setter>
  3780. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticAccessor(
  3781. const char* utf8name, napi_property_attributes attributes, void* data) {
  3782. napi_property_descriptor desc = napi_property_descriptor();
  3783. desc.utf8name = utf8name;
  3784. desc.getter = details::TemplatedCallback<getter>;
  3785. desc.setter = This::WrapStaticSetter(This::StaticSetterTag<setter>());
  3786. desc.data = data;
  3787. desc.attributes =
  3788. static_cast<napi_property_attributes>(attributes | napi_static);
  3789. return desc;
  3790. }
  3791. template <typename T>
  3792. template <typename ObjectWrap<T>::StaticGetterCallback getter,
  3793. typename ObjectWrap<T>::StaticSetterCallback setter>
  3794. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticAccessor(
  3795. Symbol name, napi_property_attributes attributes, void* data) {
  3796. napi_property_descriptor desc = napi_property_descriptor();
  3797. desc.name = name;
  3798. desc.getter = details::TemplatedCallback<getter>;
  3799. desc.setter = This::WrapStaticSetter(This::StaticSetterTag<setter>());
  3800. desc.data = data;
  3801. desc.attributes =
  3802. static_cast<napi_property_attributes>(attributes | napi_static);
  3803. return desc;
  3804. }
  3805. template <typename T>
  3806. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticValue(
  3807. const char* utf8name,
  3808. Napi::Value value,
  3809. napi_property_attributes attributes) {
  3810. napi_property_descriptor desc = napi_property_descriptor();
  3811. desc.utf8name = utf8name;
  3812. desc.value = value;
  3813. desc.attributes =
  3814. static_cast<napi_property_attributes>(attributes | napi_static);
  3815. return desc;
  3816. }
  3817. template <typename T>
  3818. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticValue(
  3819. Symbol name, Napi::Value value, napi_property_attributes attributes) {
  3820. napi_property_descriptor desc = napi_property_descriptor();
  3821. desc.name = name;
  3822. desc.value = value;
  3823. desc.attributes =
  3824. static_cast<napi_property_attributes>(attributes | napi_static);
  3825. return desc;
  3826. }
  3827. template <typename T>
  3828. inline Value ObjectWrap<T>::OnCalledAsFunction(
  3829. const Napi::CallbackInfo& callbackInfo) {
  3830. NAPI_THROW(
  3831. TypeError::New(callbackInfo.Env(),
  3832. "Class constructors cannot be invoked without 'new'"),
  3833. Napi::Value());
  3834. }
  3835. template <typename T>
  3836. inline void ObjectWrap<T>::Finalize(Napi::Env /*env*/) {}
  3837. template <typename T>
  3838. inline napi_value ObjectWrap<T>::ConstructorCallbackWrapper(
  3839. napi_env env, napi_callback_info info) {
  3840. napi_value new_target;
  3841. napi_status status = napi_get_new_target(env, info, &new_target);
  3842. if (status != napi_ok) return nullptr;
  3843. bool isConstructCall = (new_target != nullptr);
  3844. if (!isConstructCall) {
  3845. return details::WrapCallback(
  3846. [&] { return T::OnCalledAsFunction(CallbackInfo(env, info)); });
  3847. }
  3848. napi_value wrapper = details::WrapCallback([&] {
  3849. CallbackInfo callbackInfo(env, info);
  3850. T* instance = new T(callbackInfo);
  3851. #ifdef NAPI_CPP_EXCEPTIONS
  3852. instance->_construction_failed = false;
  3853. #else
  3854. if (callbackInfo.Env().IsExceptionPending()) {
  3855. // We need to clear the exception so that removing the wrap might work.
  3856. Error e = callbackInfo.Env().GetAndClearPendingException();
  3857. delete instance;
  3858. e.ThrowAsJavaScriptException();
  3859. } else {
  3860. instance->_construction_failed = false;
  3861. }
  3862. #endif // NAPI_CPP_EXCEPTIONS
  3863. return callbackInfo.This();
  3864. });
  3865. return wrapper;
  3866. }
  3867. template <typename T>
  3868. inline napi_value ObjectWrap<T>::StaticVoidMethodCallbackWrapper(
  3869. napi_env env, napi_callback_info info) {
  3870. return details::WrapCallback([&] {
  3871. CallbackInfo callbackInfo(env, info);
  3872. StaticVoidMethodCallbackData* callbackData =
  3873. reinterpret_cast<StaticVoidMethodCallbackData*>(callbackInfo.Data());
  3874. callbackInfo.SetData(callbackData->data);
  3875. callbackData->callback(callbackInfo);
  3876. return nullptr;
  3877. });
  3878. }
  3879. template <typename T>
  3880. inline napi_value ObjectWrap<T>::StaticMethodCallbackWrapper(
  3881. napi_env env, napi_callback_info info) {
  3882. return details::WrapCallback([&] {
  3883. CallbackInfo callbackInfo(env, info);
  3884. StaticMethodCallbackData* callbackData =
  3885. reinterpret_cast<StaticMethodCallbackData*>(callbackInfo.Data());
  3886. callbackInfo.SetData(callbackData->data);
  3887. return callbackData->callback(callbackInfo);
  3888. });
  3889. }
  3890. template <typename T>
  3891. inline napi_value ObjectWrap<T>::StaticGetterCallbackWrapper(
  3892. napi_env env, napi_callback_info info) {
  3893. return details::WrapCallback([&] {
  3894. CallbackInfo callbackInfo(env, info);
  3895. StaticAccessorCallbackData* callbackData =
  3896. reinterpret_cast<StaticAccessorCallbackData*>(callbackInfo.Data());
  3897. callbackInfo.SetData(callbackData->data);
  3898. return callbackData->getterCallback(callbackInfo);
  3899. });
  3900. }
  3901. template <typename T>
  3902. inline napi_value ObjectWrap<T>::StaticSetterCallbackWrapper(
  3903. napi_env env, napi_callback_info info) {
  3904. return details::WrapCallback([&] {
  3905. CallbackInfo callbackInfo(env, info);
  3906. StaticAccessorCallbackData* callbackData =
  3907. reinterpret_cast<StaticAccessorCallbackData*>(callbackInfo.Data());
  3908. callbackInfo.SetData(callbackData->data);
  3909. callbackData->setterCallback(callbackInfo, callbackInfo[0]);
  3910. return nullptr;
  3911. });
  3912. }
  3913. template <typename T>
  3914. inline void ObjectWrap<T>::FinalizeCallback(napi_env env,
  3915. void* data,
  3916. void* /*hint*/) {
  3917. HandleScope scope(env);
  3918. T* instance = static_cast<T*>(data);
  3919. instance->Finalize(Napi::Env(env));
  3920. delete instance;
  3921. }
  3922. template <typename T>
  3923. template <typename ObjectWrap<T>::StaticSetterCallback method>
  3924. inline napi_value ObjectWrap<T>::WrappedMethod(
  3925. napi_env env, napi_callback_info info) NAPI_NOEXCEPT {
  3926. return details::WrapCallback([&] {
  3927. const CallbackInfo cbInfo(env, info);
  3928. method(cbInfo, cbInfo[0]);
  3929. return nullptr;
  3930. });
  3931. }
  3932. ////////////////////////////////////////////////////////////////////////////////
  3933. // HandleScope class
  3934. ////////////////////////////////////////////////////////////////////////////////
  3935. inline HandleScope::HandleScope(napi_env env, napi_handle_scope scope)
  3936. : _env(env), _scope(scope) {}
  3937. inline HandleScope::HandleScope(Napi::Env env) : _env(env) {
  3938. napi_status status = napi_open_handle_scope(_env, &_scope);
  3939. NAPI_THROW_IF_FAILED_VOID(_env, status);
  3940. }
  3941. inline HandleScope::~HandleScope() {
  3942. napi_status status = napi_close_handle_scope(_env, _scope);
  3943. NAPI_FATAL_IF_FAILED(
  3944. status, "HandleScope::~HandleScope", "napi_close_handle_scope");
  3945. }
  3946. inline HandleScope::operator napi_handle_scope() const {
  3947. return _scope;
  3948. }
  3949. inline Napi::Env HandleScope::Env() const {
  3950. return Napi::Env(_env);
  3951. }
  3952. ////////////////////////////////////////////////////////////////////////////////
  3953. // EscapableHandleScope class
  3954. ////////////////////////////////////////////////////////////////////////////////
  3955. inline EscapableHandleScope::EscapableHandleScope(
  3956. napi_env env, napi_escapable_handle_scope scope)
  3957. : _env(env), _scope(scope) {}
  3958. inline EscapableHandleScope::EscapableHandleScope(Napi::Env env) : _env(env) {
  3959. napi_status status = napi_open_escapable_handle_scope(_env, &_scope);
  3960. NAPI_THROW_IF_FAILED_VOID(_env, status);
  3961. }
  3962. inline EscapableHandleScope::~EscapableHandleScope() {
  3963. napi_status status = napi_close_escapable_handle_scope(_env, _scope);
  3964. NAPI_FATAL_IF_FAILED(status,
  3965. "EscapableHandleScope::~EscapableHandleScope",
  3966. "napi_close_escapable_handle_scope");
  3967. }
  3968. inline EscapableHandleScope::operator napi_escapable_handle_scope() const {
  3969. return _scope;
  3970. }
  3971. inline Napi::Env EscapableHandleScope::Env() const {
  3972. return Napi::Env(_env);
  3973. }
  3974. inline Value EscapableHandleScope::Escape(napi_value escapee) {
  3975. napi_value result;
  3976. napi_status status = napi_escape_handle(_env, _scope, escapee, &result);
  3977. NAPI_THROW_IF_FAILED(_env, status, Value());
  3978. return Value(_env, result);
  3979. }
  3980. #if (NAPI_VERSION > 2)
  3981. ////////////////////////////////////////////////////////////////////////////////
  3982. // CallbackScope class
  3983. ////////////////////////////////////////////////////////////////////////////////
  3984. inline CallbackScope::CallbackScope(napi_env env, napi_callback_scope scope)
  3985. : _env(env), _scope(scope) {}
  3986. inline CallbackScope::CallbackScope(napi_env env, napi_async_context context)
  3987. : _env(env) {
  3988. napi_status status =
  3989. napi_open_callback_scope(_env, Object::New(env), context, &_scope);
  3990. NAPI_THROW_IF_FAILED_VOID(_env, status);
  3991. }
  3992. inline CallbackScope::~CallbackScope() {
  3993. napi_status status = napi_close_callback_scope(_env, _scope);
  3994. NAPI_FATAL_IF_FAILED(
  3995. status, "CallbackScope::~CallbackScope", "napi_close_callback_scope");
  3996. }
  3997. inline CallbackScope::operator napi_callback_scope() const {
  3998. return _scope;
  3999. }
  4000. inline Napi::Env CallbackScope::Env() const {
  4001. return Napi::Env(_env);
  4002. }
  4003. #endif
  4004. ////////////////////////////////////////////////////////////////////////////////
  4005. // AsyncContext class
  4006. ////////////////////////////////////////////////////////////////////////////////
  4007. inline AsyncContext::AsyncContext(napi_env env, const char* resource_name)
  4008. : AsyncContext(env, resource_name, Object::New(env)) {}
  4009. inline AsyncContext::AsyncContext(napi_env env,
  4010. const char* resource_name,
  4011. const Object& resource)
  4012. : _env(env), _context(nullptr) {
  4013. napi_value resource_id;
  4014. napi_status status = napi_create_string_utf8(
  4015. _env, resource_name, NAPI_AUTO_LENGTH, &resource_id);
  4016. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4017. status = napi_async_init(_env, resource, resource_id, &_context);
  4018. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4019. }
  4020. inline AsyncContext::~AsyncContext() {
  4021. if (_context != nullptr) {
  4022. napi_async_destroy(_env, _context);
  4023. _context = nullptr;
  4024. }
  4025. }
  4026. inline AsyncContext::AsyncContext(AsyncContext&& other) {
  4027. _env = other._env;
  4028. other._env = nullptr;
  4029. _context = other._context;
  4030. other._context = nullptr;
  4031. }
  4032. inline AsyncContext& AsyncContext::operator=(AsyncContext&& other) {
  4033. _env = other._env;
  4034. other._env = nullptr;
  4035. _context = other._context;
  4036. other._context = nullptr;
  4037. return *this;
  4038. }
  4039. inline AsyncContext::operator napi_async_context() const {
  4040. return _context;
  4041. }
  4042. inline Napi::Env AsyncContext::Env() const {
  4043. return Napi::Env(_env);
  4044. }
  4045. ////////////////////////////////////////////////////////////////////////////////
  4046. // AsyncWorker class
  4047. ////////////////////////////////////////////////////////////////////////////////
  4048. inline AsyncWorker::AsyncWorker(const Function& callback)
  4049. : AsyncWorker(callback, "generic") {}
  4050. inline AsyncWorker::AsyncWorker(const Function& callback,
  4051. const char* resource_name)
  4052. : AsyncWorker(callback, resource_name, Object::New(callback.Env())) {}
  4053. inline AsyncWorker::AsyncWorker(const Function& callback,
  4054. const char* resource_name,
  4055. const Object& resource)
  4056. : AsyncWorker(
  4057. Object::New(callback.Env()), callback, resource_name, resource) {}
  4058. inline AsyncWorker::AsyncWorker(const Object& receiver,
  4059. const Function& callback)
  4060. : AsyncWorker(receiver, callback, "generic") {}
  4061. inline AsyncWorker::AsyncWorker(const Object& receiver,
  4062. const Function& callback,
  4063. const char* resource_name)
  4064. : AsyncWorker(
  4065. receiver, callback, resource_name, Object::New(callback.Env())) {}
  4066. inline AsyncWorker::AsyncWorker(const Object& receiver,
  4067. const Function& callback,
  4068. const char* resource_name,
  4069. const Object& resource)
  4070. : _env(callback.Env()),
  4071. _receiver(Napi::Persistent(receiver)),
  4072. _callback(Napi::Persistent(callback)),
  4073. _suppress_destruct(false) {
  4074. napi_value resource_id;
  4075. napi_status status = napi_create_string_latin1(
  4076. _env, resource_name, NAPI_AUTO_LENGTH, &resource_id);
  4077. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4078. status = napi_create_async_work(_env,
  4079. resource,
  4080. resource_id,
  4081. OnAsyncWorkExecute,
  4082. OnAsyncWorkComplete,
  4083. this,
  4084. &_work);
  4085. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4086. }
  4087. inline AsyncWorker::AsyncWorker(Napi::Env env) : AsyncWorker(env, "generic") {}
  4088. inline AsyncWorker::AsyncWorker(Napi::Env env, const char* resource_name)
  4089. : AsyncWorker(env, resource_name, Object::New(env)) {}
  4090. inline AsyncWorker::AsyncWorker(Napi::Env env,
  4091. const char* resource_name,
  4092. const Object& resource)
  4093. : _env(env), _receiver(), _callback(), _suppress_destruct(false) {
  4094. napi_value resource_id;
  4095. napi_status status = napi_create_string_latin1(
  4096. _env, resource_name, NAPI_AUTO_LENGTH, &resource_id);
  4097. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4098. status = napi_create_async_work(_env,
  4099. resource,
  4100. resource_id,
  4101. OnAsyncWorkExecute,
  4102. OnAsyncWorkComplete,
  4103. this,
  4104. &_work);
  4105. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4106. }
  4107. inline AsyncWorker::~AsyncWorker() {
  4108. if (_work != nullptr) {
  4109. napi_delete_async_work(_env, _work);
  4110. _work = nullptr;
  4111. }
  4112. }
  4113. inline void AsyncWorker::Destroy() {
  4114. delete this;
  4115. }
  4116. inline AsyncWorker::AsyncWorker(AsyncWorker&& other) {
  4117. _env = other._env;
  4118. other._env = nullptr;
  4119. _work = other._work;
  4120. other._work = nullptr;
  4121. _receiver = std::move(other._receiver);
  4122. _callback = std::move(other._callback);
  4123. _error = std::move(other._error);
  4124. _suppress_destruct = other._suppress_destruct;
  4125. }
  4126. inline AsyncWorker& AsyncWorker::operator=(AsyncWorker&& other) {
  4127. _env = other._env;
  4128. other._env = nullptr;
  4129. _work = other._work;
  4130. other._work = nullptr;
  4131. _receiver = std::move(other._receiver);
  4132. _callback = std::move(other._callback);
  4133. _error = std::move(other._error);
  4134. _suppress_destruct = other._suppress_destruct;
  4135. return *this;
  4136. }
  4137. inline AsyncWorker::operator napi_async_work() const {
  4138. return _work;
  4139. }
  4140. inline Napi::Env AsyncWorker::Env() const {
  4141. return Napi::Env(_env);
  4142. }
  4143. inline void AsyncWorker::Queue() {
  4144. napi_status status = napi_queue_async_work(_env, _work);
  4145. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4146. }
  4147. inline void AsyncWorker::Cancel() {
  4148. napi_status status = napi_cancel_async_work(_env, _work);
  4149. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4150. }
  4151. inline ObjectReference& AsyncWorker::Receiver() {
  4152. return _receiver;
  4153. }
  4154. inline FunctionReference& AsyncWorker::Callback() {
  4155. return _callback;
  4156. }
  4157. inline void AsyncWorker::SuppressDestruct() {
  4158. _suppress_destruct = true;
  4159. }
  4160. inline void AsyncWorker::OnOK() {
  4161. if (!_callback.IsEmpty()) {
  4162. _callback.Call(_receiver.Value(), GetResult(_callback.Env()));
  4163. }
  4164. }
  4165. inline void AsyncWorker::OnError(const Error& e) {
  4166. if (!_callback.IsEmpty()) {
  4167. _callback.Call(_receiver.Value(),
  4168. std::initializer_list<napi_value>{e.Value()});
  4169. }
  4170. }
  4171. inline void AsyncWorker::SetError(const std::string& error) {
  4172. _error = error;
  4173. }
  4174. inline std::vector<napi_value> AsyncWorker::GetResult(Napi::Env /*env*/) {
  4175. return {};
  4176. }
  4177. // The OnAsyncWorkExecute method receives an napi_env argument. However, do NOT
  4178. // use it within this method, as it does not run on the JavaScript thread and
  4179. // must not run any method that would cause JavaScript to run. In practice,
  4180. // this means that almost any use of napi_env will be incorrect.
  4181. inline void AsyncWorker::OnAsyncWorkExecute(napi_env env, void* asyncworker) {
  4182. AsyncWorker* self = static_cast<AsyncWorker*>(asyncworker);
  4183. self->OnExecute(env);
  4184. }
  4185. // The OnExecute method receives an napi_env argument. However, do NOT
  4186. // use it within this method, as it does not run on the JavaScript thread and
  4187. // must not run any method that would cause JavaScript to run. In practice,
  4188. // this means that almost any use of napi_env will be incorrect.
  4189. inline void AsyncWorker::OnExecute(Napi::Env /*DO_NOT_USE*/) {
  4190. #ifdef NAPI_CPP_EXCEPTIONS
  4191. try {
  4192. Execute();
  4193. } catch (const std::exception& e) {
  4194. SetError(e.what());
  4195. }
  4196. #else // NAPI_CPP_EXCEPTIONS
  4197. Execute();
  4198. #endif // NAPI_CPP_EXCEPTIONS
  4199. }
  4200. inline void AsyncWorker::OnAsyncWorkComplete(napi_env env,
  4201. napi_status status,
  4202. void* asyncworker) {
  4203. AsyncWorker* self = static_cast<AsyncWorker*>(asyncworker);
  4204. self->OnWorkComplete(env, status);
  4205. }
  4206. inline void AsyncWorker::OnWorkComplete(Napi::Env /*env*/, napi_status status) {
  4207. if (status != napi_cancelled) {
  4208. HandleScope scope(_env);
  4209. details::WrapCallback([&] {
  4210. if (_error.size() == 0) {
  4211. OnOK();
  4212. } else {
  4213. OnError(Error::New(_env, _error));
  4214. }
  4215. return nullptr;
  4216. });
  4217. }
  4218. if (!_suppress_destruct) {
  4219. Destroy();
  4220. }
  4221. }
  4222. #if (NAPI_VERSION > 3 && !defined(__wasm32__))
  4223. ////////////////////////////////////////////////////////////////////////////////
  4224. // TypedThreadSafeFunction<ContextType,DataType,CallJs> class
  4225. ////////////////////////////////////////////////////////////////////////////////
  4226. // Starting with NAPI 5, the JavaScript function `func` parameter of
  4227. // `napi_create_threadsafe_function` is optional.
  4228. #if NAPI_VERSION > 4
  4229. // static, with Callback [missing] Resource [missing] Finalizer [missing]
  4230. template <typename ContextType,
  4231. typename DataType,
  4232. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4233. template <typename ResourceString>
  4234. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4235. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4236. napi_env env,
  4237. ResourceString resourceName,
  4238. size_t maxQueueSize,
  4239. size_t initialThreadCount,
  4240. ContextType* context) {
  4241. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4242. napi_status status =
  4243. napi_create_threadsafe_function(env,
  4244. nullptr,
  4245. nullptr,
  4246. String::From(env, resourceName),
  4247. maxQueueSize,
  4248. initialThreadCount,
  4249. nullptr,
  4250. nullptr,
  4251. context,
  4252. CallJsInternal,
  4253. &tsfn._tsfn);
  4254. if (status != napi_ok) {
  4255. NAPI_THROW_IF_FAILED(
  4256. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4257. }
  4258. return tsfn;
  4259. }
  4260. // static, with Callback [missing] Resource [passed] Finalizer [missing]
  4261. template <typename ContextType,
  4262. typename DataType,
  4263. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4264. template <typename ResourceString>
  4265. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4266. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4267. napi_env env,
  4268. const Object& resource,
  4269. ResourceString resourceName,
  4270. size_t maxQueueSize,
  4271. size_t initialThreadCount,
  4272. ContextType* context) {
  4273. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4274. napi_status status =
  4275. napi_create_threadsafe_function(env,
  4276. nullptr,
  4277. resource,
  4278. String::From(env, resourceName),
  4279. maxQueueSize,
  4280. initialThreadCount,
  4281. nullptr,
  4282. nullptr,
  4283. context,
  4284. CallJsInternal,
  4285. &tsfn._tsfn);
  4286. if (status != napi_ok) {
  4287. NAPI_THROW_IF_FAILED(
  4288. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4289. }
  4290. return tsfn;
  4291. }
  4292. // static, with Callback [missing] Resource [missing] Finalizer [passed]
  4293. template <typename ContextType,
  4294. typename DataType,
  4295. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4296. template <typename ResourceString,
  4297. typename Finalizer,
  4298. typename FinalizerDataType>
  4299. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4300. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4301. napi_env env,
  4302. ResourceString resourceName,
  4303. size_t maxQueueSize,
  4304. size_t initialThreadCount,
  4305. ContextType* context,
  4306. Finalizer finalizeCallback,
  4307. FinalizerDataType* data) {
  4308. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4309. auto* finalizeData = new details::
  4310. ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>(
  4311. {data, finalizeCallback});
  4312. napi_status status = napi_create_threadsafe_function(
  4313. env,
  4314. nullptr,
  4315. nullptr,
  4316. String::From(env, resourceName),
  4317. maxQueueSize,
  4318. initialThreadCount,
  4319. finalizeData,
  4320. details::ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>::
  4321. FinalizeFinalizeWrapperWithDataAndContext,
  4322. context,
  4323. CallJsInternal,
  4324. &tsfn._tsfn);
  4325. if (status != napi_ok) {
  4326. delete finalizeData;
  4327. NAPI_THROW_IF_FAILED(
  4328. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4329. }
  4330. return tsfn;
  4331. }
  4332. // static, with Callback [missing] Resource [passed] Finalizer [passed]
  4333. template <typename ContextType,
  4334. typename DataType,
  4335. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4336. template <typename ResourceString,
  4337. typename Finalizer,
  4338. typename FinalizerDataType>
  4339. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4340. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4341. napi_env env,
  4342. const Object& resource,
  4343. ResourceString resourceName,
  4344. size_t maxQueueSize,
  4345. size_t initialThreadCount,
  4346. ContextType* context,
  4347. Finalizer finalizeCallback,
  4348. FinalizerDataType* data) {
  4349. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4350. auto* finalizeData = new details::
  4351. ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>(
  4352. {data, finalizeCallback});
  4353. napi_status status = napi_create_threadsafe_function(
  4354. env,
  4355. nullptr,
  4356. resource,
  4357. String::From(env, resourceName),
  4358. maxQueueSize,
  4359. initialThreadCount,
  4360. finalizeData,
  4361. details::ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>::
  4362. FinalizeFinalizeWrapperWithDataAndContext,
  4363. context,
  4364. CallJsInternal,
  4365. &tsfn._tsfn);
  4366. if (status != napi_ok) {
  4367. delete finalizeData;
  4368. NAPI_THROW_IF_FAILED(
  4369. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4370. }
  4371. return tsfn;
  4372. }
  4373. #endif
  4374. // static, with Callback [passed] Resource [missing] Finalizer [missing]
  4375. template <typename ContextType,
  4376. typename DataType,
  4377. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4378. template <typename ResourceString>
  4379. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4380. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4381. napi_env env,
  4382. const Function& callback,
  4383. ResourceString resourceName,
  4384. size_t maxQueueSize,
  4385. size_t initialThreadCount,
  4386. ContextType* context) {
  4387. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4388. napi_status status =
  4389. napi_create_threadsafe_function(env,
  4390. callback,
  4391. nullptr,
  4392. String::From(env, resourceName),
  4393. maxQueueSize,
  4394. initialThreadCount,
  4395. nullptr,
  4396. nullptr,
  4397. context,
  4398. CallJsInternal,
  4399. &tsfn._tsfn);
  4400. if (status != napi_ok) {
  4401. NAPI_THROW_IF_FAILED(
  4402. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4403. }
  4404. return tsfn;
  4405. }
  4406. // static, with Callback [passed] Resource [passed] Finalizer [missing]
  4407. template <typename ContextType,
  4408. typename DataType,
  4409. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4410. template <typename ResourceString>
  4411. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4412. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4413. napi_env env,
  4414. const Function& callback,
  4415. const Object& resource,
  4416. ResourceString resourceName,
  4417. size_t maxQueueSize,
  4418. size_t initialThreadCount,
  4419. ContextType* context) {
  4420. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4421. napi_status status =
  4422. napi_create_threadsafe_function(env,
  4423. callback,
  4424. resource,
  4425. String::From(env, resourceName),
  4426. maxQueueSize,
  4427. initialThreadCount,
  4428. nullptr,
  4429. nullptr,
  4430. context,
  4431. CallJsInternal,
  4432. &tsfn._tsfn);
  4433. if (status != napi_ok) {
  4434. NAPI_THROW_IF_FAILED(
  4435. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4436. }
  4437. return tsfn;
  4438. }
  4439. // static, with Callback [passed] Resource [missing] Finalizer [passed]
  4440. template <typename ContextType,
  4441. typename DataType,
  4442. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4443. template <typename ResourceString,
  4444. typename Finalizer,
  4445. typename FinalizerDataType>
  4446. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4447. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4448. napi_env env,
  4449. const Function& callback,
  4450. ResourceString resourceName,
  4451. size_t maxQueueSize,
  4452. size_t initialThreadCount,
  4453. ContextType* context,
  4454. Finalizer finalizeCallback,
  4455. FinalizerDataType* data) {
  4456. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4457. auto* finalizeData = new details::
  4458. ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>(
  4459. {data, finalizeCallback});
  4460. napi_status status = napi_create_threadsafe_function(
  4461. env,
  4462. callback,
  4463. nullptr,
  4464. String::From(env, resourceName),
  4465. maxQueueSize,
  4466. initialThreadCount,
  4467. finalizeData,
  4468. details::ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>::
  4469. FinalizeFinalizeWrapperWithDataAndContext,
  4470. context,
  4471. CallJsInternal,
  4472. &tsfn._tsfn);
  4473. if (status != napi_ok) {
  4474. delete finalizeData;
  4475. NAPI_THROW_IF_FAILED(
  4476. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4477. }
  4478. return tsfn;
  4479. }
  4480. // static, with: Callback [passed] Resource [passed] Finalizer [passed]
  4481. template <typename ContextType,
  4482. typename DataType,
  4483. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4484. template <typename CallbackType,
  4485. typename ResourceString,
  4486. typename Finalizer,
  4487. typename FinalizerDataType>
  4488. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4489. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4490. napi_env env,
  4491. CallbackType callback,
  4492. const Object& resource,
  4493. ResourceString resourceName,
  4494. size_t maxQueueSize,
  4495. size_t initialThreadCount,
  4496. ContextType* context,
  4497. Finalizer finalizeCallback,
  4498. FinalizerDataType* data) {
  4499. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4500. auto* finalizeData = new details::
  4501. ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>(
  4502. {data, finalizeCallback});
  4503. napi_status status = napi_create_threadsafe_function(
  4504. env,
  4505. details::DefaultCallbackWrapper<
  4506. CallbackType,
  4507. TypedThreadSafeFunction<ContextType, DataType, CallJs>>(env,
  4508. callback),
  4509. resource,
  4510. String::From(env, resourceName),
  4511. maxQueueSize,
  4512. initialThreadCount,
  4513. finalizeData,
  4514. details::ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>::
  4515. FinalizeFinalizeWrapperWithDataAndContext,
  4516. context,
  4517. CallJsInternal,
  4518. &tsfn._tsfn);
  4519. if (status != napi_ok) {
  4520. delete finalizeData;
  4521. NAPI_THROW_IF_FAILED(
  4522. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4523. }
  4524. return tsfn;
  4525. }
  4526. template <typename ContextType,
  4527. typename DataType,
  4528. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4529. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>::
  4530. TypedThreadSafeFunction()
  4531. : _tsfn() {}
  4532. template <typename ContextType,
  4533. typename DataType,
  4534. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4535. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>::
  4536. TypedThreadSafeFunction(napi_threadsafe_function tsfn)
  4537. : _tsfn(tsfn) {}
  4538. template <typename ContextType,
  4539. typename DataType,
  4540. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4541. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>::
  4542. operator napi_threadsafe_function() const {
  4543. return _tsfn;
  4544. }
  4545. template <typename ContextType,
  4546. typename DataType,
  4547. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4548. inline napi_status
  4549. TypedThreadSafeFunction<ContextType, DataType, CallJs>::BlockingCall(
  4550. DataType* data) const {
  4551. return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_blocking);
  4552. }
  4553. template <typename ContextType,
  4554. typename DataType,
  4555. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4556. inline napi_status
  4557. TypedThreadSafeFunction<ContextType, DataType, CallJs>::NonBlockingCall(
  4558. DataType* data) const {
  4559. return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_nonblocking);
  4560. }
  4561. template <typename ContextType,
  4562. typename DataType,
  4563. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4564. inline void TypedThreadSafeFunction<ContextType, DataType, CallJs>::Ref(
  4565. napi_env env) const {
  4566. if (_tsfn != nullptr) {
  4567. napi_status status = napi_ref_threadsafe_function(env, _tsfn);
  4568. NAPI_THROW_IF_FAILED_VOID(env, status);
  4569. }
  4570. }
  4571. template <typename ContextType,
  4572. typename DataType,
  4573. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4574. inline void TypedThreadSafeFunction<ContextType, DataType, CallJs>::Unref(
  4575. napi_env env) const {
  4576. if (_tsfn != nullptr) {
  4577. napi_status status = napi_unref_threadsafe_function(env, _tsfn);
  4578. NAPI_THROW_IF_FAILED_VOID(env, status);
  4579. }
  4580. }
  4581. template <typename ContextType,
  4582. typename DataType,
  4583. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4584. inline napi_status
  4585. TypedThreadSafeFunction<ContextType, DataType, CallJs>::Acquire() const {
  4586. return napi_acquire_threadsafe_function(_tsfn);
  4587. }
  4588. template <typename ContextType,
  4589. typename DataType,
  4590. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4591. inline napi_status
  4592. TypedThreadSafeFunction<ContextType, DataType, CallJs>::Release() const {
  4593. return napi_release_threadsafe_function(_tsfn, napi_tsfn_release);
  4594. }
  4595. template <typename ContextType,
  4596. typename DataType,
  4597. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4598. inline napi_status
  4599. TypedThreadSafeFunction<ContextType, DataType, CallJs>::Abort() const {
  4600. return napi_release_threadsafe_function(_tsfn, napi_tsfn_abort);
  4601. }
  4602. template <typename ContextType,
  4603. typename DataType,
  4604. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4605. inline ContextType*
  4606. TypedThreadSafeFunction<ContextType, DataType, CallJs>::GetContext() const {
  4607. void* context;
  4608. napi_status status = napi_get_threadsafe_function_context(_tsfn, &context);
  4609. NAPI_FATAL_IF_FAILED(status,
  4610. "TypedThreadSafeFunction::GetContext",
  4611. "napi_get_threadsafe_function_context");
  4612. return static_cast<ContextType*>(context);
  4613. }
  4614. // static
  4615. template <typename ContextType,
  4616. typename DataType,
  4617. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4618. void TypedThreadSafeFunction<ContextType, DataType, CallJs>::CallJsInternal(
  4619. napi_env env, napi_value jsCallback, void* context, void* data) {
  4620. details::CallJsWrapper<ContextType, DataType, decltype(CallJs), CallJs>(
  4621. env, jsCallback, context, data);
  4622. }
  4623. #if NAPI_VERSION == 4
  4624. // static
  4625. template <typename ContextType,
  4626. typename DataType,
  4627. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4628. Napi::Function
  4629. TypedThreadSafeFunction<ContextType, DataType, CallJs>::EmptyFunctionFactory(
  4630. Napi::Env env) {
  4631. return Napi::Function::New(env, [](const CallbackInfo& cb) {});
  4632. }
  4633. // static
  4634. template <typename ContextType,
  4635. typename DataType,
  4636. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4637. Napi::Function
  4638. TypedThreadSafeFunction<ContextType, DataType, CallJs>::FunctionOrEmpty(
  4639. Napi::Env env, Napi::Function& callback) {
  4640. if (callback.IsEmpty()) {
  4641. return EmptyFunctionFactory(env);
  4642. }
  4643. return callback;
  4644. }
  4645. #else
  4646. // static
  4647. template <typename ContextType,
  4648. typename DataType,
  4649. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4650. std::nullptr_t
  4651. TypedThreadSafeFunction<ContextType, DataType, CallJs>::EmptyFunctionFactory(
  4652. Napi::Env /*env*/) {
  4653. return nullptr;
  4654. }
  4655. // static
  4656. template <typename ContextType,
  4657. typename DataType,
  4658. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4659. Napi::Function
  4660. TypedThreadSafeFunction<ContextType, DataType, CallJs>::FunctionOrEmpty(
  4661. Napi::Env /*env*/, Napi::Function& callback) {
  4662. return callback;
  4663. }
  4664. #endif
  4665. ////////////////////////////////////////////////////////////////////////////////
  4666. // ThreadSafeFunction class
  4667. ////////////////////////////////////////////////////////////////////////////////
  4668. // static
  4669. template <typename ResourceString>
  4670. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4671. const Function& callback,
  4672. ResourceString resourceName,
  4673. size_t maxQueueSize,
  4674. size_t initialThreadCount) {
  4675. return New(
  4676. env, callback, Object(), resourceName, maxQueueSize, initialThreadCount);
  4677. }
  4678. // static
  4679. template <typename ResourceString, typename ContextType>
  4680. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4681. const Function& callback,
  4682. ResourceString resourceName,
  4683. size_t maxQueueSize,
  4684. size_t initialThreadCount,
  4685. ContextType* context) {
  4686. return New(env,
  4687. callback,
  4688. Object(),
  4689. resourceName,
  4690. maxQueueSize,
  4691. initialThreadCount,
  4692. context);
  4693. }
  4694. // static
  4695. template <typename ResourceString, typename Finalizer>
  4696. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4697. const Function& callback,
  4698. ResourceString resourceName,
  4699. size_t maxQueueSize,
  4700. size_t initialThreadCount,
  4701. Finalizer finalizeCallback) {
  4702. return New(env,
  4703. callback,
  4704. Object(),
  4705. resourceName,
  4706. maxQueueSize,
  4707. initialThreadCount,
  4708. finalizeCallback);
  4709. }
  4710. // static
  4711. template <typename ResourceString,
  4712. typename Finalizer,
  4713. typename FinalizerDataType>
  4714. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4715. const Function& callback,
  4716. ResourceString resourceName,
  4717. size_t maxQueueSize,
  4718. size_t initialThreadCount,
  4719. Finalizer finalizeCallback,
  4720. FinalizerDataType* data) {
  4721. return New(env,
  4722. callback,
  4723. Object(),
  4724. resourceName,
  4725. maxQueueSize,
  4726. initialThreadCount,
  4727. finalizeCallback,
  4728. data);
  4729. }
  4730. // static
  4731. template <typename ResourceString, typename ContextType, typename Finalizer>
  4732. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4733. const Function& callback,
  4734. ResourceString resourceName,
  4735. size_t maxQueueSize,
  4736. size_t initialThreadCount,
  4737. ContextType* context,
  4738. Finalizer finalizeCallback) {
  4739. return New(env,
  4740. callback,
  4741. Object(),
  4742. resourceName,
  4743. maxQueueSize,
  4744. initialThreadCount,
  4745. context,
  4746. finalizeCallback);
  4747. }
  4748. // static
  4749. template <typename ResourceString,
  4750. typename ContextType,
  4751. typename Finalizer,
  4752. typename FinalizerDataType>
  4753. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4754. const Function& callback,
  4755. ResourceString resourceName,
  4756. size_t maxQueueSize,
  4757. size_t initialThreadCount,
  4758. ContextType* context,
  4759. Finalizer finalizeCallback,
  4760. FinalizerDataType* data) {
  4761. return New(env,
  4762. callback,
  4763. Object(),
  4764. resourceName,
  4765. maxQueueSize,
  4766. initialThreadCount,
  4767. context,
  4768. finalizeCallback,
  4769. data);
  4770. }
  4771. // static
  4772. template <typename ResourceString>
  4773. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4774. const Function& callback,
  4775. const Object& resource,
  4776. ResourceString resourceName,
  4777. size_t maxQueueSize,
  4778. size_t initialThreadCount) {
  4779. return New(env,
  4780. callback,
  4781. resource,
  4782. resourceName,
  4783. maxQueueSize,
  4784. initialThreadCount,
  4785. static_cast<void*>(nullptr) /* context */);
  4786. }
  4787. // static
  4788. template <typename ResourceString, typename ContextType>
  4789. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4790. const Function& callback,
  4791. const Object& resource,
  4792. ResourceString resourceName,
  4793. size_t maxQueueSize,
  4794. size_t initialThreadCount,
  4795. ContextType* context) {
  4796. return New(env,
  4797. callback,
  4798. resource,
  4799. resourceName,
  4800. maxQueueSize,
  4801. initialThreadCount,
  4802. context,
  4803. [](Env, ContextType*) {} /* empty finalizer */);
  4804. }
  4805. // static
  4806. template <typename ResourceString, typename Finalizer>
  4807. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4808. const Function& callback,
  4809. const Object& resource,
  4810. ResourceString resourceName,
  4811. size_t maxQueueSize,
  4812. size_t initialThreadCount,
  4813. Finalizer finalizeCallback) {
  4814. return New(env,
  4815. callback,
  4816. resource,
  4817. resourceName,
  4818. maxQueueSize,
  4819. initialThreadCount,
  4820. static_cast<void*>(nullptr) /* context */,
  4821. finalizeCallback,
  4822. static_cast<void*>(nullptr) /* data */,
  4823. details::ThreadSafeFinalize<void, Finalizer>::Wrapper);
  4824. }
  4825. // static
  4826. template <typename ResourceString,
  4827. typename Finalizer,
  4828. typename FinalizerDataType>
  4829. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4830. const Function& callback,
  4831. const Object& resource,
  4832. ResourceString resourceName,
  4833. size_t maxQueueSize,
  4834. size_t initialThreadCount,
  4835. Finalizer finalizeCallback,
  4836. FinalizerDataType* data) {
  4837. return New(env,
  4838. callback,
  4839. resource,
  4840. resourceName,
  4841. maxQueueSize,
  4842. initialThreadCount,
  4843. static_cast<void*>(nullptr) /* context */,
  4844. finalizeCallback,
  4845. data,
  4846. details::ThreadSafeFinalize<void, Finalizer, FinalizerDataType>::
  4847. FinalizeWrapperWithData);
  4848. }
  4849. // static
  4850. template <typename ResourceString, typename ContextType, typename Finalizer>
  4851. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4852. const Function& callback,
  4853. const Object& resource,
  4854. ResourceString resourceName,
  4855. size_t maxQueueSize,
  4856. size_t initialThreadCount,
  4857. ContextType* context,
  4858. Finalizer finalizeCallback) {
  4859. return New(
  4860. env,
  4861. callback,
  4862. resource,
  4863. resourceName,
  4864. maxQueueSize,
  4865. initialThreadCount,
  4866. context,
  4867. finalizeCallback,
  4868. static_cast<void*>(nullptr) /* data */,
  4869. details::ThreadSafeFinalize<ContextType,
  4870. Finalizer>::FinalizeWrapperWithContext);
  4871. }
  4872. // static
  4873. template <typename ResourceString,
  4874. typename ContextType,
  4875. typename Finalizer,
  4876. typename FinalizerDataType>
  4877. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4878. const Function& callback,
  4879. const Object& resource,
  4880. ResourceString resourceName,
  4881. size_t maxQueueSize,
  4882. size_t initialThreadCount,
  4883. ContextType* context,
  4884. Finalizer finalizeCallback,
  4885. FinalizerDataType* data) {
  4886. return New(
  4887. env,
  4888. callback,
  4889. resource,
  4890. resourceName,
  4891. maxQueueSize,
  4892. initialThreadCount,
  4893. context,
  4894. finalizeCallback,
  4895. data,
  4896. details::ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>::
  4897. FinalizeFinalizeWrapperWithDataAndContext);
  4898. }
  4899. inline ThreadSafeFunction::ThreadSafeFunction() : _tsfn() {}
  4900. inline ThreadSafeFunction::ThreadSafeFunction(napi_threadsafe_function tsfn)
  4901. : _tsfn(tsfn) {}
  4902. inline ThreadSafeFunction::operator napi_threadsafe_function() const {
  4903. return _tsfn;
  4904. }
  4905. inline napi_status ThreadSafeFunction::BlockingCall() const {
  4906. return CallInternal(nullptr, napi_tsfn_blocking);
  4907. }
  4908. template <>
  4909. inline napi_status ThreadSafeFunction::BlockingCall(void* data) const {
  4910. return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_blocking);
  4911. }
  4912. template <typename Callback>
  4913. inline napi_status ThreadSafeFunction::BlockingCall(Callback callback) const {
  4914. return CallInternal(new CallbackWrapper(callback), napi_tsfn_blocking);
  4915. }
  4916. template <typename DataType, typename Callback>
  4917. inline napi_status ThreadSafeFunction::BlockingCall(DataType* data,
  4918. Callback callback) const {
  4919. auto wrapper = [data, callback](Env env, Function jsCallback) {
  4920. callback(env, jsCallback, data);
  4921. };
  4922. return CallInternal(new CallbackWrapper(wrapper), napi_tsfn_blocking);
  4923. }
  4924. inline napi_status ThreadSafeFunction::NonBlockingCall() const {
  4925. return CallInternal(nullptr, napi_tsfn_nonblocking);
  4926. }
  4927. template <>
  4928. inline napi_status ThreadSafeFunction::NonBlockingCall(void* data) const {
  4929. return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_nonblocking);
  4930. }
  4931. template <typename Callback>
  4932. inline napi_status ThreadSafeFunction::NonBlockingCall(
  4933. Callback callback) const {
  4934. return CallInternal(new CallbackWrapper(callback), napi_tsfn_nonblocking);
  4935. }
  4936. template <typename DataType, typename Callback>
  4937. inline napi_status ThreadSafeFunction::NonBlockingCall(
  4938. DataType* data, Callback callback) const {
  4939. auto wrapper = [data, callback](Env env, Function jsCallback) {
  4940. callback(env, jsCallback, data);
  4941. };
  4942. return CallInternal(new CallbackWrapper(wrapper), napi_tsfn_nonblocking);
  4943. }
  4944. inline void ThreadSafeFunction::Ref(napi_env env) const {
  4945. if (_tsfn != nullptr) {
  4946. napi_status status = napi_ref_threadsafe_function(env, _tsfn);
  4947. NAPI_THROW_IF_FAILED_VOID(env, status);
  4948. }
  4949. }
  4950. inline void ThreadSafeFunction::Unref(napi_env env) const {
  4951. if (_tsfn != nullptr) {
  4952. napi_status status = napi_unref_threadsafe_function(env, _tsfn);
  4953. NAPI_THROW_IF_FAILED_VOID(env, status);
  4954. }
  4955. }
  4956. inline napi_status ThreadSafeFunction::Acquire() const {
  4957. return napi_acquire_threadsafe_function(_tsfn);
  4958. }
  4959. inline napi_status ThreadSafeFunction::Release() const {
  4960. return napi_release_threadsafe_function(_tsfn, napi_tsfn_release);
  4961. }
  4962. inline napi_status ThreadSafeFunction::Abort() const {
  4963. return napi_release_threadsafe_function(_tsfn, napi_tsfn_abort);
  4964. }
  4965. inline ThreadSafeFunction::ConvertibleContext ThreadSafeFunction::GetContext()
  4966. const {
  4967. void* context;
  4968. napi_status status = napi_get_threadsafe_function_context(_tsfn, &context);
  4969. NAPI_FATAL_IF_FAILED(status,
  4970. "ThreadSafeFunction::GetContext",
  4971. "napi_get_threadsafe_function_context");
  4972. return ConvertibleContext({context});
  4973. }
  4974. // static
  4975. template <typename ResourceString,
  4976. typename ContextType,
  4977. typename Finalizer,
  4978. typename FinalizerDataType>
  4979. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4980. const Function& callback,
  4981. const Object& resource,
  4982. ResourceString resourceName,
  4983. size_t maxQueueSize,
  4984. size_t initialThreadCount,
  4985. ContextType* context,
  4986. Finalizer finalizeCallback,
  4987. FinalizerDataType* data,
  4988. napi_finalize wrapper) {
  4989. static_assert(details::can_make_string<ResourceString>::value ||
  4990. std::is_convertible<ResourceString, napi_value>::value,
  4991. "Resource name should be convertible to the string type");
  4992. ThreadSafeFunction tsfn;
  4993. auto* finalizeData = new details::
  4994. ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>(
  4995. {data, finalizeCallback});
  4996. napi_status status =
  4997. napi_create_threadsafe_function(env,
  4998. callback,
  4999. resource,
  5000. Value::From(env, resourceName),
  5001. maxQueueSize,
  5002. initialThreadCount,
  5003. finalizeData,
  5004. wrapper,
  5005. context,
  5006. CallJS,
  5007. &tsfn._tsfn);
  5008. if (status != napi_ok) {
  5009. delete finalizeData;
  5010. NAPI_THROW_IF_FAILED(env, status, ThreadSafeFunction());
  5011. }
  5012. return tsfn;
  5013. }
  5014. inline napi_status ThreadSafeFunction::CallInternal(
  5015. CallbackWrapper* callbackWrapper,
  5016. napi_threadsafe_function_call_mode mode) const {
  5017. napi_status status =
  5018. napi_call_threadsafe_function(_tsfn, callbackWrapper, mode);
  5019. if (status != napi_ok && callbackWrapper != nullptr) {
  5020. delete callbackWrapper;
  5021. }
  5022. return status;
  5023. }
  5024. // static
  5025. inline void ThreadSafeFunction::CallJS(napi_env env,
  5026. napi_value jsCallback,
  5027. void* /* context */,
  5028. void* data) {
  5029. if (env == nullptr && jsCallback == nullptr) {
  5030. return;
  5031. }
  5032. if (data != nullptr) {
  5033. auto* callbackWrapper = static_cast<CallbackWrapper*>(data);
  5034. (*callbackWrapper)(env, Function(env, jsCallback));
  5035. delete callbackWrapper;
  5036. } else if (jsCallback != nullptr) {
  5037. Function(env, jsCallback).Call({});
  5038. }
  5039. }
  5040. ////////////////////////////////////////////////////////////////////////////////
  5041. // Async Progress Worker Base class
  5042. ////////////////////////////////////////////////////////////////////////////////
  5043. template <typename DataType>
  5044. inline AsyncProgressWorkerBase<DataType>::AsyncProgressWorkerBase(
  5045. const Object& receiver,
  5046. const Function& callback,
  5047. const char* resource_name,
  5048. const Object& resource,
  5049. size_t queue_size)
  5050. : AsyncWorker(receiver, callback, resource_name, resource) {
  5051. // Fill all possible arguments to work around ambiguous
  5052. // ThreadSafeFunction::New signatures.
  5053. _tsfn = ThreadSafeFunction::New(callback.Env(),
  5054. callback,
  5055. resource,
  5056. resource_name,
  5057. queue_size,
  5058. /** initialThreadCount */ 1,
  5059. /** context */ this,
  5060. OnThreadSafeFunctionFinalize,
  5061. /** finalizeData */ this);
  5062. }
  5063. #if NAPI_VERSION > 4
  5064. template <typename DataType>
  5065. inline AsyncProgressWorkerBase<DataType>::AsyncProgressWorkerBase(
  5066. Napi::Env env,
  5067. const char* resource_name,
  5068. const Object& resource,
  5069. size_t queue_size)
  5070. : AsyncWorker(env, resource_name, resource) {
  5071. // TODO: Once the changes to make the callback optional for threadsafe
  5072. // functions are available on all versions we can remove the dummy Function
  5073. // here.
  5074. Function callback;
  5075. // Fill all possible arguments to work around ambiguous
  5076. // ThreadSafeFunction::New signatures.
  5077. _tsfn = ThreadSafeFunction::New(env,
  5078. callback,
  5079. resource,
  5080. resource_name,
  5081. queue_size,
  5082. /** initialThreadCount */ 1,
  5083. /** context */ this,
  5084. OnThreadSafeFunctionFinalize,
  5085. /** finalizeData */ this);
  5086. }
  5087. #endif
  5088. template <typename DataType>
  5089. inline AsyncProgressWorkerBase<DataType>::~AsyncProgressWorkerBase() {
  5090. // Abort pending tsfn call.
  5091. // Don't send progress events after we've already completed.
  5092. // It's ok to call ThreadSafeFunction::Abort and ThreadSafeFunction::Release
  5093. // duplicated.
  5094. _tsfn.Abort();
  5095. }
  5096. template <typename DataType>
  5097. inline void AsyncProgressWorkerBase<DataType>::OnAsyncWorkProgress(
  5098. Napi::Env /* env */, Napi::Function /* jsCallback */, void* data) {
  5099. ThreadSafeData* tsd = static_cast<ThreadSafeData*>(data);
  5100. tsd->asyncprogressworker()->OnWorkProgress(tsd->data());
  5101. delete tsd;
  5102. }
  5103. template <typename DataType>
  5104. inline napi_status AsyncProgressWorkerBase<DataType>::NonBlockingCall(
  5105. DataType* data) {
  5106. auto tsd = new AsyncProgressWorkerBase::ThreadSafeData(this, data);
  5107. auto ret = _tsfn.NonBlockingCall(tsd, OnAsyncWorkProgress);
  5108. if (ret != napi_ok) {
  5109. delete tsd;
  5110. }
  5111. return ret;
  5112. }
  5113. template <typename DataType>
  5114. inline void AsyncProgressWorkerBase<DataType>::OnWorkComplete(
  5115. Napi::Env /* env */, napi_status status) {
  5116. _work_completed = true;
  5117. _complete_status = status;
  5118. _tsfn.Release();
  5119. }
  5120. template <typename DataType>
  5121. inline void AsyncProgressWorkerBase<DataType>::OnThreadSafeFunctionFinalize(
  5122. Napi::Env env, void* /* data */, AsyncProgressWorkerBase* context) {
  5123. if (context->_work_completed) {
  5124. context->AsyncWorker::OnWorkComplete(env, context->_complete_status);
  5125. }
  5126. }
  5127. ////////////////////////////////////////////////////////////////////////////////
  5128. // Async Progress Worker class
  5129. ////////////////////////////////////////////////////////////////////////////////
  5130. template <class T>
  5131. inline AsyncProgressWorker<T>::AsyncProgressWorker(const Function& callback)
  5132. : AsyncProgressWorker(callback, "generic") {}
  5133. template <class T>
  5134. inline AsyncProgressWorker<T>::AsyncProgressWorker(const Function& callback,
  5135. const char* resource_name)
  5136. : AsyncProgressWorker(
  5137. callback, resource_name, Object::New(callback.Env())) {}
  5138. template <class T>
  5139. inline AsyncProgressWorker<T>::AsyncProgressWorker(const Function& callback,
  5140. const char* resource_name,
  5141. const Object& resource)
  5142. : AsyncProgressWorker(
  5143. Object::New(callback.Env()), callback, resource_name, resource) {}
  5144. template <class T>
  5145. inline AsyncProgressWorker<T>::AsyncProgressWorker(const Object& receiver,
  5146. const Function& callback)
  5147. : AsyncProgressWorker(receiver, callback, "generic") {}
  5148. template <class T>
  5149. inline AsyncProgressWorker<T>::AsyncProgressWorker(const Object& receiver,
  5150. const Function& callback,
  5151. const char* resource_name)
  5152. : AsyncProgressWorker(
  5153. receiver, callback, resource_name, Object::New(callback.Env())) {}
  5154. template <class T>
  5155. inline AsyncProgressWorker<T>::AsyncProgressWorker(const Object& receiver,
  5156. const Function& callback,
  5157. const char* resource_name,
  5158. const Object& resource)
  5159. : AsyncProgressWorkerBase(receiver, callback, resource_name, resource),
  5160. _asyncdata(nullptr),
  5161. _asyncsize(0),
  5162. _signaled(false) {}
  5163. #if NAPI_VERSION > 4
  5164. template <class T>
  5165. inline AsyncProgressWorker<T>::AsyncProgressWorker(Napi::Env env)
  5166. : AsyncProgressWorker(env, "generic") {}
  5167. template <class T>
  5168. inline AsyncProgressWorker<T>::AsyncProgressWorker(Napi::Env env,
  5169. const char* resource_name)
  5170. : AsyncProgressWorker(env, resource_name, Object::New(env)) {}
  5171. template <class T>
  5172. inline AsyncProgressWorker<T>::AsyncProgressWorker(Napi::Env env,
  5173. const char* resource_name,
  5174. const Object& resource)
  5175. : AsyncProgressWorkerBase(env, resource_name, resource),
  5176. _asyncdata(nullptr),
  5177. _asyncsize(0) {}
  5178. #endif
  5179. template <class T>
  5180. inline AsyncProgressWorker<T>::~AsyncProgressWorker() {
  5181. {
  5182. std::lock_guard<std::mutex> lock(this->_mutex);
  5183. _asyncdata = nullptr;
  5184. _asyncsize = 0;
  5185. }
  5186. }
  5187. template <class T>
  5188. inline void AsyncProgressWorker<T>::Execute() {
  5189. ExecutionProgress progress(this);
  5190. Execute(progress);
  5191. }
  5192. template <class T>
  5193. inline void AsyncProgressWorker<T>::OnWorkProgress(void*) {
  5194. T* data;
  5195. size_t size;
  5196. bool signaled;
  5197. {
  5198. std::lock_guard<std::mutex> lock(this->_mutex);
  5199. data = this->_asyncdata;
  5200. size = this->_asyncsize;
  5201. signaled = this->_signaled;
  5202. this->_asyncdata = nullptr;
  5203. this->_asyncsize = 0;
  5204. this->_signaled = false;
  5205. }
  5206. /**
  5207. * The callback of ThreadSafeFunction is not been invoked immediately on the
  5208. * callback of uv_async_t (uv io poll), rather the callback of TSFN is
  5209. * invoked on the right next uv idle callback. There are chances that during
  5210. * the deferring the signal of uv_async_t is been sent again, i.e. potential
  5211. * not coalesced two calls of the TSFN callback.
  5212. */
  5213. if (data == nullptr && !signaled) {
  5214. return;
  5215. }
  5216. this->OnProgress(data, size);
  5217. delete[] data;
  5218. }
  5219. template <class T>
  5220. inline void AsyncProgressWorker<T>::SendProgress_(const T* data, size_t count) {
  5221. T* new_data = new T[count];
  5222. std::copy(data, data + count, new_data);
  5223. T* old_data;
  5224. {
  5225. std::lock_guard<std::mutex> lock(this->_mutex);
  5226. old_data = _asyncdata;
  5227. _asyncdata = new_data;
  5228. _asyncsize = count;
  5229. _signaled = false;
  5230. }
  5231. this->NonBlockingCall(nullptr);
  5232. delete[] old_data;
  5233. }
  5234. template <class T>
  5235. inline void AsyncProgressWorker<T>::Signal() {
  5236. {
  5237. std::lock_guard<std::mutex> lock(this->_mutex);
  5238. _signaled = true;
  5239. }
  5240. this->NonBlockingCall(static_cast<T*>(nullptr));
  5241. }
  5242. template <class T>
  5243. inline void AsyncProgressWorker<T>::ExecutionProgress::Signal() const {
  5244. this->_worker->Signal();
  5245. }
  5246. template <class T>
  5247. inline void AsyncProgressWorker<T>::ExecutionProgress::Send(
  5248. const T* data, size_t count) const {
  5249. _worker->SendProgress_(data, count);
  5250. }
  5251. ////////////////////////////////////////////////////////////////////////////////
  5252. // Async Progress Queue Worker class
  5253. ////////////////////////////////////////////////////////////////////////////////
  5254. template <class T>
  5255. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5256. const Function& callback)
  5257. : AsyncProgressQueueWorker(callback, "generic") {}
  5258. template <class T>
  5259. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5260. const Function& callback, const char* resource_name)
  5261. : AsyncProgressQueueWorker(
  5262. callback, resource_name, Object::New(callback.Env())) {}
  5263. template <class T>
  5264. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5265. const Function& callback, const char* resource_name, const Object& resource)
  5266. : AsyncProgressQueueWorker(
  5267. Object::New(callback.Env()), callback, resource_name, resource) {}
  5268. template <class T>
  5269. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5270. const Object& receiver, const Function& callback)
  5271. : AsyncProgressQueueWorker(receiver, callback, "generic") {}
  5272. template <class T>
  5273. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5274. const Object& receiver, const Function& callback, const char* resource_name)
  5275. : AsyncProgressQueueWorker(
  5276. receiver, callback, resource_name, Object::New(callback.Env())) {}
  5277. template <class T>
  5278. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5279. const Object& receiver,
  5280. const Function& callback,
  5281. const char* resource_name,
  5282. const Object& resource)
  5283. : AsyncProgressWorkerBase<std::pair<T*, size_t>>(
  5284. receiver,
  5285. callback,
  5286. resource_name,
  5287. resource,
  5288. /** unlimited queue size */ 0) {}
  5289. #if NAPI_VERSION > 4
  5290. template <class T>
  5291. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(Napi::Env env)
  5292. : AsyncProgressQueueWorker(env, "generic") {}
  5293. template <class T>
  5294. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5295. Napi::Env env, const char* resource_name)
  5296. : AsyncProgressQueueWorker(env, resource_name, Object::New(env)) {}
  5297. template <class T>
  5298. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5299. Napi::Env env, const char* resource_name, const Object& resource)
  5300. : AsyncProgressWorkerBase<std::pair<T*, size_t>>(
  5301. env, resource_name, resource, /** unlimited queue size */ 0) {}
  5302. #endif
  5303. template <class T>
  5304. inline void AsyncProgressQueueWorker<T>::Execute() {
  5305. ExecutionProgress progress(this);
  5306. Execute(progress);
  5307. }
  5308. template <class T>
  5309. inline void AsyncProgressQueueWorker<T>::OnWorkProgress(
  5310. std::pair<T*, size_t>* datapair) {
  5311. if (datapair == nullptr) {
  5312. return;
  5313. }
  5314. T* data = datapair->first;
  5315. size_t size = datapair->second;
  5316. this->OnProgress(data, size);
  5317. delete datapair;
  5318. delete[] data;
  5319. }
  5320. template <class T>
  5321. inline void AsyncProgressQueueWorker<T>::SendProgress_(const T* data,
  5322. size_t count) {
  5323. T* new_data = new T[count];
  5324. std::copy(data, data + count, new_data);
  5325. auto pair = new std::pair<T*, size_t>(new_data, count);
  5326. this->NonBlockingCall(pair);
  5327. }
  5328. template <class T>
  5329. inline void AsyncProgressQueueWorker<T>::Signal() const {
  5330. this->SendProgress_(static_cast<T*>(nullptr), 0);
  5331. }
  5332. template <class T>
  5333. inline void AsyncProgressQueueWorker<T>::OnWorkComplete(Napi::Env env,
  5334. napi_status status) {
  5335. // Draining queued items in TSFN.
  5336. AsyncProgressWorkerBase<std::pair<T*, size_t>>::OnWorkComplete(env, status);
  5337. }
  5338. template <class T>
  5339. inline void AsyncProgressQueueWorker<T>::ExecutionProgress::Signal() const {
  5340. _worker->SendProgress_(static_cast<T*>(nullptr), 0);
  5341. }
  5342. template <class T>
  5343. inline void AsyncProgressQueueWorker<T>::ExecutionProgress::Send(
  5344. const T* data, size_t count) const {
  5345. _worker->SendProgress_(data, count);
  5346. }
  5347. #endif // NAPI_VERSION > 3 && !defined(__wasm32__)
  5348. ////////////////////////////////////////////////////////////////////////////////
  5349. // Memory Management class
  5350. ////////////////////////////////////////////////////////////////////////////////
  5351. inline int64_t MemoryManagement::AdjustExternalMemory(Env env,
  5352. int64_t change_in_bytes) {
  5353. int64_t result;
  5354. napi_status status =
  5355. napi_adjust_external_memory(env, change_in_bytes, &result);
  5356. NAPI_THROW_IF_FAILED(env, status, 0);
  5357. return result;
  5358. }
  5359. ////////////////////////////////////////////////////////////////////////////////
  5360. // Version Management class
  5361. ////////////////////////////////////////////////////////////////////////////////
  5362. inline uint32_t VersionManagement::GetNapiVersion(Env env) {
  5363. uint32_t result;
  5364. napi_status status = napi_get_version(env, &result);
  5365. NAPI_THROW_IF_FAILED(env, status, 0);
  5366. return result;
  5367. }
  5368. inline const napi_node_version* VersionManagement::GetNodeVersion(Env env) {
  5369. const napi_node_version* result;
  5370. napi_status status = napi_get_node_version(env, &result);
  5371. NAPI_THROW_IF_FAILED(env, status, 0);
  5372. return result;
  5373. }
  5374. #if NAPI_VERSION > 5
  5375. ////////////////////////////////////////////////////////////////////////////////
  5376. // Addon<T> class
  5377. ////////////////////////////////////////////////////////////////////////////////
  5378. template <typename T>
  5379. inline Object Addon<T>::Init(Env env, Object exports) {
  5380. T* addon = new T(env, exports);
  5381. env.SetInstanceData(addon);
  5382. return addon->entry_point_;
  5383. }
  5384. template <typename T>
  5385. inline T* Addon<T>::Unwrap(Object wrapper) {
  5386. return wrapper.Env().GetInstanceData<T>();
  5387. }
  5388. template <typename T>
  5389. inline void Addon<T>::DefineAddon(
  5390. Object exports, const std::initializer_list<AddonProp>& props) {
  5391. DefineProperties(exports, props);
  5392. entry_point_ = exports;
  5393. }
  5394. template <typename T>
  5395. inline Napi::Object Addon<T>::DefineProperties(
  5396. Object object, const std::initializer_list<AddonProp>& props) {
  5397. const napi_property_descriptor* properties =
  5398. reinterpret_cast<const napi_property_descriptor*>(props.begin());
  5399. size_t size = props.size();
  5400. napi_status status =
  5401. napi_define_properties(object.Env(), object, size, properties);
  5402. NAPI_THROW_IF_FAILED(object.Env(), status, object);
  5403. for (size_t idx = 0; idx < size; idx++)
  5404. T::AttachPropData(object.Env(), object, &properties[idx]);
  5405. return object;
  5406. }
  5407. #endif // NAPI_VERSION > 5
  5408. #if NAPI_VERSION > 2
  5409. template <typename Hook, typename Arg>
  5410. Env::CleanupHook<Hook, Arg> Env::AddCleanupHook(Hook hook, Arg* arg) {
  5411. return CleanupHook<Hook, Arg>(*this, hook, arg);
  5412. }
  5413. template <typename Hook>
  5414. Env::CleanupHook<Hook> Env::AddCleanupHook(Hook hook) {
  5415. return CleanupHook<Hook>(*this, hook);
  5416. }
  5417. template <typename Hook, typename Arg>
  5418. Env::CleanupHook<Hook, Arg>::CleanupHook() {
  5419. data = nullptr;
  5420. }
  5421. template <typename Hook, typename Arg>
  5422. Env::CleanupHook<Hook, Arg>::CleanupHook(Napi::Env env, Hook hook)
  5423. : wrapper(Env::CleanupHook<Hook, Arg>::Wrapper) {
  5424. data = new CleanupData{std::move(hook), nullptr};
  5425. napi_status status = napi_add_env_cleanup_hook(env, wrapper, data);
  5426. if (status != napi_ok) {
  5427. delete data;
  5428. data = nullptr;
  5429. }
  5430. }
  5431. template <typename Hook, typename Arg>
  5432. Env::CleanupHook<Hook, Arg>::CleanupHook(Napi::Env env, Hook hook, Arg* arg)
  5433. : wrapper(Env::CleanupHook<Hook, Arg>::WrapperWithArg) {
  5434. data = new CleanupData{std::move(hook), arg};
  5435. napi_status status = napi_add_env_cleanup_hook(env, wrapper, data);
  5436. if (status != napi_ok) {
  5437. delete data;
  5438. data = nullptr;
  5439. }
  5440. }
  5441. template <class Hook, class Arg>
  5442. bool Env::CleanupHook<Hook, Arg>::Remove(Env env) {
  5443. napi_status status = napi_remove_env_cleanup_hook(env, wrapper, data);
  5444. delete data;
  5445. data = nullptr;
  5446. return status == napi_ok;
  5447. }
  5448. template <class Hook, class Arg>
  5449. bool Env::CleanupHook<Hook, Arg>::IsEmpty() const {
  5450. return data == nullptr;
  5451. }
  5452. #endif // NAPI_VERSION > 2
  5453. #ifdef NAPI_CPP_CUSTOM_NAMESPACE
  5454. } // namespace NAPI_CPP_CUSTOM_NAMESPACE
  5455. #endif
  5456. } // namespace Napi
  5457. #endif // SRC_NAPI_INL_H_