-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathModuleInternal.cpp
More file actions
1739 lines (1500 loc) · 53.9 KB
/
Copy pathModuleInternal.cpp
File metadata and controls
1739 lines (1500 loc) · 53.9 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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "ModuleInternal.h"
#include <dlfcn.h>
#include <libgen.h>
#include <sys/stat.h>
#include <utime.h>
#include <cassert>
#include <ctime>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <regex>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include "native_api_util.h"
#include "runtime/NativeScriptException.h"
#include "runtime/RuntimeConfig.h"
#include "runtime/Util.h"
#include "runtime/modules/node/Node.h"
#include "runtime/modules/web/Web.h"
#ifdef TARGET_ENGINE_V8
#include "../../napi/v8/v8-module-loader.h"
#elif defined(TARGET_ENGINE_QUICKJS)
#include "quickjs.h"
#include "quicks-runtime.h"
#endif
typedef napi_value (*napi_module_init)(napi_env env, napi_value exports);
namespace nativescript {
extern std::unordered_map<std::string, napi_module_init> napiModuleRegistry;
}
using namespace nativescript;
using namespace std;
namespace {
// Cache for package.json \"type\" field lookups
std::unordered_map<std::string, bool> g_modulePackageTypeCache;
// 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;
}
#if defined(TARGET_ENGINE_HERMES) || defined(TARGET_ENGINE_JSC)
std::string RewriteCommonJSDynamicImportsForFallbackEngines(
const std::string& source) {
static const std::regex kDynamicImportPattern(
R"((^|[^A-Za-z0-9_$\.])import\s*\()",
std::regex::ECMAScript | std::regex::multiline);
return std::regex_replace(source, kDynamicImportPattern,
"$1__dynamicImport(");
}
#endif
// 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 FindNearestPackageJson(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_modulePackageTypeCache.find(packageJsonPath);
if (cacheIt != g_modulePackageTypeCache.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"
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_modulePackageTypeCache[packageJsonPath] = isModule;
return isModule;
}
// Determine if a .js file should be treated as ESM based on nearest
// package.json
bool ShouldTreatJsAsESModule(const std::string& path) {
std::filesystem::path filePath(path);
std::string packageJson = FindNearestPackageJson(filePath.parent_path());
if (!packageJson.empty()) {
return IsPackageTypeModule(packageJson);
}
return false; // Default to CommonJS
}
bool PathExistsWithExactCase(const std::filesystem::path& path) {
std::error_code ec;
if (!std::filesystem::exists(path, ec) || ec) {
return false;
}
std::filesystem::path normalized = path.lexically_normal();
std::filesystem::path current;
for (const auto& component : normalized) {
if (component == normalized.root_name() ||
component == normalized.root_directory()) {
current /= component;
continue;
}
if (component == ".") {
continue;
}
if (component == "..") {
current = current.parent_path();
continue;
}
std::filesystem::path parent = current.empty() ? "." : current;
bool matched = false;
std::error_code iterEc;
for (std::filesystem::directory_iterator it(parent, iterEc), end;
!iterEc && it != end; it.increment(iterEc)) {
if (it->path().filename() == component) {
matched = true;
break;
}
}
if (iterEc) {
// On device the sandbox forbids enumerating everything above the app
// container (/private/var/...), so case verification is only possible
// for listable levels; exists() already vouched for the full path.
current /= component;
continue;
}
if (!matched) {
return false;
}
current /= component;
}
return true;
}
bool IsRegularFileWithExactCase(const std::filesystem::path& path) {
std::error_code ec;
return PathExistsWithExactCase(path) &&
std::filesystem::is_regular_file(path, ec) && !ec;
}
bool IsDirectoryWithExactCase(const std::filesystem::path& path) {
std::error_code ec;
return PathExistsWithExactCase(path) &&
std::filesystem::is_directory(path, ec) && !ec;
}
napi_value LoadRegisteredNapiModule(napi_env env,
const std::string& moduleName) {
const auto loadByName = [&](const std::string& name) -> napi_value {
auto it = nativescript::napiModuleRegistry.find(name);
if (it == nativescript::napiModuleRegistry.end() || it->second == nullptr) {
return nullptr;
}
napi_value moduleObj;
napi_create_object(env, &moduleObj);
napi_value exports;
napi_create_object(env, &exports);
napi_value moduleExports = it->second(env, exports);
bool hasPendingException = false;
napi_is_exception_pending(env, &hasPendingException);
if (hasPendingException) {
napi_value exception;
napi_get_and_clear_last_exception(env, &exception);
throw NativeScriptException(
env, exception, "Error initializing native module '" + name + "'");
}
if (moduleExports == nullptr) {
moduleExports = exports;
}
napi_set_named_property(env, moduleObj, "exports", moduleExports);
return moduleObj;
};
napi_value moduleObj = loadByName(moduleName);
if (moduleObj != nullptr) {
return moduleObj;
}
if (moduleName.rfind("node:", 0) == 0) {
return loadByName(moduleName.substr(5));
}
return nullptr;
}
std::string ModulePathToURL(const std::string& modulePath) {
if (modulePath.rfind("file://", 0) == 0) {
return modulePath;
}
if (modulePath.rfind("nativescript:", 0) == 0 ||
modulePath.rfind("node:", 0) == 0) {
return "nativescript:" + modulePath;
}
if (!modulePath.empty() && modulePath[0] == '/') {
return "file://" + modulePath;
}
return "nativescript:" + 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",
"vm", "node:vm", "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 == "vm") {
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 __vm = __load("node:vm");
export const Script = __vm.Script;
export const Module = __vm.Module;
export const SourceTextModule = __vm.SourceTextModule;
export const SyntheticModule = __vm.SyntheticModule;
export const compileFunction = __vm.compileFunction;
export const constants = __vm.constants;
export const createContext = __vm.createContext;
export const isContext = __vm.isContext;
export const measureMemory = __vm.measureMemory;
export const runInContext = __vm.runInContext;
export const runInNewContext = __vm.runInNewContext;
export const runInThisContext = __vm.runInThisContext;
export default __vm;
)";
}
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 "";
}
} // namespace
ModuleInternal::ModuleInternal()
: m_env(nullptr),
m_requireFunction(nullptr),
m_requireFactoryFunction(nullptr) {}
void ModuleInternal::DeInit() {
#ifdef TARGET_ENGINE_V8
for (auto& kv : v8impl::g_moduleRegistry) {
kv.second.Reset();
}
v8impl::g_moduleRegistry.clear();
#endif
// Clear the package.json type cache
g_modulePackageTypeCache.clear();
if (m_env != nullptr) {
napi_delete_reference(m_env, this->m_requireFunction);
napi_delete_reference(m_env, this->m_requireFactoryFunction);
}
for (const auto& pair : this->m_requireCache) {
if (m_env != nullptr) {
napi_delete_reference(m_env, pair.second);
}
}
this->m_requireCache.clear();
}
void ModuleInternal::Init(napi_env env, const std::string& baseDir) {
napi_status status;
m_env = env;
#ifdef TARGET_ENGINE_V8
// Bootstrap V8 ES module hooks early so dynamic import() from CommonJS
// settles even before the first explicit .mjs module load.
napi_value bootstrapSource;
if (napi_create_string_utf8(env, "export default 0;", NAPI_AUTO_LENGTH,
&bootstrapSource) == napi_ok) {
const std::string bootstrapModulePath =
RuntimeConfig.ApplicationPath + "/app/.nativescript-esm-bootstrap.mjs";
napi_value bootstrapNamespace;
napi_status bootstrapStatus = napi_run_script_as_module(
env, bootstrapSource, bootstrapModulePath.c_str(), &bootstrapNamespace);
if (bootstrapStatus != napi_ok) {
bool pendingException = false;
napi_is_exception_pending(env, &pendingException);
if (pendingException) {
napi_value ignored;
napi_get_and_clear_last_exception(env, &ignored);
}
}
}
#endif
const char* requireFactoryScript = R"(
(function () {
return function require_factory(requireInternal, dirName) {
return function require(modulePath) {
if(typeof global.__requireOverride !== "undefined") {
var result = global.__requireOverride(modulePath, dirName);
if(result) {
return result;
}
}
return requireInternal(modulePath, dirName);
}
}
})();
)";
napi_value source;
napi_create_string_utf8(env, requireFactoryScript, NAPI_AUTO_LENGTH, &source);
napi_value global;
napi_get_global(env, &global);
napi_value globalEnv;
napi_create_external(env, env, nullptr, nullptr, &globalEnv);
napi_set_named_property(env, global, "__globalEnv", globalEnv);
napi_value result;
status = napi_run_script(env, source, &result);
assert(status == napi_ok);
m_requireFactoryFunction = napi_util::make_ref(m_env, result);
napi_value requireFunction = napi_util::napi_set_function(
env, global, "__nativeRequire", RequireCallback, this);
m_requireFunction = napi_util::make_ref(m_env, requireFunction);
napi_value globalRequire = GetRequireFunction(
env, baseDir.empty() ? RuntimeConfig.ApplicationPath : baseDir);
status = napi_set_named_property(env, global, "require", globalRequire);
assert(status == napi_ok);
#if defined(TARGET_ENGINE_QUICKJS)
InitQuickJSESModuleLoader(env);
#endif
}
napi_value ModuleInternal::GetRequireFunction(napi_env env,
const std::string& dirName) {
napi_value requireFunc;
auto itFound = m_requireCache.find(dirName);
if (itFound != m_requireCache.end()) {
requireFunc = napi_util::get_ref_value(env, itFound->second);
} else {
napi_value requireFuncFactory =
napi_util::get_ref_value(env, m_requireFactoryFunction);
napi_value requireInternalFunc =
napi_util::get_ref_value(env, m_requireFunction);
napi_value args[2];
args[0] = requireInternalFunc;
napi_create_string_utf8(env, dirName.c_str(), NAPI_AUTO_LENGTH, &args[1]);
napi_value thiz;
napi_create_object(env, &thiz);
napi_value result;
napi_status status =
napi_call_function(env, thiz, requireFuncFactory, 2, args, &result);
assert(status == napi_ok && result != nullptr);
bool isFunction = napi_util::is_of_type(env, result, napi_function);
assert(isFunction);
requireFunc = result;
napi_ref poFunc = napi_util::make_ref(env, requireFunc);
m_requireCache.emplace(dirName, poFunc);
}
return requireFunc;
}
napi_value ModuleInternal::RequireCallback(napi_env env,
napi_callback_info info) {
NAPI_CALLBACK_BEGIN(0)
try {
auto thiz = static_cast<ModuleInternal*>(data);
return thiz->RequireCallbackImpl(env, info);
} catch (NativeScriptException& e) {
e.ReThrowToJS(env);
} catch (std::exception& e) {
stringstream ss;
ss << "Error: C++ Exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToJS(env);
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToJS(env);
}
return nullptr;
}
napi_value ModuleInternal::Require(napi_env env, const std::string& moduleName,
const std::string& callingModuleDirName) {
auto isData = false;
napi_value moduleObj =
LoadImpl(env, moduleName, callingModuleDirName, isData);
if (isData) {
assert(!napi_util::is_null_or_undefined(env, moduleObj));
return moduleObj;
} else {
// Check if this is an ES module by looking for __esModule property
bool hasEsModuleProp;
napi_status status =
napi_has_named_property(env, moduleObj, "__esModule", &hasEsModuleProp);
bool isEsModule = false;
if (status == napi_ok && hasEsModuleProp) {
napi_value esModuleFlag;
napi_get_named_property(env, moduleObj, "__esModule", &esModuleFlag);
napi_get_value_bool(env, esModuleFlag, &isEsModule);
}
if (isEsModule) {
// For ES modules, return the module namespace directly
return moduleObj;
} else {
// For CommonJS modules, return the exports
napi_value exports;
napi_get_named_property(env, moduleObj, "exports", &exports);
assert(!napi_util::is_null_or_undefined(env, exports));
return exports;
}
}
}
napi_value ModuleInternal::RequireCallbackImpl(napi_env env,
napi_callback_info info) {
NAPI_CALLBACK_BEGIN_VARGS()
if (argc != 2) {
throw NativeScriptException(
string("require should be called with two parameters"));
}
if (!napi_util::is_of_type(env, argv[0], napi_string)) {
throw NativeScriptException(
string("require's first parameter should be string"));
}
if (!napi_util::is_of_type(env, argv[1], napi_string)) {
throw NativeScriptException(
string("require's second parameter should be string"));
}
string moduleName = napi_util::get_cxx_string(env, argv[0]);
string callingModuleDirName = napi_util::get_cxx_string(env, argv[1]);
try {
return Require(env, moduleName, callingModuleDirName);
} catch (NativeScriptException& e) {
e.ReThrowToJS(env);
return nullptr;
}
}
napi_value ModuleInternal::RequireNativeCallback(napi_env env,
napi_callback_info info) {
void* data;
napi_get_cb_info(env, info, nullptr, nullptr, nullptr, &data);
auto cb = reinterpret_cast<napi_register_module_v*>(data);
napi_value exports;
napi_create_object(env, &exports);
return cb(env, exports);
}
napi_status ModuleInternal::Load(napi_env env, const std::string& path) {
napi_value global;
napi_get_global(env, &global);
napi_value require;
napi_get_named_property(env, global, "require", &require);
napi_value args[1];
napi_create_string_utf8(env, path.c_str(), path.size(), &args[0]);
napi_value result;
napi_status status =
napi_call_function(env, global, require, 1, args, &result);
return status;
}
void ModuleInternal::LoadWorker(napi_env env, const string& path) {
Load(env, path);
bool hasPendingException;
napi_is_exception_pending(env, &hasPendingException);
if (hasPendingException) {
napi_value error;
napi_get_and_clear_last_exception(env, &error);
// TODO
// CallbackHandlers::CallWorkerScopeOnErrorHandle(env, error);
}
}
void ModuleInternal::CheckFileExists(napi_env env, const std::string& path,
const std::string& baseDir) {
struct stat buffer;
if (stat(path.c_str(), &buffer) != 0) {
std::string errMsg = "Module not found: " + path;
throw NativeScriptException(errMsg);
}
if (baseDir != "") {
std::string fullPath = baseDir + "/" + path;
if (stat(fullPath.c_str(), &buffer) != 0) {
std::string errMsg = "Module not found: " + fullPath;
throw NativeScriptException(errMsg);
}
}
}
napi_value ModuleInternal::LoadInternalModule(napi_env env,
const std::string& moduleName) {
auto nodeModule = Node::LoadInternalModule(env, moduleName);
if (nodeModule != nullptr) {
return nodeModule;
}
#ifdef __APPLE__
auto webModule = Web::LoadInternalModule(env, moduleName);
if (webModule != nullptr) {
return webModule;
}
#endif
auto napiModule = LoadRegisteredNapiModule(env, moduleName);
if (napiModule != nullptr) {
return napiModule;
}
if (moduleName == "url" || moduleName == "node:url") {
napi_value moduleObj;
napi_create_object(env, &moduleObj);
napi_value url;
napi_value exports;
napi_create_object(env, &exports);
napi_get_named_property(env, napi_util::global(env), "URL", &url);
napi_set_named_property(env, exports, "URL", url);
napi_set_named_property(env, moduleObj, "exports", exports);
napi_util::napi_set_function(
env, exports, "pathToFileURL",
[](napi_env env, napi_callback_info info) -> napi_value {
return napi_util::to_js_string(env, "file://");
});
return moduleObj;
}
return nullptr;
}
std::string ModuleInternal::ResolvePathFromPackageJson(
napi_env env, const std::string& packageJsonPath, bool& error) {
error = false;
if (!IsRegularFileWithExactCase(packageJsonPath)) {
return "";
}
std::ifstream packageJsonFile(packageJsonPath);
if (!packageJsonFile.is_open()) {
// Missing package.json is not fatal for directory resolution.
error = false;
return "";
}
std::string line;
std::stringstream packageJsonStream;
while (std::getline(packageJsonFile, line)) {
packageJsonStream << line;
}
packageJsonFile.close();
std::string packageJson = packageJsonStream.str();
napi_value obj = JsonParse(env, packageJson);
if (obj == nullptr) {
bool hasPendingException = false;
napi_is_exception_pending(env, &hasPendingException);
if (hasPendingException) {
napi_value exception;
napi_get_and_clear_last_exception(env, &exception);
}
error = true;
return "";
}
bool hasMain = false;
napi_status hasMainStatus =
napi_has_named_property(env, obj, "main", &hasMain);
if (hasMainStatus != napi_ok || !hasMain) {
// package.json without "main" should fall back to
// index.js/index.mjs/index.cjs
error = false;
return "";
}
napi_value mainValue;
napi_get_named_property(env, obj, "main", &mainValue);
if (mainValue == nullptr) {
error = false;
return "";
}
napi_valuetype type;
napi_typeof(env, mainValue, &type);
if (type != napi_string) {
error = false;
return "";
}
std::string main = napi_util::get_cxx_string(env, mainValue);
if (main.empty()) {
error = false;
return "";
}
std::filesystem::path packageJsonDir(packageJsonPath);
std::filesystem::path packageJsonDirName =
packageJsonDir.parent_path().string();
std::filesystem::path mainPath = packageJsonDirName / main;
if (IsDirectoryWithExactCase(mainPath)) {
mainPath = mainPath / "package.json";
if (IsRegularFileWithExactCase(mainPath)) {
return ResolvePathFromPackageJson(env, mainPath.string(), error);
}
std::filesystem::path indexMjs = mainPath.parent_path() / "index.mjs";
if (IsRegularFileWithExactCase(indexMjs)) {
return indexMjs.string();
}
std::filesystem::path indexJs = mainPath.parent_path() / "index.js";
if (IsRegularFileWithExactCase(indexJs)) {
return indexJs.string();
}
std::filesystem::path indexCjs = mainPath.parent_path() / "index.cjs";
if (IsRegularFileWithExactCase(indexCjs)) {
return indexCjs.string();
}
error = false;
return "";
}
if (IsRegularFileWithExactCase(mainPath)) {
return mainPath.string();
}
// Support extensionless "main" entries (e.g. "bundle") by resolving to
// modern ESM/CJS bundle outputs.
if (!mainPath.has_extension()) {
std::filesystem::path mjsPath = mainPath;
mjsPath.replace_extension(".mjs");
if (IsRegularFileWithExactCase(mjsPath)) {
return mjsPath.string();
}
std::filesystem::path jsPath = mainPath;
jsPath.replace_extension(".js");
if (IsRegularFileWithExactCase(jsPath)) {
return jsPath.string();
}
std::filesystem::path cjsPath = mainPath;
cjsPath.replace_extension(".cjs");
if (IsRegularFileWithExactCase(cjsPath)) {
return cjsPath.string();
}
}
// Unresolvable "main" should fall back to index.js/index.mjs/index.cjs.
error = false;
return "";
}
std::string ModuleInternal::ResolvePath(napi_env env,
const std::string& baseDir,
const std::string& moduleName) {
std::string moduleNameCopy = moduleName;
if (moduleName.starts_with("~")) {
moduleNameCopy = RuntimeConfig.ApplicationPath + moduleNameCopy.substr(1);
}
std::filesystem::path baseDirPath(baseDir);
std::filesystem::path moduleNamePath(moduleNameCopy);
std::filesystem::path fullPath = baseDirPath / moduleNamePath;
// Normalize the path to remove redundant ./ sequences
fullPath = fullPath.lexically_normal();
bool exists = PathExistsWithExactCase(fullPath);
bool isDirectory = exists && IsDirectoryWithExactCase(fullPath);