-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathNodeApiMultiHost.ts
More file actions
263 lines (232 loc) · 8.6 KB
/
NodeApiMultiHost.ts
File metadata and controls
263 lines (232 loc) · 8.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import type { FunctionDecl } from "../../src/node-api-functions.js";
import { generateFunction } from "./shared.js";
const ARGUMENT_NAMES_PR_FUNCTION: Record<string, undefined | string[]> = {
napi_create_threadsafe_function: [
"env",
"func",
"async_resource",
"async_resource_name",
"max_queue_size",
"initial_thread_count",
"thread_finalize_data",
"thread_finalize_cb",
"context",
"call_js_cb",
"result",
],
napi_add_async_cleanup_hook: ["env", "hook", "arg", "remove_handle"],
napi_fatal_error: ["location", "location_len", "message", "message_len"],
};
export function generateFunctionDecl(fn: FunctionDecl) {
return generateFunction({ ...fn, static: true });
}
export function generateHeader(functions: FunctionDecl[]) {
return `
#pragma once
#include <memory>
#include <vector>
#include <node_api.h>
#include "NodeApiHost.hpp"
struct NodeApiMultiHost : public NodeApiHost {
struct WrappedEnv;
struct WrappedThreadsafeFunction {
napi_threadsafe_function value;
WrappedEnv *env;
std::weak_ptr<NodeApiHost> host;
};
struct WrappedAsyncCleanupHookHandle {
napi_async_cleanup_hook_handle value;
WrappedEnv *env;
std::weak_ptr<NodeApiHost> host;
};
struct WrappedEnv {
WrappedEnv(napi_env &&value, std::weak_ptr<NodeApiHost> &&host);
napi_env value;
std::weak_ptr<NodeApiHost> host;
private:
std::vector<std::unique_ptr<WrappedThreadsafeFunction>>
threadsafe_functions;
std::vector<std::unique_ptr<WrappedAsyncCleanupHookHandle>>
async_cleanup_hook_handles;
public:
napi_threadsafe_function wrap(napi_threadsafe_function original,
WrappedEnv *env,
std::weak_ptr<NodeApiHost>);
napi_async_cleanup_hook_handle wrap(napi_async_cleanup_hook_handle original,
WrappedEnv *env,
std::weak_ptr<NodeApiHost>);
};
napi_env wrap(napi_env original, std::weak_ptr<NodeApiHost>);
NodeApiMultiHost(
void napi_module_register(napi_module *),
void napi_fatal_error(const char *, size_t, const char *, size_t)
);
private:
std::vector<std::unique_ptr<WrappedEnv>> envs;
public:
${functions.map(generateFunctionDecl).join("\n")}
};
`;
}
function generateFunctionImpl(fn: FunctionDecl) {
const { name, argumentTypes, returnType } = fn;
const [firstArgument] = argumentTypes;
const argumentNames =
ARGUMENT_NAMES_PR_FUNCTION[name] ??
argumentTypes.map((_, index) => `arg${index}`);
if (name === "napi_fatal_error") {
// Providing a default implementation
return generateFunction({
...fn,
namespace: "NodeApiMultiHost",
argumentNames,
body: `
if (location && location_len) {
fprintf(stderr, "Fatal Node-API error: %.*s %.*s",
static_cast<int>(location_len),
location,
static_cast<int>(message_len),
message
);
} else {
fprintf(stderr, "Fatal Node-API error: %.*s", static_cast<int>(message_len), message);
}
abort();
`,
});
} else if (name === "napi_module_register") {
// Providing a default implementation
return generateFunction({
...fn,
namespace: "NodeApiMultiHost",
argumentNames: [""],
body: `
fprintf(stderr, "napi_module_register is not implemented for this NodeApiMultiHost");
abort();
`,
});
} else if (
[
"napi_env",
"node_api_basic_env",
"napi_threadsafe_function",
"napi_async_cleanup_hook_handle",
].includes(firstArgument)
) {
const joinedArguments = argumentTypes
.map((_, index) =>
index === 0 ? "wrapped->value" : argumentNames[index],
)
.join(", ");
function generateCall() {
if (name === "napi_create_threadsafe_function") {
return `
auto status = host->${name}(${joinedArguments});
if (status == napi_status::napi_ok) {
*${argumentNames[10]} = wrapped->wrap(*${argumentNames[10]}, wrapped, wrapped->host);
}
return status;
`;
} else if (name === "napi_add_async_cleanup_hook") {
return `
auto status = host->${name}(${joinedArguments});
if (status == napi_status::napi_ok) {
*${argumentNames[3]} = wrapped->wrap(*${argumentNames[3]}, wrapped, wrapped->host);
}
return status;
`;
} else {
return `
${returnType === "void" ? "" : "return"} host->${name}(${joinedArguments});
`;
}
}
function getWrappedType(nodeApiType: string) {
if (nodeApiType === "napi_env" || nodeApiType === "node_api_basic_env") {
return "WrappedEnv";
} else if (nodeApiType === "napi_threadsafe_function") {
return "WrappedThreadsafeFunction";
} else if (nodeApiType === "napi_async_cleanup_hook_handle") {
return "WrappedAsyncCleanupHookHandle";
} else {
throw new Error(`Unexpected Node-API type '${nodeApiType}'`);
}
}
return generateFunction({
...fn,
namespace: "NodeApiMultiHost",
argumentNames,
body: `
auto wrapped = reinterpret_cast<${getWrappedType(firstArgument)}*>(${argumentNames[0]});
if (auto host = wrapped->host.lock()) {
if (host->${name} == nullptr) {
fprintf(stderr, "Node-API function '${name}' called on a host which doesn't provide an implementation\\n");
return napi_status::napi_generic_failure;
}
${generateCall()}
} else {
fprintf(stderr, "Node-API function '${name}' called after host was destroyed.\\n");
return napi_status::napi_generic_failure;
}
`,
});
} else {
throw new Error(`Unexpected signature for '${name}' Node-API function`);
}
}
export function generateSource(functions: FunctionDecl[]) {
return `
#include "NodeApiMultiHost.hpp"
NodeApiMultiHost::NodeApiMultiHost(
void napi_module_register(napi_module *),
void napi_fatal_error(const char *, size_t, const char *, size_t)
)
: NodeApiHost({
${functions
.map(({ name }) => {
if (
name === "napi_module_register" ||
name === "napi_fatal_error"
) {
// We take functions not taking a wrap-able argument via the constructor and call them directly
return `.${name} = ${name} == nullptr ? NodeApiMultiHost::${name} : ${name},`;
} else {
return `.${name} = NodeApiMultiHost::${name},`;
}
})
.join("\n")}
}), envs{} {};
// TODO: Ensure the Node-API functions aren't throwing (using NOEXCEPT)
// TODO: Find a better way to delete these along the way
NodeApiMultiHost::WrappedEnv::WrappedEnv(napi_env &&value,
std::weak_ptr<NodeApiHost> &&host)
: value(value), host(host), threadsafe_functions{},
async_cleanup_hook_handles{} {}
napi_env NodeApiMultiHost::wrap(napi_env value,
std::weak_ptr<NodeApiHost> host) {
auto ptr = std::make_unique<WrappedEnv>(std::move(value), std::move(host));
auto raw_ptr = ptr.get();
envs.push_back(std::move(ptr));
return reinterpret_cast<napi_env>(raw_ptr);
}
napi_threadsafe_function
NodeApiMultiHost::WrappedEnv::wrap(napi_threadsafe_function original,
WrappedEnv *env,
std::weak_ptr<NodeApiHost> weak_host) {
auto ptr = std::make_unique<WrappedThreadsafeFunction>(original, env, weak_host);
auto raw_ptr = ptr.get();
env->threadsafe_functions.push_back(std::move(ptr));
return reinterpret_cast<napi_threadsafe_function>(raw_ptr);
}
napi_async_cleanup_hook_handle
NodeApiMultiHost::WrappedEnv::wrap(napi_async_cleanup_hook_handle original,
WrappedEnv *env,
std::weak_ptr<NodeApiHost> weak_host) {
auto ptr = std::make_unique<WrappedAsyncCleanupHookHandle>(original, env, weak_host);
auto raw_ptr = ptr.get();
env->async_cleanup_hook_handles.push_back(std::move(ptr));
return reinterpret_cast<napi_async_cleanup_hook_handle>(raw_ptr);
}
${functions.map(generateFunctionImpl).join("\n")}
`;
}