-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathgenerate-weak-node-api-injector.ts
More file actions
69 lines (58 loc) · 2.17 KB
/
generate-weak-node-api-injector.ts
File metadata and controls
69 lines (58 loc) · 2.17 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
import fs from "node:fs";
import path from "node:path";
import { spawnSyncCrossPlatform } from "./platform-utils.js";
import { FunctionDecl, getNodeApiFunctions } from "./node-api-functions";
export const CPP_SOURCE_PATH = path.join(__dirname, "../cpp");
/**
* Generates source code which injects the Node API functions from the host.
*/
export function generateSource(functions: FunctionDecl[]) {
return `
// This file is generated by react-native-node-api-modules
#include <Logger.hpp>
#include <dlfcn.h>
#include <weak_node_api.hpp>
#if defined(__APPLE__)
#define WEAK_NODE_API_LIBRARY_NAME "@rpath/weak-node-api.framework/weak-node-api"
#elif defined(__ANDROID__)
#define WEAK_NODE_API_LIBRARY_NAME "libweak-node-api.so"
#elif defined(_WIN32)
#define WEAK_NODE_API_LIBRARY_NAME "weak-node-api.dll"
#else
#error "WEAK_NODE_API_LIBRARY_NAME cannot be defined for this platform"
#endif
namespace callstack::nodeapihost {
void injectIntoWeakNodeApi() {
void *module = dlopen(WEAK_NODE_API_LIBRARY_NAME, RTLD_NOW | RTLD_LOCAL);
if (nullptr == module) {
log_debug("NapiHost: Failed to load weak-node-api: %s", dlerror());
abort();
}
auto inject_weak_node_api_host = (InjectHostFunction)dlsym(
module, "inject_weak_node_api_host");
if (nullptr == inject_weak_node_api_host) {
log_debug("NapiHost: Failed to find 'inject_weak_node_api_host' function: %s", dlerror());
abort();
}
log_debug("Injecting WeakNodeApiHost");
inject_weak_node_api_host(WeakNodeApiHost {
${functions
.filter(({ kind }) => kind === "engine")
.flatMap(({ name }) => `.${name} = ${name},`)
.join("\n")}
});
}
} // namespace callstack::nodeapihost
`;
}
async function run() {
const nodeApiFunctions = getNodeApiFunctions();
const source = generateSource(nodeApiFunctions);
const sourcePath = path.join(CPP_SOURCE_PATH, "WeakNodeApiInjector.cpp");
await fs.promises.writeFile(sourcePath, source, "utf-8");
spawnSyncCrossPlatform("clang-format", ["-i", sourcePath], { stdio: "inherit" });
}
run().catch((err) => {
console.error(err);
process.exitCode = 1;
});