Repository navigation
Expand file tree
/
Copy pathCommonJsModule.cpp
More file actions
75 lines (68 loc) · 2.55 KB
/
Copy pathCommonJsModule.cpp
File metadata and controls
75 lines (68 loc) · 2.55 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
#include <array>
#include <exception>
#include <string>
#include "loader/ImportInternal.h"
#include "ns/JsError.h"
#include "ns/V8Helpers.h"
#include "ns/loader/ModuleRegistry.h"
#include "ns/loader/Transitional.h"
namespace nativescript::common::loader {
namespace {
v8::MaybeLocal<v8::Value> CommonJsModuleEvaluationSteps(
v8::Local<v8::Context> context, v8::Local<v8::Module> module) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
const std::string key = FindKeyForModule(isolate, module);
if (key.empty()) {
isolate->ThrowException(v8::Exception::Error(ToV8String(
isolate,
"CommonJS module is no longer registered: it was invalidated or the "
"loader was closed")));
return v8::MaybeLocal<v8::Value>();
}
v8::Local<v8::Value> exports;
try {
if (!platform::RequireFileForImport(context,
ModuleFilePathForKey(isolate, key))
.ToLocal(&exports)) {
return v8::MaybeLocal<v8::Value>();
}
} catch (const JsError& error) {
error.ThrowToV8(isolate);
return v8::MaybeLocal<v8::Value>();
} catch (const Terminated& terminated) {
terminated.ThrowToV8(isolate);
return v8::MaybeLocal<v8::Value>();
} catch (const std::exception& error) {
JsError(std::string("C++ exception: ") + error.what()).ThrowToV8(isolate);
return v8::MaybeLocal<v8::Value>();
} catch (...) {
JsError("C++ exception").ThrowToV8(isolate);
return v8::MaybeLocal<v8::Value>();
}
for (const char* name : {"default", "module.exports"}) {
if (module
->SetSyntheticModuleExport(isolate, ToV8String(isolate, name),
exports)
.IsNothing()) {
return v8::MaybeLocal<v8::Value>();
}
}
v8::Local<v8::Promise::Resolver> done;
if (!v8::Promise::Resolver::New(context).ToLocal(&done) ||
done->Resolve(context, v8::Undefined(isolate)).IsNothing()) {
return v8::MaybeLocal<v8::Value>();
}
return done->GetPromise();
}
} // namespace
v8::Local<v8::Module> CreateCommonJsModule(v8::Isolate* isolate,
v8::Local<v8::String> url) {
const std::array<v8::Local<v8::String>, 2> exportNames{
ToV8String(isolate, "default"), ToV8String(isolate, "module.exports")};
return v8::Module::CreateSyntheticModule(
isolate, url,
v8::MemorySpan<const v8::Local<v8::String>>(exportNames.data(),
exportNames.size()),
CommonJsModuleEvaluationSteps);
}
} // namespace nativescript::common::loader