Skip to content

Commit 29ca6a3

Browse files
kraenhansenclaude
andauthored
Build addon paths in TypeScript and expose dlopen(module, filename) (#500)
* Build addon paths in TypeScript and expose dlopen(module, filename) Move platform path construction and the exports cache out of CxxNodeApiHostModule into TypeScript, replacing the native requireNodeAddon with a dlopen(module, filename) matching Node's process.dlopen. requireNodeAddon is rebuilt on top of it. Refs #498 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U2xSE4KqJbTcKKr4FKKUX2 * Trigger CI with labels applied Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U2xSE4KqJbTcKKr4FKKUX2 * Trigger CI against next Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01U2xSE4KqJbTcKKr4FKKUX2 --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 831e233 commit 29ca6a3

5 files changed

Lines changed: 138 additions & 134 deletions

File tree

‎.changeset/expose-dlopen.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"react-native-node-api": minor
3+
---
4+
5+
Export `dlopen(module, filename)`, loading a Node-API addon with the same semantics as Node's `process.dlopen`: `filename` is passed as-is to the system's `dlopen` (e.g. `lib<name>.so` on Android, `@rpath/<name>.framework/<name>` on Apple platforms), the addon's exports are assigned to `module.exports` and nothing is cached.
6+
7+
`requireNodeAddon` is now built on top of it, with the platform specific path and the per-runtime exports cache moving from native code into TypeScript. Its behavior is unchanged.

‎docs/HOW-IT-WORKS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,13 +93,13 @@ module.exports = require("react-native-node-api").requireNodeAddon(
9393
9494
## `react-native-node-api` creates a `napi_env` for the addon
9595

96-
The native implementation of `requireNodeAddon` turns the library name into a platform specific path (`@rpath/<name>.framework/<name>` on Apple platforms, `lib<name>.so` on Android) and creates a `napi_env` for the addon by calling `hermes_napi_create_env` with the low-level Hermes VM runtime behind the `jsi::Runtime`. As in Node.js, each addon gets its own environment.
96+
`requireNodeAddon` returns the exports cached from an earlier load of the same library. Otherwise it turns the library name into a platform specific path (`@rpath/<name>.framework/<name>` on Apple platforms, `lib<name>.so` on Android) and calls `dlopen(module, filename)`, which has the same semantics as Node's `process.dlopen`. The native implementation of `dlopen` creates a `napi_env` for the addon by calling `hermes_napi_create_env` with the low-level Hermes VM runtime behind the `jsi::Runtime`. As in Node.js, each load gets its own environment.
9797

9898
## Hermes loads the platform specific dynamic library and initializes the addon
9999

100100
The host hands the path and the environment to `hermes_napi_load_module`, which opens the dynamic library and finds the addon's initialization function, either by looking up an exported `napi_register_module_v1` symbol or by falling back to the `napi_module` passed to a (deprecated) `napi_module_register` call made while the library was loading. It then calls that function with the environment and a fresh `exports` object.
101101

102-
If the library cannot be opened, or exports no initialization function, `requireNodeAddon` throws.
102+
If the library cannot be opened, or exports no initialization function, `dlopen` throws (and so does `requireNodeAddon`, without caching the failure). Otherwise the resulting exports object is assigned to `module.exports`.
103103

104104
## The library's C++ code initialize the `exports` object
105105

‎packages/host/cpp/CxxNodeApiHostModule.cpp‎

Lines changed: 69 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -13,40 +13,60 @@ namespace callstack::react_native_node_api {
1313

1414
namespace {
1515

16-
/// Renders the exception Hermes left pending on `env` as a message, clearing
17-
/// it so the env is usable again. Returns an empty string if the exception
18-
/// cannot be read, in which case the caller reports the status alone.
19-
std::string takePendingExceptionMessage(napi_env env) {
16+
/// Hands `value` over to JSI. Hermes has no public bridge between `napi_value`
17+
/// and `jsi::Value`, so it crosses through a global property named after the
18+
/// env (unique per runtime), which is removed again straight after.
19+
jsi::Value toJsiValue(jsi::Runtime &rt, napi_env env, napi_value value) {
20+
char name[32];
21+
snprintf(name, sizeof(name), "RN$NodeAddon_%p", static_cast<void *>(env));
22+
23+
napi_value global = nullptr;
24+
napi_status status = napi_get_global(env, &global);
25+
assert(status == napi_ok);
26+
status = napi_set_named_property(env, global, name, value);
27+
assert(status == napi_ok);
28+
29+
jsi::Value result = rt.global().getProperty(rt, name);
30+
31+
napi_value key = nullptr;
32+
status = napi_create_string_utf8(env, name, NAPI_AUTO_LENGTH, &key);
33+
assert(status == napi_ok);
34+
bool deleted = false;
35+
status = napi_delete_property(env, global, key, &deleted);
36+
assert(status == napi_ok && deleted);
37+
(void)status;
38+
(void)deleted;
39+
return result;
40+
}
41+
42+
/// Takes the exception Hermes left pending on `env`, clearing it so the env is
43+
/// usable again, or creates an error from `status` if there is none.
44+
napi_value takeLoadError(napi_env env, napi_status status) {
2045
napi_value error = nullptr;
21-
if (napi_get_and_clear_last_exception(env, &error) != napi_ok ||
22-
error == nullptr) {
23-
return {};
24-
}
25-
napi_value asString = nullptr;
26-
if (napi_coerce_to_string(env, error, &asString) != napi_ok) {
27-
return {};
28-
}
29-
size_t length = 0;
30-
if (napi_get_value_string_utf8(env, asString, nullptr, 0, &length) !=
31-
napi_ok) {
32-
return {};
33-
}
34-
std::string message(length, '\0');
35-
if (napi_get_value_string_utf8(env, asString, message.data(), length + 1,
36-
&length) != napi_ok) {
37-
return {};
46+
if (napi_get_and_clear_last_exception(env, &error) == napi_ok &&
47+
error != nullptr) {
48+
napi_valuetype type = napi_undefined;
49+
if (napi_typeof(env, error, &type) == napi_ok && type != napi_undefined) {
50+
return error;
51+
}
3852
}
39-
message.resize(length);
40-
return message;
53+
const std::string message = "Node-API status " + std::to_string(status);
54+
napi_value messageValue = nullptr;
55+
napi_status createStatus = napi_create_string_utf8(
56+
env, message.c_str(), message.size(), &messageValue);
57+
assert(createStatus == napi_ok);
58+
createStatus = napi_create_error(env, nullptr, messageValue, &error);
59+
assert(createStatus == napi_ok);
60+
(void)createStatus;
61+
return error;
4162
}
4263

4364
} // namespace
4465

4566
CxxNodeApiHostModule::CxxNodeApiHostModule(
4667
std::shared_ptr<react::CallInvoker> jsInvoker)
4768
: TurboModule(CxxNodeApiHostModule::kModuleName, jsInvoker) {
48-
methodMap_["requireNodeAddon"] =
49-
MethodMetadata{1, &CxxNodeApiHostModule::requireNodeAddon};
69+
methodMap_["dlopen"] = MethodMetadata{2, &CxxNodeApiHostModule::dlopen};
5070

5171
callInvoker_ = std::move(jsInvoker);
5272

@@ -85,60 +105,26 @@ CxxNodeApiHostModule::CxxNodeApiHostModule(
85105
HostContext::retainForProcessLifetime(hostContext_);
86106
}
87107

88-
jsi::Value
89-
CxxNodeApiHostModule::requireNodeAddon(jsi::Runtime &rt,
90-
react::TurboModule &turboModule,
91-
const jsi::Value args[], size_t count) {
108+
jsi::Value CxxNodeApiHostModule::dlopen(jsi::Runtime &rt,
109+
react::TurboModule &turboModule,
110+
const jsi::Value args[], size_t count) {
92111
auto &thisModule = static_cast<CxxNodeApiHostModule &>(turboModule);
93-
if (1 == count && args[0].isString()) {
94-
return thisModule.requireNodeAddon(rt, args[0].asString(rt));
112+
if (count >= 2 && args[0].isObject() && args[1].isString()) {
113+
thisModule.dlopen(rt, args[0].asObject(rt), args[1].asString(rt).utf8(rt));
114+
return jsi::Value::undefined();
95115
}
96-
throw jsi::JSError(rt, "Expected requireNodeAddon to be called with a single "
97-
"library name string");
116+
throw jsi::JSError(
117+
rt, "Expected dlopen to be called with a module object and a filename");
98118
}
99119

100-
jsi::Value
101-
CxxNodeApiHostModule::requireNodeAddon(jsi::Runtime &rt,
102-
const jsi::String libraryName) {
103-
const std::string libraryNameStr = libraryName.utf8(rt);
104-
105-
auto [it, inserted] = nodeAddons_.emplace(libraryNameStr, NodeAddon());
106-
NodeAddon &addon = it->second;
107-
108-
// Check if this module has been loaded already, if not then load it...
109-
if (inserted) {
110-
try {
111-
loadNodeAddon(rt, addon, libraryNameStr);
112-
} catch (...) {
113-
// Leave no half-initialized entry behind, so a later require of the same
114-
// addon retries the load instead of reading a missing global.
115-
nodeAddons_.erase(it);
116-
throw;
117-
}
118-
}
119-
120-
// Look the exports up (using JSI) and return it...
121-
return rt.global().getProperty(rt, addon.generatedName.c_str());
122-
}
123-
124-
void CxxNodeApiHostModule::loadNodeAddon(jsi::Runtime &rt, NodeAddon &addon,
125-
const std::string &libraryName) {
126-
#if defined(__APPLE__)
127-
const std::string libraryPath =
128-
"@rpath/" + libraryName + ".framework/" + libraryName;
129-
#elif defined(__ANDROID__)
130-
const std::string libraryPath = "lib" + libraryName + ".so";
131-
#else
132-
#error "Loading Node-API addons is unsupported on this platform"
133-
#endif
134-
135-
log_debug("[%s] Loading addon by '%s'", libraryName.c_str(),
136-
libraryPath.c_str());
120+
void CxxNodeApiHostModule::dlopen(jsi::Runtime &rt, const jsi::Object &module,
121+
const std::string &filename) {
122+
log_debug("Loading addon from '%s'", filename.c_str());
137123

138124
// Create this addon's Node-API environment. Hermes binds an env to its
139125
// low-level VM runtime, which we reach through the (unstable) IHermes JSI
140126
// interface, and takes ownership: the env is torn down with the runtime, so
141-
// there is nothing to free here. Each addon gets its own env, as in Node.
127+
// there is nothing to free here. Each load gets its own env, as in Node.
142128
//
143129
// Fully qualified: `using namespace facebook` makes a bare `hermes`
144130
// ambiguous with the top-level `::hermes` (VM) namespace pulled in via
@@ -149,52 +135,32 @@ void CxxNodeApiHostModule::loadNodeAddon(jsi::Runtime &rt, NodeAddon &addon,
149135
"create a Node-API environment");
150136
abort();
151137
}
152-
addon.env = hermes_napi_create_env(hermes->getVMRuntimeUnsafe(),
153-
hostContext_->host());
154-
assert(addon.env != nullptr);
155-
napi_env env = addon.env;
156-
157-
// A name to reference the exports object by from JSI. Instead of using
158-
// random numbers to avoid name clashes, we use the address of the env, which
159-
// is unique per addon per runtime.
160-
char generatedName[32];
161-
snprintf(generatedName, sizeof(generatedName), "RN$NodeAddon_%p",
162-
static_cast<void *>(env));
163-
addon.generatedName = generatedName;
138+
napi_env env = hermes_napi_create_env(hermes->getVMRuntimeUnsafe(),
139+
hostContext_->host());
140+
assert(env != nullptr);
164141

165142
// Every napi_value below is created in this scope, and only reachable from
166-
// the JavaScript global (or dropped) once it closes.
143+
// JSI (or dropped) once it closes.
167144
napi_handle_scope scope = nullptr;
168145
napi_status status = napi_open_handle_scope(env, &scope);
169146
assert(status == napi_ok);
170147

148+
// Hermes creates the exports object itself rather than taking
149+
// `module.exports`, so its result replaces `module.exports` below.
171150
napi_value exports = nullptr;
172-
status = hermes_napi_load_module(env, libraryPath.c_str(), &exports);
173-
if (status == napi_ok) {
174-
napi_value global = nullptr;
175-
status = napi_get_global(env, &global);
176-
assert(status == napi_ok);
177-
status = napi_set_named_property(env, global, addon.generatedName.c_str(),
178-
exports);
179-
assert(status == napi_ok);
180-
}
181-
151+
status = hermes_napi_load_module(env, filename.c_str(), &exports);
182152
const bool failed = status != napi_ok;
183-
std::string message;
184-
if (failed) {
185-
message = takePendingExceptionMessage(env);
186-
if (message.empty()) {
187-
message = "Node-API status " + std::to_string(status);
188-
}
189-
}
153+
jsi::Value result =
154+
toJsiValue(rt, env, failed ? takeLoadError(env, status) : exports);
155+
190156
const napi_status closeStatus = napi_close_handle_scope(env, scope);
191157
assert(closeStatus == napi_ok);
192158
(void)closeStatus;
193159

194160
if (failed) {
195-
throw jsi::JSError(rt, "Failed to load '" + libraryName + "' addon from '" +
196-
libraryPath + "': " + message);
161+
throw jsi::JSError(rt, std::move(result));
197162
}
163+
module.setProperty(rt, "exports", std::move(result));
198164
}
199165

200166
} // namespace callstack::react_native_node_api

‎packages/host/cpp/CxxNodeApiHostModule.hpp‎

Lines changed: 6 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88

99
#include <memory>
1010
#include <string>
11-
#include <unordered_map>
1211

1312
namespace callstack::react_native_node_api {
1413

@@ -18,35 +17,18 @@ class JSI_EXPORT CxxNodeApiHostModule : public facebook::react::TurboModule {
1817

1918
CxxNodeApiHostModule(std::shared_ptr<facebook::react::CallInvoker> jsInvoker);
2019

21-
static facebook::jsi::Value
22-
requireNodeAddon(facebook::jsi::Runtime &rt,
23-
facebook::react::TurboModule &turboModule,
24-
const facebook::jsi::Value args[], size_t count);
25-
facebook::jsi::Value requireNodeAddon(facebook::jsi::Runtime &rt,
26-
const facebook::jsi::String path);
20+
static facebook::jsi::Value dlopen(facebook::jsi::Runtime &rt,
21+
facebook::react::TurboModule &turboModule,
22+
const facebook::jsi::Value args[],
23+
size_t count);
24+
void dlopen(facebook::jsi::Runtime &rt, const facebook::jsi::Object &module,
25+
const std::string &filename);
2726

2827
protected:
29-
struct NodeAddon {
30-
// The name the addon's exports object is stored under on the JavaScript
31-
// global, which is how the napi_value crosses over to JSI.
32-
std::string generatedName;
33-
34-
// The Node-API environment for this addon, created when the addon is
35-
// initialized. Node creates one env per addon (see
36-
// napi_module_register_by_symbol in Node's src/node_api.cc) and the env
37-
// carries addon-scoped state — instance data, last error info, the addon's
38-
// Node-API version — so addons must not share one. Owned by the Hermes
39-
// runtime, which tears it down when the runtime is destroyed.
40-
napi_env env = nullptr;
41-
};
42-
std::unordered_map<std::string, NodeAddon> nodeAddons_;
4328
std::shared_ptr<facebook::react::CallInvoker> callInvoker_;
4429
// The hermes_napi_host integration passed to every env this module creates.
4530
// Also retained process-wide, as the envs outlive this module on teardown.
4631
std::shared_ptr<HostContext> hostContext_;
47-
48-
void loadNodeAddon(facebook::jsi::Runtime &rt, NodeAddon &addon,
49-
const std::string &libraryName);
5032
};
5133

5234
} // namespace callstack::react_native_node_api
Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,63 @@
1-
import { type TurboModule, TurboModuleRegistry } from "react-native";
1+
import { Platform, type TurboModule, TurboModuleRegistry } from "react-native";
2+
3+
export interface Module {
4+
exports: unknown;
5+
}
26

37
export interface Spec extends TurboModule {
4-
requireNodeAddon<T = unknown>(libraryName: string): T;
8+
dlopen(module: Module, filename: string): void;
59
}
610

711
const native = TurboModuleRegistry.getEnforcing<Spec>("NodeApiHost");
812

913
/**
10-
* Loads a native Node-API addon by filename.
14+
* Loads the Node-API addon at `filename` and assigns its exports to `module.exports`,
15+
* with the same semantics as Node's `process.dlopen`.
16+
*
17+
* `filename` is passed as-is to the system's `dlopen`: e.g. `lib<name>.so` on Android
18+
* and `@rpath/<name>.framework/<name>` on Apple platforms.
19+
* Nothing is cached: calling it again runs the addon's initialization function again.
20+
*/
21+
export function dlopen(module: Module, filename: string): void {
22+
native.dlopen(module, filename);
23+
}
24+
25+
const APPLE_PLATFORMS: readonly string[] = ["ios", "macos", "visionos"];
26+
27+
function getLibraryFilename(libraryName: string): string {
28+
if (Platform.OS === "android") {
29+
return `lib${libraryName}.so`;
30+
} else if (APPLE_PLATFORMS.includes(Platform.OS)) {
31+
return `@rpath/${libraryName}.framework/${libraryName}`;
32+
} else {
33+
throw new Error(
34+
`Loading Node-API addons is unsupported on '${Platform.OS}'`,
35+
);
36+
}
37+
}
38+
39+
// Module scope is per JS runtime, so is this cache.
40+
const addons = new Map<string, Module>();
41+
42+
/**
43+
* Loads a native Node-API addon by library name, returning the exports of a previous load of the same library.
1144
*/
12-
export function requireNodeAddon<T = unknown>(libraryName: string): T {
13-
return native.requireNodeAddon<T>(libraryName);
45+
export function requireNodeAddon<T = unknown>(libraryName: string): T;
46+
export function requireNodeAddon(libraryName: string): unknown {
47+
const cached = addons.get(libraryName);
48+
if (cached) {
49+
return cached.exports;
50+
}
51+
const filename = getLibraryFilename(libraryName);
52+
const module: Module = { exports: {} };
53+
try {
54+
dlopen(module, filename);
55+
} catch (error) {
56+
const reason = error instanceof Error ? error.message : String(error);
57+
throw new Error(
58+
`Failed to load '${libraryName}' addon from '${filename}': ${reason}`,
59+
);
60+
}
61+
addons.set(libraryName, module);
62+
return module.exports;
1463
}

0 commit comments

Comments
 (0)