napi-inl.h 228 KB

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