-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathv8-module-loader.cpp
More file actions
886 lines (763 loc) · 28.6 KB
/
v8-module-loader.cpp
File metadata and controls
886 lines (763 loc) · 28.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
#include "v8-module-loader.h"
#include <sys/stat.h>
#include <unistd.h>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include "runtime/RuntimeConfig.h"
typedef napi_value (*napi_module_init)(napi_env env, napi_value exports);
namespace nativescript {
extern std::unordered_map<std::string, napi_module_init> napiModuleRegistry;
}
namespace v8impl {
namespace {
// Cache for package.json "type" field lookups
std::unordered_map<std::string, bool> g_packageTypeCache;
// Strip shebang line from source code (e.g., #!/usr/bin/env node)
std::string StripShebang(const std::string& source) {
if (source.size() >= 2 && source[0] == '#' && source[1] == '!') {
size_t lineEnd = source.find('\n');
if (lineEnd != std::string::npos) {
return source.substr(lineEnd + 1);
}
return ""; // Entire file is just a shebang
}
return source;
}
// Check if path has .cjs extension (explicitly CommonJS)
bool IsCJSModule(const std::string& path) {
return path.size() >= 4 && path.compare(path.size() - 4, 4, ".cjs") == 0;
}
// Find nearest package.json by walking up from directory
std::string FindPackageJson(const std::filesystem::path& startDir) {
std::filesystem::path current = startDir;
while (!current.empty() && current != current.root_path()) {
std::filesystem::path packagePath = current / "package.json";
std::error_code ec;
if (std::filesystem::exists(packagePath, ec) && !ec) {
return packagePath.string();
}
current = current.parent_path();
}
return "";
}
// Check if package.json has "type": "module"
bool IsPackageTypeModule(const std::string& packageJsonPath) {
auto cacheIt = g_packageTypeCache.find(packageJsonPath);
if (cacheIt != g_packageTypeCache.end()) {
return cacheIt->second;
}
bool isModule = false;
std::ifstream file(packageJsonPath);
if (file.is_open()) {
std::string content((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
file.close();
// Simple JSON parsing for "type": "module"
// Look for "type" followed by : and "module"
size_t typePos = content.find("\"type\"");
if (typePos != std::string::npos) {
size_t colonPos = content.find(':', typePos + 6);
if (colonPos != std::string::npos) {
size_t valueStart = content.find('"', colonPos + 1);
if (valueStart != std::string::npos) {
size_t valueEnd = content.find('"', valueStart + 1);
if (valueEnd != std::string::npos) {
std::string typeValue =
content.substr(valueStart + 1, valueEnd - valueStart - 1);
isModule = (typeValue == "module");
}
}
}
}
}
g_packageTypeCache[packageJsonPath] = isModule;
return isModule;
}
// Determine if a .js file should be treated as ESM based on nearest
// package.json
bool ShouldTreatAsESModule(const std::string& path) {
std::filesystem::path filePath(path);
std::string packageJson = FindPackageJson(filePath.parent_path());
if (!packageJson.empty()) {
return IsPackageTypeModule(packageJson);
}
return false; // Default to CommonJS
}
} // namespace
// Global registry for ES modules
std::unordered_map<std::string, v8::Global<v8::Module>> g_moduleRegistry;
std::string NormalizeModulePath(const std::filesystem::path& path) {
std::error_code ec;
auto absolutePath = std::filesystem::absolute(path, ec);
if (ec) {
ec.clear();
absolutePath = path;
}
auto normalizedPath = absolutePath.lexically_normal();
auto canonicalPath = std::filesystem::weakly_canonical(normalizedPath, ec);
if (!ec) {
return canonicalPath.string();
}
return normalizedPath.string();
}
std::string GetModulePathFromRegistry(v8::Isolate* isolate,
v8::Local<v8::Module> module) {
for (auto& kv : g_moduleRegistry) {
v8::Local<v8::Module> registered = kv.second.Get(isolate);
if (registered == module) {
return kv.first;
}
}
return "";
}
std::string ModulePathToURL(const std::string& modulePath) {
if (modulePath.rfind("file://", 0) == 0) {
return modulePath;
}
if (modulePath.rfind("nativescript:", 0) == 0) {
return modulePath;
}
if (!modulePath.empty() && modulePath[0] == '/') {
return "file://" + modulePath;
}
return "file:///" + modulePath;
}
bool IsNodeBuiltinSpecifier(const std::string& specifier) {
static const std::unordered_set<std::string> kBuiltins = {
"url", "node:url", "fs", "node:fs", "fs/promises", "node:fs/promises",
"path", "node:path", "web", "node:web", "stream/web", "node:stream/web"};
return kBuiltins.contains(specifier);
}
std::string NormalizeNodeBuiltinSpecifier(const std::string& specifier) {
if (specifier.rfind("node:", 0) == 0) {
return specifier.substr(5);
}
return specifier;
}
std::string EscapeForSingleQuotedJsString(const std::string& value) {
std::string escaped;
escaped.reserve(value.size());
for (char c : value) {
switch (c) {
case '\\':
escaped += "\\\\";
break;
case '\'':
escaped += "\\'";
break;
case '\n':
escaped += "\\n";
break;
case '\r':
escaped += "\\r";
break;
default:
escaped += c;
break;
}
}
return escaped;
}
std::string NormalizeRegisteredNapiModuleSpecifier(
const std::string& specifier) {
auto it = nativescript::napiModuleRegistry.find(specifier);
if (it != nativescript::napiModuleRegistry.end() && it->second != nullptr) {
return specifier;
}
if (specifier.rfind("node:", 0) == 0) {
std::string withoutPrefix = specifier.substr(5);
it = nativescript::napiModuleRegistry.find(withoutPrefix);
if (it != nativescript::napiModuleRegistry.end() && it->second != nullptr) {
return withoutPrefix;
}
}
return "";
}
std::string GetRegisteredNapiESModuleSource(const std::string& specifier) {
std::string normalized = NormalizeRegisteredNapiModuleSpecifier(specifier);
if (normalized.empty()) {
return "";
}
std::string escapedSpecifier = EscapeForSingleQuotedJsString(normalized);
return R"(
const __load = (name) => {
if (typeof globalThis.require === "function") {
return globalThis.require(name);
}
if (typeof globalThis.__nativeRequire === "function") {
const dir = typeof globalThis.__approot === "string" ? `${globalThis.__approot}/app` : "";
return globalThis.__nativeRequire(name, dir);
}
throw new Error(`Cannot load native module '${name}'`);
};
const __nativeModule = __load(')" +
escapedSpecifier + R"(');
export default __nativeModule;
)";
}
std::string GetBuiltinESModuleSource(const std::string& specifier) {
const auto builtinName = NormalizeNodeBuiltinSpecifier(specifier);
if (builtinName == "url") {
return R"(
const __toURL = (input) => input instanceof URL ? input : new URL(String(input));
export const URL = globalThis.URL;
export const URLSearchParams = globalThis.URLSearchParams;
export function pathToFileURL(path) {
const value = String(path);
return new URL(value.startsWith("/") ? `file://${value}` : `file:///${value}`);
}
export function fileURLToPath(value) {
const u = __toURL(value);
if (u.protocol !== "file:") {
throw new TypeError("The URL must be of scheme file:");
}
return decodeURIComponent(u.pathname);
}
export default { URL, URLSearchParams, pathToFileURL, fileURLToPath };
)";
}
if (builtinName == "fs") {
return R"(
const __load = (name) => {
if (typeof globalThis.require === "function") {
return globalThis.require(name);
}
if (typeof globalThis.__nativeRequire === "function") {
const dir = typeof globalThis.__approot === "string" ? `${globalThis.__approot}/app` : "";
return globalThis.__nativeRequire(name, dir);
}
throw new Error(`Cannot load builtin module '${name}'`);
};
const __fs = __load("node:fs");
export const readFileSync = __fs.readFileSync;
export const writeFileSync = __fs.writeFileSync;
export const existsSync = __fs.existsSync;
export const mkdirSync = __fs.mkdirSync;
export const readdirSync = __fs.readdirSync;
export const statSync = __fs.statSync;
export const lstatSync = __fs.lstatSync;
export const unlinkSync = __fs.unlinkSync;
export const rmSync = __fs.rmSync;
export const readFile = __fs.readFile;
export const writeFile = __fs.writeFile;
export const constants = __fs.constants;
export const promises = __fs.promises;
export default __fs;
)";
}
if (builtinName == "fs/promises") {
return R"(
const __load = (name) => {
if (typeof globalThis.require === "function") {
return globalThis.require(name);
}
if (typeof globalThis.__nativeRequire === "function") {
const dir = typeof globalThis.__approot === "string" ? `${globalThis.__approot}/app` : "";
return globalThis.__nativeRequire(name, dir);
}
throw new Error(`Cannot load builtin module '${name}'`);
};
const __fsp = __load("node:fs").promises;
export const readFile = __fsp.readFile;
export const writeFile = __fsp.writeFile;
export const mkdir = __fsp.mkdir;
export const readdir = __fsp.readdir;
export const stat = __fsp.stat;
export const lstat = __fsp.lstat;
export const unlink = __fsp.unlink;
export const rm = __fsp.rm;
export default __fsp;
)";
}
if (builtinName == "path") {
return R"(
const __load = (name) => {
if (typeof globalThis.require === "function") {
return globalThis.require(name);
}
if (typeof globalThis.__nativeRequire === "function") {
const dir = typeof globalThis.__approot === "string" ? `${globalThis.__approot}/app` : "";
return globalThis.__nativeRequire(name, dir);
}
throw new Error(`Cannot load builtin module '${name}'`);
};
const __path = __load("node:path");
export const basename = __path.basename;
export const dirname = __path.dirname;
export const extname = __path.extname;
export const isAbsolute = __path.isAbsolute;
export const join = __path.join;
export const normalize = __path.normalize;
export const parse = __path.parse;
export const format = __path.format;
export const relative = __path.relative;
export const resolve = __path.resolve;
export const toNamespacedPath = __path.toNamespacedPath;
export const sep = __path.sep;
export const delimiter = __path.delimiter;
export const posix = __path.posix;
export const win32 = __path.win32;
export default __path;
)";
}
if (builtinName == "web") {
return R"(
const __load = (name) => {
if (typeof globalThis.require === "function") {
return globalThis.require(name);
}
if (typeof globalThis.__nativeRequire === "function") {
const dir = typeof globalThis.__approot === "string" ? `${globalThis.__approot}/app` : "";
return globalThis.__nativeRequire(name, dir);
}
throw new Error(`Cannot load builtin module '${name}'`);
};
const __web = __load("web");
export const fetch = __web.fetch;
export const Headers = __web.Headers;
export const Request = __web.Request;
export const Response = __web.Response;
export const WebSocket = __web.WebSocket;
export const ReadableStream = __web.ReadableStream;
export const WritableStream = __web.WritableStream;
export const TransformStream = __web.TransformStream;
export default __web;
)";
}
if (builtinName == "stream/web") {
return R"(
const __load = (name) => {
if (typeof globalThis.require === "function") {
return globalThis.require(name);
}
if (typeof globalThis.__nativeRequire === "function") {
const dir = typeof globalThis.__approot === "string" ? `${globalThis.__approot}/app` : "";
return globalThis.__nativeRequire(name, dir);
}
throw new Error(`Cannot load builtin module '${name}'`);
};
const __streamWeb = __load("stream/web");
export const ReadableStream = __streamWeb.ReadableStream;
export const ReadableStreamDefaultReader = __streamWeb.ReadableStreamDefaultReader;
export const WritableStream = __streamWeb.WritableStream;
export const TransformStream = __streamWeb.TransformStream;
export const ByteLengthQueuingStrategy = __streamWeb.ByteLengthQueuingStrategy;
export const CountQueuingStrategy = __streamWeb.CountQueuingStrategy;
export default __streamWeb;
)";
}
return "";
}
bool IsESModule(const std::string& path) {
// .mjs is always ESM
if (path.size() >= 4 && path.compare(path.size() - 4, 4, ".mjs") == 0) {
return true;
}
// .cjs is always CommonJS
if (IsCJSModule(path)) {
return false;
}
// .js files: check package.json "type" field
if (path.size() >= 3 && path.compare(path.size() - 3, 3, ".js") == 0) {
return ShouldTreatAsESModule(path);
}
return false;
}
bool IsJSONModule(const std::string& path) {
return path.size() >= 5 && path.compare(path.size() - 5, 5, ".json") == 0;
}
std::string ReadFileContent(const std::string& path) {
std::ifstream file(path);
if (!file.is_open()) {
throw std::runtime_error("Cannot open file: " + path);
}
std::stringstream buffer;
buffer << file.rdbuf();
return StripShebang(buffer.str());
}
v8::Local<v8::String> WrapModuleContent(v8::Isolate* isolate,
const std::string& path) {
std::string sourceText = ReadFileContent(path);
if (IsJSONModule(path)) {
std::string wrappedJsonModule = "export default " + sourceText + ";";
return v8::String::NewFromUtf8(isolate, wrappedJsonModule.c_str())
.ToLocalChecked();
}
if (IsESModule(path)) {
// For ES modules, return source as-is to preserve import/export syntax
return v8::String::NewFromUtf8(isolate, sourceText.c_str())
.ToLocalChecked();
}
// For CommonJS modules, wrap in factory function
std::string wrappedSource =
"(function (exports, require, module, __filename, __dirname) { " +
sourceText + "\n});";
return v8::String::NewFromUtf8(isolate, wrappedSource.c_str())
.ToLocalChecked();
}
std::string ResolveESModulePath(v8::Isolate* isolate,
const std::string& baseDir,
const std::string& moduleName) {
std::string moduleNameCopy = moduleName;
// Keep "~" alias behavior aligned with CommonJS resolution.
if (!moduleNameCopy.empty() && moduleNameCopy[0] == '~') {
moduleNameCopy = RuntimeConfig.ApplicationPath + moduleNameCopy.substr(1);
}
std::filesystem::path baseDirPath(baseDir);
std::filesystem::path moduleNamePath(moduleNameCopy);
std::filesystem::path fullPath = baseDirPath / moduleNamePath;
// Check if file exists as-is
if (std::filesystem::exists(fullPath) &&
std::filesystem::is_regular_file(fullPath)) {
return NormalizeModulePath(fullPath);
}
// Try with .mjs extension first (ES modules have priority)
std::filesystem::path mjsPath = fullPath.string() + ".mjs";
if (std::filesystem::exists(mjsPath) &&
std::filesystem::is_regular_file(mjsPath)) {
return NormalizeModulePath(mjsPath);
}
// Try with .js extension
std::filesystem::path jsPath = fullPath.string() + ".js";
if (std::filesystem::exists(jsPath) &&
std::filesystem::is_regular_file(jsPath)) {
return NormalizeModulePath(jsPath);
}
// Try with .cjs extension (explicit CommonJS)
std::filesystem::path cjsPath = fullPath.string() + ".cjs";
if (std::filesystem::exists(cjsPath) &&
std::filesystem::is_regular_file(cjsPath)) {
return NormalizeModulePath(cjsPath);
}
// Try directory with index.mjs
if (std::filesystem::exists(fullPath) &&
std::filesystem::is_directory(fullPath)) {
std::filesystem::path indexMjs = fullPath / "index.mjs";
if (std::filesystem::exists(indexMjs) &&
std::filesystem::is_regular_file(indexMjs)) {
return NormalizeModulePath(indexMjs);
}
// Try directory with index.js
std::filesystem::path indexJs = fullPath / "index.js";
if (std::filesystem::exists(indexJs) &&
std::filesystem::is_regular_file(indexJs)) {
return NormalizeModulePath(indexJs);
}
// Try directory with index.cjs
std::filesystem::path indexCjs = fullPath / "index.cjs";
if (std::filesystem::exists(indexCjs) &&
std::filesystem::is_regular_file(indexCjs)) {
return NormalizeModulePath(indexCjs);
}
}
throw std::runtime_error("Module not found: " + moduleName);
}
v8::MaybeLocal<v8::Module> CompileESModule(v8::Isolate* isolate,
const std::string& path) {
const std::string absPath = NormalizeModulePath(path);
// Check if already compiled
auto it = g_moduleRegistry.find(absPath);
if (it != g_moduleRegistry.end()) {
v8::Local<v8::Module> existing = it->second.Get(isolate);
return v8::MaybeLocal<v8::Module>(existing);
}
// Prepare URL & source - use the absolute path consistently
v8::Local<v8::String> sourceText = WrapModuleContent(isolate, absPath);
#if V8_MAJOR_VERSION >= 14
v8::ScriptOrigin origin(
v8::String::NewFromUtf8(isolate, absPath.c_str()).ToLocalChecked(), 0, 0,
false, -1, v8::Local<v8::Value>(), false, false,
true // is_module
);
#else
v8::ScriptOrigin origin(
isolate,
v8::String::NewFromUtf8(isolate, absPath.c_str()).ToLocalChecked(), 0, 0,
false, -1, v8::Local<v8::Value>(), false, false,
true // is_module
);
#endif
v8::ScriptCompiler::Source source(sourceText, origin);
// Compile ES module
v8::Local<v8::Module> module;
v8::MaybeLocal<v8::Module> maybeMod = v8::ScriptCompiler::CompileModule(
isolate, &source, v8::ScriptCompiler::kNoCompileOptions);
if (!maybeMod.ToLocal(&module)) {
// Compilation failed - return empty MaybeLocal, let V8 handle the
// JavaScript exception
return v8::MaybeLocal<v8::Module>();
}
// Register in global registry with absolute path
g_moduleRegistry[absPath].Reset(isolate, module);
return v8::MaybeLocal<v8::Module>(module);
}
v8::MaybeLocal<v8::Module> CompileVirtualESModule(v8::Isolate* isolate,
const std::string& moduleId,
const std::string& source) {
auto it = g_moduleRegistry.find(moduleId);
if (it != g_moduleRegistry.end()) {
v8::Local<v8::Module> existing = it->second.Get(isolate);
return v8::MaybeLocal<v8::Module>(existing);
}
v8::Local<v8::String> sourceText =
v8::String::NewFromUtf8(isolate, source.c_str()).ToLocalChecked();
#if V8_MAJOR_VERSION >= 14
v8::ScriptOrigin origin(
v8::String::NewFromUtf8(isolate, moduleId.c_str()).ToLocalChecked(), 0, 0,
false, -1, v8::Local<v8::Value>(), false, false, true);
#else
v8::ScriptOrigin origin(
isolate,
v8::String::NewFromUtf8(isolate, moduleId.c_str()).ToLocalChecked(), 0, 0,
false, -1, v8::Local<v8::Value>(), false, false, true);
#endif
v8::ScriptCompiler::Source scriptSource(sourceText, origin);
v8::Local<v8::Module> module;
v8::MaybeLocal<v8::Module> maybeMod = v8::ScriptCompiler::CompileModule(
isolate, &scriptSource, v8::ScriptCompiler::kNoCompileOptions);
if (!maybeMod.ToLocal(&module)) {
return v8::MaybeLocal<v8::Module>();
}
g_moduleRegistry[moduleId].Reset(isolate, module);
return v8::MaybeLocal<v8::Module>(module);
}
v8::Local<v8::Value> LoadESModule(v8::Isolate* isolate,
const std::string& path) {
auto context = isolate->GetCurrentContext();
const std::string absPath = NormalizeModulePath(path);
// First, compile the module and all its dependencies
v8::MaybeLocal<v8::Module> maybeModule = CompileESModule(isolate, absPath);
v8::Local<v8::Module> module;
if (!maybeModule.ToLocal(&module)) {
// Compilation failed - throw exception
throw std::runtime_error("Cannot compile ES module: " + absPath);
}
// Instantiate (link) - this will recursively resolve dependencies
v8::TryCatch tcLink(isolate);
bool linked = module->InstantiateModule(context, &ResolveModuleCallback)
.FromMaybe(false);
if (!linked) {
if (tcLink.HasCaught()) {
v8::String::Utf8Value error(isolate, tcLink.Exception());
throw std::runtime_error("Cannot instantiate module " + absPath + ": " +
std::string(*error));
} else {
throw std::runtime_error("Cannot instantiate module " + absPath);
}
}
// Evaluate
v8::Local<v8::Value> result;
v8::TryCatch tcEval(isolate);
if (!module->Evaluate(context).ToLocal(&result)) {
if (tcEval.HasCaught()) {
v8::String::Utf8Value error(isolate, tcEval.Exception());
throw std::runtime_error("Cannot evaluate module " + absPath + ": " +
std::string(*error));
} else {
throw std::runtime_error("Cannot evaluate module " + absPath);
}
}
// Handle top-level await (if result is a Promise)
if (result->IsPromise()) {
v8::Local<v8::Promise> promise = result.As<v8::Promise>();
// Process microtasks to allow Promise resolution
int maxAttempts = 100;
int attempts = 0;
while (attempts < maxAttempts) {
isolate->PerformMicrotaskCheckpoint();
v8::Promise::PromiseState state = promise->State();
if (state != v8::Promise::kPending) {
if (state == v8::Promise::kRejected) {
v8::Local<v8::Value> reason = promise->Result();
isolate->ThrowException(reason);
throw std::runtime_error("Module evaluation promise rejected");
}
break;
}
attempts++;
usleep(100); // 0.1ms delay
}
}
// Return the namespace
return module->GetModuleNamespace();
}
v8::MaybeLocal<v8::Module> ResolveModuleCallback(
v8::Local<v8::Context> context, v8::Local<v8::String> specifier,
v8::Local<v8::FixedArray> import_assertions,
v8::Local<v8::Module> referrer) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
// Convert specifier to std::string
v8::String::Utf8Value specUtf8(isolate, specifier);
std::string spec = *specUtf8 ? *specUtf8 : "";
if (spec.empty()) {
return v8::MaybeLocal<v8::Module>();
}
if (IsNodeBuiltinSpecifier(spec)) {
const auto builtinName = NormalizeNodeBuiltinSpecifier(spec);
const auto source = GetBuiltinESModuleSource(spec);
if (source.empty()) {
std::string errorMsg = "Unsupported builtin module '" + spec + "'";
isolate->ThrowException(v8::Exception::Error(
v8::String::NewFromUtf8(isolate, errorMsg.c_str()).ToLocalChecked()));
return v8::MaybeLocal<v8::Module>();
}
const std::string moduleId = "nativescript:node_builtin/" + builtinName;
return CompileVirtualESModule(isolate, moduleId, source);
}
const auto registeredSource = GetRegisteredNapiESModuleSource(spec);
if (!registeredSource.empty()) {
const auto normalized = NormalizeRegisteredNapiModuleSpecifier(spec);
const std::string moduleId = "nativescript:napi_module/" + normalized;
return CompileVirtualESModule(isolate, moduleId, registeredSource);
}
// Find referrer path
std::string referrerPath = GetModulePathFromRegistry(isolate, referrer);
if (referrerPath.empty()) {
// Check if this is a relative import that needs a referrer context
bool specIsRelative = !spec.empty() && spec[0] == '.';
if (specIsRelative) {
std::string errorMsg = "Cannot resolve relative module '" + spec +
"': referrer module not found in registry";
isolate->ThrowException(v8::Exception::Error(
v8::String::NewFromUtf8(isolate, errorMsg.c_str()).ToLocalChecked()));
return v8::MaybeLocal<v8::Module>();
} else {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != nullptr) {
referrerPath =
std::string(cwd) + "/dummy.mjs"; // Create a dummy referrer path
} else {
std::string errorMsg =
"Cannot resolve module '" + spec +
"': no referrer and cannot get current directory";
isolate->ThrowException(v8::Exception::Error(
v8::String::NewFromUtf8(isolate, errorMsg.c_str())
.ToLocalChecked()));
return v8::MaybeLocal<v8::Module>();
}
}
}
// Compute base directory - ensure it's absolute
std::filesystem::path referrerFilePath = NormalizeModulePath(referrerPath);
std::string baseDir = referrerFilePath.parent_path().string();
// Resolve the module path
std::string absPath;
try {
absPath = ResolveESModulePath(isolate, baseDir, spec);
} catch (const std::exception& e) {
std::string errorMsg = "Cannot resolve module '" + spec + "': " + e.what();
isolate->ThrowException(v8::Exception::Error(
v8::String::NewFromUtf8(isolate, errorMsg.c_str()).ToLocalChecked()));
return v8::MaybeLocal<v8::Module>();
}
v8::MaybeLocal<v8::Module> maybeModule = CompileESModule(isolate, absPath);
if (maybeModule.IsEmpty()) {
// Compilation failed - throw an exception if none exists
std::string errorMsg = "Failed to compile module: " + absPath;
isolate->ThrowException(v8::Exception::Error(
v8::String::NewFromUtf8(isolate, errorMsg.c_str()).ToLocalChecked()));
return v8::MaybeLocal<v8::Module>();
}
return maybeModule;
}
v8::MaybeLocal<v8::Promise> ImportModuleDynamicallyCallback(
v8::Local<v8::Context> context, v8::Local<v8::Data> host_defined_options,
v8::Local<v8::Value> resource_name, v8::Local<v8::String> specifier,
v8::Local<v8::FixedArray> import_assertions) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
// Create Promise resolver
v8::Local<v8::Promise::Resolver> resolver =
v8::Promise::Resolver::New(context).ToLocalChecked();
try {
// Use the static resolver to locate/compile the module
v8::Local<v8::Module> refMod;
v8::MaybeLocal<v8::Module> maybeModule =
ResolveModuleCallback(context, specifier, import_assertions, refMod);
v8::Local<v8::Module> module;
if (!maybeModule.ToLocal(&module)) {
resolver
->Reject(context,
v8::Exception::Error(v8::String::NewFromUtf8(
isolate, "Failed to resolve module")
.ToLocalChecked()))
.Check();
isolate->PerformMicrotaskCheckpoint();
return scope.Escape(resolver->GetPromise());
}
// If not yet instantiated/evaluated, do it now
if (module->GetStatus() == v8::Module::kUninstantiated) {
if (!module->InstantiateModule(context, &ResolveModuleCallback)
.FromMaybe(false)) {
resolver
->Reject(context, v8::Exception::Error(
v8::String::NewFromUtf8(
isolate, "Failed to instantiate module")
.ToLocalChecked()))
.Check();
isolate->PerformMicrotaskCheckpoint();
return scope.Escape(resolver->GetPromise());
}
}
if (module->GetStatus() != v8::Module::kEvaluated) {
if (module->Evaluate(context).IsEmpty()) {
resolver
->Reject(context, v8::Exception::Error(
v8::String::NewFromUtf8(
isolate, "Failed to evaluate module")
.ToLocalChecked()))
.Check();
isolate->PerformMicrotaskCheckpoint();
return scope.Escape(resolver->GetPromise());
}
}
resolver->Resolve(context, module->GetModuleNamespace()).Check();
isolate->PerformMicrotaskCheckpoint();
} catch (const std::exception& e) {
resolver
->Reject(
context,
v8::Exception::Error(
v8::String::NewFromUtf8(isolate, e.what()).ToLocalChecked()))
.Check();
isolate->PerformMicrotaskCheckpoint();
}
return scope.Escape(resolver->GetPromise());
}
void InitializeESModuleSystem(v8::Isolate* isolate) {
// Set module resolution and dynamic import callbacks
isolate->SetHostImportModuleDynamicallyCallback(
ImportModuleDynamicallyCallback);
isolate->SetHostInitializeImportMetaObjectCallback(
[](v8::Local<v8::Context> context, v8::Local<v8::Module> module,
v8::Local<v8::Object> meta) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
const std::string modulePath =
GetModulePathFromRegistry(isolate, module);
if (modulePath.empty()) {
return;
}
const std::string moduleURL = ModulePathToURL(modulePath);
v8::Local<v8::String> key =
v8::String::NewFromUtf8(isolate, "url").ToLocalChecked();
v8::Local<v8::String> value =
v8::String::NewFromUtf8(isolate, moduleURL.c_str())
.ToLocalChecked();
meta->CreateDataProperty(context, key, value).Check();
});
}
void CleanupESModuleSystem(v8::Isolate* isolate) {
// Reset all Global handles before V8 isolate cleanup
for (auto& kv : g_moduleRegistry) {
kv.second.Reset();
}
// Clear the registry
g_moduleRegistry.clear();
// Clear the package.json type cache
g_packageTypeCache.clear();
}
} // namespace v8impl