[napi] Support import and require of .node modules

This commit is contained in:
Jarred Sumner
2022-05-09 00:24:25 -07:00
parent 3bd83eb134
commit 8014a0b8d8
6 changed files with 80 additions and 53 deletions

View File

@@ -108,6 +108,9 @@ using JSObject = JSC::JSObject;
using JSNonFinalObject = JSC::JSNonFinalObject;
namespace JSCastingHelpers = JSC::JSCastingHelpers;
using JSBuffer = WebCore::JSBuffer;
#include <dlfcn.h>
// #include <iostream>
static bool has_loaded_jsc = false;
@@ -1041,6 +1044,38 @@ JSC::JSInternalPromise* GlobalObject::moduleLoaderFetch(JSGlobalObject* globalOb
auto moduleKey = key.toWTFString(globalObject);
RETURN_IF_EXCEPTION(scope, promise->rejectWithCaughtException(globalObject, scope));
if (moduleKey.endsWith(".node")) {
CString utf8 = moduleKey.utf8();
void* handle = dlopen(utf8.data(), RTLD_LAZY);
if (!handle) {
WTF::String msg = WTF::String::fromUTF8(dlerror());
return rejectWithError(JSC::createTypeError(globalObject, msg));
}
JSC::EncodedJSValue (*napi_register_module_v1)(JSC::JSGlobalObject * globalObject,
JSC::EncodedJSValue exports);
napi_register_module_v1 = reinterpret_cast<JSC::EncodedJSValue (*)(JSC::JSGlobalObject*,
JSC::EncodedJSValue)>(
dlsym(handle, "napi_register_module_v1"));
if (!napi_register_module_v1) {
dlclose(handle);
return rejectWithError(JSC::createTypeError(globalObject, "symbol 'napi_register_module_v1' not found in native module. Is this a Node API (napi) module?"_s));
}
JSC::JSValue exports = JSC::constructEmptyObject(globalObject);
JSC::JSValue returnedExports = JSC::JSValue::decode(napi_register_module_v1(globalObject, JSC::JSValue::encode(exports)));
auto sourceCode = Napi::generateSourceCode(moduleKey, vm, returnedExports.getObject(), globalObject);
scope.releaseAssertNoExceptionExceptTermination();
auto jsSourceCode = JSC::JSSourceCode::create(vm, WTFMove(sourceCode));
promise->resolve(globalObject, jsSourceCode);
return promise;
}
auto moduleKeyZig = toZigString(moduleKey);
auto source = Zig::toZigString(value1, globalObject);
ErrorableResolvedSource res;