@encharm/cws 4.5.3 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/CLAUDE.md +83 -0
  3. package/README.md +20 -4
  4. package/binding.gyp +8 -2
  5. package/dist/bindings/cws_darwin_arm64_node115.node +0 -0
  6. package/dist/bindings/cws_darwin_arm64_node127.node +0 -0
  7. package/dist/bindings/cws_darwin_arm64_node137.node +0 -0
  8. package/dist/bindings/cws_darwin_arm64_node147.node +0 -0
  9. package/dist/bindings/cws_linux_arm64_node115.node +0 -0
  10. package/dist/bindings/cws_linux_arm64_node127.node +0 -0
  11. package/dist/bindings/cws_linux_arm64_node137.node +0 -0
  12. package/dist/bindings/cws_linux_arm64_node147.node +0 -0
  13. package/dist/bindings/cws_linux_x64_node115.node +0 -0
  14. package/dist/bindings/cws_linux_x64_node127.node +0 -0
  15. package/dist/bindings/cws_linux_x64_node137.node +0 -0
  16. package/dist/bindings/cws_linux_x64_node147.node +0 -0
  17. package/dist/bindings/cws_win32_x64_node115.node +0 -0
  18. package/dist/bindings/cws_win32_x64_node127.node +0 -0
  19. package/dist/bindings/cws_win32_x64_node137.node +0 -0
  20. package/dist/bindings/cws_win32_x64_node147.node +0 -0
  21. package/dist/client.d.ts +1 -0
  22. package/dist/client.js +15 -1
  23. package/dist/index.d.ts +6 -1
  24. package/dist/index.js +2 -0
  25. package/dist/server.d.ts +1 -0
  26. package/dist/server.js +16 -2
  27. package/dist/shared.d.ts +1 -0
  28. package/dist/shared.js +3 -2
  29. package/package.json +1 -1
  30. package/src/Addon.cpp +4 -1
  31. package/src/Addon.h +80 -15
  32. package/src/Extensions.cpp +7 -1
  33. package/src/Extensions.h +2 -1
  34. package/src/Group.cpp +1 -1
  35. package/src/Group.h +4 -1
  36. package/src/HTTPSocket.cpp +1 -1
  37. package/src/Hub.cpp +11 -76
  38. package/src/Hub.h +12 -10
  39. package/src/Networking.h +11 -0
  40. package/src/Socket.h +201 -6
  41. package/src/WebSocket.cpp +8 -5
  42. package/src/Zlib.cpp +138 -0
  43. package/src/Zlib.h +38 -0
  44. package/src/cSNode.cpp +2 -0
  45. package/src/cSNode.h +4 -0
  46. package/src/headers/26/acorn_version.h +6 -0
  47. package/src/headers/26/aliased_buffer-inl.h +264 -0
  48. package/src/headers/26/aliased_buffer.h +205 -0
  49. package/src/headers/26/aliased_struct-inl.h +143 -0
  50. package/src/headers/26/aliased_struct.h +248 -0
  51. package/src/headers/26/amaro_version.h +6 -0
  52. package/src/headers/26/async_context_frame.h +33 -0
  53. package/src/headers/26/async_wrap-inl.h +123 -0
  54. package/src/headers/26/async_wrap.h +254 -0
  55. package/src/headers/26/base_object-inl.h +333 -0
  56. package/src/headers/26/base_object.h +339 -0
  57. package/src/headers/26/base_object_types.h +76 -0
  58. package/src/headers/26/blob_serializer_deserializer-inl.h +385 -0
  59. package/src/headers/26/blob_serializer_deserializer.h +142 -0
  60. package/src/headers/26/builtin_info.h +57 -0
  61. package/src/headers/26/callback_queue-inl.h +97 -0
  62. package/src/headers/26/callback_queue.h +79 -0
  63. package/src/headers/26/cares_wrap.h +475 -0
  64. package/src/headers/26/cleanup_queue-inl.h +36 -0
  65. package/src/headers/26/cleanup_queue.h +79 -0
  66. package/src/headers/26/compile_cache.h +134 -0
  67. package/src/headers/26/connect_wrap.h +26 -0
  68. package/src/headers/26/connection_wrap.h +30 -0
  69. package/src/headers/26/cppgc_helpers-inl.h +69 -0
  70. package/src/headers/26/cppgc_helpers.h +162 -0
  71. package/src/headers/26/crypto/crypto_aes.h +107 -0
  72. package/src/headers/26/crypto/crypto_argon2.h +88 -0
  73. package/src/headers/26/crypto/crypto_bio.h +193 -0
  74. package/src/headers/26/crypto/crypto_chacha20_poly1305.h +62 -0
  75. package/src/headers/26/crypto/crypto_cipher.h +291 -0
  76. package/src/headers/26/crypto/crypto_common.h +48 -0
  77. package/src/headers/26/crypto/crypto_context.h +219 -0
  78. package/src/headers/26/crypto/crypto_dh.h +104 -0
  79. package/src/headers/26/crypto/crypto_dsa.h +50 -0
  80. package/src/headers/26/crypto/crypto_ec.h +102 -0
  81. package/src/headers/26/crypto/crypto_hash.h +157 -0
  82. package/src/headers/26/crypto/crypto_hkdf.h +62 -0
  83. package/src/headers/26/crypto/crypto_hmac.h +92 -0
  84. package/src/headers/26/crypto/crypto_kem.h +131 -0
  85. package/src/headers/26/crypto/crypto_keygen.h +382 -0
  86. package/src/headers/26/crypto/crypto_keys.h +366 -0
  87. package/src/headers/26/crypto/crypto_kmac.h +79 -0
  88. package/src/headers/26/crypto/crypto_pbkdf2.h +76 -0
  89. package/src/headers/26/crypto/crypto_pqc.h +39 -0
  90. package/src/headers/26/crypto/crypto_random.h +127 -0
  91. package/src/headers/26/crypto/crypto_rsa.h +108 -0
  92. package/src/headers/26/crypto/crypto_scrypt.h +85 -0
  93. package/src/headers/26/crypto/crypto_sig.h +159 -0
  94. package/src/headers/26/crypto/crypto_spkac.h +21 -0
  95. package/src/headers/26/crypto/crypto_timing.h +20 -0
  96. package/src/headers/26/crypto/crypto_tls.h +342 -0
  97. package/src/headers/26/crypto/crypto_turboshake.h +105 -0
  98. package/src/headers/26/crypto/crypto_util.h +775 -0
  99. package/src/headers/26/crypto/crypto_x509.h +140 -0
  100. package/src/headers/26/dataqueue/queue.h +311 -0
  101. package/src/headers/26/debug_utils-inl.h +291 -0
  102. package/src/headers/26/debug_utils.h +200 -0
  103. package/src/headers/26/diagnosticfilename-inl.h +33 -0
  104. package/src/headers/26/embedded_data.h +17 -0
  105. package/src/headers/26/encoding_binding.h +59 -0
  106. package/src/headers/26/env-inl.h +956 -0
  107. package/src/headers/26/env.h +1294 -0
  108. package/src/headers/26/env_properties.h +562 -0
  109. package/src/headers/26/ffi/data.h +30 -0
  110. package/src/headers/26/ffi/fast.h +96 -0
  111. package/src/headers/26/ffi/jit_memory.h +26 -0
  112. package/src/headers/26/ffi/types.h +99 -0
  113. package/src/headers/26/handle_wrap.h +123 -0
  114. package/src/headers/26/histogram-inl.h +211 -0
  115. package/src/headers/26/histogram.h +474 -0
  116. package/src/headers/26/inspector/dom_storage_agent.h +68 -0
  117. package/src/headers/26/inspector/inspector_object_utils.h +38 -0
  118. package/src/headers/26/inspector/io_agent.h +30 -0
  119. package/src/headers/26/inspector/main_thread_interface.h +116 -0
  120. package/src/headers/26/inspector/network_agent.h +110 -0
  121. package/src/headers/26/inspector/network_inspector.h +45 -0
  122. package/src/headers/26/inspector/network_requests_buffer.h +195 -0
  123. package/src/headers/26/inspector/network_resource_manager.h +29 -0
  124. package/src/headers/26/inspector/node_json.h +24 -0
  125. package/src/headers/26/inspector/node_string.h +101 -0
  126. package/src/headers/26/inspector/notification_emitter.h +38 -0
  127. package/src/headers/26/inspector/protocol_helper.h +27 -0
  128. package/src/headers/26/inspector/runtime_agent.h +41 -0
  129. package/src/headers/26/inspector/storage_agent.h +33 -0
  130. package/src/headers/26/inspector/target_agent.h +59 -0
  131. package/src/headers/26/inspector/target_manager.h +70 -0
  132. package/src/headers/26/inspector/tracing_agent.h +43 -0
  133. package/src/headers/26/inspector/worker_agent.h +40 -0
  134. package/src/headers/26/inspector/worker_inspector.h +124 -0
  135. package/src/headers/26/inspector_agent.h +168 -0
  136. package/src/headers/26/inspector_io.h +78 -0
  137. package/src/headers/26/inspector_profiler.h +149 -0
  138. package/src/headers/26/inspector_socket.h +60 -0
  139. package/src/headers/26/inspector_socket_server.h +110 -0
  140. package/src/headers/26/js_native_api.h +634 -0
  141. package/src/headers/26/js_native_api_types.h +244 -0
  142. package/src/headers/26/js_native_api_v8.h +485 -0
  143. package/src/headers/26/js_native_api_v8_internals.h +45 -0
  144. package/src/headers/26/js_stream.h +57 -0
  145. package/src/headers/26/json_utils.h +172 -0
  146. package/src/headers/26/large_pages/node_large_page.h +34 -0
  147. package/src/headers/26/lru_cache-inl.h +69 -0
  148. package/src/headers/26/memory_tracker-inl.h +461 -0
  149. package/src/headers/26/memory_tracker.h +341 -0
  150. package/src/headers/26/module_wrap.h +231 -0
  151. package/src/headers/26/ncrypto.h +2008 -0
  152. package/src/headers/26/node.h +1693 -0
  153. package/src/headers/26/node_api.h +265 -0
  154. package/src/headers/26/node_api_internals.h +48 -0
  155. package/src/headers/26/node_api_types.h +58 -0
  156. package/src/headers/26/node_binding.h +170 -0
  157. package/src/headers/26/node_blob.h +160 -0
  158. package/src/headers/26/node_bob-inl.h +36 -0
  159. package/src/headers/26/node_bob.h +107 -0
  160. package/src/headers/26/node_buffer.h +92 -0
  161. package/src/headers/26/node_builtins.h +239 -0
  162. package/src/headers/26/node_concepts.h +46 -0
  163. package/src/headers/26/node_config_file.h +77 -0
  164. package/src/headers/26/node_constants.h +82 -0
  165. package/src/headers/26/node_context_data.h +171 -0
  166. package/src/headers/26/node_contextify.h +261 -0
  167. package/src/headers/26/node_crypto.h +66 -0
  168. package/src/headers/26/node_debug.h +30 -0
  169. package/src/headers/26/node_diagnostics_channel.h +121 -0
  170. package/src/headers/26/node_dir.h +52 -0
  171. package/src/headers/26/node_dotenv.h +45 -0
  172. package/src/headers/26/node_errors.h +378 -0
  173. package/src/headers/26/node_exit_code.h +54 -0
  174. package/src/headers/26/node_external_reference.h +171 -0
  175. package/src/headers/26/node_ffi.h +212 -0
  176. package/src/headers/26/node_file-inl.h +421 -0
  177. package/src/headers/26/node_file.h +561 -0
  178. package/src/headers/26/node_file_utils.h +39 -0
  179. package/src/headers/26/node_hash.h +212 -0
  180. package/src/headers/26/node_http2.h +1202 -0
  181. package/src/headers/26/node_http2_state.h +159 -0
  182. package/src/headers/26/node_http_common-inl.h +199 -0
  183. package/src/headers/26/node_http_common.h +535 -0
  184. package/src/headers/26/node_i18n.h +132 -0
  185. package/src/headers/26/node_internals.h +485 -0
  186. package/src/headers/26/node_locks.h +184 -0
  187. package/src/headers/26/node_main_instance.h +67 -0
  188. package/src/headers/26/node_mem-inl.h +113 -0
  189. package/src/headers/26/node_mem.h +45 -0
  190. package/src/headers/26/node_messaging.h +389 -0
  191. package/src/headers/26/node_metadata.h +172 -0
  192. package/src/headers/26/node_modules.h +102 -0
  193. package/src/headers/26/node_mutex.h +323 -0
  194. package/src/headers/26/node_object_wrap.h +145 -0
  195. package/src/headers/26/node_options-inl.h +524 -0
  196. package/src/headers/26/node_options.h +710 -0
  197. package/src/headers/26/node_perf.h +167 -0
  198. package/src/headers/26/node_perf_common.h +103 -0
  199. package/src/headers/26/node_platform.h +290 -0
  200. package/src/headers/26/node_process-inl.h +26 -0
  201. package/src/headers/26/node_process.h +112 -0
  202. package/src/headers/26/node_profiling.h +38 -0
  203. package/src/headers/26/node_realm-inl.h +156 -0
  204. package/src/headers/26/node_realm.h +236 -0
  205. package/src/headers/26/node_report.h +43 -0
  206. package/src/headers/26/node_revert.h +82 -0
  207. package/src/headers/26/node_root_certs.h +2937 -0
  208. package/src/headers/26/node_sea.h +101 -0
  209. package/src/headers/26/node_shadow_realm.h +46 -0
  210. package/src/headers/26/node_snapshot_builder.h +57 -0
  211. package/src/headers/26/node_snapshotable.h +167 -0
  212. package/src/headers/26/node_sockaddr-inl.h +248 -0
  213. package/src/headers/26/node_sockaddr.h +459 -0
  214. package/src/headers/26/node_sqlite.h +607 -0
  215. package/src/headers/26/node_stat_watcher.h +73 -0
  216. package/src/headers/26/node_task_runner.h +92 -0
  217. package/src/headers/26/node_threadsafe_cow-inl.h +54 -0
  218. package/src/headers/26/node_threadsafe_cow.h +105 -0
  219. package/src/headers/26/node_union_bytes.h +81 -0
  220. package/src/headers/26/node_url.h +101 -0
  221. package/src/headers/26/node_url_pattern.h +118 -0
  222. package/src/headers/26/node_v8.h +78 -0
  223. package/src/headers/26/node_v8_embedder.h +26 -0
  224. package/src/headers/26/node_v8_platform-inl.h +96 -0
  225. package/src/headers/26/node_version.h +116 -0
  226. package/src/headers/26/node_wasi.h +184 -0
  227. package/src/headers/26/node_wasm_web_api.h +55 -0
  228. package/src/headers/26/node_watchdog.h +164 -0
  229. package/src/headers/26/node_webstorage.h +62 -0
  230. package/src/headers/26/node_worker.h +162 -0
  231. package/src/headers/26/path.h +36 -0
  232. package/src/headers/26/permission/boolean_permission.h +50 -0
  233. package/src/headers/26/permission/fs_permission.h +192 -0
  234. package/src/headers/26/permission/permission.h +155 -0
  235. package/src/headers/26/permission/permission_base.h +79 -0
  236. package/src/headers/26/pipe_wrap.h +80 -0
  237. package/src/headers/26/quic/application.h +279 -0
  238. package/src/headers/26/quic/arena.h +373 -0
  239. package/src/headers/26/quic/bindingdata.h +440 -0
  240. package/src/headers/26/quic/cid.h +127 -0
  241. package/src/headers/26/quic/data.h +358 -0
  242. package/src/headers/26/quic/defs.h +417 -0
  243. package/src/headers/26/quic/endpoint.h +519 -0
  244. package/src/headers/26/quic/guard.h +5 -0
  245. package/src/headers/26/quic/http3.h +25 -0
  246. package/src/headers/26/quic/packet.h +166 -0
  247. package/src/headers/26/quic/preferredaddress.h +72 -0
  248. package/src/headers/26/quic/session.h +770 -0
  249. package/src/headers/26/quic/session_manager.h +107 -0
  250. package/src/headers/26/quic/sessionticket.h +110 -0
  251. package/src/headers/26/quic/streams.h +518 -0
  252. package/src/headers/26/quic/tlscontext.h +353 -0
  253. package/src/headers/26/quic/tokens.h +263 -0
  254. package/src/headers/26/quic/transportparams.h +184 -0
  255. package/src/headers/26/req_wrap-inl.h +175 -0
  256. package/src/headers/26/req_wrap.h +79 -0
  257. package/src/headers/26/spawn_sync.h +243 -0
  258. package/src/headers/26/stream_base-inl.h +170 -0
  259. package/src/headers/26/stream_base.h +487 -0
  260. package/src/headers/26/stream_pipe.h +76 -0
  261. package/src/headers/26/stream_wrap.h +137 -0
  262. package/src/headers/26/string_bytes.h +114 -0
  263. package/src/headers/26/string_decoder-inl.h +31 -0
  264. package/src/headers/26/string_decoder.h +49 -0
  265. package/src/headers/26/tcp_wrap.h +138 -0
  266. package/src/headers/26/threadpoolwork-inl.h +70 -0
  267. package/src/headers/26/timer_wrap-inl.h +32 -0
  268. package/src/headers/26/timer_wrap.h +87 -0
  269. package/src/headers/26/timers.h +70 -0
  270. package/src/headers/26/tracing/agent.h +125 -0
  271. package/src/headers/26/tracing/agent_legacy.h +146 -0
  272. package/src/headers/26/tracing/agent_perfetto.h +145 -0
  273. package/src/headers/26/tracing/node_trace_buffer.h +91 -0
  274. package/src/headers/26/tracing/node_trace_writer.h +79 -0
  275. package/src/headers/26/tracing/trace_event.h +27 -0
  276. package/src/headers/26/tracing/trace_event_helper.h +40 -0
  277. package/src/headers/26/tracing/trace_event_legacy.h +1113 -0
  278. package/src/headers/26/tracing/trace_event_legacy_inl.h +711 -0
  279. package/src/headers/26/tracing/trace_event_perfetto.h +47 -0
  280. package/src/headers/26/tracing/traced_value.h +167 -0
  281. package/src/headers/26/tty_wrap.h +65 -0
  282. package/src/headers/26/udp_wrap.h +231 -0
  283. package/src/headers/26/undici_version.h +6 -0
  284. package/src/headers/26/util-inl.h +788 -0
  285. package/src/headers/26/util.h +1207 -0
  286. package/src/headers/26/v8-cpp-heap-external.h +56 -0
  287. package/src/headers/26/v8-external-memory-accounter.h +60 -0
  288. package/src/headers/26/v8-fast-api-calls.h +784 -0
  289. package/src/headers/26/v8-inspector-protocol.h +13 -0
  290. package/src/headers/26/v8-inspector.h +458 -0
  291. package/src/headers/26/v8-metrics.h +273 -0
  292. package/src/headers/26/v8-trace-categories.h +28 -0
  293. package/src/headers/26/v8-unwinder-state.h +30 -0
  294. package/src/headers/26/v8-util.h +549 -0
  295. package/src/headers/26/v8-value-serializer-version.h +24 -0
  296. package/src/headers/26/v8-version-string.h +38 -0
  297. package/src/headers/26/v8-wasm-trap-handler-posix.h +31 -0
  298. package/src/headers/26/v8-wasm-trap-handler-win.h +28 -0
  299. package/src/headers/26/zlib_version.h +6 -0
  300. package/dist/bindings/cws_darwin_arm64_node115.node.dSYM/Contents/Info.plist +0 -20
  301. package/dist/bindings/cws_darwin_arm64_node115.node.dSYM/Contents/Resources/DWARF/cws_darwin_arm64_node115.node +0 -0
  302. package/dist/bindings/cws_darwin_arm64_node115.node.dSYM/Contents/Resources/Relocations/aarch64/cws_darwin_arm64_node115.node.yml +0 -931
  303. package/dist/bindings/cws_darwin_arm64_node127.node.dSYM/Contents/Info.plist +0 -20
  304. package/dist/bindings/cws_darwin_arm64_node127.node.dSYM/Contents/Resources/DWARF/cws_darwin_arm64_node127.node +0 -0
  305. package/dist/bindings/cws_darwin_arm64_node127.node.dSYM/Contents/Resources/Relocations/aarch64/cws_darwin_arm64_node127.node.yml +0 -931
@@ -0,0 +1,1693 @@
1
+ // Copyright Joyent, Inc. and other Node contributors.
2
+ //
3
+ // Permission is hereby granted, free of charge, to any person obtaining a
4
+ // copy of this software and associated documentation files (the
5
+ // "Software"), to deal in the Software without restriction, including
6
+ // without limitation the rights to use, copy, modify, merge, publish,
7
+ // distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ // persons to whom the Software is furnished to do so, subject to the
9
+ // following conditions:
10
+ //
11
+ // The above copyright notice and this permission notice shall be included
12
+ // in all copies or substantial portions of the Software.
13
+ //
14
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
+ // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
+ // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
+ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
+ // USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ #ifndef SRC_NODE_H_
23
+ #define SRC_NODE_H_
24
+
25
+ #ifdef _WIN32
26
+ # ifndef BUILDING_NODE_EXTENSION
27
+ # define NODE_EXTERN __declspec(dllexport)
28
+ # else
29
+ # define NODE_EXTERN __declspec(dllimport)
30
+ # endif
31
+ #else
32
+ # define NODE_EXTERN __attribute__((visibility("default")))
33
+ #endif
34
+
35
+ // Declarations annotated with NODE_EXTERN_PRIVATE do not form part of
36
+ // the public API. They are implementation details that can and will
37
+ // change between releases, even in semver patch releases. Do not use
38
+ // any such symbol in external code.
39
+ #ifdef NODE_SHARED_MODE
40
+ #define NODE_EXTERN_PRIVATE NODE_EXTERN
41
+ #else
42
+ #define NODE_EXTERN_PRIVATE
43
+ #endif
44
+
45
+ #ifdef BUILDING_NODE_EXTENSION
46
+ # undef BUILDING_V8_SHARED
47
+ # undef BUILDING_UV_SHARED
48
+ # define USING_V8_SHARED 1
49
+ # define USING_UV_SHARED 1
50
+ #endif
51
+
52
+ // This should be defined in make system.
53
+ // See issue https://github.com/nodejs/node-v0.x-archive/issues/1236
54
+ #if defined(__MINGW32__) || defined(_MSC_VER)
55
+ #ifndef _WIN32_WINNT
56
+ # define _WIN32_WINNT 0x0600 // Windows Server 2008
57
+ #endif
58
+
59
+ #ifndef NOMINMAX
60
+ # define NOMINMAX
61
+ #endif
62
+
63
+ #endif
64
+
65
+ #if defined(_MSC_VER)
66
+ #define PATH_MAX MAX_PATH
67
+ #endif
68
+
69
+ #ifdef _WIN32
70
+ #define SIGQUIT 3
71
+ #define SIGKILL 9
72
+ #endif
73
+
74
+ #include "v8.h" // NOLINT(build/include_order)
75
+
76
+ #include "v8-platform.h" // NOLINT(build/include_order)
77
+ #include "node_version.h" // NODE_MODULE_VERSION
78
+
79
+ #include "node_api_types.h" // napi_addon_register_func
80
+
81
+ #include <functional>
82
+ #include <memory>
83
+ #include <optional>
84
+ #include <ostream>
85
+
86
+ // We cannot use __POSIX__ in this header because that's only defined when
87
+ // building Node.js.
88
+ #ifndef _WIN32
89
+ #include <signal.h>
90
+ #endif // _WIN32
91
+
92
+ #define NODE_MAKE_VERSION(major, minor, patch) \
93
+ ((major) * 0x1000 + (minor) * 0x100 + (patch))
94
+
95
+ #ifdef __clang__
96
+ # define NODE_CLANG_AT_LEAST(major, minor, patch) \
97
+ (NODE_MAKE_VERSION(major, minor, patch) <= \
98
+ NODE_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__))
99
+ #else
100
+ # define NODE_CLANG_AT_LEAST(major, minor, patch) (0)
101
+ #endif
102
+
103
+ #ifdef __GNUC__
104
+ # define NODE_GNUC_AT_LEAST(major, minor, patch) \
105
+ (NODE_MAKE_VERSION(major, minor, patch) <= \
106
+ NODE_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__))
107
+ #else
108
+ # define NODE_GNUC_AT_LEAST(major, minor, patch) (0)
109
+ #endif
110
+
111
+ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
112
+ # define NODE_DEPRECATED(message, declarator) declarator
113
+ #else // NODE_WANT_INTERNALS
114
+ #define NODE_DEPRECATED(message, declarator) [[deprecated(message)]] declarator
115
+ #endif
116
+
117
+ // Forward-declare libuv loop
118
+ struct uv_loop_s;
119
+ struct napi_module;
120
+ struct ssl_ctx_st; // Forward declaration of SSL_CTX for OpenSSL.
121
+
122
+ // Forward-declare these functions now to stop MSVS from becoming
123
+ // terminally confused when it's done in node_internals.h
124
+ namespace node {
125
+
126
+ struct SnapshotData;
127
+
128
+ namespace tracing {
129
+
130
+ class TracingController;
131
+
132
+ }
133
+
134
+ NODE_EXTERN v8::Local<v8::Value> ErrnoException(v8::Isolate* isolate,
135
+ int errorno,
136
+ const char* syscall = nullptr,
137
+ const char* message = nullptr,
138
+ const char* path = nullptr);
139
+ NODE_EXTERN v8::Local<v8::Value> UVException(v8::Isolate* isolate,
140
+ int errorno,
141
+ const char* syscall = nullptr,
142
+ const char* message = nullptr,
143
+ const char* path = nullptr,
144
+ const char* dest = nullptr);
145
+
146
+ NODE_DEPRECATED("Use ErrnoException(isolate, ...)",
147
+ inline v8::Local<v8::Value> ErrnoException(
148
+ int errorno,
149
+ const char* syscall = nullptr,
150
+ const char* message = nullptr,
151
+ const char* path = nullptr) {
152
+ return ErrnoException(v8::Isolate::GetCurrent(),
153
+ errorno,
154
+ syscall,
155
+ message,
156
+ path);
157
+ })
158
+
159
+ NODE_DEPRECATED("Use UVException(isolate, ...)",
160
+ inline v8::Local<v8::Value> UVException(int errorno,
161
+ const char* syscall = nullptr,
162
+ const char* message = nullptr,
163
+ const char* path = nullptr) {
164
+ return UVException(v8::Isolate::GetCurrent(),
165
+ errorno,
166
+ syscall,
167
+ message,
168
+ path);
169
+ })
170
+
171
+ } // namespace node
172
+
173
+ #include <cassert>
174
+ #include <cstdint>
175
+
176
+ #ifndef NODE_STRINGIFY
177
+ # define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n)
178
+ # define NODE_STRINGIFY_HELPER(n) #n
179
+ #endif
180
+
181
+ #ifdef _WIN32
182
+ #if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED)
183
+ typedef intptr_t ssize_t;
184
+ # define _SSIZE_T_
185
+ # define _SSIZE_T_DEFINED
186
+ #endif
187
+ #else // !_WIN32
188
+ # include <sys/types.h> // size_t, ssize_t
189
+ #endif // _WIN32
190
+
191
+
192
+ namespace node {
193
+
194
+ class IsolateData;
195
+ class Environment;
196
+ class MultiIsolatePlatform;
197
+ class InitializationResultImpl;
198
+
199
+ namespace ProcessInitializationFlags {
200
+ enum Flags : uint32_t {
201
+ kNoFlags = 0,
202
+ // Enable stdio inheritance, which is disabled by default.
203
+ // This flag is also implied by kNoStdioInitialization.
204
+ kEnableStdioInheritance = 1 << 0,
205
+ // Disable reading the NODE_OPTIONS environment variable.
206
+ kDisableNodeOptionsEnv = 1 << 1,
207
+ // Do not parse CLI options.
208
+ kDisableCLIOptions = 1 << 2,
209
+ // Do not initialize ICU.
210
+ kNoICU = 1 << 3,
211
+ // Do not modify stdio file descriptor or TTY state.
212
+ kNoStdioInitialization = 1 << 4,
213
+ // Do not register Node.js-specific signal handlers
214
+ // and reset other signal handlers to default state.
215
+ kNoDefaultSignalHandling = 1 << 5,
216
+ // Do not perform V8 initialization.
217
+ kNoInitializeV8 = 1 << 6,
218
+ // Do not initialize a default Node.js-provided V8 platform instance.
219
+ kNoInitializeNodeV8Platform = 1 << 7,
220
+ // Do not initialize OpenSSL config.
221
+ kNoInitOpenSSL = 1 << 8,
222
+ // Do not initialize Node.js debugging based on environment variables.
223
+ kNoParseGlobalDebugVariables = 1 << 9,
224
+ // Do not adjust OS resource limits for this process.
225
+ kNoAdjustResourceLimits = 1 << 10,
226
+ // Do not map code segments into large pages for this process.
227
+ kNoUseLargePages = 1 << 11,
228
+ // Skip printing output for --help, --version, --v8-options.
229
+ kNoPrintHelpOrVersionOutput = 1 << 12,
230
+ // Do not perform cppgc initialization. If set, the embedder must call
231
+ // cppgc::InitializeProcess() before creating a Node.js environment
232
+ // and call cppgc::ShutdownProcess() before process shutdown.
233
+ kNoInitializeCppgc = 1 << 13,
234
+ // Initialize the process for predictable snapshot generation.
235
+ kGeneratePredictableSnapshot = 1 << 14,
236
+
237
+ // Emulate the behavior of InitializeNodeWithArgs() when passing
238
+ // a flags argument to the InitializeOncePerProcess() replacement
239
+ // function.
240
+ kLegacyInitializeNodeWithArgsBehavior =
241
+ kNoStdioInitialization | kNoDefaultSignalHandling | kNoInitializeV8 |
242
+ kNoInitializeNodeV8Platform | kNoInitOpenSSL |
243
+ kNoParseGlobalDebugVariables | kNoAdjustResourceLimits |
244
+ kNoUseLargePages | kNoPrintHelpOrVersionOutput | kNoInitializeCppgc,
245
+ };
246
+ } // namespace ProcessInitializationFlags
247
+ namespace ProcessFlags = ProcessInitializationFlags; // Legacy alias.
248
+
249
+ namespace StopFlags {
250
+ enum Flags : uint32_t {
251
+ kNoFlags = 0,
252
+ // Do not explicitly terminate the Isolate
253
+ // when exiting the Environment.
254
+ kDoNotTerminateIsolate = 1 << 0,
255
+ };
256
+ } // namespace StopFlags
257
+
258
+ class NODE_EXTERN InitializationResult {
259
+ public:
260
+ virtual ~InitializationResult() = default;
261
+
262
+ // Returns a suggested process exit code.
263
+ virtual int exit_code() const = 0;
264
+
265
+ // Returns 'true' if initialization was aborted early due to errors.
266
+ virtual bool early_return() const = 0;
267
+
268
+ // Returns the parsed list of non-Node.js arguments.
269
+ virtual const std::vector<std::string>& args() const = 0;
270
+
271
+ // Returns the parsed list of Node.js arguments.
272
+ virtual const std::vector<std::string>& exec_args() const = 0;
273
+
274
+ // Returns an array of errors. Note that these may be warnings
275
+ // whose existence does not imply a non-zero exit code.
276
+ virtual const std::vector<std::string>& errors() const = 0;
277
+
278
+ // If kNoInitializeNodeV8Platform was not specified, the global Node.js
279
+ // platform instance.
280
+ virtual MultiIsolatePlatform* platform() const = 0;
281
+
282
+ private:
283
+ InitializationResult() = default;
284
+ friend class InitializationResultImpl;
285
+ };
286
+
287
+ // TODO(addaleax): Officially deprecate this and replace it with something
288
+ // better suited for a public embedder API.
289
+ NODE_EXTERN int Start(int argc, char* argv[]);
290
+
291
+ // Tear down Node.js while it is running (there are active handles
292
+ // in the loop and / or actively executing JavaScript code).
293
+ NODE_EXTERN int Stop(Environment* env,
294
+ StopFlags::Flags flags = StopFlags::kNoFlags);
295
+
296
+ // Set up per-process state needed to run Node.js. This will consume arguments
297
+ // from args, and return information about the initialization success,
298
+ // including the arguments split into argv/exec_argv, a list of potential
299
+ // errors encountered during initialization, and a potential suggested
300
+ // exit code.
301
+ NODE_EXTERN std::shared_ptr<InitializationResult> InitializeOncePerProcess(
302
+ const std::vector<std::string>& args,
303
+ ProcessInitializationFlags::Flags flags =
304
+ ProcessInitializationFlags::kNoFlags);
305
+ // Undoes the initialization performed by InitializeOncePerProcess(),
306
+ // where cleanup is necessary.
307
+ NODE_EXTERN void TearDownOncePerProcess();
308
+ // Convenience overload for specifying multiple flags without having
309
+ // to worry about casts.
310
+ inline std::shared_ptr<InitializationResult> InitializeOncePerProcess(
311
+ const std::vector<std::string>& args,
312
+ std::initializer_list<ProcessInitializationFlags::Flags> list) {
313
+ uint64_t flags_accum = ProcessInitializationFlags::kNoFlags;
314
+ for (const auto flag : list) flags_accum |= static_cast<uint64_t>(flag);
315
+ return InitializeOncePerProcess(
316
+ args, static_cast<ProcessInitializationFlags::Flags>(flags_accum));
317
+ }
318
+
319
+ enum OptionEnvvarSettings {
320
+ // Allow the options to be set via the environment variable, like
321
+ // `NODE_OPTIONS`.
322
+ kAllowedInEnvvar = 0,
323
+ // Disallow the options to be set via the environment variable, like
324
+ // `NODE_OPTIONS`.
325
+ kDisallowedInEnvvar = 1,
326
+ };
327
+
328
+ // Process the arguments and set up the per-process options.
329
+ // If the `settings` is set as OptionEnvvarSettings::kAllowedInEnvvar, the
330
+ // options that are allowed in the environment variable are processed. Options
331
+ // that are disallowed to be set via environment variable are processed as
332
+ // errors.
333
+ // Otherwise all the options that are disallowed (and those are allowed) to be
334
+ // set via environment variable are processed.
335
+ NODE_EXTERN int ProcessGlobalArgs(std::vector<std::string>* args,
336
+ std::vector<std::string>* exec_args,
337
+ std::vector<std::string>* errors,
338
+ OptionEnvvarSettings settings);
339
+
340
+ class NodeArrayBufferAllocator;
341
+
342
+ // An ArrayBuffer::Allocator class with some Node.js-specific tweaks. If you do
343
+ // not have to use another allocator, using this class is recommended:
344
+ // - It supports Buffer.allocUnsafe() and Buffer.allocUnsafeSlow() with
345
+ // uninitialized memory.
346
+ // - It supports transferring, rather than copying, ArrayBuffers when using
347
+ // MessagePorts.
348
+ class NODE_EXTERN ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
349
+ public:
350
+ // If `always_debug` is true, create an ArrayBuffer::Allocator instance
351
+ // that performs additional integrity checks (e.g. make sure that only memory
352
+ // that was allocated by the it is also freed by it).
353
+ // This can also be set using the --debug-arraybuffer-allocations flag.
354
+ static std::unique_ptr<ArrayBufferAllocator> Create(
355
+ bool always_debug = false);
356
+
357
+ private:
358
+ virtual NodeArrayBufferAllocator* GetImpl() = 0;
359
+
360
+ friend class IsolateData;
361
+ };
362
+
363
+ // Legacy equivalents for ArrayBufferAllocator::Create().
364
+ NODE_EXTERN ArrayBufferAllocator* CreateArrayBufferAllocator();
365
+ NODE_EXTERN void FreeArrayBufferAllocator(ArrayBufferAllocator* allocator);
366
+
367
+ class NODE_EXTERN IsolatePlatformDelegate {
368
+ public:
369
+ virtual std::shared_ptr<v8::TaskRunner> GetForegroundTaskRunner() = 0;
370
+ virtual bool IdleTasksEnabled() = 0;
371
+ };
372
+
373
+ class NODE_EXTERN MultiIsolatePlatform : public v8::Platform {
374
+ public:
375
+ ~MultiIsolatePlatform() override = default;
376
+ // Returns true if work was dispatched or executed. New tasks that are
377
+ // posted during flushing of the queue are postponed until the next
378
+ // flushing.
379
+ virtual bool FlushForegroundTasks(v8::Isolate* isolate) = 0;
380
+ virtual void DrainTasks(v8::Isolate* isolate) = 0;
381
+
382
+ // This needs to be called between the calls to `Isolate::Allocate()` and
383
+ // `Isolate::Initialize()`, so that initialization can already start
384
+ // using the platform.
385
+ // When using `NewIsolate()`, this is taken care of by that function.
386
+ // This function may only be called once per `Isolate`.
387
+ virtual void RegisterIsolate(v8::Isolate* isolate,
388
+ struct uv_loop_s* loop) = 0;
389
+ // This method can be used when an application handles task scheduling on its
390
+ // own through `IsolatePlatformDelegate`. Upon registering an isolate with
391
+ // this overload any other method in this class with the exception of
392
+ // `UnregisterIsolate` *must not* be used on that isolate.
393
+ virtual void RegisterIsolate(v8::Isolate* isolate,
394
+ IsolatePlatformDelegate* delegate) = 0;
395
+
396
+ // This function may only be called once per `Isolate`, and discard any
397
+ // pending delayed tasks scheduled for that isolate.
398
+ // This needs to be called right after calling `Isolate::Dispose()`.
399
+ virtual void UnregisterIsolate(v8::Isolate* isolate) = 0;
400
+ // This disposes, unregisters and frees up an isolate that's allocated using
401
+ // v8::Isolate::Allocate() in the correct order to prevent race conditions.
402
+ void DisposeIsolate(v8::Isolate* isolate);
403
+
404
+ // The platform should call the passed function once all state associated
405
+ // with the given isolate has been cleaned up. This can, but does not have to,
406
+ // happen asynchronously.
407
+ virtual void AddIsolateFinishedCallback(v8::Isolate* isolate,
408
+ void (*callback)(void*),
409
+ void* data) = 0;
410
+
411
+ static std::unique_ptr<MultiIsolatePlatform> Create(
412
+ int thread_pool_size,
413
+ v8::TracingController* tracing_controller = nullptr,
414
+ v8::PageAllocator* page_allocator = nullptr);
415
+ };
416
+
417
+ enum IsolateSettingsFlags {
418
+ MESSAGE_LISTENER_WITH_ERROR_LEVEL = 1 << 0,
419
+ DETAILED_SOURCE_POSITIONS_FOR_PROFILING = 1 << 1,
420
+ SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK = 1 << 2,
421
+ SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK = 1 << 3,
422
+ ALLOW_MODIFY_CODE_GENERATION_FROM_STRINGS_CALLBACK = 0, /* legacy no-op */
423
+ };
424
+
425
+ struct IsolateSettings {
426
+ uint64_t flags = MESSAGE_LISTENER_WITH_ERROR_LEVEL |
427
+ DETAILED_SOURCE_POSITIONS_FOR_PROFILING;
428
+ v8::MicrotasksPolicy policy = v8::MicrotasksPolicy::kExplicit;
429
+
430
+ // Error handling callbacks
431
+ v8::Isolate::AbortOnUncaughtExceptionCallback
432
+ should_abort_on_uncaught_exception_callback = nullptr;
433
+ v8::FatalErrorCallback fatal_error_callback = nullptr;
434
+ v8::OOMErrorCallback oom_error_callback = nullptr;
435
+ v8::PrepareStackTraceCallback prepare_stack_trace_callback = nullptr;
436
+
437
+ // Miscellaneous callbacks
438
+ v8::PromiseRejectCallback promise_reject_callback = nullptr;
439
+ v8::AllowWasmCodeGenerationCallback
440
+ allow_wasm_code_generation_callback = nullptr;
441
+ v8::ModifyCodeGenerationFromStringsCallback2
442
+ modify_code_generation_from_strings_callback = nullptr;
443
+
444
+ // When the settings is passed to NewIsolate():
445
+ // - If cpp_heap is not nullptr, this CppHeap will be used to create
446
+ // the isolate and its ownership will be passed to V8.
447
+ // - If this is nullptr, Node.js will create a CppHeap that will be
448
+ // owned by V8.
449
+ //
450
+ // When the settings is passed to SetIsolateUpForNode():
451
+ // cpp_heap will be ignored. Embedders must ensure that the
452
+ // v8::Isolate has a CppHeap attached while it's still used by
453
+ // Node.js, for example using v8::CreateParams.
454
+ //
455
+ // See https://issues.chromium.org/issues/42203693. In future version
456
+ // of V8, this CppHeap will be created by V8 if not provided.
457
+ v8::CppHeap* cpp_heap = nullptr;
458
+ };
459
+
460
+ // Represents a startup snapshot blob, e.g. created by passing
461
+ // --node-snapshot-main=entry.js to the configure script at build time,
462
+ // or by running Node.js with the --build-snapshot option.
463
+ //
464
+ // If used, the snapshot *must* have been built with the same Node.js
465
+ // version and V8 flags as the version that is currently running, and will
466
+ // be rejected otherwise.
467
+ // The same EmbedderSnapshotData instance *must* be passed to both
468
+ // `NewIsolate()` and `CreateIsolateData()`. The first `Environment` instance
469
+ // should be created with an empty `context` argument and will then
470
+ // use the main context included in the snapshot blob. It can be retrieved
471
+ // using `GetMainContext()`. `LoadEnvironment` can receive an empty
472
+ // `StartExecutionCallback` in this case.
473
+ // If V8 was configured with the shared-readonly-heap option, it requires
474
+ // all snapshots used to create `Isolate` instances to be identical.
475
+ // This option *must* be unset by embedders who wish to use the startup
476
+ // feature during the build step by passing the --disable-shared-readonly-heap
477
+ // flag to the configure script.
478
+ //
479
+ // The snapshot *must* be kept alive during the execution of the Isolate
480
+ // that was created using it.
481
+ //
482
+ // Snapshots are an *experimental* feature. In particular, the embedder API
483
+ // exposed through this class is subject to change or removal between Node.js
484
+ // versions, including possible API and ABI breakage.
485
+ class EmbedderSnapshotData {
486
+ public:
487
+ struct DeleteSnapshotData {
488
+ void operator()(const EmbedderSnapshotData*) const;
489
+ };
490
+ using Pointer =
491
+ std::unique_ptr<const EmbedderSnapshotData, DeleteSnapshotData>;
492
+
493
+ // Return an EmbedderSnapshotData object that refers to the built-in
494
+ // snapshot of Node.js. This can have been configured through e.g.
495
+ // --node-snapshot-main=entry.js.
496
+ static Pointer BuiltinSnapshotData();
497
+
498
+ // Return an EmbedderSnapshotData object that is based on an input file.
499
+ // Calling this method will consume but not close the FILE* handle.
500
+ // The FILE* handle can be closed immediately following this call.
501
+ // If the snapshot is invalid, this returns an empty pointer.
502
+ static Pointer FromFile(FILE* in);
503
+ static Pointer FromBlob(const std::vector<char>& in);
504
+ static Pointer FromBlob(std::string_view in);
505
+
506
+ // Write this EmbedderSnapshotData object to an output file.
507
+ // Calling this method will not close the FILE* handle.
508
+ // The FILE* handle can be closed immediately following this call.
509
+ void ToFile(FILE* out) const;
510
+ std::vector<char> ToBlob() const;
511
+
512
+ // Returns whether custom snapshots can be used. Currently, this always
513
+ // returns false since V8 enforces shared readonly-heap.
514
+ static bool CanUseCustomSnapshotPerIsolate();
515
+
516
+ EmbedderSnapshotData(const EmbedderSnapshotData&) = delete;
517
+ EmbedderSnapshotData& operator=(const EmbedderSnapshotData&) = delete;
518
+ EmbedderSnapshotData(EmbedderSnapshotData&&) = delete;
519
+ EmbedderSnapshotData& operator=(EmbedderSnapshotData&&) = delete;
520
+
521
+ protected:
522
+ EmbedderSnapshotData(const SnapshotData* impl, bool owns_impl);
523
+
524
+ private:
525
+ const SnapshotData* impl_;
526
+ bool owns_impl_;
527
+ friend struct SnapshotData;
528
+ friend class CommonEnvironmentSetup;
529
+ };
530
+
531
+ // Overriding IsolateSettings may produce unexpected behavior
532
+ // in Node.js core functionality, so proceed at your own risk.
533
+ NODE_EXTERN void SetIsolateUpForNode(v8::Isolate* isolate,
534
+ const IsolateSettings& settings);
535
+
536
+ // Set a number of callbacks for the `isolate`, in particular the Node.js
537
+ // uncaught exception listener.
538
+ NODE_EXTERN void SetIsolateUpForNode(v8::Isolate* isolate);
539
+
540
+ // Creates a new isolate with Node.js-specific settings.
541
+ // This is a convenience method equivalent to using SetIsolateCreateParams(),
542
+ // Isolate::Allocate(), MultiIsolatePlatform::RegisterIsolate(),
543
+ // Isolate::Initialize(), and SetIsolateUpForNode().
544
+ NODE_EXTERN v8::Isolate* NewIsolate(
545
+ ArrayBufferAllocator* allocator,
546
+ struct uv_loop_s* event_loop,
547
+ MultiIsolatePlatform* platform,
548
+ const EmbedderSnapshotData* snapshot_data = nullptr,
549
+ const IsolateSettings& settings = {});
550
+ NODE_EXTERN v8::Isolate* NewIsolate(
551
+ std::shared_ptr<ArrayBufferAllocator> allocator,
552
+ struct uv_loop_s* event_loop,
553
+ MultiIsolatePlatform* platform,
554
+ const EmbedderSnapshotData* snapshot_data = nullptr,
555
+ const IsolateSettings& settings = {});
556
+
557
+ // Creates a new context with Node.js-specific tweaks.
558
+ // Call `RegisterContext` after the context been created to register
559
+ // the context with Node.js specific setups like the inspector.
560
+ NODE_EXTERN v8::Local<v8::Context> NewContext(
561
+ v8::Isolate* isolate,
562
+ v8::Local<v8::ObjectTemplate> object_template =
563
+ v8::Local<v8::ObjectTemplate>());
564
+
565
+ // Runs Node.js-specific tweaks on an already constructed context
566
+ // Return value indicates success of operation
567
+ NODE_EXTERN v8::Maybe<bool> InitializeContext(v8::Local<v8::Context> context);
568
+
569
+ // Associate the context with the given Environment. This registers the context
570
+ // as known to Node.js, makes it available to the inspector. This also registers
571
+ // Node.js promise hooks on the context.
572
+ NODE_EXTERN void RegisterContext(Environment* env,
573
+ v8::Local<v8::Context> context,
574
+ std::string_view name = "",
575
+ std::string_view origin = "");
576
+ // Unregister the context. Call this when the embedder finished all work with
577
+ // this context.
578
+ NODE_EXTERN void UnregisterContext(Environment* env,
579
+ v8::Local<v8::Context> context);
580
+
581
+ // If `platform` is passed, it will be used to register new Worker instances.
582
+ // It can be `nullptr`, in which case creating new Workers inside of
583
+ // Environments that use this `IsolateData` will not work.
584
+ NODE_EXTERN IsolateData* CreateIsolateData(
585
+ v8::Isolate* isolate,
586
+ struct uv_loop_s* loop,
587
+ MultiIsolatePlatform* platform = nullptr,
588
+ ArrayBufferAllocator* allocator = nullptr,
589
+ const EmbedderSnapshotData* snapshot_data = nullptr);
590
+ NODE_EXTERN void FreeIsolateData(IsolateData* isolate_data);
591
+
592
+ struct ThreadId {
593
+ uint64_t id = static_cast<uint64_t>(-1);
594
+ };
595
+ NODE_EXTERN ThreadId AllocateEnvironmentThreadId();
596
+
597
+ namespace EnvironmentFlags {
598
+ enum Flags : uint64_t {
599
+ kNoFlags = 0,
600
+ // Use the default behaviour for Node.js instances.
601
+ kDefaultFlags = 1 << 0,
602
+ // Controls whether this Environment is allowed to affect per-process state
603
+ // (e.g. cwd, process title, uid, etc.).
604
+ // This is set when using kDefaultFlags.
605
+ kOwnsProcessState = 1 << 1,
606
+ // Set if this Environment instance is associated with the global inspector
607
+ // handling code (i.e. listening on SIGUSR1).
608
+ // This is set when using kDefaultFlags.
609
+ kOwnsInspector = 1 << 2,
610
+ // Set if Node.js should not run its own esm loader. This is needed by some
611
+ // embedders, because it's possible for the Node.js esm loader to conflict
612
+ // with another one in an embedder environment, e.g. Blink's in Chromium.
613
+ kNoRegisterESMLoader = 1 << 3,
614
+ // Set this flag to make Node.js track "raw" file descriptors, i.e. managed
615
+ // by fs.open() and fs.close(), and close them during FreeEnvironment().
616
+ kTrackUnmanagedFds = 1 << 4,
617
+ // Set this flag to force hiding console windows when spawning child
618
+ // processes. This is usually used when embedding Node.js in GUI programs on
619
+ // Windows.
620
+ kHideConsoleWindows = 1 << 5,
621
+ // Set this flag to disable loading native addons via `process.dlopen`.
622
+ // This environment flag is especially important for worker threads
623
+ // so that a worker thread can't load a native addon even if `execArgv`
624
+ // is overwritten and `--no-addons` is not specified but was specified
625
+ // for this Environment instance.
626
+ kNoNativeAddons = 1 << 6,
627
+ // Set this flag to disable searching modules from global paths like
628
+ // $HOME/.node_modules and $NODE_PATH. This is used by standalone apps that
629
+ // do not expect to have their behaviors changed because of globally
630
+ // installed modules.
631
+ kNoGlobalSearchPaths = 1 << 7,
632
+ // Do not export browser globals like setTimeout, console, etc.
633
+ kNoBrowserGlobals = 1 << 8,
634
+ // Controls whether or not the Environment should call V8Inspector::create().
635
+ // This control is needed by embedders who may not want to initialize the V8
636
+ // inspector in situations where one has already been created,
637
+ // e.g. Blink's in Chromium.
638
+ kNoCreateInspector = 1 << 9,
639
+ // Controls whether or not the InspectorAgent for this Environment should
640
+ // call StartDebugSignalHandler. This control is needed by embedders who may
641
+ // not want to allow other processes to start the V8 inspector.
642
+ kNoStartDebugSignalHandler = 1 << 10,
643
+ // Controls whether the InspectorAgent created for this Environment waits for
644
+ // Inspector frontend events during the Environment creation. It's used to
645
+ // call node::Stop(env) on a Worker thread that is waiting for the events.
646
+ kNoWaitForInspectorFrontend = 1 << 11
647
+ };
648
+ } // namespace EnvironmentFlags
649
+
650
+ enum class SnapshotFlags : uint32_t {
651
+ kDefault = 0,
652
+ // Whether code cache should be generated as part of the snapshot.
653
+ // Code cache reduces the time spent on compiling functions included
654
+ // in the snapshot at the expense of a bigger snapshot size and
655
+ // potentially breaking portability of the snapshot.
656
+ kWithoutCodeCache = 1 << 0,
657
+ };
658
+
659
+ struct SnapshotConfig {
660
+ SnapshotFlags flags = SnapshotFlags::kDefault;
661
+
662
+ // When builder_script_path is std::nullopt, the snapshot is generated as a
663
+ // built-in snapshot instead of a custom one, and it's expected that the
664
+ // built-in snapshot only contains states that reproduce in every run of the
665
+ // application. The event loop won't be run when generating a built-in
666
+ // snapshot, so asynchronous operations should be avoided.
667
+ //
668
+ // When builder_script_path is an std::string, it should match args[1]
669
+ // passed to CreateForSnapshotting(). The embedder is also expected to use
670
+ // LoadEnvironment() to run a script matching this path. In that case the
671
+ // snapshot is generated as a custom snapshot and the event loop is run, so
672
+ // the snapshot builder can execute asynchronous operations as long as they
673
+ // are run to completion when the snapshot is taken.
674
+ std::optional<std::string> builder_script_path;
675
+ };
676
+
677
+ struct InspectorParentHandle {
678
+ virtual ~InspectorParentHandle() = default;
679
+ };
680
+
681
+ // TODO(addaleax): Maybe move per-Environment options parsing here.
682
+ // Returns nullptr when the Environment cannot be created e.g. there are
683
+ // pending JavaScript exceptions.
684
+ // `context` may be empty if an `EmbedderSnapshotData` instance was provided
685
+ // to `NewIsolate()` and `CreateIsolateData()`.
686
+ NODE_EXTERN Environment* CreateEnvironment(
687
+ IsolateData* isolate_data,
688
+ v8::Local<v8::Context> context,
689
+ const std::vector<std::string>& args,
690
+ const std::vector<std::string>& exec_args,
691
+ EnvironmentFlags::Flags flags = EnvironmentFlags::kDefaultFlags,
692
+ ThreadId thread_id = {} /* allocates a thread id automatically */,
693
+ std::unique_ptr<InspectorParentHandle> inspector_parent_handle = {});
694
+
695
+ NODE_EXTERN Environment* CreateEnvironment(
696
+ IsolateData* isolate_data,
697
+ v8::Local<v8::Context> context,
698
+ const std::vector<std::string>& args,
699
+ const std::vector<std::string>& exec_args,
700
+ EnvironmentFlags::Flags flags,
701
+ ThreadId thread_id,
702
+ std::unique_ptr<InspectorParentHandle> inspector_parent_handle,
703
+ std::string_view thread_name);
704
+
705
+ // Returns a handle that can be passed to `LoadEnvironment()`, making the
706
+ // child Environment accessible to the inspector as if it were a Node.js Worker.
707
+ // `child_thread_id` can be created using `AllocateEnvironmentThreadId()`
708
+ // and then later passed on to `CreateEnvironment()` to create the child
709
+ // Environment, together with the inspector handle.
710
+ // This method should not be called while the parent Environment is active
711
+ // on another thread.
712
+ NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
713
+ Environment* parent_env,
714
+ ThreadId child_thread_id,
715
+ const char* child_url);
716
+
717
+ NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
718
+ Environment* parent_env,
719
+ ThreadId child_thread_id,
720
+ const char* child_url,
721
+ const char* name);
722
+
723
+ NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
724
+ Environment* parent_env,
725
+ ThreadId child_thread_id,
726
+ std::string_view child_url,
727
+ std::string_view name);
728
+
729
+ struct StartExecutionCallbackInfo {
730
+ v8::Local<v8::Object> process_object;
731
+ v8::Local<v8::Function> native_require;
732
+ v8::Local<v8::Function> run_cjs;
733
+ };
734
+
735
+ enum class ModuleFormat : uint8_t {
736
+ kCommonJS,
737
+ kModule, // i.e. ES Module/SourceTextModule
738
+ // TODO(joyeecheung): support TypeScriptModule, TypeScriptCommonJS
739
+ };
740
+
741
+ // Information passed to embedder callbacks during environment startup.
742
+ // This class is created by Node.js and passed to the embedder's callback.
743
+ // The layout is opaque to allow future additions without breaking ABI.
744
+ class NODE_EXTERN StartExecutionCallbackInfoWithModule {
745
+ public:
746
+ StartExecutionCallbackInfoWithModule();
747
+ ~StartExecutionCallbackInfoWithModule();
748
+
749
+ StartExecutionCallbackInfoWithModule(
750
+ const StartExecutionCallbackInfoWithModule&) = delete;
751
+ StartExecutionCallbackInfoWithModule& operator=(
752
+ const StartExecutionCallbackInfoWithModule&) = delete;
753
+ StartExecutionCallbackInfoWithModule(StartExecutionCallbackInfoWithModule&&);
754
+ StartExecutionCallbackInfoWithModule& operator=(
755
+ StartExecutionCallbackInfoWithModule&&);
756
+
757
+ Environment* env() const;
758
+ v8::Local<v8::Object> process_object() const;
759
+ v8::Local<v8::Function> native_require() const;
760
+ v8::Local<v8::Function> run_module() const;
761
+
762
+ void set_env(Environment* env);
763
+ void set_process_object(v8::Local<v8::Object> process_object);
764
+ void set_native_require(v8::Local<v8::Function> native_require);
765
+ void set_run_module(v8::Local<v8::Function> run_module);
766
+
767
+ private:
768
+ struct Impl;
769
+ std::unique_ptr<Impl> impl_;
770
+ };
771
+
772
+ using StartExecutionCallback =
773
+ std::function<v8::MaybeLocal<v8::Value>(const StartExecutionCallbackInfo&)>;
774
+ using StartExecutionCallbackWithModule =
775
+ std::function<v8::MaybeLocal<v8::Value>(
776
+ const StartExecutionCallbackInfoWithModule&)>;
777
+ using EmbedderPreloadCallback =
778
+ std::function<void(Environment* env,
779
+ v8::Local<v8::Value> process,
780
+ v8::Local<v8::Value> require)>;
781
+
782
+ // Run initialization for the environment.
783
+ //
784
+ // The |preload| function, usually used by embedders to inject scripts,
785
+ // will be run by Node.js before Node.js executes the entry point.
786
+ // The function is guaranteed to run before the user land module loader running
787
+ // any user code, so it is safe to assume that at this point, no user code has
788
+ // been run yet.
789
+ // The function will be executed with preload(process, require), and the passed
790
+ // require function has access to internal Node.js modules. There is no
791
+ // stability guarantee about the internals exposed to the internal require
792
+ // function. Expect breakages when updating Node.js versions if the embedder
793
+ // imports internal modules with the internal require function.
794
+ // Worker threads created in the environment will also respect The |preload|
795
+ // function, so make sure the function is thread-safe.
796
+ NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
797
+ Environment* env,
798
+ StartExecutionCallback cb,
799
+ EmbedderPreloadCallback preload = nullptr);
800
+
801
+ NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
802
+ Environment* env,
803
+ StartExecutionCallbackWithModule cb,
804
+ EmbedderPreloadCallback preload = nullptr);
805
+
806
+ NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
807
+ Environment* env,
808
+ std::string_view main_script_source_utf8,
809
+ EmbedderPreloadCallback preload = nullptr);
810
+
811
+ // Data for specifying an entry point script for LoadEnvironment().
812
+ // This class uses an opaque layout to allow future additions without
813
+ // breaking ABI. Use the setter methods to configure the entry point.
814
+ class NODE_EXTERN ModuleData {
815
+ public:
816
+ ModuleData();
817
+ ~ModuleData();
818
+
819
+ ModuleData(const ModuleData&) = delete;
820
+ ModuleData& operator=(const ModuleData&) = delete;
821
+ ModuleData(ModuleData&&);
822
+ ModuleData& operator=(ModuleData&&);
823
+
824
+ void set_source(std::string_view source);
825
+ void set_format(ModuleFormat format);
826
+ void set_resource_name(std::string_view name);
827
+
828
+ std::string_view source() const;
829
+ ModuleFormat format() const;
830
+ std::string_view resource_name() const;
831
+
832
+ private:
833
+ struct Impl;
834
+ std::unique_ptr<Impl> impl_;
835
+ };
836
+
837
+ NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
838
+ Environment* env,
839
+ const ModuleData* entry_point,
840
+ EmbedderPreloadCallback preload = nullptr);
841
+
842
+ NODE_EXTERN void FreeEnvironment(Environment* env);
843
+
844
+ // Set a callback that is called when process.exit() is called from JS,
845
+ // overriding the default handler.
846
+ // It receives the Environment* instance and the exit code as arguments.
847
+ // This could e.g. call Stop(env); in order to terminate execution and stop
848
+ // the event loop.
849
+ // The default handler disposes of the global V8 platform instance, if one is
850
+ // being used, and calls exit().
851
+ NODE_EXTERN void SetProcessExitHandler(
852
+ Environment* env,
853
+ std::function<void(Environment*, int)>&& handler);
854
+ NODE_EXTERN void DefaultProcessExitHandler(Environment* env, int exit_code);
855
+
856
+ // Sets a process-global handler invoked when Node.js programmatically aborts.
857
+ // Nullable strings representing the location and reason for the abort may or
858
+ // may not be passed as a parameter to the handler. The handler should not
859
+ // return, but node will ensure that the process exits after the handler is
860
+ // called regardless of whether or not it returns. Passing nullptr restores the
861
+ // default handler. This is process-global and may be invoked before any Isolate
862
+ // or Environment exists.
863
+ using AbortHandler = void (*)(const char* location, const char* message);
864
+ NODE_EXTERN void SetAbortHandler(AbortHandler handler);
865
+
866
+ // This may return nullptr if context is not associated with a Node instance.
867
+ NODE_EXTERN Environment* GetCurrentEnvironment(v8::Local<v8::Context> context);
868
+ NODE_EXTERN IsolateData* GetEnvironmentIsolateData(Environment* env);
869
+ NODE_EXTERN ArrayBufferAllocator* GetArrayBufferAllocator(IsolateData* data);
870
+ // This is mostly useful for Environment* instances that were created through
871
+ // a snapshot and have a main context that was read from that snapshot.
872
+ NODE_EXTERN v8::Local<v8::Context> GetMainContext(Environment* env);
873
+
874
+ [[noreturn]] NODE_EXTERN void OnFatalError(const char* location,
875
+ const char* message);
876
+ NODE_EXTERN void PromiseRejectCallback(v8::PromiseRejectMessage message);
877
+ NODE_EXTERN bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context,
878
+ v8::Local<v8::String>);
879
+ NODE_EXTERN bool ShouldAbortOnUncaughtException(v8::Isolate* isolate);
880
+ NODE_EXTERN v8::MaybeLocal<v8::Value> PrepareStackTraceCallback(
881
+ v8::Local<v8::Context> context,
882
+ v8::Local<v8::Value> exception,
883
+ v8::Local<v8::Array> trace);
884
+
885
+ // Writes a diagnostic report to a file. If filename is not provided, the
886
+ // default filename includes the date, time, PID, and a sequence number.
887
+ // The report's JavaScript stack trace is taken from err, if present.
888
+ // If isolate is nullptr, no information about the JavaScript environment
889
+ // is included in the report.
890
+ // Returns the filename of the written report.
891
+ NODE_EXTERN std::string TriggerNodeReport(v8::Isolate* isolate,
892
+ std::string_view message,
893
+ std::string_view trigger,
894
+ std::string_view filename,
895
+ v8::Local<v8::Value> error);
896
+ NODE_EXTERN std::string TriggerNodeReport(Environment* env,
897
+ std::string_view message,
898
+ std::string_view trigger,
899
+ std::string_view filename,
900
+ v8::Local<v8::Value> error);
901
+ NODE_EXTERN void GetNodeReport(v8::Isolate* isolate,
902
+ std::string_view message,
903
+ std::string_view trigger,
904
+ v8::Local<v8::Value> error,
905
+ std::ostream& out);
906
+ NODE_EXTERN void GetNodeReport(Environment* env,
907
+ std::string_view message,
908
+ std::string_view trigger,
909
+ v8::Local<v8::Value> error,
910
+ std::ostream& out);
911
+
912
+ // This returns the MultiIsolatePlatform used for an Environment or IsolateData
913
+ // instance, if one exists.
914
+ NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(Environment* env);
915
+ NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env);
916
+
917
+ // Get/set the currently active tracing controller. Using
918
+ // MultiIsolatePlatform::Create() will implicitly set this by default. This is
919
+ // global and should be initialized along with the v8::Platform instance that is
920
+ // being used. `controller` is allowed to be `nullptr`. This is used for tracing
921
+ // events from Node.js itself. V8 uses the tracing controller returned from the
922
+ // active `v8::Platform` instance.
923
+ NODE_EXTERN v8::TracingController* GetTracingController();
924
+ NODE_EXTERN void SetTracingController(v8::TracingController* controller);
925
+
926
+ // Run `process.emit('beforeExit')` as it would usually happen when Node.js is
927
+ // run in standalone mode.
928
+ NODE_EXTERN v8::Maybe<bool> EmitProcessBeforeExit(Environment* env);
929
+ // Run `process.emit('exit')` as it would usually happen when Node.js is run
930
+ // in standalone mode. The return value corresponds to the exit code.
931
+ NODE_EXTERN v8::Maybe<int> EmitProcessExit(Environment* env);
932
+
933
+ // Runs hooks added through `AtExit()`. This is part of `FreeEnvironment()`,
934
+ // so calling it manually is typically not necessary.
935
+ NODE_EXTERN void RunAtExit(Environment* env);
936
+
937
+ // This may return nullptr if the current v8::Context is not associated
938
+ // with a Node instance.
939
+ NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate);
940
+
941
+ // Runs the main loop for a given Environment. This roughly performs the
942
+ // following steps:
943
+ // 1. Call uv_run() on the event loop until it is drained.
944
+ // 2. Call platform->DrainTasks() on the associated platform/isolate.
945
+ // 3. If the event loop is alive again, go to Step 1.
946
+ // 4. Call EmitProcessBeforeExit().
947
+ // 5. If the event loop is alive again, go to Step 1.
948
+ // 6. Call EmitProcessExit() and forward the return value.
949
+ // If at any point node::Stop() is called, the function will attempt to return
950
+ // as soon as possible, returning an empty `Maybe`.
951
+ // This function only works if `env` has an associated `MultiIsolatePlatform`.
952
+ NODE_EXTERN v8::Maybe<int> SpinEventLoop(Environment* env);
953
+
954
+ NODE_EXTERN std::string GetAnonymousMainPath();
955
+
956
+ class NODE_EXTERN CommonEnvironmentSetup {
957
+ public:
958
+ ~CommonEnvironmentSetup();
959
+
960
+ // Create a new CommonEnvironmentSetup, that is, a group of objects that
961
+ // together form the typical setup for a single Node.js Environment instance.
962
+ // If any error occurs, `*errors` will be populated and the returned pointer
963
+ // will be empty.
964
+ // env_args will be passed through as arguments to CreateEnvironment(), after
965
+ // `isolate_data` and `context`.
966
+ template <typename... EnvironmentArgs>
967
+ static std::unique_ptr<CommonEnvironmentSetup> Create(
968
+ MultiIsolatePlatform* platform,
969
+ std::vector<std::string>* errors,
970
+ EnvironmentArgs&&... env_args);
971
+ template <typename... EnvironmentArgs>
972
+ static std::unique_ptr<CommonEnvironmentSetup> CreateFromSnapshot(
973
+ MultiIsolatePlatform* platform,
974
+ std::vector<std::string>* errors,
975
+ const EmbedderSnapshotData* snapshot_data,
976
+ EnvironmentArgs&&... env_args);
977
+
978
+ // Create an embedding setup which will be used for creating a snapshot
979
+ // using CreateSnapshot().
980
+ //
981
+ // This will create and attach a v8::SnapshotCreator to this instance,
982
+ // and the same restrictions apply to this instance that also apply to
983
+ // other V8 snapshotting environments.
984
+ // Not all Node.js APIs are supported in this case. Currently, there is
985
+ // no support for native/host objects other than Node.js builtins
986
+ // in the snapshot.
987
+ //
988
+ // If the embedder wants to use LoadEnvironment() later to run a snapshot
989
+ // builder script they should make sure args[1] contains the path of the
990
+ // snapshot script, which will be used to create __filename and __dirname
991
+ // in the context where the builder script is run. If they do not want to
992
+ // include the build-time paths into the snapshot, use the string returned
993
+ // by GetAnonymousMainPath() as args[1] to anonymize the script.
994
+ //
995
+ // Snapshots are an *experimental* feature. In particular, the embedder API
996
+ // exposed through this class is subject to change or removal between Node.js
997
+ // versions, including possible API and ABI breakage.
998
+ static std::unique_ptr<CommonEnvironmentSetup> CreateForSnapshotting(
999
+ MultiIsolatePlatform* platform,
1000
+ std::vector<std::string>* errors,
1001
+ const std::vector<std::string>& args = {},
1002
+ const std::vector<std::string>& exec_args = {},
1003
+ const SnapshotConfig& snapshot_config = {});
1004
+ EmbedderSnapshotData::Pointer CreateSnapshot();
1005
+
1006
+ struct uv_loop_s* event_loop() const;
1007
+ v8::SnapshotCreator* snapshot_creator();
1008
+ // Empty for snapshotting environments.
1009
+ std::shared_ptr<ArrayBufferAllocator> array_buffer_allocator() const;
1010
+ v8::Isolate* isolate() const;
1011
+ IsolateData* isolate_data() const;
1012
+ Environment* env() const;
1013
+ v8::Local<v8::Context> context() const;
1014
+
1015
+ CommonEnvironmentSetup(const CommonEnvironmentSetup&) = delete;
1016
+ CommonEnvironmentSetup& operator=(const CommonEnvironmentSetup&) = delete;
1017
+ CommonEnvironmentSetup(CommonEnvironmentSetup&&) = delete;
1018
+ CommonEnvironmentSetup& operator=(CommonEnvironmentSetup&&) = delete;
1019
+
1020
+ private:
1021
+ enum Flags : uint32_t {
1022
+ kNoFlags = 0,
1023
+ kIsForSnapshotting = 1,
1024
+ };
1025
+
1026
+ struct Impl;
1027
+ Impl* impl_;
1028
+
1029
+ CommonEnvironmentSetup(
1030
+ MultiIsolatePlatform*,
1031
+ std::vector<std::string>*,
1032
+ std::function<Environment*(const CommonEnvironmentSetup*)>);
1033
+ CommonEnvironmentSetup(
1034
+ MultiIsolatePlatform*,
1035
+ std::vector<std::string>*,
1036
+ const EmbedderSnapshotData*,
1037
+ uint32_t flags,
1038
+ std::function<Environment*(const CommonEnvironmentSetup*)>,
1039
+ const SnapshotConfig* config = nullptr);
1040
+ };
1041
+
1042
+ // Implementation for CommonEnvironmentSetup::Create
1043
+ template <typename... EnvironmentArgs>
1044
+ std::unique_ptr<CommonEnvironmentSetup> CommonEnvironmentSetup::Create(
1045
+ MultiIsolatePlatform* platform,
1046
+ std::vector<std::string>* errors,
1047
+ EnvironmentArgs&&... env_args) {
1048
+ auto ret = std::unique_ptr<CommonEnvironmentSetup>(new CommonEnvironmentSetup(
1049
+ platform, errors,
1050
+ [&](const CommonEnvironmentSetup* setup) -> Environment* {
1051
+ return CreateEnvironment(
1052
+ setup->isolate_data(), setup->context(),
1053
+ std::forward<EnvironmentArgs>(env_args)...);
1054
+ }));
1055
+ if (!errors->empty()) ret.reset();
1056
+ return ret;
1057
+ }
1058
+
1059
+ // Implementation for ::CreateFromSnapshot -- the ::Create() method
1060
+ // could call this with a nullptr snapshot_data in a major version.
1061
+ template <typename... EnvironmentArgs>
1062
+ std::unique_ptr<CommonEnvironmentSetup>
1063
+ CommonEnvironmentSetup::CreateFromSnapshot(
1064
+ MultiIsolatePlatform* platform,
1065
+ std::vector<std::string>* errors,
1066
+ const EmbedderSnapshotData* snapshot_data,
1067
+ EnvironmentArgs&&... env_args) {
1068
+ auto ret = std::unique_ptr<CommonEnvironmentSetup>(new CommonEnvironmentSetup(
1069
+ platform,
1070
+ errors,
1071
+ snapshot_data,
1072
+ Flags::kNoFlags,
1073
+ [&](const CommonEnvironmentSetup* setup) -> Environment* {
1074
+ return CreateEnvironment(setup->isolate_data(),
1075
+ setup->context(),
1076
+ std::forward<EnvironmentArgs>(env_args)...);
1077
+ }));
1078
+ if (!errors->empty()) ret.reset();
1079
+ return ret;
1080
+ }
1081
+
1082
+ /* Converts a unixtime to V8 Date */
1083
+ NODE_DEPRECATED("Use v8::Date::New() directly",
1084
+ inline v8::Local<v8::Value> NODE_UNIXTIME_V8(double time) {
1085
+ return v8::Date::New(
1086
+ v8::Isolate::GetCurrent()->GetCurrentContext(),
1087
+ 1000 * time)
1088
+ .ToLocalChecked();
1089
+ })
1090
+ #define NODE_UNIXTIME_V8 node::NODE_UNIXTIME_V8
1091
+ NODE_DEPRECATED("Use v8::Date::ValueOf() directly",
1092
+ inline double NODE_V8_UNIXTIME(v8::Local<v8::Date> date) {
1093
+ return date->ValueOf() / 1000;
1094
+ })
1095
+ #define NODE_V8_UNIXTIME node::NODE_V8_UNIXTIME
1096
+
1097
+ #define NODE_DEFINE_CONSTANT(target, constant) \
1098
+ do { \
1099
+ v8::Isolate* isolate = v8::Isolate::GetCurrent(); \
1100
+ v8::Local<v8::Context> context = isolate->GetCurrentContext(); \
1101
+ v8::Local<v8::String> constant_name = v8::String::NewFromUtf8Literal( \
1102
+ isolate, #constant, v8::NewStringType::kInternalized); \
1103
+ v8::Local<v8::Number> constant_value = \
1104
+ v8::Number::New(isolate, static_cast<double>(constant)); \
1105
+ v8::PropertyAttribute constant_attributes = \
1106
+ static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete); \
1107
+ (target) \
1108
+ ->DefineOwnProperty( \
1109
+ context, constant_name, constant_value, constant_attributes) \
1110
+ .Check(); \
1111
+ } while (0)
1112
+
1113
+ #define NODE_DEFINE_HIDDEN_CONSTANT(target, constant) \
1114
+ do { \
1115
+ v8::Isolate* isolate = v8::Isolate::GetCurrent(); \
1116
+ v8::Local<v8::Context> context = isolate->GetCurrentContext(); \
1117
+ v8::Local<v8::String> constant_name = v8::String::NewFromUtf8Literal( \
1118
+ isolate, #constant, v8::NewStringType::kInternalized); \
1119
+ v8::Local<v8::Number> constant_value = \
1120
+ v8::Number::New(isolate, static_cast<double>(constant)); \
1121
+ v8::PropertyAttribute constant_attributes = \
1122
+ static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete | \
1123
+ v8::DontEnum); \
1124
+ (target) \
1125
+ ->DefineOwnProperty( \
1126
+ context, constant_name, constant_value, constant_attributes) \
1127
+ .Check(); \
1128
+ } while (0)
1129
+
1130
+ // Used to be a macro, hence the uppercase name.
1131
+ inline void NODE_SET_METHOD(v8::Local<v8::Template> recv,
1132
+ const char* name,
1133
+ v8::FunctionCallback callback) {
1134
+ v8::Isolate* isolate = v8::Isolate::GetCurrent();
1135
+ v8::HandleScope handle_scope(isolate);
1136
+ v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
1137
+ callback);
1138
+ v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
1139
+ v8::NewStringType::kInternalized).ToLocalChecked();
1140
+ t->SetClassName(fn_name);
1141
+ recv->Set(fn_name, t);
1142
+ }
1143
+
1144
+ // Used to be a macro, hence the uppercase name.
1145
+ inline void NODE_SET_METHOD(v8::Local<v8::Object> recv,
1146
+ const char* name,
1147
+ v8::FunctionCallback callback) {
1148
+ v8::Isolate* isolate = v8::Isolate::GetCurrent();
1149
+ v8::HandleScope handle_scope(isolate);
1150
+ v8::Local<v8::Context> context = isolate->GetCurrentContext();
1151
+ v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
1152
+ callback);
1153
+ v8::Local<v8::Function> fn = t->GetFunction(context).ToLocalChecked();
1154
+ v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
1155
+ v8::NewStringType::kInternalized).ToLocalChecked();
1156
+ fn->SetName(fn_name);
1157
+ recv->Set(context, fn_name, fn).Check();
1158
+ }
1159
+ #define NODE_SET_METHOD node::NODE_SET_METHOD
1160
+
1161
+ // Used to be a macro, hence the uppercase name.
1162
+ // Not a template because it only makes sense for FunctionTemplates.
1163
+ inline void NODE_SET_PROTOTYPE_METHOD(v8::Local<v8::FunctionTemplate> recv,
1164
+ const char* name,
1165
+ v8::FunctionCallback callback) {
1166
+ v8::Isolate* isolate = v8::Isolate::GetCurrent();
1167
+ v8::HandleScope handle_scope(isolate);
1168
+ v8::Local<v8::Signature> s = v8::Signature::New(isolate, recv);
1169
+ v8::Local<v8::FunctionTemplate> t =
1170
+ v8::FunctionTemplate::New(isolate, callback, v8::Local<v8::Value>(), s);
1171
+ v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
1172
+ v8::NewStringType::kInternalized).ToLocalChecked();
1173
+ t->SetClassName(fn_name);
1174
+ recv->PrototypeTemplate()->Set(fn_name, t);
1175
+ }
1176
+ #define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD
1177
+
1178
+ // BINARY is a deprecated alias of LATIN1.
1179
+ // BASE64URL is not currently exposed to the JavaScript side.
1180
+ enum encoding {
1181
+ ASCII,
1182
+ UTF8,
1183
+ BASE64,
1184
+ UCS2,
1185
+ BINARY,
1186
+ HEX,
1187
+ BUFFER,
1188
+ BASE64URL,
1189
+ LATIN1 = BINARY
1190
+ };
1191
+
1192
+ NODE_EXTERN enum encoding ParseEncoding(
1193
+ v8::Isolate* isolate,
1194
+ v8::Local<v8::Value> encoding_v,
1195
+ enum encoding default_encoding = LATIN1);
1196
+
1197
+ NODE_EXTERN void FatalException(v8::Isolate* isolate,
1198
+ const v8::TryCatch& try_catch);
1199
+
1200
+ NODE_EXTERN v8::MaybeLocal<v8::Value> TryEncode(
1201
+ v8::Isolate* isolate,
1202
+ const char* buf,
1203
+ size_t len,
1204
+ enum encoding encoding = LATIN1);
1205
+
1206
+ // Warning: This reverses endianness on Big Endian platforms, even though the
1207
+ // signature using uint16_t implies that it should not.
1208
+ NODE_EXTERN v8::MaybeLocal<v8::Value> TryEncode(v8::Isolate* isolate,
1209
+ const uint16_t* buf,
1210
+ size_t len);
1211
+
1212
+ // The original Encode(...) functions are deprecated because they do not
1213
+ // appropriately propagate exceptions and instead rely on ToLocalChecked()
1214
+ // which crashes the process if an exception occurs. We cannot just remove
1215
+ // these as it would break ABI compatibility, so we keep them around but
1216
+ // deprecate them in favor of the TryEncode(...) variations which return
1217
+ // a MaybeLocal<> and do not crash the process if an exception occurs.
1218
+ NODE_DEPRECATED(
1219
+ "Use TryEncode(...) instead",
1220
+ NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
1221
+ const char* buf,
1222
+ size_t len,
1223
+ enum encoding encoding = LATIN1));
1224
+
1225
+ // Warning: This reverses endianness on Big Endian platforms, even though the
1226
+ // signature using uint16_t implies that it should not.
1227
+ NODE_DEPRECATED("Use TryEncode(...) instead",
1228
+ NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
1229
+ const uint16_t* buf,
1230
+ size_t len));
1231
+
1232
+ // Returns -1 if the handle was not valid for decoding
1233
+ NODE_EXTERN ssize_t DecodeBytes(v8::Isolate* isolate,
1234
+ v8::Local<v8::Value>,
1235
+ enum encoding encoding = LATIN1);
1236
+ // returns bytes written.
1237
+ NODE_EXTERN ssize_t DecodeWrite(v8::Isolate* isolate,
1238
+ char* buf,
1239
+ size_t buflen,
1240
+ v8::Local<v8::Value>,
1241
+ enum encoding encoding = LATIN1);
1242
+ #ifdef _WIN32
1243
+ NODE_EXTERN v8::Local<v8::Value> WinapiErrnoException(
1244
+ v8::Isolate* isolate,
1245
+ int errorno,
1246
+ const char* syscall = nullptr,
1247
+ const char* msg = "",
1248
+ const char* path = nullptr);
1249
+ #endif
1250
+
1251
+ const char* signo_string(int errorno);
1252
+
1253
+
1254
+ typedef void (*addon_register_func)(
1255
+ v8::Local<v8::Object> exports,
1256
+ v8::Local<v8::Value> module,
1257
+ void* priv);
1258
+
1259
+ typedef void (*addon_context_register_func)(
1260
+ v8::Local<v8::Object> exports,
1261
+ v8::Local<v8::Value> module,
1262
+ v8::Local<v8::Context> context,
1263
+ void* priv);
1264
+
1265
+ enum ModuleFlags {
1266
+ kLinked = 0x02
1267
+ };
1268
+
1269
+ struct node_module {
1270
+ int nm_version;
1271
+ unsigned int nm_flags;
1272
+ void* nm_dso_handle;
1273
+ const char* nm_filename;
1274
+ node::addon_register_func nm_register_func;
1275
+ node::addon_context_register_func nm_context_register_func;
1276
+ const char* nm_modname;
1277
+ void* nm_priv;
1278
+ struct node_module* nm_link;
1279
+ };
1280
+
1281
+ extern "C" NODE_EXTERN void node_module_register(void* mod);
1282
+
1283
+ #ifdef _WIN32
1284
+ # define NODE_MODULE_EXPORT __declspec(dllexport)
1285
+ #else
1286
+ # define NODE_MODULE_EXPORT __attribute__((visibility("default")))
1287
+ #endif
1288
+
1289
+ #ifdef NODE_SHARED_MODE
1290
+ # define NODE_CTOR_PREFIX
1291
+ #else
1292
+ # define NODE_CTOR_PREFIX static
1293
+ #endif
1294
+
1295
+ #if defined(_MSC_VER)
1296
+ #define NODE_C_CTOR(fn) \
1297
+ NODE_CTOR_PREFIX void __cdecl fn(void); \
1298
+ namespace { \
1299
+ struct fn##_ { \
1300
+ fn##_() { fn(); }; \
1301
+ } fn##_v_; \
1302
+ } \
1303
+ NODE_CTOR_PREFIX void __cdecl fn(void)
1304
+ #else
1305
+ #define NODE_C_CTOR(fn) \
1306
+ NODE_CTOR_PREFIX void fn(void) __attribute__((constructor)); \
1307
+ NODE_CTOR_PREFIX void fn(void)
1308
+ #endif
1309
+
1310
+ #define NODE_MODULE_X(modname, regfunc, priv, flags) \
1311
+ extern "C" { \
1312
+ static node::node_module _module = \
1313
+ { \
1314
+ NODE_MODULE_VERSION, \
1315
+ flags, \
1316
+ NULL, /* NOLINT (readability/null_usage) */ \
1317
+ __FILE__, \
1318
+ (node::addon_register_func) (regfunc), \
1319
+ NULL, /* NOLINT (readability/null_usage) */ \
1320
+ NODE_STRINGIFY(modname), \
1321
+ priv, \
1322
+ NULL /* NOLINT (readability/null_usage) */ \
1323
+ }; \
1324
+ NODE_C_CTOR(_register_ ## modname) { \
1325
+ node_module_register(&_module); \
1326
+ } \
1327
+ }
1328
+
1329
+ #define NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, priv, flags) \
1330
+ extern "C" { \
1331
+ static node::node_module _module = \
1332
+ { \
1333
+ NODE_MODULE_VERSION, \
1334
+ flags, \
1335
+ NULL, /* NOLINT (readability/null_usage) */ \
1336
+ __FILE__, \
1337
+ NULL, /* NOLINT (readability/null_usage) */ \
1338
+ (node::addon_context_register_func) (regfunc), \
1339
+ NODE_STRINGIFY(modname), \
1340
+ priv, \
1341
+ NULL /* NOLINT (readability/null_usage) */ \
1342
+ }; \
1343
+ NODE_C_CTOR(_register_ ## modname) { \
1344
+ node_module_register(&_module); \
1345
+ } \
1346
+ }
1347
+
1348
+ // Usage: `NODE_MODULE(NODE_GYP_MODULE_NAME, InitializerFunction)`
1349
+ // If no NODE_MODULE is declared, Node.js looks for the well-known
1350
+ // symbol `node_register_module_v${NODE_MODULE_VERSION}`.
1351
+ #define NODE_MODULE(modname, regfunc) \
1352
+ NODE_MODULE_X(modname, regfunc, NULL, 0) // NOLINT (readability/null_usage)
1353
+
1354
+ #define NODE_MODULE_CONTEXT_AWARE(modname, regfunc) \
1355
+ /* NOLINTNEXTLINE (readability/null_usage) */ \
1356
+ NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, 0)
1357
+
1358
+ // Embedders can use this type of binding for statically linked native bindings.
1359
+ // It is used the same way addon bindings are used, except that linked bindings
1360
+ // can be accessed through `process._linkedBinding(modname)`.
1361
+ #define NODE_MODULE_LINKED(modname, regfunc) \
1362
+ /* NOLINTNEXTLINE (readability/null_usage) */ \
1363
+ NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, \
1364
+ node::ModuleFlags::kLinked)
1365
+
1366
+ /*
1367
+ * For backward compatibility in add-on modules.
1368
+ */
1369
+ #define NODE_MODULE_DECL /* nothing */
1370
+
1371
+ #define NODE_MODULE_INITIALIZER_BASE node_register_module_v
1372
+
1373
+ #define NODE_MODULE_INITIALIZER_X(base, version) \
1374
+ NODE_MODULE_INITIALIZER_X_HELPER(base, version)
1375
+
1376
+ #define NODE_MODULE_INITIALIZER_X_HELPER(base, version) base##version
1377
+
1378
+ #define NODE_MODULE_INITIALIZER \
1379
+ NODE_MODULE_INITIALIZER_X(NODE_MODULE_INITIALIZER_BASE, \
1380
+ NODE_MODULE_VERSION)
1381
+
1382
+ #define NODE_MODULE_INIT() \
1383
+ extern "C" NODE_MODULE_EXPORT void \
1384
+ NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports, \
1385
+ v8::Local<v8::Value> module, \
1386
+ v8::Local<v8::Context> context); \
1387
+ NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, \
1388
+ NODE_MODULE_INITIALIZER) \
1389
+ void NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports, \
1390
+ v8::Local<v8::Value> module, \
1391
+ v8::Local<v8::Context> context)
1392
+
1393
+ // Allows embedders to add a binding to the current Environment* that can be
1394
+ // accessed through process._linkedBinding() in the target Environment and all
1395
+ // Worker threads that it creates.
1396
+ // In each variant, the registration function needs to be usable at least for
1397
+ // the time during which the Environment exists.
1398
+ NODE_EXTERN void AddLinkedBinding(Environment* env, const node_module& mod);
1399
+ NODE_EXTERN void AddLinkedBinding(Environment* env,
1400
+ const struct napi_module& mod);
1401
+ NODE_EXTERN void AddLinkedBinding(Environment* env,
1402
+ const char* name,
1403
+ addon_context_register_func fn,
1404
+ void* priv);
1405
+ NODE_EXTERN void AddLinkedBinding(
1406
+ Environment* env,
1407
+ const char* name,
1408
+ napi_addon_register_func fn,
1409
+ int32_t module_api_version = NODE_API_DEFAULT_MODULE_API_VERSION);
1410
+
1411
+ /* Registers a callback with the passed-in Environment instance. The callback
1412
+ * is called after the event loop exits, but before the VM is disposed.
1413
+ * Callbacks are run in reverse order of registration, i.e. newest first.
1414
+ */
1415
+ NODE_EXTERN void AtExit(Environment* env,
1416
+ void (*cb)(void* arg),
1417
+ void* arg);
1418
+
1419
+ typedef double async_id;
1420
+ struct async_context {
1421
+ ::node::async_id async_id;
1422
+ ::node::async_id trigger_async_id;
1423
+ };
1424
+
1425
+ /* This is a lot like node::AtExit, except that the hooks added via this
1426
+ * function are run before the AtExit ones and will always be registered
1427
+ * for the current Environment instance.
1428
+ * These functions are safe to use in an addon supporting multiple
1429
+ * threads/isolates. */
1430
+ NODE_EXTERN void AddEnvironmentCleanupHook(v8::Isolate* isolate,
1431
+ void (*fun)(void* arg),
1432
+ void* arg);
1433
+
1434
+ NODE_EXTERN void RemoveEnvironmentCleanupHook(v8::Isolate* isolate,
1435
+ void (*fun)(void* arg),
1436
+ void* arg);
1437
+
1438
+ /* These are async equivalents of the above. After the cleanup hook is invoked,
1439
+ * `cb(cbarg)` *must* be called, and attempting to remove the cleanup hook will
1440
+ * have no effect. */
1441
+ struct ACHHandle;
1442
+ struct NODE_EXTERN DeleteACHHandle { void operator()(ACHHandle*) const; };
1443
+ typedef std::unique_ptr<ACHHandle, DeleteACHHandle> AsyncCleanupHookHandle;
1444
+
1445
+ /* This function is not intended to be used externally, it exists to aid in
1446
+ * keeping ABI compatibility between Node and Electron. */
1447
+ NODE_EXTERN ACHHandle* AddEnvironmentCleanupHookInternal(
1448
+ v8::Isolate* isolate,
1449
+ void (*fun)(void* arg, void (*cb)(void*), void* cbarg),
1450
+ void* arg);
1451
+ inline AsyncCleanupHookHandle AddEnvironmentCleanupHook(
1452
+ v8::Isolate* isolate,
1453
+ void (*fun)(void* arg, void (*cb)(void*), void* cbarg),
1454
+ void* arg) {
1455
+ return AsyncCleanupHookHandle(AddEnvironmentCleanupHookInternal(isolate, fun,
1456
+ arg));
1457
+ }
1458
+
1459
+ /* This function is not intended to be used externally, it exists to aid in
1460
+ * keeping ABI compatibility between Node and Electron. */
1461
+ NODE_EXTERN void RemoveEnvironmentCleanupHookInternal(ACHHandle* holder);
1462
+ inline void RemoveEnvironmentCleanupHook(AsyncCleanupHookHandle holder) {
1463
+ RemoveEnvironmentCleanupHookInternal(holder.get());
1464
+ }
1465
+
1466
+ // This behaves like V8's Isolate::RequestInterrupt(), but also wakes up
1467
+ // the event loop if it is currently idle. Interrupt requests are drained
1468
+ // in `FreeEnvironment()`. The passed callback can not call back into
1469
+ // JavaScript.
1470
+ // This function can be called from any thread.
1471
+ NODE_EXTERN void RequestInterrupt(Environment* env,
1472
+ void (*fun)(void* arg),
1473
+ void* arg);
1474
+
1475
+ /* Returns the id of the current execution context. If the return value is
1476
+ * zero then no execution has been set. This will happen if the user handles
1477
+ * I/O from native code. */
1478
+ NODE_EXTERN async_id AsyncHooksGetExecutionAsyncId(v8::Isolate* isolate);
1479
+
1480
+ /* Returns the id of the current execution context. If the return value is
1481
+ * zero then no execution has been set. This will happen if the user handles
1482
+ * I/O from native code. */
1483
+ NODE_EXTERN async_id
1484
+ AsyncHooksGetExecutionAsyncId(v8::Local<v8::Context> context);
1485
+
1486
+ /* Return same value as async_hooks.triggerAsyncId(); */
1487
+ NODE_EXTERN async_id AsyncHooksGetTriggerAsyncId(v8::Isolate* isolate);
1488
+
1489
+ /* If the native API doesn't inherit from the helper class then the callbacks
1490
+ * must be triggered manually. This triggers the init() callback. The return
1491
+ * value is the async id assigned to the resource.
1492
+ *
1493
+ * The `trigger_async_id` parameter should correspond to the resource which is
1494
+ * creating the new resource, which will usually be the return value of
1495
+ * `AsyncHooksGetTriggerAsyncId()`. */
1496
+ NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
1497
+ v8::Local<v8::Object> resource,
1498
+ const char* name,
1499
+ async_id trigger_async_id = -1);
1500
+ NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
1501
+ v8::Local<v8::Object> resource,
1502
+ std::string_view name,
1503
+ async_id trigger_async_id = -1);
1504
+
1505
+ NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
1506
+ v8::Local<v8::Object> resource,
1507
+ v8::Local<v8::String> name,
1508
+ async_id trigger_async_id = -1);
1509
+
1510
+ /* Emit the destroy() callback. The overload taking an `Environment*` argument
1511
+ * should be used when the Isolate’s current Context is not associated with
1512
+ * a Node.js Environment, or when there is no current Context, for example
1513
+ * when calling this function during garbage collection. In that case, the
1514
+ * `Environment*` value should have been acquired previously, e.g. through
1515
+ * `GetCurrentEnvironment()`. */
1516
+ NODE_EXTERN void EmitAsyncDestroy(v8::Isolate* isolate,
1517
+ async_context asyncContext);
1518
+ NODE_EXTERN void EmitAsyncDestroy(Environment* env,
1519
+ async_context asyncContext);
1520
+
1521
+ class InternalCallbackScope;
1522
+
1523
+ /* This class works like `MakeCallback()` in that it sets up a specific
1524
+ * asyncContext as the current one and informs the async_hooks and domains
1525
+ * modules that this context is currently active.
1526
+ *
1527
+ * `MakeCallback()` is a wrapper around this class as well as
1528
+ * `Function::Call()`. Either one of these mechanisms needs to be used for
1529
+ * top-level calls into JavaScript (i.e. without any existing JS stack).
1530
+ *
1531
+ * This object should be stack-allocated to ensure that it is contained in a
1532
+ * valid HandleScope.
1533
+ *
1534
+ * Exceptions happening within this scope will be treated like uncaught
1535
+ * exceptions. If this behaviour is undesirable, a new `v8::TryCatch` scope
1536
+ * needs to be created inside of this scope.
1537
+ */
1538
+ class NODE_EXTERN CallbackScope {
1539
+ public:
1540
+ CallbackScope(v8::Isolate* isolate,
1541
+ v8::Local<v8::Object> resource,
1542
+ async_context asyncContext);
1543
+ CallbackScope(Environment* env,
1544
+ v8::Local<v8::Object> resource,
1545
+ async_context asyncContext);
1546
+ // `resource` needs to outlive the scope in this case.
1547
+ // This is for the rare situation in which `CallbackScope` cannot be
1548
+ // stack-allocated. `resource` needs to outlive this scope.
1549
+ CallbackScope(Environment* env,
1550
+ v8::Global<v8::Object>* resource,
1551
+ async_context asyncContext);
1552
+ ~CallbackScope();
1553
+
1554
+ void operator=(const CallbackScope&) = delete;
1555
+ void operator=(CallbackScope&&) = delete;
1556
+ CallbackScope(const CallbackScope&) = delete;
1557
+ CallbackScope(CallbackScope&&) = delete;
1558
+
1559
+ private:
1560
+ [[maybe_unused]] void* reserved_;
1561
+ union {
1562
+ v8::Local<v8::Object> local;
1563
+ v8::Global<v8::Object>* global_ptr;
1564
+ } resource_storage_;
1565
+ InternalCallbackScope* private_;
1566
+ v8::TryCatch try_catch_;
1567
+ };
1568
+
1569
+ /* An API specific to emit before/after callbacks is unnecessary because
1570
+ * MakeCallback will automatically call them for you.
1571
+ *
1572
+ * These methods may create handles on their own, so run them inside a
1573
+ * HandleScope.
1574
+ *
1575
+ * `asyncId` and `triggerAsyncId` should correspond to the values returned by
1576
+ * `EmitAsyncInit()` and `AsyncHooksGetTriggerAsyncId()`, respectively, when the
1577
+ * invoking resource was created. If these values are unknown, 0 can be passed.
1578
+ * */
1579
+ NODE_EXTERN
1580
+ v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1581
+ v8::Local<v8::Object> recv,
1582
+ v8::Local<v8::Function> callback,
1583
+ int argc,
1584
+ v8::Local<v8::Value>* argv,
1585
+ async_context asyncContext);
1586
+ NODE_EXTERN
1587
+ v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1588
+ v8::Local<v8::Object> recv,
1589
+ const char* method,
1590
+ int argc,
1591
+ v8::Local<v8::Value>* argv,
1592
+ async_context asyncContext);
1593
+ NODE_EXTERN
1594
+ v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1595
+ v8::Local<v8::Object> recv,
1596
+ v8::Local<v8::String> symbol,
1597
+ int argc,
1598
+ v8::Local<v8::Value>* argv,
1599
+ async_context asyncContext);
1600
+
1601
+ /* Helper class users can optionally inherit from. If
1602
+ * `AsyncResource::MakeCallback()` is used, then all four callbacks will be
1603
+ * called automatically. */
1604
+ class NODE_EXTERN AsyncResource {
1605
+ public:
1606
+ AsyncResource(v8::Isolate* isolate,
1607
+ v8::Local<v8::Object> resource,
1608
+ const char* name,
1609
+ async_id trigger_async_id = -1);
1610
+ AsyncResource(v8::Isolate* isolate,
1611
+ v8::Local<v8::Object> resource,
1612
+ std::string_view name,
1613
+ async_id trigger_async_id = -1);
1614
+
1615
+ virtual ~AsyncResource();
1616
+
1617
+ AsyncResource(const AsyncResource&) = delete;
1618
+ void operator=(const AsyncResource&) = delete;
1619
+
1620
+ v8::MaybeLocal<v8::Value> MakeCallback(
1621
+ v8::Local<v8::Function> callback,
1622
+ int argc,
1623
+ v8::Local<v8::Value>* argv);
1624
+
1625
+ v8::MaybeLocal<v8::Value> MakeCallback(
1626
+ const char* method,
1627
+ int argc,
1628
+ v8::Local<v8::Value>* argv);
1629
+
1630
+ v8::MaybeLocal<v8::Value> MakeCallback(
1631
+ v8::Local<v8::String> symbol,
1632
+ int argc,
1633
+ v8::Local<v8::Value>* argv);
1634
+
1635
+ v8::Local<v8::Object> get_resource();
1636
+ async_id get_async_id() const;
1637
+ async_id get_trigger_async_id() const;
1638
+
1639
+ protected:
1640
+ class NODE_EXTERN CallbackScope : public node::CallbackScope {
1641
+ public:
1642
+ explicit CallbackScope(AsyncResource* res);
1643
+ };
1644
+
1645
+ private:
1646
+ Environment* env_;
1647
+ v8::Global<v8::Object> resource_;
1648
+ v8::Global<v8::Value> context_frame_;
1649
+ async_context async_context_;
1650
+ };
1651
+
1652
+ #ifndef _WIN32
1653
+ // Register a signal handler without interrupting any handlers that node
1654
+ // itself needs. This does override handlers registered through
1655
+ // process.on('SIG...', function() { ... }). The `reset_handler` flag indicates
1656
+ // whether the signal handler for the given signal should be reset to its
1657
+ // default value before executing the handler (i.e. it works like SA_RESETHAND).
1658
+ // The `reset_handler` flag is invalid when `signal` is SIGSEGV.
1659
+ NODE_EXTERN
1660
+ void RegisterSignalHandler(int signal,
1661
+ void (*handler)(int signal,
1662
+ siginfo_t* info,
1663
+ void* ucontext),
1664
+ bool reset_handler = false);
1665
+ #endif // _WIN32
1666
+
1667
+ // This is kept as a compatibility layer for addons to wrap cppgc-managed
1668
+ // objects on Node.js versions without v8::Object::Wrap(). Addons created to
1669
+ // work with only Node.js versions with v8::Object::Wrap() should use that
1670
+ // instead.
1671
+ NODE_DEPRECATED(
1672
+ "Use v8::Object::Wrap()",
1673
+ NODE_EXTERN void SetCppgcReference(v8::Isolate* isolate,
1674
+ v8::Local<v8::Object> object,
1675
+ v8::Object::Wrappable* wrappable));
1676
+
1677
+ namespace crypto {
1678
+
1679
+ // Returns the SSL_CTX* from a SecureContext JS object, as returned by
1680
+ // tls.createSecureContext().
1681
+ // Returns nullptr if the value is not a SecureContext instance,
1682
+ // or if Node.js was built without OpenSSL.
1683
+ //
1684
+ // The returned pointer is not owned by the caller and must not be freed.
1685
+ // It is valid only while the SecureContext JS object remains alive.
1686
+ NODE_EXTERN struct ssl_ctx_st* GetSSLCtx(v8::Local<v8::Context> context,
1687
+ v8::Local<v8::Value> secure_context);
1688
+
1689
+ } // namespace crypto
1690
+
1691
+ } // namespace node
1692
+
1693
+ #endif // SRC_NODE_H_