-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathModuleInternalCallbacks.mm
More file actions
2544 lines (2388 loc) · 119 KB
/
ModuleInternalCallbacks.mm
File metadata and controls
2544 lines (2388 loc) · 119 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
// ModuleInternalCallbacks.mm
#include "ModuleInternalCallbacks.h"
#import <Foundation/Foundation.h>
#include <sys/stat.h>
#include <v8.h>
#include <dispatch/dispatch.h>
#include <algorithm>
#include <cstddef>
#include <queue>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "Helpers.h" // for tns::Exists
#include "ModuleInternal.h" // for LoadScript(...)
#include "NativeScriptException.h"
#include "HMRSupport.h"
#include "DevFlags.h"
#include "Runtime.h" // for GetAppConfigValue
#include "RuntimeConfig.h"
// Do NOT pull all v8 symbols into namespace here; String would clash with
// other typedefs inside the NativeScript codebase. We refer to v8 symbols
// with explicit `v8::` qualification to avoid ambiguities.
namespace tns {
// Helper function to check if a module name looks like an optional external module
static bool IsLikelyOptionalModule(const std::string& moduleName) {
// Skip Node.js built-in modules (they should be handled separately)
if (moduleName.rfind("node:", 0) == 0) {
return false;
}
// Check if it's a bare module name (no path separators) that could be an npm package
if (moduleName.find('/') == std::string::npos && moduleName.find('\\') == std::string::npos &&
moduleName[0] != '.' && moduleName[0] != '~' && moduleName[0] != '/') {
return true;
}
return false;
}
// Helper function to check if a module name is a Node.js built-in module
static bool IsNodeBuiltinModule(const std::string& moduleName) {
return moduleName.rfind("node:", 0) == 0;
}
// Normalize absolute paths so we avoid duplicate registry entries caused by
// differing path representations (e.g. duplicate slashes, "./" segments).
static std::string NormalizePath(const std::string& path) {
if (path.empty()) {
return path;
}
NSString* nsPath = [NSString stringWithUTF8String:path.c_str()];
if (nsPath == nil) {
return path;
}
NSString* standardized = [nsPath stringByStandardizingPath];
if (standardized == nil) {
return path;
}
return std::string([standardized UTF8String]);
}
// Convert a file:// URL to a filesystem path using NSURL for correct decoding.
static std::string FileURLToPath(const std::string& url) {
if (url.empty()) {
return url;
}
if (url.rfind("file://", 0) != 0) {
return url; // not a file URL; return as-is
}
@autoreleasepool {
NSString* ns = [NSString stringWithUTF8String:url.c_str()];
if (!ns) {
return url;
}
NSURL* u = [NSURL URLWithString:ns];
if (u && u.isFileURL) {
NSString* p = [u path];
if (p) {
return std::string([[p stringByStandardizingPath] UTF8String]);
}
}
}
return url;
}
// Simple suffix check utility
static inline bool EndsWith(const std::string& value, const std::string& suffix) {
if (suffix.size() > value.size()) return false;
return std::equal(suffix.rbegin(), suffix.rend(), value.rbegin());
}
static inline bool StartsWith(const std::string& s, const char* prefix) {
size_t n = strlen(prefix);
return s.size() >= n && s.compare(0, n, prefix) == 0;
}
static v8::MaybeLocal<v8::Module> CompileModuleFromSource(v8::Isolate* isolate, v8::Local<v8::Context> context,
const std::string& code, const std::string& urlStr) {
v8::EscapableHandleScope hs(isolate);
v8::Local<v8::String> sourceText = tns::ToV8String(isolate, code.c_str());
v8::Local<v8::String> urlV8;
if (!v8::String::NewFromUtf8(isolate, urlStr.c_str(), v8::NewStringType::kNormal).ToLocal(&urlV8)) {
return v8::MaybeLocal<v8::Module>();
}
v8::ScriptOrigin origin(isolate, urlV8, 0, 0, false, -1, v8::Local<v8::Value>(), false, false, true);
v8::ScriptCompiler::Source src(sourceText, origin);
v8::Local<v8::Module> mod;
if (!v8::ScriptCompiler::CompileModule(isolate, &src).ToLocal(&mod)) {
return v8::MaybeLocal<v8::Module>();
}
if (mod->GetStatus() == v8::Module::kUninstantiated) {
if (!mod->InstantiateModule(context, &ResolveModuleCallback).FromMaybe(false)) {
return v8::MaybeLocal<v8::Module>();
}
}
if (mod->GetStatus() != v8::Module::kEvaluated) {
if (mod->Evaluate(context).IsEmpty()) {
return v8::MaybeLocal<v8::Module>();
}
}
return hs.Escape(mod);
}
// Like CompileModuleFromSource, but registers the module into g_moduleRegistry under urlStr
// immediately after compilation and before instantiation. This allows cyclic imports to
// resolve to the same in-progress module instance without refetching.
static v8::MaybeLocal<v8::Module> CompileModuleFromSourceRegisterFirst(v8::Isolate* isolate,
v8::Local<v8::Context> context,
const std::string& code,
const std::string& urlStr) {
v8::EscapableHandleScope hs(isolate);
v8::TryCatch tc(isolate);
v8::Local<v8::String> sourceText = tns::ToV8String(isolate, code.c_str());
v8::Local<v8::String> urlV8;
if (!v8::String::NewFromUtf8(isolate, urlStr.c_str(), v8::NewStringType::kNormal).ToLocal(&urlV8)) {
return v8::MaybeLocal<v8::Module>();
}
v8::ScriptOrigin origin(isolate, urlV8, 0, 0, false, -1, v8::Local<v8::Value>(), false, false, true);
v8::ScriptCompiler::Source src(sourceText, origin);
v8::Local<v8::Module> mod;
if (!v8::ScriptCompiler::CompileModule(isolate, &src).ToLocal(&mod)) {
return v8::MaybeLocal<v8::Module>();
}
// If an entry already exists for urlStr, do not overwrite it—use that module instead
auto itExisting = g_moduleRegistry.find(urlStr);
if (itExisting != g_moduleRegistry.end()) {
v8::Local<v8::Module> existing = itExisting->second.Get(isolate);
if (!existing.IsEmpty()) {
return hs.Escape(existing);
}
}
// Register immediately so cycles see the same instance
g_moduleRegistry[urlStr].Reset(isolate, mod);
// Instantiate
if (mod->GetStatus() == v8::Module::kUninstantiated) {
if (!mod->InstantiateModule(context, &ResolveModuleCallback).FromMaybe(false)) {
// Cleanup on failure to avoid leaving broken entries
RemoveModuleFromRegistry(urlStr);
return v8::MaybeLocal<v8::Module>();
}
}
// Evaluate if needed
if (mod->GetStatus() != v8::Module::kEvaluated) {
if (mod->Evaluate(context).IsEmpty()) {
RemoveModuleFromRegistry(urlStr);
return v8::MaybeLocal<v8::Module>();
}
}
// If any exception was caught, clean and bail
if (tc.HasCaught()) {
RemoveModuleFromRegistry(urlStr);
return v8::MaybeLocal<v8::Module>();
}
return hs.Escape(mod);
}
// Compile-only variant for use inside ResolveModuleCallback. It compiles a v8::Module and
// registers it under urlStr but does NOT instantiate or evaluate. V8 is currently instantiating
// the importer and will handle instantiation of this dependency.
static v8::MaybeLocal<v8::Module> CompileModuleForResolveRegisterOnly(v8::Isolate* isolate,
v8::Local<v8::Context> context,
const std::string& code,
const std::string& urlStr) {
v8::EscapableHandleScope hs(isolate);
v8::Local<v8::String> sourceText = tns::ToV8String(isolate, code.c_str());
v8::Local<v8::String> urlV8;
if (!v8::String::NewFromUtf8(isolate, urlStr.c_str(), v8::NewStringType::kNormal).ToLocal(&urlV8)) {
return v8::MaybeLocal<v8::Module>();
}
v8::ScriptOrigin origin(isolate, urlV8, 0, 0, false, -1, v8::Local<v8::Value>(), false, false, true);
v8::ScriptCompiler::Source src(sourceText, origin);
v8::Local<v8::Module> mod;
{
v8::TryCatch tcCompile(isolate);
if (!v8::ScriptCompiler::CompileModule(isolate, &src).ToLocal(&mod)) {
if (RuntimeConfig.IsDebug) {
uint64_t h = 1469598103934665603ull; // FNV-1a 64-bit
for (unsigned char c : code) { h ^= c; h *= 1099511628211ull; }
std::string snippet = code.substr(0, 600);
for (char& ch : snippet) { if (ch == '\n' || ch == '\r') ch = ' '; }
const char* classification = "unknown";
v8::Local<v8::Message> message = tcCompile.Message();
std::string msgStr = ""; std::string srcLineStr = ""; int lineNum = 0; int startCol = 0; int endCol = 0;
if (!message.IsEmpty()) {
v8::String::Utf8Value m8(isolate, message->Get()); if (*m8) msgStr = *m8;
lineNum = message->GetLineNumber(context).FromMaybe(0);
startCol = message->GetStartColumn(); endCol = message->GetEndColumn();
v8::MaybeLocal<v8::String> maybeLine = message->GetSourceLine(context);
if (!maybeLine.IsEmpty()) { v8::String::Utf8Value l8(isolate, maybeLine.ToLocalChecked()); if (*l8) srcLineStr = *l8; }
// Classification heuristics based on message
if (msgStr.find("Unexpected identifier") != std::string::npos || msgStr.find("Unexpected token") != std::string::npos) {
// refine unexpected token categories
if (msgStr.find("export") != std::string::npos && code.find("export default") == std::string::npos && code.find("__sfc__") != std::string::npos) classification = "missing-export-default";
else classification = "syntax";
} else if (msgStr.find("Cannot use import statement") != std::string::npos) {
classification = "wrap-error";
}
}
if (classification == std::string("unknown")) {
if (code.find("export default") == std::string::npos && code.find("__sfc__") != std::string::npos) classification = "missing-export-default";
else if (code.find("__sfc__") != std::string::npos && code.find("export {") == std::string::npos && code.find("export ") == std::string::npos) classification = "no-exports";
else if (code.find("import ") == std::string::npos && code.find("export ") == std::string::npos) classification = "not-module";
else if (code.find("_openBlock") != std::string::npos && code.find("openBlock") == std::string::npos) classification = "underscore-helper-unmapped";
}
// Trim srcLineStr
if (srcLineStr.size() > 240) srcLineStr = srcLineStr.substr(0, 240);
Log(@"[http-esm][compile][v8-error][%s] %s line=%d col=%d..%d hash=%llx bytes=%lu msg=%s srcLine=%s snippet=%s",
classification, urlStr.c_str(), lineNum, startCol, endCol, (unsigned long long)h, (unsigned long)code.size(), msgStr.c_str(), srcLineStr.c_str(), snippet.c_str());
}
return v8::MaybeLocal<v8::Module>();
}
}
// If an entry already exists, reuse it
auto itExisting = g_moduleRegistry.find(urlStr);
if (itExisting != g_moduleRegistry.end()) {
v8::Local<v8::Module> existing = itExisting->second.Get(isolate);
if (!existing.IsEmpty()) {
return hs.Escape(existing);
}
}
g_moduleRegistry[urlStr].Reset(isolate, mod);
return hs.Escape(mod);
}
// ────────────────────────────────────────────────────────────────────────────
// Simple in-process registry: maps absolute file paths → compiled Module handles
std::unordered_map<std::string, v8::Global<v8::Module>> g_moduleRegistry;
static std::unordered_map<std::string, v8::Global<v8::Module>> g_moduleFallbackRegistry;
static std::unordered_map<std::string, v8::Global<v8::Module>> g_moduleFallbackByRelative;
// g_modulesInFlight is defined later in this translation unit (thread_local static); no extern needed here.
static bool IsDocumentsPath(const std::string& path);
static std::vector<std::string> DocumentsPathAliases(const std::string& path);
static std::string ExtractRelativePath(const std::string& path);
// Returns the normalized iOS Documents directory (cached). Empty string if unavailable.
static const std::string& GetDocumentsDirectory() {
static std::string s_docsDir; // normalized without trailing slash
if (s_docsDir.empty()) {
@autoreleasepool {
NSString* docsDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
if (docsDir) {
std::string raw = [docsDir UTF8String];
std::string norm = NormalizePath(raw);
// Remove trailing slash if NormalizePath produced one, to have canonical base form
if (!norm.empty() && norm.back() == '/') {
norm.pop_back();
}
s_docsDir = norm;
}
}
}
return s_docsDir;
}
void RemoveModuleFromRegistry(const std::string& canonicalPath) {
// Defensive: never operate on an anomalous/sentinel key.
// This covers the bare "@" anomaly and the special invalid-at stub module used by the dev HTTP loader.
auto isSentinel = [](const std::string& s) -> bool {
if (s == "@") return true;
// Match any path or URL that includes the invalid-at stub filename
return s.find("__invalid_at__.mjs") != std::string::npos;
};
if (isSentinel(canonicalPath)) {
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][guard-v3] ignore remove for sentinel %s", canonicalPath.c_str());
}
return;
}
// Classification helper for diagnostics
auto classify = [](const std::string& s) -> const char* {
if (s == "@") return "sentinel:@";
if (s.find("__invalid_at__.mjs") != std::string::npos) return "sentinel:invalid_at";
bool http = StartsWith(s, "http://") || StartsWith(s, "https://");
if (http) {
if (s.find("/@ns/sfc/") != std::string::npos) return "http:sfc";
if (s.find("/@ns/m/") != std::string::npos) return "http:m";
return "http:other";
}
if (StartsWith(s, "file://")) return "file-url";
return "path";
};
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][remove:pre] key=%s class=%s", canonicalPath.c_str(), classify(canonicalPath));
}
size_t regPre = g_moduleRegistry.size();
size_t fbPre = g_moduleFallbackRegistry.size();
size_t relPre = g_moduleFallbackByRelative.size();
auto it = g_moduleRegistry.find(canonicalPath);
if (it != g_moduleRegistry.end()) {
// Only log stale removal for non-HTTP keys to avoid noisy dev HTTP churn.
bool isHttpKey = StartsWith(canonicalPath, "http://") || StartsWith(canonicalPath, "https://");
if (IsScriptLoadingLogEnabled() && !isHttpKey) {
Log(@"[resolver] removing stale module %@", [NSString stringWithUTF8String:canonicalPath.c_str()]);
}
it->second.Reset();
g_moduleRegistry.erase(it);
}
else if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][remove:miss] key not found, proceed to clear fallbacks (%s)", canonicalPath.c_str());
}
// Also clear fallbacks linked to this path
auto fb = g_moduleFallbackRegistry.find(canonicalPath);
if (fb != g_moduleFallbackRegistry.end()) {
fb->second.Reset();
g_moduleFallbackRegistry.erase(fb);
}
std::string rel = ExtractRelativePath(canonicalPath);
if (!rel.empty()) {
auto fbr = g_moduleFallbackByRelative.find(rel);
if (fbr != g_moduleFallbackByRelative.end()) {
fbr->second.Reset();
g_moduleFallbackByRelative.erase(fbr);
}
}
if (IsScriptLoadingLogEnabled()) {
size_t regPost = g_moduleRegistry.size();
size_t fbPost = g_moduleFallbackRegistry.size();
size_t relPost = g_moduleFallbackByRelative.size();
Log(@"[resolver][remove:post] reg %lu→%lu fb %lu→%lu rel %lu→%lu",
(unsigned long)regPre, (unsigned long)regPost,
(unsigned long)fbPre, (unsigned long)fbPost,
(unsigned long)relPre, (unsigned long)relPost);
}
}
void UpdateModuleFallback(v8::Isolate* isolate, const std::string& canonicalPath,
v8::Local<v8::Module> module) {
auto fallbackIt = g_moduleFallbackRegistry.find(canonicalPath);
if (fallbackIt != g_moduleFallbackRegistry.end()) {
fallbackIt->second.Reset();
}
if (!module.IsEmpty()) {
g_moduleFallbackRegistry[canonicalPath].Reset(isolate, module);
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver] fallback updated for %s from evaluated module",
canonicalPath.c_str());
}
std::string relative = ExtractRelativePath(canonicalPath);
if (!relative.empty()) {
auto relativeIt = g_moduleFallbackByRelative.find(relative);
if (relativeIt != g_moduleFallbackByRelative.end()) {
relativeIt->second.Reset();
}
g_moduleFallbackByRelative[relative].Reset(isolate, module);
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver] fallback relative updated for %s", relative.c_str());
}
}
if (IsDocumentsPath(canonicalPath)) {
for (const std::string& appAlias : DocumentsPathAliases(canonicalPath)) {
auto aliasIt = g_moduleFallbackRegistry.find(appAlias);
if (aliasIt != g_moduleFallbackRegistry.end()) {
aliasIt->second.Reset();
}
g_moduleFallbackRegistry[appAlias].Reset(isolate, module);
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver] fallback alias updated for %s (alias of %s)", appAlias.c_str(),
canonicalPath.c_str());
}
std::string aliasRelative = ExtractRelativePath(appAlias);
if (!aliasRelative.empty()) {
auto aliasRelativeIt = g_moduleFallbackByRelative.find(aliasRelative);
if (aliasRelativeIt != g_moduleFallbackByRelative.end()) {
aliasRelativeIt->second.Reset();
}
g_moduleFallbackByRelative[aliasRelative].Reset(isolate, module);
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver] fallback relative updated for %s (alias of %s)",
aliasRelative.c_str(), canonicalPath.c_str());
}
}
}
}
}
}
// Track active resolution stack to detect and short-circuit self-recursive module loads
static thread_local std::vector<std::string> g_moduleResolutionStack;
static thread_local std::unordered_map<std::string, size_t> g_moduleReentryCounts;
static thread_local std::unordered_map<std::string, std::unordered_set<std::string>>
g_moduleReentryParents;
static thread_local std::unordered_map<std::string, std::string> g_modulePrimaryImporters;
static thread_local std::unordered_set<std::string> g_modulesInFlight;
static thread_local std::unordered_set<std::string> g_modulesPendingReset;
// The threshold for detecting circular dependencies during module resolution.
// 256 was chosen as a high enough value to allow deep but legitimate module graphs,
// but low enough to catch runaway recursion or infinite circular imports.
// If a module is re-entered more than this limit, module loading is aborted and
// an error is reported to prevent stack overflow or infinite loops.
static constexpr size_t kMaxModuleReentryCount = 256;
// Waiters: module path -> list of Promise resolvers waiting for completion (instantiated/evaluated or errored)
static std::unordered_map<std::string, std::vector<v8::Global<v8::Promise::Resolver>>> g_moduleWaiters;
// Dynamic HTTP import waiters: resolve to module namespace when available.
static thread_local std::unordered_map<std::string, std::vector<v8::Global<v8::Promise::Resolver>>> g_httpDynamicWaiters;
// Bulk await state + callbacks (non-capturing for V8 function compatibility)
struct BulkWaitState {
size_t remaining;
bool rejected;
v8::Global<v8::Promise::Resolver> master;
};
static bool IsDocumentsPath(const std::string& path) {
if (path.empty()) return false;
const std::string& docs = GetDocumentsDirectory();
if (docs.empty()) {
// Fallback heuristic (legacy) if we cannot resolve the real Documents dir.
return path.find("/Documents/") != std::string::npos || path.find("\\Documents\\") != std::string::npos;
}
std::string normalizedInput = NormalizePath(path);
// Fast exact match
if (normalizedInput == docs) return true;
// Compare with prefix docs + '/'
std::string docsPrefix = docs + "/";
if (normalizedInput.rfind(docsPrefix, 0) == 0) return true;
return false;
}
static std::vector<std::string> DocumentsPathAliases(const std::string& path) {
const std::string marker = "/Documents/";
size_t pos = path.find(marker);
if (pos == std::string::npos) {
return {};
}
std::string relative = path.substr(pos + marker.size());
if (relative.empty()) {
return {};
}
std::vector<std::string> candidates;
auto tryPush = [&candidates](const std::string& p) {
if (!p.empty()) {
std::string normalized = NormalizePath(p);
if (std::find(candidates.begin(), candidates.end(), normalized) == candidates.end()) {
candidates.push_back(normalized);
}
}
};
tryPush(RuntimeConfig.ApplicationPath + "/" + relative);
tryPush(RuntimeConfig.ApplicationPath + "/app/" + relative);
return candidates;
}
static std::string ExtractRelativePath(const std::string& path) {
const std::string documentsMarker = "/Documents/";
size_t docPos = path.find(documentsMarker);
if (docPos != std::string::npos) {
return path.substr(docPos + documentsMarker.size());
}
std::string appPrefix = NormalizePath(RuntimeConfig.ApplicationPath);
if (!appPrefix.empty()) {
// Direct prefix
std::string directPrefix = appPrefix + "/";
if (path.rfind(directPrefix, 0) == 0) {
return path.substr(directPrefix.size());
}
// With bundled app folder (…/app/...)
std::string appFolderPrefix = appPrefix + "/app/";
if (path.rfind(appFolderPrefix, 0) == 0) {
return path.substr(appFolderPrefix.size());
}
}
return "";
}
static const char* ModuleStatusToString(v8::Module::Status status) {
switch (status) {
case v8::Module::kUninstantiated:
return "Uninstantiated";
case v8::Module::kInstantiating:
return "Instantiating";
case v8::Module::kInstantiated:
return "Instantiated";
case v8::Module::kEvaluating:
return "Evaluating";
case v8::Module::kEvaluated:
return "Evaluated";
case v8::Module::kErrored:
return "Errored";
}
return "Unknown";
}
namespace {
struct ResolutionStackGuard {
ResolutionStackGuard(v8::Isolate* isolate, std::vector<std::string>& stack,
const std::string& entry)
: isolate_(isolate), stack_(stack), entry_(entry), active_(true) {
stack_.push_back(entry_);
g_moduleReentryCounts[entry_] = 0;
g_moduleReentryParents.erase(entry_);
if (stack_.size() > 1) {
g_modulePrimaryImporters[entry_] = stack_[stack_.size() - 2];
} else {
g_modulePrimaryImporters.erase(entry_);
}
g_modulesInFlight.insert(entry_);
g_modulesPendingReset.erase(entry_);
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][stack] push (%lu) %s",
static_cast<unsigned long>(stack_.size()), entry_.c_str());
if (stack_.size() > 1) {
Log(@" ↳ parent: %s", stack_[stack_.size() - 2].c_str());
}
}
}
~ResolutionStackGuard() {
if (active_ && !stack_.empty()) {
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][stack] pop (%lu) %s",
static_cast<unsigned long>(stack_.size()), entry_.c_str());
}
g_moduleReentryCounts.erase(entry_);
g_moduleReentryParents.erase(entry_);
g_modulePrimaryImporters.erase(entry_);
g_modulesInFlight.erase(entry_);
// Determine final status for waiter resolution / rejection
v8::Module::Status finalStatus = v8::Module::kErrored;
auto regIt = g_moduleRegistry.find(entry_);
if (regIt != g_moduleRegistry.end()) {
v8::Local<v8::Module> m = regIt->second.Get(isolate_);
if (!m.IsEmpty()) {
finalStatus = m->GetStatus();
}
}
bool isError = finalStatus == v8::Module::kErrored;
auto waitIt = g_moduleWaiters.find(entry_);
if (waitIt != g_moduleWaiters.end()) {
std::vector<v8::Global<v8::Promise::Resolver>> resolvers;
resolvers.swap(waitIt->second);
g_moduleWaiters.erase(waitIt);
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][await] resolving %lu waiter(s) for %s status=%s",
(unsigned long)resolvers.size(), entry_.c_str(), ModuleStatusToString(finalStatus));
}
for (auto &resGlobal : resolvers) {
v8::Local<v8::Promise::Resolver> r = resGlobal.Get(isolate_);
if (!r.IsEmpty()) {
if (isError) {
v8::Local<v8::String> errMsg = tns::ToV8String(isolate_, ("Module evaluation failed: " + entry_).c_str());
v8::Local<v8::Value> errObj = v8::Exception::Error(errMsg);
r->Reject(isolate_->GetCurrentContext(), errObj).FromMaybe(false);
} else {
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][await] module now evaluated; fulfilling waiter: %s", entry_.c_str());
}
r->Resolve(isolate_->GetCurrentContext(), v8::Undefined(isolate_)).FromMaybe(false);
}
}
resGlobal.Reset();
}
}
stack_.pop_back();
auto pendingIt = g_modulesPendingReset.find(entry_);
if (pendingIt != g_modulesPendingReset.end()) {
bool removedFromRegistry = false;
auto it = g_moduleRegistry.find(entry_);
if (it != g_moduleRegistry.end()) {
v8::Local<v8::Module> module = it->second.Get(isolate_);
v8::Module::Status status = module.IsEmpty() ? v8::Module::kErrored : module->GetStatus();
if (status != v8::Module::kEvaluated && status != v8::Module::kErrored) {
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver] dropping incomplete module after unwind %s (status=%s)",
entry_.c_str(), ModuleStatusToString(status));
}
RemoveModuleFromRegistry(entry_);
removedFromRegistry = true;
} else if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver] module %s marked for reset completed evaluation (status=%s) – keeping for next importer",
entry_.c_str(), ModuleStatusToString(status));
}
} else if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver] pending reset module %s already removed from registry", entry_.c_str());
}
g_modulesPendingReset.erase(pendingIt);
if (!removedFromRegistry && IsScriptLoadingLogEnabled()) {
Log(@"[resolver] cleared pending reset flag for %s", entry_.c_str());
}
}
auto fallbackIt = g_moduleFallbackRegistry.find(entry_);
auto activeIt = g_moduleRegistry.find(entry_);
v8::Local<v8::Module> activeModule;
v8::Module::Status activeStatus = v8::Module::kErrored;
bool hasActiveModule = false;
if (activeIt != g_moduleRegistry.end()) {
activeModule = activeIt->second.Get(isolate_);
activeStatus = activeModule.IsEmpty() ? v8::Module::kErrored : activeModule->GetStatus();
hasActiveModule = true;
}
if (hasActiveModule) {
if (activeStatus == v8::Module::kEvaluated) {
g_moduleFallbackRegistry[entry_].Reset(isolate_, activeModule);
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver] updated fallback module for %s after successful evaluation",
entry_.c_str());
}
} else if (activeStatus == v8::Module::kErrored && fallbackIt != g_moduleFallbackRegistry.end()) {
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver] retaining fallback module for %s because active evaluation errored",
entry_.c_str());
}
}
} else if (fallbackIt != g_moduleFallbackRegistry.end()) {
v8::Local<v8::Module> fallback = fallbackIt->second.Get(isolate_);
if (!fallback.IsEmpty()) {
g_moduleRegistry[entry_].Reset(isolate_, fallback);
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver] restored fallback module for %s after in-flight reload failed",
entry_.c_str());
}
}
// Keep the fallback entry so that subsequent imports still have a stable copy.
}
}
}
// Disable automatic pop if ownership gets transferred (not used currently, but keeps guard safe)
void Release() { active_ = false; }
private:
v8::Isolate* isolate_;
std::vector<std::string>& stack_;
std::string entry_;
bool active_;
};
} // namespace
// Callback invoked by V8 to resolve `import X from 'specifier';`
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 = context->GetIsolate();
// 1) Turn the specifier literal into a std::string:
v8::String::Utf8Value specUtf8(isolate, specifier);
const std::string rawSpec = *specUtf8 ? *specUtf8 : "";
if (rawSpec.empty()) {
return v8::MaybeLocal<v8::Module>();
}
std::string normalizedSpec = rawSpec;
// Normalize malformed HTTP(S) schemes that sometimes appear as 'http:/host' (single slash)
// due to upstream path joins or standardization. This ensures our HTTP loader fast-path
// is used and avoids filesystem fallback attempts like '/app/http:/host'.
if (normalizedSpec.rfind("http:/", 0) == 0 && normalizedSpec.rfind("http://", 0) != 0) {
normalizedSpec.insert(5, "/"); // http:/ -> http://
} else if (normalizedSpec.rfind("https:/", 0) == 0 && normalizedSpec.rfind("https://", 0) != 0) {
normalizedSpec.insert(6, "/"); // https:/ -> https://
}
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][spec] %s", normalizedSpec.c_str());
}
// Normalize '@/' alias to '/src/' for static imports (mirrors client dynamic import normalization)
if (normalizedSpec.rfind("@/", 0) == 0) {
std::string orig = normalizedSpec;
normalizedSpec = std::string("/src/") + normalizedSpec.substr(2);
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][normalize] %@ -> %@", [NSString stringWithUTF8String:orig.c_str()], [NSString stringWithUTF8String:normalizedSpec.c_str()]);
}
}
// Guard against a bare '@' spec showing up (invalid); return empty to avoid poisoning registry with '@'
if (normalizedSpec == "@") {
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][normalize] ignoring invalid '@' static spec");
}
return v8::MaybeLocal<v8::Module>();
}
const std::string& spec = normalizedSpec; // use normalized spec for the rest of the resolution logic
// ── Early absolute-HTTP fast path ─────────────────────────────
// If the specifier itself is an absolute HTTP(S) URL, resolve it immediately via
// the HTTP loader and return before any filesystem candidate logic runs.
// Security: HttpFetchText gates remote module access centrally.
if (StartsWith(spec, "http://") || StartsWith(spec, "https://")) {
std::string key = CanonicalizeHttpUrlKey(spec);
// Added instrumentation for unified phase logging
Log(@"[http-esm][compile][begin] %s", key.c_str());
// Reuse compiled module if present and healthy
auto itExisting = g_moduleRegistry.find(key);
if (itExisting != g_moduleRegistry.end()) {
v8::Local<v8::Module> existing = itExisting->second.Get(isolate);
if (!existing.IsEmpty()) {
v8::Module::Status st = existing->GetStatus();
if (st == v8::Module::kErrored) {
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][http-cache] dropping errored %s", key.c_str());
}
RemoveModuleFromRegistry(key);
} else {
if (IsScriptLoadingLogEnabled()) {
Log(@"[http-esm][compile][cache-hit] %s", key.c_str());
}
return v8::MaybeLocal<v8::Module>(existing);
}
}
}
std::string body; std::string ct; int status = 0;
if (HttpFetchText(spec, body, ct, status) && !body.empty()) {
v8::MaybeLocal<v8::Module> m = CompileModuleForResolveRegisterOnly(isolate, context, body, key);
if (!m.IsEmpty()) {
v8::Local<v8::Module> mod;
if (m.ToLocal(&mod)) {
if (IsScriptLoadingLogEnabled()) {
Log(@"[http-esm][compile][ok] %s bytes=%zu", key.c_str(), body.size());
}
return m;
}
}
if (IsScriptLoadingLogEnabled()) {
Log(@"[http-esm][compile][fail][unknown] %s bytes=%zu", key.c_str(), body.size());
}
if (RuntimeConfig.IsDebug) {
std::string msg = "HTTP import compile failed: " + spec;
isolate->ThrowException(v8::Exception::Error(tns::ToV8String(isolate, msg.c_str())));
return v8::MaybeLocal<v8::Module>();
}
} else {
if (RuntimeConfig.IsDebug) {
std::string msg = "HTTP import failed: " + spec + " (status=" + std::to_string(status) + ")";
isolate->ThrowException(v8::Exception::Error(tns::ToV8String(isolate, msg.c_str())));
return v8::MaybeLocal<v8::Module>();
}
if (IsScriptLoadingLogEnabled()) {
Log(@"[http-esm][compile][fail][network] %s status=%d", key.c_str(), status);
}
}
// In release, fall through to normal path if HTTP load failed
}
// Debug: Log all module resolution attempts, especially for @nativescript/core/globals
std::shared_ptr<Caches> cache = Caches::Get(isolate);
if (cache->isWorker) {
if (IsScriptLoadingLogEnabled()) {
Log("ResolveModuleCallback: Worker trying to resolve '%s'\n", spec.c_str());
}
}
// 2) Find which filepath the referrer was compiled under
std::string referrerPath;
for (auto& kv : g_moduleRegistry) {
v8::Local<v8::Module> registered = kv.second.Get(isolate);
if (registered == referrer) {
referrerPath = kv.first;
break;
}
}
// If we couldn't identify the referrer (e.g. coming from a dynamic import
// where the embedder did not pass the compiled Module), we can still proceed
// for absolute and application-rooted specifiers. Only bail out early when
// the specifier is clearly relative (starts with "./" or "../") and we
// would need the referrer's directory to resolve it.
bool specIsRelative = !spec.empty() && spec[0] == '.';
if (referrerPath.empty() && specIsRelative) {
// For dynamic imports, assume the base directory is the application root
// This handles cases where runtime.mjs calls import("./chunk.mjs")
// but the referrer module isn't properly registered
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver] No referrer found for relative import '%s', assuming app root",
spec.c_str());
}
referrerPath =
RuntimeConfig.ApplicationPath + "/runtime.mjs"; // Default to runtime.mjs as referrer
}
// 3) Compute its directory
size_t slash = referrerPath.find_last_of("/\\");
std::string baseDir = slash == std::string::npos ? "" : referrerPath.substr(0, slash + 1);
// If the referrer itself was compiled from an HTTP(S) URL, then any relative
// ("./" or "../") or root-absolute ("/") specifiers should resolve against the
// referrer's URL, not the local filesystem. Mirror browser behavior by using NSURL
// to construct the absolute URL, then return an HTTP-loaded module immediately.
// Security: HttpFetchText gates remote module access centrally.
bool referrerIsHttp = (!referrerPath.empty() && (StartsWith(referrerPath, "http://") || StartsWith(referrerPath, "https://")));
bool specIsRootAbs = !spec.empty() && spec[0] == '/';
if (referrerIsHttp && (specIsRelative || specIsRootAbs)) {
std::string resolvedHttp;
@autoreleasepool {
NSString* baseStr = [NSString stringWithUTF8String:referrerPath.c_str()];
NSString* specStr = [NSString stringWithUTF8String:spec.c_str()];
if (baseStr && specStr) {
NSURL* baseURL = [NSURL URLWithString:baseStr];
NSURL* rel = [NSURL URLWithString:specStr relativeToURL:baseURL];
NSURL* absURL = [rel absoluteURL];
if (absURL) {
NSString* absStr = [absURL absoluteString];
if (absStr) {
resolvedHttp = std::string([absStr UTF8String] ?: "");
}
}
}
}
if (!resolvedHttp.empty() && (StartsWith(resolvedHttp, "http://") || StartsWith(resolvedHttp, "https://"))) {
// Security: HttpFetchText gates remote module access centrally.
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][http-rel] base=%s spec=%s -> %s", referrerPath.c_str(), spec.c_str(), resolvedHttp.c_str());
}
std::string key = CanonicalizeHttpUrlKey(resolvedHttp);
// If we've already compiled this URL, return it immediately
auto itExisting = g_moduleRegistry.find(key);
if (itExisting != g_moduleRegistry.end()) {
v8::Local<v8::Module> existing = itExisting->second.Get(isolate);
if (!existing.IsEmpty()) {
v8::Module::Status st = existing->GetStatus();
if (st == v8::Module::kErrored) {
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][http-cache] dropping errored %s", key.c_str());
}
RemoveModuleFromRegistry(key);
} else {
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][http-cache] hit %s", key.c_str());
}
return v8::MaybeLocal<v8::Module>(existing);
}
}
}
std::string body; std::string ct; int status = 0;
if (HttpFetchText(resolvedHttp, body, ct, status) && !body.empty()) {
v8::MaybeLocal<v8::Module> m = CompileModuleForResolveRegisterOnly(isolate, context, body, key);
if (!m.IsEmpty()) {
v8::Local<v8::Module> mod;
if (m.ToLocal(&mod)) {
return m;
}
}
} else {
if (RuntimeConfig.IsDebug) {
std::string msg = "HTTP import failed: " + resolvedHttp + " (status=" + std::to_string(status) + ")";
isolate->ThrowException(v8::Exception::Error(tns::ToV8String(isolate, msg.c_str())));
return v8::MaybeLocal<v8::Module>();
}
}
// In release, fall through to normal resolution if fetch failed
}
}
// 4) Resolve the import specifier relative to that directory.
// The incoming specifier may omit the file extension (e.g. "./foo") or
// point to a directory. Try to follow Node-style resolution rules for
// the most common cases so that we locate the actual .mjs file on disk
// before handing the path to LoadScript.
// ────────────────────────────────────────────────
// Build initial absolute path candidates
// ────────────────────────────────────────────────
std::vector<std::string> candidateBases;
if (!spec.empty() && spec[0] == '.') {
// Relative import (./ or ../)
std::string cleanSpec = spec.rfind("./", 0) == 0 ? spec.substr(2) : spec;
// Join baseDir and spec using NSString to collapse dot segments reliably
@autoreleasepool {
NSString* nsBase = [NSString stringWithUTF8String:baseDir.c_str()];
NSString* nsRel = [NSString stringWithUTF8String:cleanSpec.c_str()];
if (nsBase && nsRel) {
NSString* joined = [nsBase stringByAppendingPathComponent:nsRel];
NSString* std = [joined stringByStandardizingPath];
if (std) {
std::string candidate = std.UTF8String;
candidate = NormalizePath(candidate);
candidateBases.push_back(candidate);
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][normalize-rel] %s + %s -> %s", baseDir.c_str(), cleanSpec.c_str(), candidate.c_str());
}
}
}
}
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver] Relative import: '%s' + '%s' -> '%s'", baseDir.c_str(), cleanSpec.c_str(),
candidateBases.empty() ? "<none>" : candidateBases.back().c_str());
}
} else if (spec.rfind("file://", 0) == 0) {
// Absolute file URL, e.g. file:///app/path/to/chunk.mjs
std::string tail = spec.substr(7); // strip file://
if (tail.rfind("/", 0) != 0) {
tail = "/" + tail;
}
// If starts with /app/... drop the leading /app
const std::string appPrefix = "/app/";
std::string tailNoApp = tail;
if (tail.rfind(appPrefix, 0) == 0) {
tailNoApp = tail.substr(appPrefix.size());
}
// Candidate that keeps /app/ prefix stripped
std::string baseNoApp = NormalizePath(RuntimeConfig.ApplicationPath + "/" + tailNoApp);
candidateBases.push_back(baseNoApp);
// Also try path with original tail (includes /app/...) directly under application dir
std::string baseWithApp = NormalizePath(RuntimeConfig.ApplicationPath + tail);
candidateBases.push_back(baseWithApp);
} else if (!spec.empty() && spec[0] == '~') {
// Alias to application root using ~/path
std::string tail = spec.size() >= 2 && spec[1] == '/' ? spec.substr(2) : spec.substr(1);
std::string base = NormalizePath(RuntimeConfig.ApplicationPath + "/" + tail);
candidateBases.push_back(base);
// Also try ApplicationPath/app for projects that bundle JS under an app folder
std::string baseApp = NormalizePath(RuntimeConfig.ApplicationPath + "/app/" + tail);
if (baseApp != base) {
candidateBases.push_back(baseApp);
}
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][tilde] spec=%s base=%s appBase=%s",
spec.c_str(), base.c_str(), baseApp.c_str());
}
// Debug: Log tilde resolution for worker context
if (cache->isWorker) {
if (IsScriptLoadingLogEnabled()) {
Log("ResolveModuleCallback: Worker resolving tilde path '%s' -> '%s'\n", spec.c_str(),
base.c_str());
}
}
} else if (!spec.empty() && spec[0] == '/') {
// Absolute path within the bundle (e.g., /app/..., /src/...)
// Resolve against the application directory and try both with and without the '/app' prefix.
std::string base = NormalizePath(RuntimeConfig.ApplicationPath + spec);
candidateBases.push_back(base);
const std::string appPrefix = "/app/";
if (spec.rfind(appPrefix, 0) == 0) {
std::string tailNoApp = spec.substr(appPrefix.size() - 1); // keep leading '/'
// spec starts with '/app/...', so tailNoApp becomes '/...'
std::string baseNoApp = NormalizePath(RuntimeConfig.ApplicationPath + tailNoApp);
if (baseNoApp != base) {
candidateBases.push_back(baseNoApp);
}
if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][abs] spec=%s base=%s baseNoApp=%s",
spec.c_str(), base.c_str(), baseNoApp.c_str());
}
} else if (IsScriptLoadingLogEnabled()) {
Log(@"[resolver][abs] spec=%s base=%s", spec.c_str(), base.c_str());
}
} else {
// Bare specifier – resolve relative to the application root directory
std::string base = NormalizePath(RuntimeConfig.ApplicationPath + "/" + spec);
candidateBases.push_back(base);
// Additional heuristic: bundlers often encode path separators as underscores in
// chunk IDs (e.g. "src_app_components_foo_bar_ts.mjs"). Try converting
// those underscores back to slashes and look for that file as well.