@encharm/cws 4.5.1 → 4.5.2

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