nan.h 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049
  1. /*********************************************************************
  2. * NAN - Native Abstractions for Node.js
  3. *
  4. * Copyright (c) 2018 NAN contributors:
  5. * - Rod Vagg <https://github.com/rvagg>
  6. * - Benjamin Byholm <https://github.com/kkoopa>
  7. * - Trevor Norris <https://github.com/trevnorris>
  8. * - Nathan Rajlich <https://github.com/TooTallNate>
  9. * - Brett Lawson <https://github.com/brett19>
  10. * - Ben Noordhuis <https://github.com/bnoordhuis>
  11. * - David Siegel <https://github.com/agnat>
  12. * - Michael Ira Krufky <https://github.com/mkrufky>
  13. *
  14. * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
  15. *
  16. * Version 2.22.0: current Node 22.9.0, Node 0.12: 0.12.18, Node 0.10: 0.10.48, iojs: 3.3.1
  17. *
  18. * See https://github.com/nodejs/nan for the latest update to this file
  19. **********************************************************************************/
  20. #ifndef NAN_H_
  21. #define NAN_H_
  22. #include <node_version.h>
  23. #define NODE_0_10_MODULE_VERSION 11
  24. #define NODE_0_12_MODULE_VERSION 14
  25. #define ATOM_0_21_MODULE_VERSION 41
  26. #define IOJS_1_0_MODULE_VERSION 42
  27. #define IOJS_1_1_MODULE_VERSION 43
  28. #define IOJS_2_0_MODULE_VERSION 44
  29. #define IOJS_3_0_MODULE_VERSION 45
  30. #define NODE_4_0_MODULE_VERSION 46
  31. #define NODE_5_0_MODULE_VERSION 47
  32. #define NODE_6_0_MODULE_VERSION 48
  33. #define NODE_7_0_MODULE_VERSION 51
  34. #define NODE_8_0_MODULE_VERSION 57
  35. #define NODE_9_0_MODULE_VERSION 59
  36. #define NODE_10_0_MODULE_VERSION 64
  37. #define NODE_11_0_MODULE_VERSION 67
  38. #define NODE_12_0_MODULE_VERSION 72
  39. #define NODE_13_0_MODULE_VERSION 79
  40. #define NODE_14_0_MODULE_VERSION 83
  41. #define NODE_15_0_MODULE_VERSION 88
  42. #define NODE_16_0_MODULE_VERSION 93
  43. #define NODE_17_0_MODULE_VERSION 102
  44. #define NODE_18_0_MODULE_VERSION 108
  45. #define NODE_19_0_MODULE_VERSION 111
  46. #define NODE_20_0_MODULE_VERSION 115
  47. #ifdef _MSC_VER
  48. # define NAN_HAS_CPLUSPLUS_11 (_MSC_VER >= 1800)
  49. #else
  50. # define NAN_HAS_CPLUSPLUS_11 (__cplusplus >= 201103L)
  51. #endif
  52. #if NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION && !NAN_HAS_CPLUSPLUS_11
  53. # error This version of node/NAN/v8 requires a C++11 compiler
  54. #endif
  55. #include <uv.h>
  56. #include <node.h>
  57. #include <node_buffer.h>
  58. #include <node_object_wrap.h>
  59. #include <algorithm>
  60. #include <cstring>
  61. #include <climits>
  62. #include <cstdlib>
  63. #include <utility>
  64. #if defined(_MSC_VER)
  65. # pragma warning( push )
  66. # pragma warning( disable : 4530 )
  67. # include <queue>
  68. # include <string>
  69. # include <vector>
  70. # pragma warning( pop )
  71. #else
  72. # include <queue>
  73. # include <string>
  74. # include <vector>
  75. #endif
  76. // uv helpers
  77. #ifdef UV_VERSION_MAJOR
  78. # ifndef UV_VERSION_PATCH
  79. # define UV_VERSION_PATCH 0
  80. # endif
  81. # define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \
  82. (UV_VERSION_MINOR << 8) | \
  83. (UV_VERSION_PATCH))
  84. #else
  85. # define NAUV_UVVERSION 0x000b00
  86. #endif
  87. #if NAUV_UVVERSION < 0x000b0b
  88. # ifdef WIN32
  89. # include <windows.h>
  90. # else
  91. # include <pthread.h>
  92. # endif
  93. #endif
  94. namespace Nan {
  95. #define NAN_CONCAT(a, b) NAN_CONCAT_HELPER(a, b)
  96. #define NAN_CONCAT_HELPER(a, b) a##b
  97. #define NAN_INLINE inline // TODO(bnoordhuis) Remove in v3.0.0.
  98. #if defined(__GNUC__) && \
  99. !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS)
  100. # define NAN_DEPRECATED __attribute__((deprecated))
  101. #elif defined(_MSC_VER) && \
  102. !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS)
  103. # define NAN_DEPRECATED __declspec(deprecated)
  104. #else
  105. # define NAN_DEPRECATED
  106. #endif
  107. #if NAN_HAS_CPLUSPLUS_11
  108. # define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete;
  109. # define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete;
  110. # define NAN_DISALLOW_MOVE(CLASS) \
  111. CLASS(CLASS&&) = delete; /* NOLINT(build/c++11) */ \
  112. void operator=(CLASS&&) = delete;
  113. #else
  114. # define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&);
  115. # define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&);
  116. # define NAN_DISALLOW_MOVE(CLASS)
  117. #endif
  118. #define NAN_DISALLOW_ASSIGN_COPY(CLASS) \
  119. NAN_DISALLOW_ASSIGN(CLASS) \
  120. NAN_DISALLOW_COPY(CLASS)
  121. #define NAN_DISALLOW_ASSIGN_MOVE(CLASS) \
  122. NAN_DISALLOW_ASSIGN(CLASS) \
  123. NAN_DISALLOW_MOVE(CLASS)
  124. #define NAN_DISALLOW_COPY_MOVE(CLASS) \
  125. NAN_DISALLOW_COPY(CLASS) \
  126. NAN_DISALLOW_MOVE(CLASS)
  127. #define NAN_DISALLOW_ASSIGN_COPY_MOVE(CLASS) \
  128. NAN_DISALLOW_ASSIGN(CLASS) \
  129. NAN_DISALLOW_COPY(CLASS) \
  130. NAN_DISALLOW_MOVE(CLASS)
  131. #define TYPE_CHECK(T, S) \
  132. while (false) { \
  133. *(static_cast<T *volatile *>(0)) = static_cast<S*>(0); \
  134. }
  135. //=== RegistrationFunction =====================================================
  136. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  137. typedef v8::Handle<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE;
  138. #else
  139. typedef v8::Local<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE;
  140. #endif
  141. #define NAN_MODULE_INIT(name) \
  142. void name(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target)
  143. #if NODE_MAJOR_VERSION >= 10 || \
  144. NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3
  145. #define NAN_MODULE_WORKER_ENABLED(module_name, registration) \
  146. extern "C" NODE_MODULE_EXPORT void \
  147. NAN_CONCAT(node_register_module_v, NODE_MODULE_VERSION)( \
  148. v8::Local<v8::Object> exports, v8::Local<v8::Value> module, \
  149. v8::Local<v8::Context> context) \
  150. { \
  151. registration(exports); \
  152. }
  153. #else
  154. #define NAN_MODULE_WORKER_ENABLED(module_name, registration) \
  155. NODE_MODULE(module_name, registration)
  156. #endif
  157. //=== CallbackInfo =============================================================
  158. #include "nan_callbacks.h" // NOLINT(build/include)
  159. //==============================================================================
  160. #if (NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION)
  161. typedef v8::Script UnboundScript;
  162. typedef v8::Script BoundScript;
  163. #else
  164. typedef v8::UnboundScript UnboundScript;
  165. typedef v8::Script BoundScript;
  166. #endif
  167. #if (NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION)
  168. typedef v8::String::ExternalAsciiStringResource
  169. ExternalOneByteStringResource;
  170. #else
  171. typedef v8::String::ExternalOneByteStringResource
  172. ExternalOneByteStringResource;
  173. #endif
  174. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  175. template<typename T>
  176. class NonCopyablePersistentTraits :
  177. public v8::NonCopyablePersistentTraits<T> {};
  178. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 10 || \
  179. (V8_MAJOR_VERSION == 10 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 5))
  180. template<typename T> struct CopyablePersistentTraits {
  181. typedef v8::Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
  182. static const bool kResetInDestructor = true;
  183. template <typename S, typename M>
  184. static NAN_INLINE void Copy(const v8::Persistent<S, M> &source,
  185. CopyablePersistent *dest) {
  186. }
  187. };
  188. #else
  189. template<typename T>
  190. class CopyablePersistentTraits :
  191. public v8::CopyablePersistentTraits<T> {};
  192. #endif
  193. template<typename T>
  194. class PersistentBase :
  195. public v8::PersistentBase<T> {};
  196. template<typename T, typename M = v8::NonCopyablePersistentTraits<T> >
  197. class Persistent;
  198. #else
  199. template<typename T> class NonCopyablePersistentTraits;
  200. template<typename T> class PersistentBase;
  201. template<typename T, typename P> class WeakCallbackData;
  202. template<typename T, typename M = NonCopyablePersistentTraits<T> >
  203. class Persistent;
  204. #endif // NODE_MODULE_VERSION
  205. template<typename T>
  206. class Maybe {
  207. public:
  208. inline bool IsNothing() const { return !has_value_; }
  209. inline bool IsJust() const { return has_value_; }
  210. inline T ToChecked() const { return FromJust(); }
  211. inline void Check() const { FromJust(); }
  212. inline bool To(T* out) const {
  213. if (IsJust()) *out = value_;
  214. return IsJust();
  215. }
  216. inline T FromJust() const {
  217. #if defined(V8_ENABLE_CHECKS)
  218. assert(IsJust() && "FromJust is Nothing");
  219. #endif // V8_ENABLE_CHECKS
  220. return value_;
  221. }
  222. inline T FromMaybe(const T& default_value) const {
  223. return has_value_ ? value_ : default_value;
  224. }
  225. inline bool operator==(const Maybe &other) const {
  226. return (IsJust() == other.IsJust()) &&
  227. (!IsJust() || FromJust() == other.FromJust());
  228. }
  229. inline bool operator!=(const Maybe &other) const {
  230. return !operator==(other);
  231. }
  232. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  233. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  234. // Allow implicit conversions from v8::Maybe<T> to Nan::Maybe<T>.
  235. Maybe(const v8::Maybe<T>& that) // NOLINT(runtime/explicit)
  236. : has_value_(that.IsJust())
  237. , value_(that.FromMaybe(T())) {}
  238. #endif
  239. private:
  240. Maybe() : has_value_(false) {}
  241. explicit Maybe(const T& t) : has_value_(true), value_(t) {}
  242. bool has_value_;
  243. T value_;
  244. template<typename U>
  245. friend Maybe<U> Nothing();
  246. template<typename U>
  247. friend Maybe<U> Just(const U& u);
  248. };
  249. template<typename T>
  250. inline Maybe<T> Nothing() {
  251. return Maybe<T>();
  252. }
  253. template<typename T>
  254. inline Maybe<T> Just(const T& t) {
  255. return Maybe<T>(t);
  256. }
  257. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  258. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  259. # include "nan_maybe_43_inl.h" // NOLINT(build/include)
  260. #else
  261. # include "nan_maybe_pre_43_inl.h" // NOLINT(build/include)
  262. #endif
  263. #include "nan_converters.h" // NOLINT(build/include)
  264. #include "nan_new.h" // NOLINT(build/include)
  265. #if NAUV_UVVERSION < 0x000b17
  266. #define NAUV_WORK_CB(func) \
  267. void func(uv_async_t *async, int)
  268. #else
  269. #define NAUV_WORK_CB(func) \
  270. void func(uv_async_t *async)
  271. #endif
  272. #if NAUV_UVVERSION >= 0x000b0b
  273. typedef uv_key_t nauv_key_t;
  274. inline int nauv_key_create(nauv_key_t *key) {
  275. return uv_key_create(key);
  276. }
  277. inline void nauv_key_delete(nauv_key_t *key) {
  278. uv_key_delete(key);
  279. }
  280. inline void* nauv_key_get(nauv_key_t *key) {
  281. return uv_key_get(key);
  282. }
  283. inline void nauv_key_set(nauv_key_t *key, void *value) {
  284. uv_key_set(key, value);
  285. }
  286. #else
  287. /* Implement thread local storage for older versions of libuv.
  288. * This is essentially a backport of libuv commit 5d2434bf
  289. * written by Ben Noordhuis, adjusted for names and inline.
  290. */
  291. #ifndef WIN32
  292. typedef pthread_key_t nauv_key_t;
  293. inline int nauv_key_create(nauv_key_t* key) {
  294. return -pthread_key_create(key, NULL);
  295. }
  296. inline void nauv_key_delete(nauv_key_t* key) {
  297. if (pthread_key_delete(*key))
  298. abort();
  299. }
  300. inline void* nauv_key_get(nauv_key_t* key) {
  301. return pthread_getspecific(*key);
  302. }
  303. inline void nauv_key_set(nauv_key_t* key, void* value) {
  304. if (pthread_setspecific(*key, value))
  305. abort();
  306. }
  307. #else
  308. typedef struct {
  309. DWORD tls_index;
  310. } nauv_key_t;
  311. inline int nauv_key_create(nauv_key_t* key) {
  312. key->tls_index = TlsAlloc();
  313. if (key->tls_index == TLS_OUT_OF_INDEXES)
  314. return UV_ENOMEM;
  315. return 0;
  316. }
  317. inline void nauv_key_delete(nauv_key_t* key) {
  318. if (TlsFree(key->tls_index) == FALSE)
  319. abort();
  320. key->tls_index = TLS_OUT_OF_INDEXES;
  321. }
  322. inline void* nauv_key_get(nauv_key_t* key) {
  323. void* value = TlsGetValue(key->tls_index);
  324. if (value == NULL)
  325. if (GetLastError() != ERROR_SUCCESS)
  326. abort();
  327. return value;
  328. }
  329. inline void nauv_key_set(nauv_key_t* key, void* value) {
  330. if (TlsSetValue(key->tls_index, value) == FALSE)
  331. abort();
  332. }
  333. #endif
  334. #endif
  335. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  336. template<typename T>
  337. v8::Local<T> New(v8::Handle<T>);
  338. #endif
  339. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  340. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  341. typedef v8::WeakCallbackType WeakCallbackType;
  342. #else
  343. struct WeakCallbackType {
  344. enum E {kParameter, kInternalFields};
  345. E type;
  346. WeakCallbackType(E other) : type(other) {} // NOLINT(runtime/explicit)
  347. inline bool operator==(E other) { return other == this->type; }
  348. inline bool operator!=(E other) { return !operator==(other); }
  349. };
  350. #endif
  351. template<typename P> class WeakCallbackInfo;
  352. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  353. # include "nan_persistent_12_inl.h" // NOLINT(build/include)
  354. #else
  355. # include "nan_persistent_pre_12_inl.h" // NOLINT(build/include)
  356. #endif
  357. namespace imp {
  358. static const size_t kMaxLength = 0x3fffffff;
  359. // v8::String::REPLACE_INVALID_UTF8 was introduced
  360. // in node.js v0.10.29 and v0.8.27.
  361. #if NODE_MAJOR_VERSION > 0 || \
  362. NODE_MINOR_VERSION > 10 || \
  363. NODE_MINOR_VERSION == 10 && NODE_PATCH_VERSION >= 29 || \
  364. NODE_MINOR_VERSION == 8 && NODE_PATCH_VERSION >= 27
  365. static const unsigned kReplaceInvalidUtf8 = v8::String::REPLACE_INVALID_UTF8;
  366. #else
  367. static const unsigned kReplaceInvalidUtf8 = 0;
  368. #endif
  369. } // end of namespace imp
  370. //=== HandleScope ==============================================================
  371. class HandleScope {
  372. v8::HandleScope scope;
  373. public:
  374. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  375. inline HandleScope() : scope(v8::Isolate::GetCurrent()) {}
  376. inline static int NumberOfHandles() {
  377. return v8::HandleScope::NumberOfHandles(v8::Isolate::GetCurrent());
  378. }
  379. #else
  380. inline HandleScope() : scope() {}
  381. inline static int NumberOfHandles() {
  382. return v8::HandleScope::NumberOfHandles();
  383. }
  384. #endif
  385. private:
  386. // Make it hard to create heap-allocated or illegal handle scopes by
  387. // disallowing certain operations.
  388. HandleScope(const HandleScope &);
  389. void operator=(const HandleScope &);
  390. void *operator new(size_t size);
  391. void operator delete(void *, size_t) {
  392. abort();
  393. }
  394. };
  395. class EscapableHandleScope {
  396. public:
  397. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  398. inline EscapableHandleScope() : scope(v8::Isolate::GetCurrent()) {}
  399. inline static int NumberOfHandles() {
  400. return v8::EscapableHandleScope::NumberOfHandles(v8::Isolate::GetCurrent());
  401. }
  402. template<typename T>
  403. inline v8::Local<T> Escape(v8::Local<T> value) {
  404. return scope.Escape(value);
  405. }
  406. private:
  407. v8::EscapableHandleScope scope;
  408. #else
  409. inline EscapableHandleScope() : scope() {}
  410. inline static int NumberOfHandles() {
  411. return v8::HandleScope::NumberOfHandles();
  412. }
  413. template<typename T>
  414. inline v8::Local<T> Escape(v8::Local<T> value) {
  415. return scope.Close(value);
  416. }
  417. private:
  418. v8::HandleScope scope;
  419. #endif
  420. private:
  421. // Make it hard to create heap-allocated or illegal handle scopes by
  422. // disallowing certain operations.
  423. EscapableHandleScope(const EscapableHandleScope &);
  424. void operator=(const EscapableHandleScope &);
  425. void *operator new(size_t size);
  426. void operator delete(void *, size_t) {
  427. abort();
  428. }
  429. };
  430. //=== TryCatch =================================================================
  431. class TryCatch {
  432. v8::TryCatch try_catch_;
  433. friend void FatalException(const TryCatch&);
  434. public:
  435. #if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
  436. TryCatch() : try_catch_(v8::Isolate::GetCurrent()) {}
  437. #endif
  438. inline bool HasCaught() const { return try_catch_.HasCaught(); }
  439. inline bool CanContinue() const { return try_catch_.CanContinue(); }
  440. inline v8::Local<v8::Value> ReThrow() {
  441. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  442. return New(try_catch_.ReThrow());
  443. #else
  444. return try_catch_.ReThrow();
  445. #endif
  446. }
  447. inline v8::Local<v8::Value> Exception() const {
  448. return try_catch_.Exception();
  449. }
  450. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  451. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  452. inline v8::MaybeLocal<v8::Value> StackTrace() const {
  453. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  454. v8::EscapableHandleScope scope(isolate);
  455. return scope.Escape(try_catch_.StackTrace(isolate->GetCurrentContext())
  456. .FromMaybe(v8::Local<v8::Value>()));
  457. }
  458. #else
  459. inline MaybeLocal<v8::Value> StackTrace() const {
  460. return try_catch_.StackTrace();
  461. }
  462. #endif
  463. inline v8::Local<v8::Message> Message() const {
  464. return try_catch_.Message();
  465. }
  466. inline void Reset() { try_catch_.Reset(); }
  467. inline void SetVerbose(bool value) { try_catch_.SetVerbose(value); }
  468. inline void SetCaptureMessage(bool value) {
  469. try_catch_.SetCaptureMessage(value);
  470. }
  471. };
  472. v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
  473. v8::Local<v8::Function> func,
  474. int argc,
  475. v8::Local<v8::Value>* argv);
  476. v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
  477. v8::Local<v8::String> symbol,
  478. int argc,
  479. v8::Local<v8::Value>* argv);
  480. v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
  481. const char* method,
  482. int argc,
  483. v8::Local<v8::Value>* argv);
  484. // === AsyncResource ===========================================================
  485. class AsyncResource {
  486. public:
  487. AsyncResource(
  488. v8::Local<v8::String> name
  489. , v8::Local<v8::Object> resource = New<v8::Object>()) {
  490. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  491. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  492. if (resource.IsEmpty()) {
  493. resource = New<v8::Object>();
  494. }
  495. context = node::EmitAsyncInit(isolate, resource, name);
  496. #endif
  497. }
  498. AsyncResource(
  499. const char* name
  500. , v8::Local<v8::Object> resource = New<v8::Object>()) {
  501. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  502. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  503. if (resource.IsEmpty()) {
  504. resource = New<v8::Object>();
  505. }
  506. v8::Local<v8::String> name_string =
  507. New<v8::String>(name).ToLocalChecked();
  508. context = node::EmitAsyncInit(isolate, resource, name_string);
  509. #endif
  510. }
  511. ~AsyncResource() {
  512. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  513. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  514. node::EmitAsyncDestroy(isolate, context);
  515. #endif
  516. }
  517. inline MaybeLocal<v8::Value> runInAsyncScope(
  518. v8::Local<v8::Object> target
  519. , v8::Local<v8::Function> func
  520. , int argc
  521. , v8::Local<v8::Value>* argv) {
  522. #if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
  523. return MakeCallback(target, func, argc, argv);
  524. #else
  525. return node::MakeCallback(
  526. v8::Isolate::GetCurrent(), target, func, argc, argv, context);
  527. #endif
  528. }
  529. inline MaybeLocal<v8::Value> runInAsyncScope(
  530. v8::Local<v8::Object> target
  531. , v8::Local<v8::String> symbol
  532. , int argc
  533. , v8::Local<v8::Value>* argv) {
  534. #if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
  535. return MakeCallback(target, symbol, argc, argv);
  536. #else
  537. return node::MakeCallback(
  538. v8::Isolate::GetCurrent(), target, symbol, argc, argv, context);
  539. #endif
  540. }
  541. inline MaybeLocal<v8::Value> runInAsyncScope(
  542. v8::Local<v8::Object> target
  543. , const char* method
  544. , int argc
  545. , v8::Local<v8::Value>* argv) {
  546. #if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
  547. return MakeCallback(target, method, argc, argv);
  548. #else
  549. return node::MakeCallback(
  550. v8::Isolate::GetCurrent(), target, method, argc, argv, context);
  551. #endif
  552. }
  553. private:
  554. NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncResource)
  555. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  556. node::async_context context;
  557. #endif
  558. };
  559. inline uv_loop_t* GetCurrentEventLoop() {
  560. #if NODE_MAJOR_VERSION >= 10 || \
  561. NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3 || \
  562. NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION >= 10
  563. return node::GetCurrentEventLoop(v8::Isolate::GetCurrent());
  564. #else
  565. return uv_default_loop();
  566. #endif
  567. }
  568. //============ =================================================================
  569. /* node 0.12 */
  570. #if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION
  571. inline
  572. void SetCounterFunction(v8::CounterLookupCallback cb) {
  573. v8::Isolate::GetCurrent()->SetCounterFunction(cb);
  574. }
  575. inline
  576. void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) {
  577. v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb);
  578. }
  579. inline
  580. void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) {
  581. v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb);
  582. }
  583. #if defined(V8_MAJOR_VERSION) && \
  584. (V8_MAJOR_VERSION > 12 || \
  585. (V8_MAJOR_VERSION == 12 && defined(V8_MINOR_VERSION) && \
  586. V8_MINOR_VERSION >= 7))
  587. NAN_DEPRECATED inline bool IdleNotification(int) {
  588. return true;
  589. }
  590. # elif defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  591. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  592. NAN_DEPRECATED inline bool IdleNotification(int idle_time_in_ms) {
  593. return v8::Isolate::GetCurrent()->IdleNotificationDeadline(
  594. idle_time_in_ms * 0.001);
  595. }
  596. # else
  597. NAN_DEPRECATED inline bool IdleNotification(int idle_time_in_ms) {
  598. return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms);
  599. }
  600. #endif
  601. inline void LowMemoryNotification() {
  602. v8::Isolate::GetCurrent()->LowMemoryNotification();
  603. }
  604. inline void ContextDisposedNotification() {
  605. v8::Isolate::GetCurrent()->ContextDisposedNotification();
  606. }
  607. #else
  608. inline
  609. void SetCounterFunction(v8::CounterLookupCallback cb) {
  610. v8::V8::SetCounterFunction(cb);
  611. }
  612. inline
  613. void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) {
  614. v8::V8::SetCreateHistogramFunction(cb);
  615. }
  616. inline
  617. void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) {
  618. v8::V8::SetAddHistogramSampleFunction(cb);
  619. }
  620. inline bool IdleNotification(int idle_time_in_ms) {
  621. return v8::V8::IdleNotification(idle_time_in_ms);
  622. }
  623. inline void LowMemoryNotification() {
  624. v8::V8::LowMemoryNotification();
  625. }
  626. inline void ContextDisposedNotification() {
  627. v8::V8::ContextDisposedNotification();
  628. }
  629. #endif
  630. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) // Node 0.12
  631. inline v8::Local<v8::Primitive> Undefined() {
  632. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  633. EscapableHandleScope scope;
  634. return scope.Escape(New(v8::Undefined(v8::Isolate::GetCurrent())));
  635. # else
  636. return v8::Undefined(v8::Isolate::GetCurrent());
  637. # endif
  638. }
  639. inline v8::Local<v8::Primitive> Null() {
  640. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  641. EscapableHandleScope scope;
  642. return scope.Escape(New(v8::Null(v8::Isolate::GetCurrent())));
  643. # else
  644. return v8::Null(v8::Isolate::GetCurrent());
  645. # endif
  646. }
  647. inline v8::Local<v8::Boolean> True() {
  648. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  649. EscapableHandleScope scope;
  650. return scope.Escape(New(v8::True(v8::Isolate::GetCurrent())));
  651. # else
  652. return v8::True(v8::Isolate::GetCurrent());
  653. # endif
  654. }
  655. inline v8::Local<v8::Boolean> False() {
  656. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  657. EscapableHandleScope scope;
  658. return scope.Escape(New(v8::False(v8::Isolate::GetCurrent())));
  659. # else
  660. return v8::False(v8::Isolate::GetCurrent());
  661. # endif
  662. }
  663. inline v8::Local<v8::String> EmptyString() {
  664. return v8::String::Empty(v8::Isolate::GetCurrent());
  665. }
  666. inline int AdjustExternalMemory(int bc) {
  667. return static_cast<int>(
  668. v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc));
  669. }
  670. inline void SetTemplate(
  671. v8::Local<v8::Template> templ
  672. , const char *name
  673. , v8::Local<v8::Data> value) {
  674. templ->Set(v8::Isolate::GetCurrent(), name, value);
  675. }
  676. inline void SetTemplate(
  677. v8::Local<v8::Template> templ
  678. , v8::Local<v8::String> name
  679. , v8::Local<v8::Data> value
  680. , v8::PropertyAttribute attributes) {
  681. templ->Set(name, value, attributes);
  682. }
  683. inline v8::Local<v8::Context> GetCurrentContext() {
  684. return v8::Isolate::GetCurrent()->GetCurrentContext();
  685. }
  686. inline void* GetInternalFieldPointer(
  687. v8::Local<v8::Object> object
  688. , int index) {
  689. return object->GetAlignedPointerFromInternalField(index);
  690. }
  691. inline void SetInternalFieldPointer(
  692. v8::Local<v8::Object> object
  693. , int index
  694. , void* value) {
  695. object->SetAlignedPointerInInternalField(index, value);
  696. }
  697. # define NAN_GC_CALLBACK(name) \
  698. void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags)
  699. #if NODE_MODULE_VERSION <= NODE_4_0_MODULE_VERSION
  700. typedef v8::Isolate::GCEpilogueCallback GCEpilogueCallback;
  701. typedef v8::Isolate::GCPrologueCallback GCPrologueCallback;
  702. #else
  703. typedef v8::Isolate::GCCallback GCEpilogueCallback;
  704. typedef v8::Isolate::GCCallback GCPrologueCallback;
  705. #endif
  706. inline void AddGCEpilogueCallback(
  707. GCEpilogueCallback callback
  708. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  709. v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter);
  710. }
  711. inline void RemoveGCEpilogueCallback(
  712. GCEpilogueCallback callback) {
  713. v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback);
  714. }
  715. inline void AddGCPrologueCallback(
  716. GCPrologueCallback callback
  717. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  718. v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter);
  719. }
  720. inline void RemoveGCPrologueCallback(
  721. GCPrologueCallback callback) {
  722. v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback);
  723. }
  724. inline void GetHeapStatistics(
  725. v8::HeapStatistics *heap_statistics) {
  726. v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics);
  727. }
  728. # define X(NAME) \
  729. inline v8::Local<v8::Value> NAME(const char *msg) { \
  730. EscapableHandleScope scope; \
  731. return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \
  732. } \
  733. \
  734. inline \
  735. v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) { \
  736. return v8::Exception::NAME(msg); \
  737. } \
  738. \
  739. inline void Throw ## NAME(const char *msg) { \
  740. HandleScope scope; \
  741. v8::Isolate::GetCurrent()->ThrowException( \
  742. v8::Exception::NAME(New(msg).ToLocalChecked())); \
  743. } \
  744. \
  745. inline void Throw ## NAME(v8::Local<v8::String> msg) { \
  746. HandleScope scope; \
  747. v8::Isolate::GetCurrent()->ThrowException( \
  748. v8::Exception::NAME(msg)); \
  749. }
  750. X(Error)
  751. X(RangeError)
  752. X(ReferenceError)
  753. X(SyntaxError)
  754. X(TypeError)
  755. # undef X
  756. inline void ThrowError(v8::Local<v8::Value> error) {
  757. v8::Isolate::GetCurrent()->ThrowException(error);
  758. }
  759. inline MaybeLocal<v8::Object> NewBuffer(
  760. char *data
  761. , size_t length
  762. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  763. , node::Buffer::FreeCallback callback
  764. #else
  765. , node::smalloc::FreeCallback callback
  766. #endif
  767. , void *hint
  768. ) {
  769. // arbitrary buffer lengths requires
  770. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  771. assert(length <= imp::kMaxLength && "too large buffer");
  772. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  773. return node::Buffer::New(
  774. v8::Isolate::GetCurrent(), data, length, callback, hint);
  775. #else
  776. return node::Buffer::New(v8::Isolate::GetCurrent(), data, length, callback,
  777. hint);
  778. #endif
  779. }
  780. inline MaybeLocal<v8::Object> CopyBuffer(
  781. const char *data
  782. , uint32_t size
  783. ) {
  784. // arbitrary buffer lengths requires
  785. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  786. assert(size <= imp::kMaxLength && "too large buffer");
  787. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  788. return node::Buffer::Copy(
  789. v8::Isolate::GetCurrent(), data, size);
  790. #else
  791. return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
  792. #endif
  793. }
  794. inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) {
  795. // arbitrary buffer lengths requires
  796. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  797. assert(size <= imp::kMaxLength && "too large buffer");
  798. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  799. return node::Buffer::New(
  800. v8::Isolate::GetCurrent(), size);
  801. #else
  802. return node::Buffer::New(v8::Isolate::GetCurrent(), size);
  803. #endif
  804. }
  805. inline MaybeLocal<v8::Object> NewBuffer(
  806. char* data
  807. , uint32_t size
  808. ) {
  809. // arbitrary buffer lengths requires
  810. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  811. assert(size <= imp::kMaxLength && "too large buffer");
  812. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  813. return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
  814. #else
  815. return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size);
  816. #endif
  817. }
  818. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  819. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  820. inline MaybeLocal<v8::String>
  821. NewOneByteString(const uint8_t * value, int length = -1) {
  822. return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value,
  823. v8::NewStringType::kNormal, length);
  824. }
  825. inline MaybeLocal<BoundScript> CompileScript(
  826. v8::Local<v8::String> s
  827. , const v8::ScriptOrigin& origin
  828. ) {
  829. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  830. v8::EscapableHandleScope scope(isolate);
  831. v8::ScriptCompiler::Source source(s, origin);
  832. return scope.Escape(
  833. v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source)
  834. .FromMaybe(v8::Local<BoundScript>()));
  835. }
  836. inline MaybeLocal<BoundScript> CompileScript(
  837. v8::Local<v8::String> s
  838. ) {
  839. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  840. v8::EscapableHandleScope scope(isolate);
  841. v8::ScriptCompiler::Source source(s);
  842. return scope.Escape(
  843. v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source)
  844. .FromMaybe(v8::Local<BoundScript>()));
  845. }
  846. inline MaybeLocal<v8::Value> RunScript(
  847. v8::Local<UnboundScript> script
  848. ) {
  849. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  850. v8::EscapableHandleScope scope(isolate);
  851. return scope.Escape(script->BindToCurrentContext()
  852. ->Run(isolate->GetCurrentContext())
  853. .FromMaybe(v8::Local<v8::Value>()));
  854. }
  855. inline MaybeLocal<v8::Value> RunScript(
  856. v8::Local<BoundScript> script
  857. ) {
  858. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  859. v8::EscapableHandleScope scope(isolate);
  860. return scope.Escape(script->Run(isolate->GetCurrentContext())
  861. .FromMaybe(v8::Local<v8::Value>()));
  862. }
  863. #else
  864. inline MaybeLocal<v8::String>
  865. NewOneByteString(const uint8_t * value, int length = -1) {
  866. return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value,
  867. v8::String::kNormalString, length);
  868. }
  869. inline MaybeLocal<BoundScript> CompileScript(
  870. v8::Local<v8::String> s
  871. , const v8::ScriptOrigin& origin
  872. ) {
  873. v8::ScriptCompiler::Source source(s, origin);
  874. return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source);
  875. }
  876. inline MaybeLocal<BoundScript> CompileScript(
  877. v8::Local<v8::String> s
  878. ) {
  879. v8::ScriptCompiler::Source source(s);
  880. return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source);
  881. }
  882. inline MaybeLocal<v8::Value> RunScript(
  883. v8::Local<UnboundScript> script
  884. ) {
  885. EscapableHandleScope scope;
  886. return scope.Escape(script->BindToCurrentContext()->Run());
  887. }
  888. inline MaybeLocal<v8::Value> RunScript(
  889. v8::Local<BoundScript> script
  890. ) {
  891. return script->Run();
  892. }
  893. #endif
  894. NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
  895. v8::Local<v8::Object> target
  896. , v8::Local<v8::Function> func
  897. , int argc
  898. , v8::Local<v8::Value>* argv) {
  899. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  900. EscapableHandleScope scope;
  901. return scope.Escape(New(node::MakeCallback(
  902. v8::Isolate::GetCurrent(), target, func, argc, argv)));
  903. #else
  904. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  905. AsyncResource res("nan:makeCallback");
  906. return res.runInAsyncScope(target, func, argc, argv)
  907. .FromMaybe(v8::Local<v8::Value>());
  908. # else
  909. return node::MakeCallback(
  910. v8::Isolate::GetCurrent(), target, func, argc, argv);
  911. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  912. #endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  913. }
  914. NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
  915. v8::Local<v8::Object> target
  916. , v8::Local<v8::String> symbol
  917. , int argc
  918. , v8::Local<v8::Value>* argv) {
  919. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  920. EscapableHandleScope scope;
  921. return scope.Escape(New(node::MakeCallback(
  922. v8::Isolate::GetCurrent(), target, symbol, argc, argv)));
  923. #else
  924. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  925. AsyncResource res("nan:makeCallback");
  926. return res.runInAsyncScope(target, symbol, argc, argv)
  927. .FromMaybe(v8::Local<v8::Value>());
  928. # else
  929. return node::MakeCallback(
  930. v8::Isolate::GetCurrent(), target, symbol, argc, argv);
  931. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  932. #endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  933. }
  934. NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
  935. v8::Local<v8::Object> target
  936. , const char* method
  937. , int argc
  938. , v8::Local<v8::Value>* argv) {
  939. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  940. EscapableHandleScope scope;
  941. return scope.Escape(New(node::MakeCallback(
  942. v8::Isolate::GetCurrent(), target, method, argc, argv)));
  943. #else
  944. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  945. AsyncResource res("nan:makeCallback");
  946. return res.runInAsyncScope(target, method, argc, argv)
  947. .FromMaybe(v8::Local<v8::Value>());
  948. # else
  949. return node::MakeCallback(
  950. v8::Isolate::GetCurrent(), target, method, argc, argv);
  951. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  952. #endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  953. }
  954. inline void FatalException(const TryCatch& try_catch) {
  955. node::FatalException(v8::Isolate::GetCurrent(), try_catch.try_catch_);
  956. }
  957. inline v8::Local<v8::Value> ErrnoException(
  958. int errorno
  959. , const char* syscall = NULL
  960. , const char* message = NULL
  961. , const char* path = NULL) {
  962. return node::ErrnoException(v8::Isolate::GetCurrent(), errorno, syscall,
  963. message, path);
  964. }
  965. NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException(
  966. int errorno
  967. , const char* syscall = NULL
  968. , const char* message = NULL
  969. , const char* path = NULL) {
  970. return ErrnoException(errorno, syscall, message, path);
  971. }
  972. template<typename T>
  973. inline void SetIsolateData(
  974. v8::Isolate *isolate
  975. , T *data
  976. ) {
  977. isolate->SetData(0, data);
  978. }
  979. template<typename T>
  980. inline T *GetIsolateData(
  981. v8::Isolate *isolate
  982. ) {
  983. return static_cast<T*>(isolate->GetData(0));
  984. }
  985. class Utf8String {
  986. public:
  987. inline explicit Utf8String(v8::Local<v8::Value> from) :
  988. length_(0), str_(str_st_) {
  989. HandleScope scope;
  990. if (!from.IsEmpty()) {
  991. #if NODE_MAJOR_VERSION >= 10
  992. v8::Local<v8::Context> context = GetCurrentContext();
  993. v8::Local<v8::String> string =
  994. from->ToString(context).FromMaybe(v8::Local<v8::String>());
  995. #else
  996. v8::Local<v8::String> string = from->ToString();
  997. #endif
  998. if (!string.IsEmpty()) {
  999. size_t len = 3 * string->Length() + 1;
  1000. assert(len <= INT_MAX);
  1001. if (len > sizeof (str_st_)) {
  1002. str_ = static_cast<char*>(malloc(len));
  1003. assert(str_ != 0);
  1004. }
  1005. const int flags =
  1006. v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8;
  1007. #if NODE_MAJOR_VERSION >= 11
  1008. length_ = string->WriteUtf8(v8::Isolate::GetCurrent(), str_,
  1009. static_cast<int>(len), 0, flags);
  1010. #else
  1011. // See https://github.com/nodejs/nan/issues/832.
  1012. // Disable the warning as there is no way around it.
  1013. #ifdef _MSC_VER
  1014. #pragma warning(push)
  1015. #pragma warning(disable : 4996)
  1016. #endif
  1017. #ifdef __GNUC__
  1018. #pragma GCC diagnostic push
  1019. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  1020. #endif
  1021. length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags);
  1022. #ifdef __GNUC__
  1023. #pragma GCC diagnostic pop
  1024. #endif
  1025. #ifdef _MSC_VER
  1026. #pragma warning(pop)
  1027. #endif
  1028. #endif // NODE_MAJOR_VERSION < 11
  1029. str_[length_] = '\0';
  1030. }
  1031. }
  1032. }
  1033. inline int length() const {
  1034. return length_;
  1035. }
  1036. inline char* operator*() { return str_; }
  1037. inline const char* operator*() const { return str_; }
  1038. inline ~Utf8String() {
  1039. if (str_ != str_st_) {
  1040. free(str_);
  1041. }
  1042. }
  1043. private:
  1044. NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String)
  1045. int length_;
  1046. char *str_;
  1047. char str_st_[1024];
  1048. };
  1049. #else // Node 0.8 and 0.10
  1050. inline v8::Local<v8::Primitive> Undefined() {
  1051. EscapableHandleScope scope;
  1052. return scope.Escape(New(v8::Undefined()));
  1053. }
  1054. inline v8::Local<v8::Primitive> Null() {
  1055. EscapableHandleScope scope;
  1056. return scope.Escape(New(v8::Null()));
  1057. }
  1058. inline v8::Local<v8::Boolean> True() {
  1059. EscapableHandleScope scope;
  1060. return scope.Escape(New(v8::True()));
  1061. }
  1062. inline v8::Local<v8::Boolean> False() {
  1063. EscapableHandleScope scope;
  1064. return scope.Escape(New(v8::False()));
  1065. }
  1066. inline v8::Local<v8::String> EmptyString() {
  1067. return v8::String::Empty();
  1068. }
  1069. inline int AdjustExternalMemory(int bc) {
  1070. return static_cast<int>(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc));
  1071. }
  1072. inline void SetTemplate(
  1073. v8::Local<v8::Template> templ
  1074. , const char *name
  1075. , v8::Local<v8::Data> value) {
  1076. templ->Set(name, value);
  1077. }
  1078. inline void SetTemplate(
  1079. v8::Local<v8::Template> templ
  1080. , v8::Local<v8::String> name
  1081. , v8::Local<v8::Data> value
  1082. , v8::PropertyAttribute attributes) {
  1083. templ->Set(name, value, attributes);
  1084. }
  1085. inline v8::Local<v8::Context> GetCurrentContext() {
  1086. return v8::Context::GetCurrent();
  1087. }
  1088. inline void* GetInternalFieldPointer(
  1089. v8::Local<v8::Object> object
  1090. , int index) {
  1091. return object->GetPointerFromInternalField(index);
  1092. }
  1093. inline void SetInternalFieldPointer(
  1094. v8::Local<v8::Object> object
  1095. , int index
  1096. , void* value) {
  1097. object->SetPointerInInternalField(index, value);
  1098. }
  1099. # define NAN_GC_CALLBACK(name) \
  1100. void name(v8::GCType type, v8::GCCallbackFlags flags)
  1101. inline void AddGCEpilogueCallback(
  1102. v8::GCEpilogueCallback callback
  1103. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  1104. v8::V8::AddGCEpilogueCallback(callback, gc_type_filter);
  1105. }
  1106. inline void RemoveGCEpilogueCallback(
  1107. v8::GCEpilogueCallback callback) {
  1108. v8::V8::RemoveGCEpilogueCallback(callback);
  1109. }
  1110. inline void AddGCPrologueCallback(
  1111. v8::GCPrologueCallback callback
  1112. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  1113. v8::V8::AddGCPrologueCallback(callback, gc_type_filter);
  1114. }
  1115. inline void RemoveGCPrologueCallback(
  1116. v8::GCPrologueCallback callback) {
  1117. v8::V8::RemoveGCPrologueCallback(callback);
  1118. }
  1119. inline void GetHeapStatistics(
  1120. v8::HeapStatistics *heap_statistics) {
  1121. v8::V8::GetHeapStatistics(heap_statistics);
  1122. }
  1123. # define X(NAME) \
  1124. inline v8::Local<v8::Value> NAME(const char *msg) { \
  1125. EscapableHandleScope scope; \
  1126. return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \
  1127. } \
  1128. \
  1129. inline \
  1130. v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) { \
  1131. return v8::Exception::NAME(msg); \
  1132. } \
  1133. \
  1134. inline void Throw ## NAME(const char *msg) { \
  1135. HandleScope scope; \
  1136. v8::ThrowException(v8::Exception::NAME(New(msg).ToLocalChecked())); \
  1137. } \
  1138. \
  1139. inline \
  1140. void Throw ## NAME(v8::Local<v8::String> errmsg) { \
  1141. HandleScope scope; \
  1142. v8::ThrowException(v8::Exception::NAME(errmsg)); \
  1143. }
  1144. X(Error)
  1145. X(RangeError)
  1146. X(ReferenceError)
  1147. X(SyntaxError)
  1148. X(TypeError)
  1149. # undef X
  1150. inline void ThrowError(v8::Local<v8::Value> error) {
  1151. v8::ThrowException(error);
  1152. }
  1153. inline MaybeLocal<v8::Object> NewBuffer(
  1154. char *data
  1155. , size_t length
  1156. , node::Buffer::free_callback callback
  1157. , void *hint
  1158. ) {
  1159. EscapableHandleScope scope;
  1160. // arbitrary buffer lengths requires
  1161. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1162. assert(length <= imp::kMaxLength && "too large buffer");
  1163. return scope.Escape(
  1164. New(node::Buffer::New(data, length, callback, hint)->handle_));
  1165. }
  1166. inline MaybeLocal<v8::Object> CopyBuffer(
  1167. const char *data
  1168. , uint32_t size
  1169. ) {
  1170. EscapableHandleScope scope;
  1171. // arbitrary buffer lengths requires
  1172. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1173. assert(size <= imp::kMaxLength && "too large buffer");
  1174. #if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION
  1175. return scope.Escape(New(node::Buffer::New(data, size)->handle_));
  1176. #else
  1177. return scope.Escape(
  1178. New(node::Buffer::New(const_cast<char *>(data), size)->handle_));
  1179. #endif
  1180. }
  1181. inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) {
  1182. // arbitrary buffer lengths requires
  1183. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1184. EscapableHandleScope scope;
  1185. assert(size <= imp::kMaxLength && "too large buffer");
  1186. return scope.Escape(New(node::Buffer::New(size)->handle_));
  1187. }
  1188. inline void FreeData(char *data, void *hint) {
  1189. (void) hint; // unused
  1190. delete[] data;
  1191. }
  1192. inline MaybeLocal<v8::Object> NewBuffer(
  1193. char* data
  1194. , uint32_t size
  1195. ) {
  1196. EscapableHandleScope scope;
  1197. // arbitrary buffer lengths requires
  1198. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1199. assert(size <= imp::kMaxLength && "too large buffer");
  1200. return scope.Escape(
  1201. New(node::Buffer::New(data, size, FreeData, NULL)->handle_));
  1202. }
  1203. namespace imp {
  1204. inline void
  1205. widenString(std::vector<uint16_t> *ws, const uint8_t *s, int l) {
  1206. size_t len = static_cast<size_t>(l);
  1207. if (l < 0) {
  1208. len = strlen(reinterpret_cast<const char*>(s));
  1209. }
  1210. assert(len <= INT_MAX && "string too long");
  1211. ws->resize(len);
  1212. std::copy(s, s + len, ws->begin()); // NOLINT(build/include_what_you_use)
  1213. }
  1214. } // end of namespace imp
  1215. inline MaybeLocal<v8::String>
  1216. NewOneByteString(const uint8_t * value, int length = -1) {
  1217. std::vector<uint16_t> wideString; // NOLINT(build/include_what_you_use)
  1218. imp::widenString(&wideString, value, length);
  1219. return v8::String::New(wideString.data(),
  1220. static_cast<int>(wideString.size()));
  1221. }
  1222. inline MaybeLocal<BoundScript> CompileScript(
  1223. v8::Local<v8::String> s
  1224. , const v8::ScriptOrigin& origin
  1225. ) {
  1226. return v8::Script::Compile(s, const_cast<v8::ScriptOrigin *>(&origin));
  1227. }
  1228. inline MaybeLocal<BoundScript> CompileScript(
  1229. v8::Local<v8::String> s
  1230. ) {
  1231. return v8::Script::Compile(s);
  1232. }
  1233. inline
  1234. MaybeLocal<v8::Value> RunScript(v8::Local<v8::Script> script) {
  1235. return script->Run();
  1236. }
  1237. inline v8::Local<v8::Value> MakeCallback(
  1238. v8::Local<v8::Object> target
  1239. , v8::Local<v8::Function> func
  1240. , int argc
  1241. , v8::Local<v8::Value>* argv) {
  1242. v8::HandleScope scope;
  1243. return scope.Close(New(node::MakeCallback(target, func, argc, argv)));
  1244. }
  1245. inline v8::Local<v8::Value> MakeCallback(
  1246. v8::Local<v8::Object> target
  1247. , v8::Local<v8::String> symbol
  1248. , int argc
  1249. , v8::Local<v8::Value>* argv) {
  1250. v8::HandleScope scope;
  1251. return scope.Close(New(node::MakeCallback(target, symbol, argc, argv)));
  1252. }
  1253. inline v8::Local<v8::Value> MakeCallback(
  1254. v8::Local<v8::Object> target
  1255. , const char* method
  1256. , int argc
  1257. , v8::Local<v8::Value>* argv) {
  1258. v8::HandleScope scope;
  1259. return scope.Close(New(node::MakeCallback(target, method, argc, argv)));
  1260. }
  1261. inline void FatalException(const TryCatch& try_catch) {
  1262. node::FatalException(const_cast<v8::TryCatch &>(try_catch.try_catch_));
  1263. }
  1264. inline v8::Local<v8::Value> ErrnoException(
  1265. int errorno
  1266. , const char* syscall = NULL
  1267. , const char* message = NULL
  1268. , const char* path = NULL) {
  1269. return node::ErrnoException(errorno, syscall, message, path);
  1270. }
  1271. NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException(
  1272. int errorno
  1273. , const char* syscall = NULL
  1274. , const char* message = NULL
  1275. , const char* path = NULL) {
  1276. return ErrnoException(errorno, syscall, message, path);
  1277. }
  1278. template<typename T>
  1279. inline void SetIsolateData(
  1280. v8::Isolate *isolate
  1281. , T *data
  1282. ) {
  1283. isolate->SetData(data);
  1284. }
  1285. template<typename T>
  1286. inline T *GetIsolateData(
  1287. v8::Isolate *isolate
  1288. ) {
  1289. return static_cast<T*>(isolate->GetData());
  1290. }
  1291. class Utf8String {
  1292. public:
  1293. inline explicit Utf8String(v8::Local<v8::Value> from) :
  1294. length_(0), str_(str_st_) {
  1295. v8::HandleScope scope;
  1296. if (!from.IsEmpty()) {
  1297. v8::Local<v8::String> string = from->ToString();
  1298. if (!string.IsEmpty()) {
  1299. size_t len = 3 * string->Length() + 1;
  1300. assert(len <= INT_MAX);
  1301. if (len > sizeof (str_st_)) {
  1302. str_ = static_cast<char*>(malloc(len));
  1303. assert(str_ != 0);
  1304. }
  1305. const int flags =
  1306. v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8;
  1307. length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags);
  1308. str_[length_] = '\0';
  1309. }
  1310. }
  1311. }
  1312. inline int length() const {
  1313. return length_;
  1314. }
  1315. inline char* operator*() { return str_; }
  1316. inline const char* operator*() const { return str_; }
  1317. inline ~Utf8String() {
  1318. if (str_ != str_st_) {
  1319. free(str_);
  1320. }
  1321. }
  1322. private:
  1323. NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String)
  1324. int length_;
  1325. char *str_;
  1326. char str_st_[1024];
  1327. };
  1328. #endif // NODE_MODULE_VERSION
  1329. typedef void (*FreeCallback)(char *data, void *hint);
  1330. typedef const FunctionCallbackInfo<v8::Value>& NAN_METHOD_ARGS_TYPE;
  1331. typedef void NAN_METHOD_RETURN_TYPE;
  1332. typedef const PropertyCallbackInfo<v8::Value>& NAN_GETTER_ARGS_TYPE;
  1333. typedef void NAN_GETTER_RETURN_TYPE;
  1334. typedef const PropertyCallbackInfo<void>& NAN_SETTER_ARGS_TYPE;
  1335. typedef void NAN_SETTER_RETURN_TYPE;
  1336. typedef const PropertyCallbackInfo<v8::Value>&
  1337. NAN_PROPERTY_GETTER_ARGS_TYPE;
  1338. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 12 || \
  1339. (V8_MAJOR_VERSION == 12 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION > 4))
  1340. typedef v8::Intercepted NAN_PROPERTY_GETTER_RETURN_TYPE;
  1341. #else
  1342. typedef void NAN_PROPERTY_GETTER_RETURN_TYPE;
  1343. #endif
  1344. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 12 || \
  1345. (V8_MAJOR_VERSION == 12 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION > 4))
  1346. typedef const PropertyCallbackInfo<void>&
  1347. NAN_PROPERTY_SETTER_ARGS_TYPE;
  1348. typedef v8::Intercepted NAN_PROPERTY_SETTER_RETURN_TYPE;
  1349. #else
  1350. typedef const PropertyCallbackInfo<v8::Value>&
  1351. NAN_PROPERTY_SETTER_ARGS_TYPE;
  1352. typedef void NAN_PROPERTY_SETTER_RETURN_TYPE;
  1353. #endif
  1354. typedef const PropertyCallbackInfo<v8::Array>&
  1355. NAN_PROPERTY_ENUMERATOR_ARGS_TYPE;
  1356. typedef void NAN_PROPERTY_ENUMERATOR_RETURN_TYPE;
  1357. typedef const PropertyCallbackInfo<v8::Boolean>&
  1358. NAN_PROPERTY_DELETER_ARGS_TYPE;
  1359. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 12 || \
  1360. (V8_MAJOR_VERSION == 12 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION > 4))
  1361. typedef v8::Intercepted NAN_PROPERTY_DELETER_RETURN_TYPE;
  1362. #else
  1363. typedef void NAN_PROPERTY_DELETER_RETURN_TYPE;
  1364. #endif
  1365. typedef const PropertyCallbackInfo<v8::Integer>&
  1366. NAN_PROPERTY_QUERY_ARGS_TYPE;
  1367. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 12 || \
  1368. (V8_MAJOR_VERSION == 12 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION > 4))
  1369. typedef v8::Intercepted NAN_PROPERTY_QUERY_RETURN_TYPE;
  1370. #else
  1371. typedef void NAN_PROPERTY_QUERY_RETURN_TYPE;
  1372. #endif
  1373. typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_GETTER_ARGS_TYPE;
  1374. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 12 || \
  1375. (V8_MAJOR_VERSION == 12 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION > 4))
  1376. typedef v8::Intercepted NAN_INDEX_GETTER_RETURN_TYPE;
  1377. #else
  1378. typedef void NAN_INDEX_GETTER_RETURN_TYPE;
  1379. #endif
  1380. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 12 || \
  1381. (V8_MAJOR_VERSION == 12 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION > 4))
  1382. typedef const PropertyCallbackInfo<void>& NAN_INDEX_SETTER_ARGS_TYPE;
  1383. typedef v8::Intercepted NAN_INDEX_SETTER_RETURN_TYPE;
  1384. #else
  1385. typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_SETTER_ARGS_TYPE;
  1386. typedef void NAN_INDEX_SETTER_RETURN_TYPE;
  1387. #endif
  1388. typedef const PropertyCallbackInfo<v8::Array>&
  1389. NAN_INDEX_ENUMERATOR_ARGS_TYPE;
  1390. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 12 || \
  1391. (V8_MAJOR_VERSION == 12 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION > 4))
  1392. typedef v8::Intercepted NAN_INDEX_ENUMERATOR_RETURN_TYPE;
  1393. #else
  1394. typedef void NAN_INDEX_ENUMERATOR_RETURN_TYPE;
  1395. #endif
  1396. typedef const PropertyCallbackInfo<v8::Boolean>&
  1397. NAN_INDEX_DELETER_ARGS_TYPE;
  1398. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 12 || \
  1399. (V8_MAJOR_VERSION == 12 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION > 4))
  1400. typedef v8::Intercepted NAN_INDEX_DELETER_RETURN_TYPE;
  1401. #else
  1402. typedef void NAN_INDEX_DELETER_RETURN_TYPE;
  1403. #endif
  1404. typedef const PropertyCallbackInfo<v8::Integer>&
  1405. NAN_INDEX_QUERY_ARGS_TYPE;
  1406. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 12 || \
  1407. (V8_MAJOR_VERSION == 12 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION > 4))
  1408. typedef v8::Intercepted NAN_INDEX_QUERY_RETURN_TYPE;
  1409. #else
  1410. typedef void NAN_INDEX_QUERY_RETURN_TYPE;
  1411. #endif
  1412. #define NAN_METHOD(name) \
  1413. Nan::NAN_METHOD_RETURN_TYPE name(Nan::NAN_METHOD_ARGS_TYPE info)
  1414. #define NAN_GETTER(name) \
  1415. Nan::NAN_GETTER_RETURN_TYPE name( \
  1416. v8::Local<v8::String> property \
  1417. , Nan::NAN_GETTER_ARGS_TYPE info)
  1418. #define NAN_SETTER(name) \
  1419. Nan::NAN_SETTER_RETURN_TYPE name( \
  1420. v8::Local<v8::String> property \
  1421. , v8::Local<v8::Value> value \
  1422. , Nan::NAN_SETTER_ARGS_TYPE info)
  1423. #define NAN_PROPERTY_GETTER(name) \
  1424. Nan::NAN_PROPERTY_GETTER_RETURN_TYPE name( \
  1425. v8::Local<v8::String> property \
  1426. , Nan::NAN_PROPERTY_GETTER_ARGS_TYPE info)
  1427. #define NAN_PROPERTY_SETTER(name) \
  1428. Nan::NAN_PROPERTY_SETTER_RETURN_TYPE name( \
  1429. v8::Local<v8::String> property \
  1430. , v8::Local<v8::Value> value \
  1431. , Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info)
  1432. #define NAN_PROPERTY_ENUMERATOR(name) \
  1433. Nan::NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name( \
  1434. Nan::NAN_PROPERTY_ENUMERATOR_ARGS_TYPE info)
  1435. #define NAN_PROPERTY_DELETER(name) \
  1436. Nan::NAN_PROPERTY_DELETER_RETURN_TYPE name( \
  1437. v8::Local<v8::String> property \
  1438. , Nan::NAN_PROPERTY_DELETER_ARGS_TYPE info)
  1439. #define NAN_PROPERTY_QUERY(name) \
  1440. Nan::NAN_PROPERTY_QUERY_RETURN_TYPE name( \
  1441. v8::Local<v8::String> property \
  1442. , Nan::NAN_PROPERTY_QUERY_ARGS_TYPE info)
  1443. # define NAN_INDEX_GETTER(name) \
  1444. Nan::NAN_INDEX_GETTER_RETURN_TYPE name( \
  1445. uint32_t index \
  1446. , Nan::NAN_INDEX_GETTER_ARGS_TYPE info)
  1447. #define NAN_INDEX_SETTER(name) \
  1448. Nan::NAN_INDEX_SETTER_RETURN_TYPE name( \
  1449. uint32_t index \
  1450. , v8::Local<v8::Value> value \
  1451. , Nan::NAN_INDEX_SETTER_ARGS_TYPE info)
  1452. #define NAN_INDEX_ENUMERATOR(name) \
  1453. Nan::NAN_INDEX_ENUMERATOR_RETURN_TYPE \
  1454. name(Nan::NAN_INDEX_ENUMERATOR_ARGS_TYPE info)
  1455. #define NAN_INDEX_DELETER(name) \
  1456. Nan::NAN_INDEX_DELETER_RETURN_TYPE name( \
  1457. uint32_t index \
  1458. , Nan::NAN_INDEX_DELETER_ARGS_TYPE info)
  1459. #define NAN_INDEX_QUERY(name) \
  1460. Nan::NAN_INDEX_QUERY_RETURN_TYPE name( \
  1461. uint32_t index \
  1462. , Nan::NAN_INDEX_QUERY_ARGS_TYPE info)
  1463. class Callback {
  1464. public:
  1465. Callback() {}
  1466. explicit Callback(const v8::Local<v8::Function> &fn) : handle_(fn) {}
  1467. ~Callback() {
  1468. handle_.Reset();
  1469. }
  1470. bool operator==(const Callback &other) const {
  1471. return handle_ == other.handle_;
  1472. }
  1473. bool operator!=(const Callback &other) const {
  1474. return !operator==(other);
  1475. }
  1476. inline
  1477. v8::Local<v8::Function> operator*() const { return GetFunction(); }
  1478. NAN_DEPRECATED inline v8::Local<v8::Value> operator()(
  1479. v8::Local<v8::Object> target
  1480. , int argc = 0
  1481. , v8::Local<v8::Value> argv[] = 0) const {
  1482. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1483. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1484. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1485. AsyncResource async("nan:Callback:operator()");
  1486. return Call_(isolate, target, argc, argv, &async)
  1487. .FromMaybe(v8::Local<v8::Value>());
  1488. # else
  1489. return Call_(isolate, target, argc, argv);
  1490. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1491. #else
  1492. return Call_(target, argc, argv);
  1493. #endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1494. }
  1495. NAN_DEPRECATED inline v8::Local<v8::Value> operator()(
  1496. int argc = 0
  1497. , v8::Local<v8::Value> argv[] = 0) const {
  1498. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1499. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1500. v8::EscapableHandleScope scope(isolate);
  1501. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1502. AsyncResource async("nan:Callback:operator()");
  1503. return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(),
  1504. argc, argv, &async)
  1505. .FromMaybe(v8::Local<v8::Value>()));
  1506. # else
  1507. return scope.Escape(
  1508. Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
  1509. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1510. #else
  1511. v8::HandleScope scope;
  1512. return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
  1513. #endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1514. }
  1515. inline MaybeLocal<v8::Value> operator()(
  1516. AsyncResource* resource
  1517. , int argc = 0
  1518. , v8::Local<v8::Value> argv[] = 0) const {
  1519. return this->Call(argc, argv, resource);
  1520. }
  1521. inline MaybeLocal<v8::Value> operator()(
  1522. AsyncResource* resource
  1523. , v8::Local<v8::Object> target
  1524. , int argc = 0
  1525. , v8::Local<v8::Value> argv[] = 0) const {
  1526. return this->Call(target, argc, argv, resource);
  1527. }
  1528. // TODO(kkoopa): remove
  1529. inline void SetFunction(const v8::Local<v8::Function> &fn) {
  1530. Reset(fn);
  1531. }
  1532. inline void Reset(const v8::Local<v8::Function> &fn) {
  1533. handle_.Reset(fn);
  1534. }
  1535. inline void Reset() {
  1536. handle_.Reset();
  1537. }
  1538. inline v8::Local<v8::Function> GetFunction() const {
  1539. return New(handle_);
  1540. }
  1541. inline bool IsEmpty() const {
  1542. return handle_.IsEmpty();
  1543. }
  1544. // Deprecated: For async callbacks Use the versions that accept an
  1545. // AsyncResource. If this callback does not correspond to an async resource,
  1546. // that is, it is a synchronous function call on a non-empty JS stack, you
  1547. // should Nan::Call instead.
  1548. NAN_DEPRECATED inline v8::Local<v8::Value>
  1549. Call(v8::Local<v8::Object> target
  1550. , int argc
  1551. , v8::Local<v8::Value> argv[]) const {
  1552. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1553. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1554. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1555. AsyncResource async("nan:Callback:Call");
  1556. return Call_(isolate, target, argc, argv, &async)
  1557. .FromMaybe(v8::Local<v8::Value>());
  1558. # else
  1559. return Call_(isolate, target, argc, argv);
  1560. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1561. #else
  1562. return Call_(target, argc, argv);
  1563. #endif
  1564. }
  1565. // Deprecated: For async callbacks Use the versions that accept an
  1566. // AsyncResource. If this callback does not correspond to an async resource,
  1567. // that is, it is a synchronous function call on a non-empty JS stack, you
  1568. // should Nan::Call instead.
  1569. NAN_DEPRECATED inline v8::Local<v8::Value>
  1570. Call(int argc, v8::Local<v8::Value> argv[]) const {
  1571. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1572. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1573. v8::EscapableHandleScope scope(isolate);
  1574. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1575. AsyncResource async("nan:Callback:Call");
  1576. return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(),
  1577. argc, argv, &async)
  1578. .FromMaybe(v8::Local<v8::Value>()));
  1579. # else
  1580. return scope.Escape(
  1581. Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
  1582. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1583. #else
  1584. v8::HandleScope scope;
  1585. return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
  1586. #endif
  1587. }
  1588. inline MaybeLocal<v8::Value>
  1589. Call(v8::Local<v8::Object> target
  1590. , int argc
  1591. , v8::Local<v8::Value> argv[]
  1592. , AsyncResource* resource) const {
  1593. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1594. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1595. return Call_(isolate, target, argc, argv, resource);
  1596. #elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1597. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1598. return Call_(isolate, target, argc, argv);
  1599. #else
  1600. return Call_(target, argc, argv);
  1601. #endif
  1602. }
  1603. inline MaybeLocal<v8::Value>
  1604. Call(int argc, v8::Local<v8::Value> argv[], AsyncResource* resource) const {
  1605. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1606. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1607. return Call(isolate->GetCurrentContext()->Global(), argc, argv, resource);
  1608. #elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1609. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1610. v8::EscapableHandleScope scope(isolate);
  1611. return scope.Escape(
  1612. Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
  1613. #else
  1614. v8::HandleScope scope;
  1615. return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
  1616. #endif
  1617. }
  1618. private:
  1619. NAN_DISALLOW_ASSIGN_COPY_MOVE(Callback)
  1620. Persistent<v8::Function> handle_;
  1621. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1622. MaybeLocal<v8::Value> Call_(v8::Isolate *isolate
  1623. , v8::Local<v8::Object> target
  1624. , int argc
  1625. , v8::Local<v8::Value> argv[]
  1626. , AsyncResource* resource) const {
  1627. EscapableHandleScope scope;
  1628. v8::Local<v8::Function> func = New(handle_);
  1629. auto maybe = resource->runInAsyncScope(target, func, argc, argv);
  1630. v8::Local<v8::Value> local;
  1631. if (!maybe.ToLocal(&local)) return MaybeLocal<v8::Value>();
  1632. return scope.Escape(local);
  1633. }
  1634. #elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1635. v8::Local<v8::Value> Call_(v8::Isolate *isolate
  1636. , v8::Local<v8::Object> target
  1637. , int argc
  1638. , v8::Local<v8::Value> argv[]) const {
  1639. EscapableHandleScope scope;
  1640. v8::Local<v8::Function> callback = New(handle_);
  1641. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  1642. return scope.Escape(New(node::MakeCallback(
  1643. isolate
  1644. , target
  1645. , callback
  1646. , argc
  1647. , argv
  1648. )));
  1649. # else
  1650. return scope.Escape(node::MakeCallback(
  1651. isolate
  1652. , target
  1653. , callback
  1654. , argc
  1655. , argv
  1656. ));
  1657. # endif
  1658. }
  1659. #else
  1660. v8::Local<v8::Value> Call_(v8::Local<v8::Object> target
  1661. , int argc
  1662. , v8::Local<v8::Value> argv[]) const {
  1663. EscapableHandleScope scope;
  1664. v8::Local<v8::Function> callback = New(handle_);
  1665. return scope.Escape(New(node::MakeCallback(
  1666. target
  1667. , callback
  1668. , argc
  1669. , argv
  1670. )));
  1671. }
  1672. #endif
  1673. };
  1674. inline MaybeLocal<v8::Value> Call(
  1675. const Nan::Callback& callback
  1676. , v8::Local<v8::Object> recv
  1677. , int argc
  1678. , v8::Local<v8::Value> argv[]) {
  1679. return Call(*callback, recv, argc, argv);
  1680. }
  1681. inline MaybeLocal<v8::Value> Call(
  1682. const Nan::Callback& callback
  1683. , int argc
  1684. , v8::Local<v8::Value> argv[]) {
  1685. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1686. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1687. v8::EscapableHandleScope scope(isolate);
  1688. return scope.Escape(
  1689. Call(*callback, isolate->GetCurrentContext()->Global(), argc, argv)
  1690. .FromMaybe(v8::Local<v8::Value>()));
  1691. #else
  1692. EscapableHandleScope scope;
  1693. return scope.Escape(
  1694. Call(*callback, v8::Context::GetCurrent()->Global(), argc, argv)
  1695. .FromMaybe(v8::Local<v8::Value>()));
  1696. #endif
  1697. }
  1698. inline MaybeLocal<v8::Value> Call(
  1699. v8::Local<v8::String> symbol
  1700. , v8::Local<v8::Object> recv
  1701. , int argc
  1702. , v8::Local<v8::Value> argv[]) {
  1703. EscapableHandleScope scope;
  1704. v8::Local<v8::Value> fn_v =
  1705. Get(recv, symbol).FromMaybe(v8::Local<v8::Value>());
  1706. if (fn_v.IsEmpty() || !fn_v->IsFunction()) return v8::Local<v8::Value>();
  1707. v8::Local<v8::Function> fn = fn_v.As<v8::Function>();
  1708. return scope.Escape(
  1709. Call(fn, recv, argc, argv).FromMaybe(v8::Local<v8::Value>()));
  1710. }
  1711. inline MaybeLocal<v8::Value> Call(
  1712. const char* method
  1713. , v8::Local<v8::Object> recv
  1714. , int argc
  1715. , v8::Local<v8::Value> argv[]) {
  1716. EscapableHandleScope scope;
  1717. v8::Local<v8::String> method_string =
  1718. New<v8::String>(method).ToLocalChecked();
  1719. return scope.Escape(
  1720. Call(method_string, recv, argc, argv).FromMaybe(v8::Local<v8::Value>()));
  1721. }
  1722. /* abstract */ class AsyncWorker {
  1723. public:
  1724. explicit AsyncWorker(Callback *callback_,
  1725. const char* resource_name = "nan:AsyncWorker")
  1726. : callback(callback_), errmsg_(NULL) {
  1727. request.data = this;
  1728. HandleScope scope;
  1729. v8::Local<v8::Object> obj = New<v8::Object>();
  1730. persistentHandle.Reset(obj);
  1731. async_resource = new AsyncResource(resource_name, obj);
  1732. }
  1733. virtual ~AsyncWorker() {
  1734. HandleScope scope;
  1735. if (!persistentHandle.IsEmpty())
  1736. persistentHandle.Reset();
  1737. delete callback;
  1738. delete[] errmsg_;
  1739. delete async_resource;
  1740. }
  1741. virtual void WorkComplete() {
  1742. HandleScope scope;
  1743. if (errmsg_ == NULL)
  1744. HandleOKCallback();
  1745. else
  1746. HandleErrorCallback();
  1747. delete callback;
  1748. callback = NULL;
  1749. }
  1750. inline void SaveToPersistent(
  1751. const char *key, const v8::Local<v8::Value> &value) {
  1752. HandleScope scope;
  1753. Set(New(persistentHandle), New(key).ToLocalChecked(), value).FromJust();
  1754. }
  1755. inline void SaveToPersistent(
  1756. const v8::Local<v8::String> &key, const v8::Local<v8::Value> &value) {
  1757. HandleScope scope;
  1758. Set(New(persistentHandle), key, value).FromJust();
  1759. }
  1760. inline void SaveToPersistent(
  1761. uint32_t index, const v8::Local<v8::Value> &value) {
  1762. HandleScope scope;
  1763. Set(New(persistentHandle), index, value).FromJust();
  1764. }
  1765. inline v8::Local<v8::Value> GetFromPersistent(const char *key) const {
  1766. EscapableHandleScope scope;
  1767. return scope.Escape(
  1768. Get(New(persistentHandle), New(key).ToLocalChecked())
  1769. .FromMaybe(v8::Local<v8::Value>()));
  1770. }
  1771. inline v8::Local<v8::Value>
  1772. GetFromPersistent(const v8::Local<v8::String> &key) const {
  1773. EscapableHandleScope scope;
  1774. return scope.Escape(
  1775. Get(New(persistentHandle), key)
  1776. .FromMaybe(v8::Local<v8::Value>()));
  1777. }
  1778. inline v8::Local<v8::Value> GetFromPersistent(uint32_t index) const {
  1779. EscapableHandleScope scope;
  1780. return scope.Escape(
  1781. Get(New(persistentHandle), index)
  1782. .FromMaybe(v8::Local<v8::Value>()));
  1783. }
  1784. virtual void Execute() = 0;
  1785. uv_work_t request;
  1786. virtual void Destroy() {
  1787. delete this;
  1788. }
  1789. protected:
  1790. Persistent<v8::Object> persistentHandle;
  1791. Callback *callback;
  1792. AsyncResource *async_resource;
  1793. virtual void HandleOKCallback() {
  1794. HandleScope scope;
  1795. callback->Call(0, NULL, async_resource);
  1796. }
  1797. virtual void HandleErrorCallback() {
  1798. HandleScope scope;
  1799. v8::Local<v8::Value> argv[] = {
  1800. v8::Exception::Error(New<v8::String>(ErrorMessage()).ToLocalChecked())
  1801. };
  1802. callback->Call(1, argv, async_resource);
  1803. }
  1804. void SetErrorMessage(const char *msg) {
  1805. delete[] errmsg_;
  1806. size_t size = strlen(msg) + 1;
  1807. errmsg_ = new char[size];
  1808. memcpy(errmsg_, msg, size);
  1809. }
  1810. const char* ErrorMessage() const {
  1811. return errmsg_;
  1812. }
  1813. private:
  1814. NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncWorker)
  1815. char *errmsg_;
  1816. };
  1817. /* abstract */ class AsyncBareProgressWorkerBase : public AsyncWorker {
  1818. public:
  1819. explicit AsyncBareProgressWorkerBase(
  1820. Callback *callback_,
  1821. const char* resource_name = "nan:AsyncBareProgressWorkerBase")
  1822. : AsyncWorker(callback_, resource_name) {
  1823. uv_async_init(
  1824. GetCurrentEventLoop()
  1825. , &async
  1826. , AsyncProgress_
  1827. );
  1828. async.data = this;
  1829. }
  1830. virtual ~AsyncBareProgressWorkerBase() {
  1831. }
  1832. virtual void WorkProgress() = 0;
  1833. virtual void Destroy() {
  1834. uv_close(reinterpret_cast<uv_handle_t*>(&async), AsyncClose_);
  1835. }
  1836. private:
  1837. inline static NAUV_WORK_CB(AsyncProgress_) {
  1838. AsyncBareProgressWorkerBase *worker =
  1839. static_cast<AsyncBareProgressWorkerBase*>(async->data);
  1840. worker->WorkProgress();
  1841. }
  1842. inline static void AsyncClose_(uv_handle_t* handle) {
  1843. AsyncBareProgressWorkerBase *worker =
  1844. static_cast<AsyncBareProgressWorkerBase*>(handle->data);
  1845. delete worker;
  1846. }
  1847. protected:
  1848. uv_async_t async;
  1849. };
  1850. template<class T>
  1851. /* abstract */
  1852. class AsyncBareProgressWorker : public AsyncBareProgressWorkerBase {
  1853. public:
  1854. explicit AsyncBareProgressWorker(
  1855. Callback *callback_,
  1856. const char* resource_name = "nan:AsyncBareProgressWorker")
  1857. : AsyncBareProgressWorkerBase(callback_, resource_name) {
  1858. uv_mutex_init(&async_lock);
  1859. }
  1860. virtual ~AsyncBareProgressWorker() {
  1861. uv_mutex_destroy(&async_lock);
  1862. }
  1863. class ExecutionProgress {
  1864. friend class AsyncBareProgressWorker;
  1865. public:
  1866. void Signal() const {
  1867. uv_mutex_lock(&that_->async_lock);
  1868. uv_async_send(&that_->async);
  1869. uv_mutex_unlock(&that_->async_lock);
  1870. }
  1871. void Send(const T* data, size_t count) const {
  1872. that_->SendProgress_(data, count);
  1873. }
  1874. private:
  1875. explicit ExecutionProgress(AsyncBareProgressWorker *that) : that_(that) {}
  1876. NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress)
  1877. AsyncBareProgressWorker* const that_;
  1878. };
  1879. virtual void Execute(const ExecutionProgress& progress) = 0;
  1880. virtual void HandleProgressCallback(const T *data, size_t size) = 0;
  1881. protected:
  1882. uv_mutex_t async_lock;
  1883. private:
  1884. void Execute() /*final override*/ {
  1885. ExecutionProgress progress(this);
  1886. Execute(progress);
  1887. }
  1888. virtual void SendProgress_(const T *data, size_t count) = 0;
  1889. };
  1890. template<class T>
  1891. /* abstract */
  1892. class AsyncProgressWorkerBase : public AsyncBareProgressWorker<T> {
  1893. public:
  1894. explicit AsyncProgressWorkerBase(
  1895. Callback *callback_,
  1896. const char* resource_name = "nan:AsyncProgressWorkerBase")
  1897. : AsyncBareProgressWorker<T>(callback_, resource_name), asyncdata_(NULL),
  1898. asyncsize_(0) {
  1899. }
  1900. virtual ~AsyncProgressWorkerBase() {
  1901. delete[] asyncdata_;
  1902. }
  1903. void WorkProgress() {
  1904. uv_mutex_lock(&this->async_lock);
  1905. T *data = asyncdata_;
  1906. size_t size = asyncsize_;
  1907. asyncdata_ = NULL;
  1908. asyncsize_ = 0;
  1909. uv_mutex_unlock(&this->async_lock);
  1910. // Don't send progress events after we've already completed.
  1911. if (this->callback) {
  1912. this->HandleProgressCallback(data, size);
  1913. }
  1914. delete[] data;
  1915. }
  1916. private:
  1917. void SendProgress_(const T *data, size_t count) {
  1918. T *new_data = new T[count];
  1919. std::copy(data, data + count, new_data);
  1920. uv_mutex_lock(&this->async_lock);
  1921. T *old_data = asyncdata_;
  1922. asyncdata_ = new_data;
  1923. asyncsize_ = count;
  1924. uv_async_send(&this->async);
  1925. uv_mutex_unlock(&this->async_lock);
  1926. delete[] old_data;
  1927. }
  1928. T *asyncdata_;
  1929. size_t asyncsize_;
  1930. };
  1931. // This ensures compatibility to the previous un-templated AsyncProgressWorker
  1932. // class definition.
  1933. typedef AsyncProgressWorkerBase<char> AsyncProgressWorker;
  1934. template<class T>
  1935. /* abstract */
  1936. class AsyncBareProgressQueueWorker : public AsyncBareProgressWorkerBase {
  1937. public:
  1938. explicit AsyncBareProgressQueueWorker(
  1939. Callback *callback_,
  1940. const char* resource_name = "nan:AsyncBareProgressQueueWorker")
  1941. : AsyncBareProgressWorkerBase(callback_, resource_name) {
  1942. }
  1943. virtual ~AsyncBareProgressQueueWorker() {
  1944. }
  1945. class ExecutionProgress {
  1946. friend class AsyncBareProgressQueueWorker;
  1947. public:
  1948. void Send(const T* data, size_t count) const {
  1949. that_->SendProgress_(data, count);
  1950. }
  1951. private:
  1952. explicit ExecutionProgress(AsyncBareProgressQueueWorker *that)
  1953. : that_(that) {}
  1954. NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress)
  1955. AsyncBareProgressQueueWorker* const that_;
  1956. };
  1957. virtual void Execute(const ExecutionProgress& progress) = 0;
  1958. virtual void HandleProgressCallback(const T *data, size_t size) = 0;
  1959. private:
  1960. void Execute() /*final override*/ {
  1961. ExecutionProgress progress(this);
  1962. Execute(progress);
  1963. }
  1964. virtual void SendProgress_(const T *data, size_t count) = 0;
  1965. };
  1966. template<class T>
  1967. /* abstract */
  1968. class AsyncProgressQueueWorker : public AsyncBareProgressQueueWorker<T> {
  1969. public:
  1970. explicit AsyncProgressQueueWorker(
  1971. Callback *callback_,
  1972. const char* resource_name = "nan:AsyncProgressQueueWorker")
  1973. : AsyncBareProgressQueueWorker<T>(callback_) {
  1974. uv_mutex_init(&async_lock);
  1975. }
  1976. virtual ~AsyncProgressQueueWorker() {
  1977. uv_mutex_lock(&async_lock);
  1978. while (!asyncdata_.empty()) {
  1979. std::pair<T*, size_t> &datapair = asyncdata_.front();
  1980. T *data = datapair.first;
  1981. asyncdata_.pop();
  1982. delete[] data;
  1983. }
  1984. uv_mutex_unlock(&async_lock);
  1985. uv_mutex_destroy(&async_lock);
  1986. }
  1987. void WorkComplete() {
  1988. WorkProgress();
  1989. AsyncWorker::WorkComplete();
  1990. }
  1991. void WorkProgress() {
  1992. uv_mutex_lock(&async_lock);
  1993. while (!asyncdata_.empty()) {
  1994. std::pair<T*, size_t> &datapair = asyncdata_.front();
  1995. T *data = datapair.first;
  1996. size_t size = datapair.second;
  1997. asyncdata_.pop();
  1998. uv_mutex_unlock(&async_lock);
  1999. // Don't send progress events after we've already completed.
  2000. if (this->callback) {
  2001. this->HandleProgressCallback(data, size);
  2002. }
  2003. delete[] data;
  2004. uv_mutex_lock(&async_lock);
  2005. }
  2006. uv_mutex_unlock(&async_lock);
  2007. }
  2008. private:
  2009. void SendProgress_(const T *data, size_t count) {
  2010. T *new_data = new T[count];
  2011. std::copy(data, data + count, new_data);
  2012. uv_mutex_lock(&async_lock);
  2013. asyncdata_.push(std::pair<T*, size_t>(new_data, count));
  2014. uv_mutex_unlock(&async_lock);
  2015. uv_async_send(&this->async);
  2016. }
  2017. uv_mutex_t async_lock;
  2018. std::queue<std::pair<T*, size_t> > asyncdata_;
  2019. };
  2020. inline void AsyncExecute (uv_work_t* req) {
  2021. AsyncWorker *worker = static_cast<AsyncWorker*>(req->data);
  2022. worker->Execute();
  2023. }
  2024. /* uv_after_work_cb has 1 argument before node-v0.9.4 and
  2025. * 2 arguments since node-v0.9.4
  2026. * https://github.com/libuv/libuv/commit/92fb84b751e18f032c02609467f44bfe927b80c5
  2027. */
  2028. inline void AsyncExecuteComplete(uv_work_t *req) {
  2029. AsyncWorker* worker = static_cast<AsyncWorker*>(req->data);
  2030. worker->WorkComplete();
  2031. worker->Destroy();
  2032. }
  2033. inline void AsyncExecuteComplete (uv_work_t* req, int status) {
  2034. AsyncExecuteComplete(req);
  2035. }
  2036. inline void AsyncQueueWorker (AsyncWorker* worker) {
  2037. uv_queue_work(
  2038. GetCurrentEventLoop()
  2039. , &worker->request
  2040. , AsyncExecute
  2041. , AsyncExecuteComplete
  2042. );
  2043. }
  2044. namespace imp {
  2045. inline
  2046. ExternalOneByteStringResource const*
  2047. GetExternalResource(v8::Local<v8::String> str) {
  2048. #if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION
  2049. return str->GetExternalAsciiStringResource();
  2050. #else
  2051. return str->GetExternalOneByteStringResource();
  2052. #endif
  2053. }
  2054. inline
  2055. bool
  2056. IsExternal(v8::Local<v8::String> str) {
  2057. #if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION
  2058. return str->IsExternalAscii();
  2059. #else
  2060. return str->IsExternalOneByte();
  2061. #endif
  2062. }
  2063. } // end of namespace imp
  2064. enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER};
  2065. #if NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION
  2066. # include "nan_string_bytes.h" // NOLINT(build/include)
  2067. #endif
  2068. inline v8::Local<v8::Value> Encode(
  2069. const void *buf, size_t len, enum Encoding encoding = BINARY) {
  2070. #if (NODE_MODULE_VERSION >= ATOM_0_21_MODULE_VERSION)
  2071. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  2072. node::encoding node_enc = static_cast<node::encoding>(encoding);
  2073. if (encoding == UCS2) {
  2074. return node::Encode(
  2075. isolate
  2076. , reinterpret_cast<const uint16_t *>(buf)
  2077. , len / 2);
  2078. } else {
  2079. return node::Encode(
  2080. isolate
  2081. , reinterpret_cast<const char *>(buf)
  2082. , len
  2083. , node_enc);
  2084. }
  2085. #elif (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  2086. return node::Encode(
  2087. v8::Isolate::GetCurrent()
  2088. , buf, len
  2089. , static_cast<node::encoding>(encoding));
  2090. #else
  2091. # if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION
  2092. return node::Encode(buf, len, static_cast<node::encoding>(encoding));
  2093. # else
  2094. return imp::Encode(reinterpret_cast<const char*>(buf), len, encoding);
  2095. # endif
  2096. #endif
  2097. }
  2098. inline ssize_t DecodeBytes(
  2099. v8::Local<v8::Value> val, enum Encoding encoding = BINARY) {
  2100. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  2101. return node::DecodeBytes(
  2102. v8::Isolate::GetCurrent()
  2103. , val
  2104. , static_cast<node::encoding>(encoding));
  2105. #else
  2106. # if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION)
  2107. if (encoding == BUFFER) {
  2108. return node::DecodeBytes(val, node::BINARY);
  2109. }
  2110. # endif
  2111. return node::DecodeBytes(val, static_cast<node::encoding>(encoding));
  2112. #endif
  2113. }
  2114. inline ssize_t DecodeWrite(
  2115. char *buf
  2116. , size_t len
  2117. , v8::Local<v8::Value> val
  2118. , enum Encoding encoding = BINARY) {
  2119. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  2120. return node::DecodeWrite(
  2121. v8::Isolate::GetCurrent()
  2122. , buf
  2123. , len
  2124. , val
  2125. , static_cast<node::encoding>(encoding));
  2126. #else
  2127. # if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION)
  2128. if (encoding == BUFFER) {
  2129. return node::DecodeWrite(buf, len, val, node::BINARY);
  2130. }
  2131. # endif
  2132. return node::DecodeWrite(
  2133. buf
  2134. , len
  2135. , val
  2136. , static_cast<node::encoding>(encoding));
  2137. #endif
  2138. }
  2139. inline void SetPrototypeTemplate(
  2140. v8::Local<v8::FunctionTemplate> templ
  2141. , const char *name
  2142. , v8::Local<v8::Data> value
  2143. ) {
  2144. HandleScope scope;
  2145. SetTemplate(templ->PrototypeTemplate(), name, value);
  2146. }
  2147. inline void SetPrototypeTemplate(
  2148. v8::Local<v8::FunctionTemplate> templ
  2149. , v8::Local<v8::String> name
  2150. , v8::Local<v8::Data> value
  2151. , v8::PropertyAttribute attributes
  2152. ) {
  2153. HandleScope scope;
  2154. SetTemplate(templ->PrototypeTemplate(), name, value, attributes);
  2155. }
  2156. inline void SetInstanceTemplate(
  2157. v8::Local<v8::FunctionTemplate> templ
  2158. , const char *name
  2159. , v8::Local<v8::Data> value
  2160. ) {
  2161. HandleScope scope;
  2162. SetTemplate(templ->InstanceTemplate(), name, value);
  2163. }
  2164. inline void SetInstanceTemplate(
  2165. v8::Local<v8::FunctionTemplate> templ
  2166. , v8::Local<v8::String> name
  2167. , v8::Local<v8::Data> value
  2168. , v8::PropertyAttribute attributes
  2169. ) {
  2170. HandleScope scope;
  2171. SetTemplate(templ->InstanceTemplate(), name, value, attributes);
  2172. }
  2173. namespace imp {
  2174. // Note(@agnat): Helper to distinguish different receiver types. The first
  2175. // version deals with receivers derived from v8::Template. The second version
  2176. // handles everything else. The final argument only serves as discriminator and
  2177. // is unused.
  2178. template <typename T>
  2179. inline
  2180. void
  2181. SetMethodAux(T recv,
  2182. v8::Local<v8::String> name,
  2183. v8::Local<v8::FunctionTemplate> tpl,
  2184. v8::Template *) {
  2185. recv->Set(name, tpl);
  2186. }
  2187. template <typename T>
  2188. inline
  2189. void
  2190. SetMethodAux(T recv,
  2191. v8::Local<v8::String> name,
  2192. v8::Local<v8::FunctionTemplate> tpl,
  2193. ...) {
  2194. Set(recv, name, GetFunction(tpl).ToLocalChecked());
  2195. }
  2196. } // end of namespace imp
  2197. template <typename T, template <typename> class HandleType>
  2198. inline void SetMethod(
  2199. HandleType<T> recv
  2200. , const char *name
  2201. , FunctionCallback callback
  2202. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2203. HandleScope scope;
  2204. v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(callback, data);
  2205. v8::Local<v8::String> fn_name = New(name).ToLocalChecked();
  2206. t->SetClassName(fn_name);
  2207. // Note(@agnat): Pass an empty T* as discriminator. See note on
  2208. // SetMethodAux(...) above
  2209. imp::SetMethodAux(recv, fn_name, t, static_cast<T*>(0));
  2210. }
  2211. inline void SetPrototypeMethod(
  2212. v8::Local<v8::FunctionTemplate> recv
  2213. , const char* name
  2214. , FunctionCallback callback
  2215. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2216. HandleScope scope;
  2217. v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(
  2218. callback
  2219. , data
  2220. , New<v8::Signature>(recv));
  2221. v8::Local<v8::String> fn_name = New(name).ToLocalChecked();
  2222. recv->PrototypeTemplate()->Set(fn_name, t);
  2223. t->SetClassName(fn_name);
  2224. }
  2225. //=== Accessors and Such =======================================================
  2226. NAN_DEPRECATED inline void SetAccessor(
  2227. v8::Local<v8::ObjectTemplate> tpl
  2228. , v8::Local<v8::String> name
  2229. , GetterCallback getter
  2230. , SetterCallback setter
  2231. , v8::Local<v8::Value> data
  2232. , v8::AccessControl settings
  2233. , v8::PropertyAttribute attribute
  2234. , imp::Sig signature) {
  2235. HandleScope scope;
  2236. imp::NativeGetter getter_ =
  2237. imp::GetterCallbackWrapper;
  2238. imp::NativeSetter setter_ =
  2239. setter ? imp::SetterCallbackWrapper : 0;
  2240. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2241. otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
  2242. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2243. obj->SetInternalField(
  2244. imp::kGetterIndex
  2245. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2246. if (setter != 0) {
  2247. obj->SetInternalField(
  2248. imp::kSetterIndex
  2249. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2250. }
  2251. if (!data.IsEmpty()) {
  2252. obj->SetInternalField(imp::kDataIndex, data);
  2253. }
  2254. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 12 || (V8_MAJOR_VERSION == 12 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 5))
  2255. tpl->SetNativeDataProperty(
  2256. #else
  2257. tpl->SetAccessor(
  2258. #endif
  2259. name
  2260. , getter_
  2261. , setter_
  2262. , obj
  2263. #if !defined(V8_MAJOR_VERSION) || V8_MAJOR_VERSION < 12
  2264. , settings
  2265. #endif
  2266. , attribute
  2267. #if (NODE_MODULE_VERSION < NODE_16_0_MODULE_VERSION)
  2268. , signature
  2269. #endif
  2270. );
  2271. }
  2272. inline void SetAccessor(
  2273. v8::Local<v8::ObjectTemplate> tpl
  2274. , v8::Local<v8::String> name
  2275. , GetterCallback getter
  2276. , SetterCallback setter = 0
  2277. , v8::Local<v8::Value> data = v8::Local<v8::Value>()
  2278. , v8::AccessControl settings = v8::DEFAULT
  2279. , v8::PropertyAttribute attribute = v8::None) {
  2280. HandleScope scope;
  2281. imp::NativeGetter getter_ =
  2282. imp::GetterCallbackWrapper;
  2283. imp::NativeSetter setter_ =
  2284. setter ? imp::SetterCallbackWrapper : 0;
  2285. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2286. otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
  2287. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2288. obj->SetInternalField(
  2289. imp::kGetterIndex
  2290. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2291. if (setter != 0) {
  2292. obj->SetInternalField(
  2293. imp::kSetterIndex
  2294. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2295. }
  2296. if (!data.IsEmpty()) {
  2297. obj->SetInternalField(imp::kDataIndex, data);
  2298. }
  2299. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 12 || (V8_MAJOR_VERSION == 12 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 5))
  2300. tpl->SetNativeDataProperty(
  2301. #else
  2302. tpl->SetAccessor(
  2303. #endif
  2304. name
  2305. , getter_
  2306. , setter_
  2307. , obj
  2308. #if !defined(V8_MAJOR_VERSION) || V8_MAJOR_VERSION < 12
  2309. , settings
  2310. #endif
  2311. , attribute
  2312. );
  2313. }
  2314. inline bool SetAccessor(
  2315. v8::Local<v8::Object> obj
  2316. , v8::Local<v8::String> name
  2317. , GetterCallback getter
  2318. , SetterCallback setter = 0
  2319. , v8::Local<v8::Value> data = v8::Local<v8::Value>()
  2320. , v8::AccessControl settings = v8::DEFAULT
  2321. , v8::PropertyAttribute attribute = v8::None) {
  2322. HandleScope scope;
  2323. imp::NativeGetter getter_ =
  2324. imp::GetterCallbackWrapper;
  2325. imp::NativeSetter setter_ =
  2326. setter ? imp::SetterCallbackWrapper : 0;
  2327. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2328. otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
  2329. v8::Local<v8::Object> dataobj = NewInstance(otpl).ToLocalChecked();
  2330. dataobj->SetInternalField(
  2331. imp::kGetterIndex
  2332. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2333. if (!data.IsEmpty()) {
  2334. dataobj->SetInternalField(imp::kDataIndex, data);
  2335. }
  2336. if (setter) {
  2337. dataobj->SetInternalField(
  2338. imp::kSetterIndex
  2339. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2340. }
  2341. #if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION)
  2342. #if defined(V8_MAJOR_VERSION) && \
  2343. (V8_MAJOR_VERSION > 12 || \
  2344. (V8_MAJOR_VERSION == 12 && defined(V8_MINOR_VERSION) && \
  2345. V8_MINOR_VERSION >= 5))
  2346. return obj->SetNativeDataProperty(
  2347. GetCurrentContext()
  2348. , name
  2349. , getter_
  2350. , setter_
  2351. , dataobj
  2352. , attribute).FromMaybe(false);
  2353. #else
  2354. return obj->SetAccessor(
  2355. GetCurrentContext()
  2356. , name
  2357. , getter_
  2358. , setter_
  2359. , dataobj
  2360. , settings
  2361. , attribute).FromMaybe(false);
  2362. #endif
  2363. #else
  2364. return obj->SetAccessor(
  2365. name
  2366. , getter_
  2367. , setter_
  2368. , dataobj
  2369. , settings
  2370. , attribute);
  2371. #endif
  2372. }
  2373. inline void SetNamedPropertyHandler(
  2374. v8::Local<v8::ObjectTemplate> tpl
  2375. , PropertyGetterCallback getter
  2376. , PropertySetterCallback setter = 0
  2377. , PropertyQueryCallback query = 0
  2378. , PropertyDeleterCallback deleter = 0
  2379. , PropertyEnumeratorCallback enumerator = 0
  2380. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2381. HandleScope scope;
  2382. imp::NativePropertyGetter getter_ =
  2383. imp::PropertyGetterCallbackWrapper;
  2384. imp::NativePropertySetter setter_ =
  2385. setter ? imp::PropertySetterCallbackWrapper : 0;
  2386. imp::NativePropertyQuery query_ =
  2387. query ? imp::PropertyQueryCallbackWrapper : 0;
  2388. imp::NativePropertyDeleter *deleter_ =
  2389. deleter ? imp::PropertyDeleterCallbackWrapper : 0;
  2390. imp::NativePropertyEnumerator enumerator_ =
  2391. enumerator ? imp::PropertyEnumeratorCallbackWrapper : 0;
  2392. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2393. otpl->SetInternalFieldCount(imp::kPropertyFieldCount);
  2394. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2395. obj->SetInternalField(
  2396. imp::kPropertyGetterIndex
  2397. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2398. if (setter) {
  2399. obj->SetInternalField(
  2400. imp::kPropertySetterIndex
  2401. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2402. }
  2403. if (query) {
  2404. obj->SetInternalField(
  2405. imp::kPropertyQueryIndex
  2406. , New<v8::External>(reinterpret_cast<void *>(query)));
  2407. }
  2408. if (deleter) {
  2409. obj->SetInternalField(
  2410. imp::kPropertyDeleterIndex
  2411. , New<v8::External>(reinterpret_cast<void *>(deleter)));
  2412. }
  2413. if (enumerator) {
  2414. obj->SetInternalField(
  2415. imp::kPropertyEnumeratorIndex
  2416. , New<v8::External>(reinterpret_cast<void *>(enumerator)));
  2417. }
  2418. if (!data.IsEmpty()) {
  2419. obj->SetInternalField(imp::kDataIndex, data);
  2420. }
  2421. #if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
  2422. tpl->SetHandler(v8::NamedPropertyHandlerConfiguration(
  2423. getter_, setter_, query_, deleter_, enumerator_, obj));
  2424. #else
  2425. tpl->SetNamedPropertyHandler(
  2426. getter_
  2427. , setter_
  2428. , query_
  2429. , deleter_
  2430. , enumerator_
  2431. , obj);
  2432. #endif
  2433. }
  2434. inline void SetIndexedPropertyHandler(
  2435. v8::Local<v8::ObjectTemplate> tpl
  2436. , IndexGetterCallback getter
  2437. , IndexSetterCallback setter = 0
  2438. , IndexQueryCallback query = 0
  2439. , IndexDeleterCallback deleter = 0
  2440. , IndexEnumeratorCallback enumerator = 0
  2441. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2442. HandleScope scope;
  2443. imp::NativeIndexGetter getter_ =
  2444. imp::IndexGetterCallbackWrapper;
  2445. imp::NativeIndexSetter setter_ =
  2446. setter ? imp::IndexSetterCallbackWrapper : 0;
  2447. imp::NativeIndexQuery query_ =
  2448. query ? imp::IndexQueryCallbackWrapper : 0;
  2449. imp::NativeIndexDeleter deleter_ =
  2450. deleter ? imp::IndexDeleterCallbackWrapper : 0;
  2451. imp::NativeIndexEnumerator enumerator_ =
  2452. enumerator ? imp::IndexEnumeratorCallbackWrapper : 0;
  2453. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2454. otpl->SetInternalFieldCount(imp::kIndexPropertyFieldCount);
  2455. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2456. obj->SetInternalField(
  2457. imp::kIndexPropertyGetterIndex
  2458. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2459. if (setter) {
  2460. obj->SetInternalField(
  2461. imp::kIndexPropertySetterIndex
  2462. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2463. }
  2464. if (query) {
  2465. obj->SetInternalField(
  2466. imp::kIndexPropertyQueryIndex
  2467. , New<v8::External>(reinterpret_cast<void *>(query)));
  2468. }
  2469. if (deleter) {
  2470. obj->SetInternalField(
  2471. imp::kIndexPropertyDeleterIndex
  2472. , New<v8::External>(reinterpret_cast<void *>(deleter)));
  2473. }
  2474. if (enumerator) {
  2475. obj->SetInternalField(
  2476. imp::kIndexPropertyEnumeratorIndex
  2477. , New<v8::External>(reinterpret_cast<void *>(enumerator)));
  2478. }
  2479. if (!data.IsEmpty()) {
  2480. obj->SetInternalField(imp::kDataIndex, data);
  2481. }
  2482. #if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
  2483. tpl->SetHandler(v8::IndexedPropertyHandlerConfiguration(
  2484. getter_, setter_, query_, deleter_, enumerator_, obj));
  2485. #else
  2486. tpl->SetIndexedPropertyHandler(
  2487. getter_
  2488. , setter_
  2489. , query_
  2490. , deleter_
  2491. , enumerator_
  2492. , obj);
  2493. #endif
  2494. }
  2495. inline void SetCallHandler(
  2496. v8::Local<v8::FunctionTemplate> tpl
  2497. , FunctionCallback callback
  2498. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2499. HandleScope scope;
  2500. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2501. otpl->SetInternalFieldCount(imp::kFunctionFieldCount);
  2502. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2503. obj->SetInternalField(
  2504. imp::kFunctionIndex
  2505. , New<v8::External>(reinterpret_cast<void *>(callback)));
  2506. if (!data.IsEmpty()) {
  2507. obj->SetInternalField(imp::kDataIndex, data);
  2508. }
  2509. tpl->SetCallHandler(imp::FunctionCallbackWrapper, obj);
  2510. }
  2511. inline void SetCallAsFunctionHandler(
  2512. v8::Local<v8::ObjectTemplate> tpl,
  2513. FunctionCallback callback,
  2514. v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2515. HandleScope scope;
  2516. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2517. otpl->SetInternalFieldCount(imp::kFunctionFieldCount);
  2518. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2519. obj->SetInternalField(
  2520. imp::kFunctionIndex
  2521. , New<v8::External>(reinterpret_cast<void *>(callback)));
  2522. if (!data.IsEmpty()) {
  2523. obj->SetInternalField(imp::kDataIndex, data);
  2524. }
  2525. tpl->SetCallAsFunctionHandler(imp::FunctionCallbackWrapper, obj);
  2526. }
  2527. //=== Weak Persistent Handling =================================================
  2528. #include "nan_weak.h" // NOLINT(build/include)
  2529. //=== ObjectWrap ===============================================================
  2530. #include "nan_object_wrap.h" // NOLINT(build/include)
  2531. //=== HiddenValue/Private ======================================================
  2532. #include "nan_private.h" // NOLINT(build/include)
  2533. //=== Export ==================================================================
  2534. inline
  2535. void
  2536. Export(ADDON_REGISTER_FUNCTION_ARGS_TYPE target, const char *name,
  2537. FunctionCallback f) {
  2538. HandleScope scope;
  2539. Set(target, New<v8::String>(name).ToLocalChecked(),
  2540. GetFunction(New<v8::FunctionTemplate>(f)).ToLocalChecked());
  2541. }
  2542. //=== Tap Reverse Binding =====================================================
  2543. struct Tap {
  2544. explicit Tap(v8::Local<v8::Value> t) : t_() {
  2545. HandleScope scope;
  2546. t_.Reset(To<v8::Object>(t).ToLocalChecked());
  2547. }
  2548. ~Tap() { t_.Reset(); } // not sure if necessary
  2549. inline void plan(int i) {
  2550. HandleScope scope;
  2551. v8::Local<v8::Value> arg = New(i);
  2552. Call("plan", New(t_), 1, &arg);
  2553. }
  2554. inline void ok(bool isOk, const char *msg = NULL) {
  2555. HandleScope scope;
  2556. v8::Local<v8::Value> args[2];
  2557. args[0] = New(isOk);
  2558. if (msg) args[1] = New(msg).ToLocalChecked();
  2559. Call("ok", New(t_), msg ? 2 : 1, args);
  2560. }
  2561. inline void pass(const char * msg = NULL) {
  2562. HandleScope scope;
  2563. v8::Local<v8::Value> hmsg;
  2564. if (msg) hmsg = New(msg).ToLocalChecked();
  2565. Call("pass", New(t_), msg ? 1 : 0, &hmsg);
  2566. }
  2567. inline void end() {
  2568. HandleScope scope;
  2569. Call("end", New(t_), 0, NULL);
  2570. }
  2571. private:
  2572. Persistent<v8::Object> t_;
  2573. };
  2574. #define NAN_STRINGIZE2(x) #x
  2575. #define NAN_STRINGIZE(x) NAN_STRINGIZE2(x)
  2576. #define NAN_TEST_EXPRESSION(expression) \
  2577. ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression
  2578. #define NAN_EXPORT(target, function) Export(target, #function, function)
  2579. #undef TYPE_CHECK
  2580. //=== Generic Maybefication ===================================================
  2581. namespace imp {
  2582. template <typename T> struct Maybefier;
  2583. template <typename T> struct Maybefier<v8::Local<T> > {
  2584. inline static MaybeLocal<T> convert(v8::Local<T> v) {
  2585. return v;
  2586. }
  2587. };
  2588. template <typename T> struct Maybefier<MaybeLocal<T> > {
  2589. inline static MaybeLocal<T> convert(MaybeLocal<T> v) {
  2590. return v;
  2591. }
  2592. };
  2593. } // end of namespace imp
  2594. template <typename T, template <typename> class MaybeMaybe>
  2595. inline MaybeLocal<T>
  2596. MakeMaybe(MaybeMaybe<T> v) {
  2597. return imp::Maybefier<MaybeMaybe<T> >::convert(v);
  2598. }
  2599. //=== TypedArrayContents =======================================================
  2600. #include "nan_typedarray_contents.h" // NOLINT(build/include)
  2601. //=== JSON =====================================================================
  2602. #include "nan_json.h" // NOLINT(build/include)
  2603. //=== ScriptOrigin =============================================================
  2604. #include "nan_scriptorigin.h" // NOLINT(build/include)
  2605. } // end of namespace Nan
  2606. #endif // NAN_H_