-
-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathModuleInternalCallbacks.cpp
More file actions
3795 lines (3497 loc) · 161 KB
/
Copy pathModuleInternalCallbacks.cpp
File metadata and controls
3795 lines (3497 loc) · 161 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.cpp
#include "ModuleInternalCallbacks.h"
#include <unistd.h>
#include <sys/stat.h>
#include <v8.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstring>
#include <memory>
#include <mutex>
#include <string>
#include <time.h>
#include <vector>
#include "ArgConverter.h"
#include "EventLoop.h"
#include "HttpLoader.h"
#include "JEnv.h"
#include "ModuleInternal.h"
#include "NativeScriptAssert.h"
#include "NativeScriptException.h"
#include "NativeScriptPlatform.h"
#include "NsBuiltinModules.h"
#include "Runtime.h"
#include "RuntimeState.h"
#include "TraceLog.h"
#include "robin_hood.h"
using namespace v8;
using namespace std;
using namespace tns;
namespace tns {
// ─────────────────────────────────────────────────────────────
// Small string helpers (kept file-local — used everywhere below).
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 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 v8::Local<v8::String> ToV8String(v8::Isolate* isolate, const char* str) {
return ArgConverter::ConvertToV8String(isolate,
str ? std::string(str) : std::string());
}
static inline v8::Local<v8::String> ToV8String(v8::Isolate* isolate,
const std::string& str) {
return ArgConverter::ConvertToV8String(isolate, str);
}
// Filesystem: `path` names an existing regular file.
static bool IsFile(const std::string& path) {
struct stat st;
if (stat(path.c_str(), &st) != 0) {
return false;
}
return (st.st_mode & S_IFMT) == S_IFREG;
}
// Append `ext` if `path` doesn't already carry it.
static std::string WithExtension(const std::string& path, const std::string& ext) {
if (path.size() >= ext.size() &&
path.compare(path.size() - ext.size(), ext.size(), ext) == 0) {
return path;
}
return path + ext;
}
// Application filesystem root for on-disk .mjs/.js resolution.
// Mirrors Module.java's getApplicationFilesPath + "/app". Cached after first
// JNI call — the value is process-stable, and re-entering JNI on every
// resolver hit would add avoidable overhead to hot module-graph walks.
static std::string GetApplicationPath() {
static std::string cached;
static std::once_flag flag;
std::call_once(flag, []() {
JEnv env;
jstring applicationFilesPath = (jstring)env.CallStaticObjectMethod(
ModuleInternal::MODULE_CLASS,
ModuleInternal::GET_APPLICATION_FILES_PATH_METHOD_ID);
if (applicationFilesPath != nullptr) {
cached = ArgConverter::jstringToString(applicationFilesPath) + "/app";
}
});
return cached;
}
// Collapse "." and ".." segments, preserving a leading "/".
static std::string NormalizeDotSegments(const std::string& path) {
std::vector<std::string> stack;
bool absolute = !path.empty() && path[0] == '/';
size_t i = 0;
while (i <= path.size()) {
size_t j = path.find('/', i);
std::string seg = (j == std::string::npos) ? path.substr(i) : path.substr(i, j - i);
if (seg.empty() || seg == ".") {
// skip
} else if (seg == "..") {
if (!stack.empty()) stack.pop_back();
} else {
stack.push_back(std::move(seg));
}
if (j == std::string::npos) break;
i = j + 1;
}
std::string norm = absolute ? "/" : std::string();
for (size_t k = 0; k < stack.size(); k++) {
if (k > 0) norm += "/";
norm += stack[k];
}
return norm;
}
// Normalize a filesystem path: collapse duplicate slashes, "./" and "../"
// segments. Same intent as iOS's `stringByStandardizingPath`, minus the
// Foundation dependency (no HOME expansion, which we never used anyway).
static std::string NormalizePath(const std::string& path) {
if (path.empty()) return path;
return NormalizeDotSegments(path);
}
// Convert a file:// URL to a filesystem path. Handles both file:///a/b and
// file:/a/b variants. Percent-decoding is deliberately omitted — the runtime
// only emits ASCII file:// URLs internally.
static std::string FileURLToPath(const std::string& url) {
if (url.empty()) return url;
if (!StartsWith(url, "file://")) return url;
std::string tail = url.substr(7);
// Strip host component when present (file://host/path → /path). NS never
// emits a host, but be tolerant.
if (!tail.empty() && tail[0] != '/') {
size_t slash = tail.find('/');
tail = (slash == std::string::npos) ? std::string() : tail.substr(slash);
}
// Drop query and fragment — these have no meaning for filesystem paths.
size_t cut = tail.find_first_of("?#");
if (cut != std::string::npos) tail = tail.substr(0, cut);
return NormalizePath(tail);
}
// Resolve a relative or root-absolute spec against an HTTP(S) referrer URL.
// Returns empty string if resolution is not applicable.
static std::string ResolveHttpRelative(const std::string& referrerUrl,
const std::string& spec) {
if (referrerUrl.empty()) return std::string();
if (!(StartsWith(referrerUrl, "http://") || StartsWith(referrerUrl, "https://"))) {
return std::string();
}
// Normalize referrer: drop fragment and query.
std::string base = referrerUrl;
size_t hashPos = base.find('#');
if (hashPos != std::string::npos) base = base.substr(0, hashPos);
size_t qPos = base.find('?');
if (qPos != std::string::npos) base = base.substr(0, qPos);
size_t schemePos = base.find("://");
if (schemePos == std::string::npos) return std::string();
size_t pathStart = base.find('/', schemePos + 3);
std::string origin = (pathStart == std::string::npos) ? base : base.substr(0, pathStart);
std::string path = (pathStart == std::string::npos) ? std::string("/")
: base.substr(pathStart);
std::string specPath = spec;
std::string specSuffix;
size_t specQ = specPath.find('?');
size_t specH = specPath.find('#');
size_t cut = std::string::npos;
if (specQ != std::string::npos && specH != std::string::npos) {
cut = std::min(specQ, specH);
} else if (specQ != std::string::npos) {
cut = specQ;
} else if (specH != std::string::npos) {
cut = specH;
}
if (cut != std::string::npos) {
specSuffix = specPath.substr(cut);
specPath = specPath.substr(0, cut);
}
std::string newPath;
if (!specPath.empty() && specPath[0] == '/') {
newPath = specPath;
} else {
size_t lastSlash = path.find_last_of('/');
std::string baseDir = (lastSlash == std::string::npos)
? std::string("/")
: path.substr(0, lastSlash + 1);
newPath = baseDir + specPath;
}
return origin + NormalizeDotSegments(newPath) + specSuffix;
}
// Forward declarations for helpers referenced before their definitions.
static const char* ModuleStatusToString(v8::Module::Status status);
static void KillAsyncGraphLoadsForIsolate(v8::Isolate* isolate);
static v8::MaybeLocal<v8::Module> CompileJsonTextAsEsModule(
v8::Isolate* isolate, v8::Local<v8::Context> context,
const std::string& jsonText, const std::string& registryAbsPath,
const std::string& displayUrl);
static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate,
v8::Local<v8::Context> context,
const std::string& registryKey);
namespace {
struct AsyncGraphLoad;
// One require(esm) exports facade and the module it wraps. Held as a pair
// because identity hashes collide: lookups compare the target handle.
struct RequireFacadeEntry {
v8::Global<v8::Module> target;
v8::Global<v8::Module> facade;
};
// ─────────────────────────────────────────────────────────────
// Per-isolate module-loader state
//
// Why per-isolate (not process-global, not thread_local): v8::Global<T>
// handles are bound to the isolate that created them; reading their internal
// state from a different isolate is undefined behaviour. NS Workers each run
// a separate v8::Isolate on their own thread and, under HMR, may fetch the
// same URLs the main thread already loaded — a shared map would hand the
// worker isolate a Module the main isolate compiled, and V8's linker would
// read the cross-isolate export table and emit bogus errors like:
// SyntaxError: The requested module 'X' does not provide an export named 'Y'
//
// Lifetime: the state lives in a RuntimeState slot, so it is destroyed with
// the runtime (Runtime::DestroyRuntime → RuntimeState::Clear), on the
// runtime's own thread while the isolate is still alive — which lets the
// v8::Global members Reset safely in their own destructors and leaves nothing
// to static/thread destructors, where a post-disposal Reset would crash.
// Access from the isolate's own thread only, per the slot contract.
struct ModuleLoaderState {
ModuleHandleMap registry; // canonical key -> compiled module
// What the dev client taught THIS isolate's loader: import map,
// canonicalization vocabulary, volatile patterns.
LoaderVocabulary vocabulary;
// In-flight async graph walks; entries are weak so a finished load frees
// itself. A pending background fetch completion can hold a load's
// shared_ptr past teardown, so QuiesceModuleLoadsForIsolate must flag these
// dead and Reset their context Globals while the isolate is still alive —
// the slot destructor alone is not enough for them.
std::vector<std::weak_ptr<AsyncGraphLoad>> asyncGraphLoads;
// HTTP dynamic imports currently fetching/evaluating, for coalescing.
robin_hood::unordered_set<std::string> modulesInFlight;
// Dynamic HTTP import waiters: resolve to the module namespace.
robin_hood::unordered_map<std::string,
std::vector<v8::Global<v8::Promise::Resolver>>>
httpDynamicWaiters;
// Reverse index: v8::Module::GetIdentityHash() -> registry keys, so
// module→key lookups (resolver referrer discovery, import.meta) are O(1)
// instead of a scan of the whole registry. Hashes collide, so a bucket holds
// candidates; FindKeyForModule confirms each against the registry and prunes
// the ones it no longer backs, so a stale candidate can never answer a
// lookup.
robin_hood::unordered_map<int, std::vector<std::string>> keysByModuleHash;
// require(esm) facades, keyed by the TARGET module's identity hash — same
// bucket-plus-handle-compare shape as keysByModuleHash. Repeated require() of
// one ES module must hand back the identical exports object, and a facade
// must never outlive the module it re-exports (UnindexRegistryKey drops the
// entry as the target stops being the registry's answer for its key).
robin_hood::unordered_map<int, std::vector<RequireFacadeEntry>>
requireFacadesByTargetHash;
// Holds the facade target across that facade's InstantiateModule and nothing
// else — the facade's resolve callback is the only reader.
v8::Global<v8::Module> pendingFacadeTarget;
};
// This isolate's loader state, or null once teardown has begun — callers must
// bail, not recreate state.
ModuleLoaderState* ModuleLoaderStateFor(v8::Isolate* isolate) {
if (isolate == nullptr) return nullptr;
return RuntimeState::For<ModuleLoaderState>(isolate);
}
// Record `key` as a candidate for `mod`'s identity hash. Call alongside every
// registry insert.
void IndexRegisteredModule(ModuleLoaderState& state, const std::string& key,
v8::Local<v8::Module> mod) {
if (mod.IsEmpty()) return;
auto& keys = state.keysByModuleHash[mod->GetIdentityHash()];
if (std::find(keys.begin(), keys.end(), key) == keys.end()) {
keys.push_back(key);
}
}
// Drop any facade wrapping `target`. Called as the target stops being the
// registry's answer for its key: a facade whose re-export source is gone would
// serve a dead namespace.
void DropRequireFacadesForTarget(ModuleLoaderState& state, v8::Isolate* isolate,
v8::Local<v8::Module> target) {
if (target.IsEmpty()) return;
auto bucketIt = state.requireFacadesByTargetHash.find(target->GetIdentityHash());
if (bucketIt == state.requireFacadesByTargetHash.end()) return;
auto& entries = bucketIt->second;
for (auto it = entries.begin(); it != entries.end();) {
if (it->target.Get(isolate) == target) {
it = entries.erase(it);
} else {
++it;
}
}
if (entries.empty()) {
state.requireFacadesByTargetHash.erase(bucketIt);
}
}
// Drop `key` from the bucket of whatever module the registry holds under it
// right now. Call before replacing or erasing that entry, while the outgoing
// handle is still reachable — afterwards its hash is unrecoverable.
void UnindexRegistryKey(ModuleLoaderState& state, v8::Isolate* isolate,
const std::string& key) {
auto regIt = state.registry.find(key);
if (regIt == state.registry.end() || regIt->second.IsEmpty()) return;
v8::Local<v8::Module> outgoing = regIt->second.Get(isolate);
if (outgoing.IsEmpty()) return;
DropRequireFacadesForTarget(state, isolate, outgoing);
auto bucketIt = state.keysByModuleHash.find(outgoing->GetIdentityHash());
if (bucketIt == state.keysByModuleHash.end()) return;
auto& keys = bucketIt->second;
keys.erase(std::remove(keys.begin(), keys.end(), key), keys.end());
if (keys.empty()) {
state.keysByModuleHash.erase(bucketIt);
}
}
// The registry key whose live entry is `mod`, or empty. Prunes candidates the
// registry no longer confirms.
std::string FindKeyForModule(ModuleLoaderState& state, v8::Isolate* isolate,
v8::Local<v8::Module> mod) {
if (mod.IsEmpty()) return std::string();
auto bucketIt = state.keysByModuleHash.find(mod->GetIdentityHash());
if (bucketIt == state.keysByModuleHash.end()) return std::string();
auto& keys = bucketIt->second;
for (auto it = keys.begin(); it != keys.end();) {
auto regIt = state.registry.find(*it);
if (regIt == state.registry.end() || regIt->second.IsEmpty()) {
it = keys.erase(it);
continue;
}
if (regIt->second.Get(isolate) == mod) {
return *it;
}
++it;
}
if (keys.empty()) {
state.keysByModuleHash.erase(bucketIt);
}
return std::string();
}
} // namespace
std::string LookupModuleKeyForModule(v8::Isolate* isolate,
v8::Local<v8::Module> mod) {
auto* state = ModuleLoaderStateFor(isolate);
if (state == nullptr) return std::string();
return FindKeyForModule(*state, isolate, mod);
}
namespace {
// The single module request in the facade source, and the source itself. Both
// match Node's required_module_facade_source_string so the semantics (live
// bindings, enumerable re-exports, overridable __esModule) stay identical.
constexpr const char* kRequireFacadeSpecifier = "original";
constexpr const char* kRequireFacadeSource =
"export * from 'original'; export { default } from 'original'; "
"export const __esModule = true;";
// Resolves the facade's one request. Passed only to a facade's
// InstantiateModule, so the general resolver never sees 'original' and user
// code can never reach this slot.
v8::MaybeLocal<v8::Module> ResolveRequireFacadeTarget(
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();
auto* state = ModuleLoaderStateFor(isolate);
v8::String::Utf8Value specUtf8(isolate, specifier);
const std::string spec = *specUtf8 ? *specUtf8 : "";
if (state == nullptr || state->pendingFacadeTarget.IsEmpty() ||
spec != kRequireFacadeSpecifier) {
DEBUG_WRITE_FORCE("FATAL: require(esm) facade resolve for '%s' with no pending target",
spec.c_str());
isolate->ThrowException(v8::Exception::Error(ArgConverter::ConvertToV8String(
isolate, "require(esm) facade could not be linked to its target module")));
return v8::MaybeLocal<v8::Module>();
}
return v8::MaybeLocal<v8::Module>(state->pendingFacadeTarget.Get(isolate));
}
} // namespace
v8::MaybeLocal<v8::Module> GetOrCreateRequireFacade(
v8::Isolate* isolate, v8::Local<v8::Context> context,
v8::Local<v8::Module> target, const std::string& targetCanonicalPath) {
if (target.IsEmpty()) return v8::MaybeLocal<v8::Module>();
auto* state = ModuleLoaderStateFor(isolate);
if (state == nullptr) return v8::MaybeLocal<v8::Module>();
auto bucketIt = state->requireFacadesByTargetHash.find(target->GetIdentityHash());
if (bucketIt != state->requireFacadesByTargetHash.end()) {
for (auto& entry : bucketIt->second) {
if (entry.target.Get(isolate) == target) {
return v8::MaybeLocal<v8::Module>(entry.facade.Get(isolate));
}
}
}
v8::EscapableHandleScope hs(isolate);
const std::string facadeUrl = "ns:require-facade:" + targetCanonicalPath;
v8::Local<v8::String> urlV8;
if (!v8::String::NewFromUtf8(isolate, facadeUrl.c_str(), v8::NewStringType::kNormal)
.ToLocal(&urlV8)) {
return v8::MaybeLocal<v8::Module>();
}
v8::ScriptOrigin origin(urlV8, 0, 0, false, -1, v8::Local<v8::Value>(), false,
false, true /* is_module */);
v8::ScriptCompiler::Source source(
ArgConverter::ConvertToV8String(isolate, kRequireFacadeSource), origin);
v8::TryCatch tc(isolate);
v8::Local<v8::Module> facade;
if (!v8::ScriptCompiler::CompileModule(isolate, &source).ToLocal(&facade)) {
throw NativeScriptException(
tc, "Cannot compile the require() facade for " + targetCanonicalPath);
}
bool linked = false;
{
// The slot must be clear again whichever way instantiation ends.
struct PendingTargetScope {
ModuleLoaderState* state;
~PendingTargetScope() { state->pendingFacadeTarget.Reset(); }
} pendingScope{state};
state->pendingFacadeTarget.Reset(isolate, target);
linked = facade->InstantiateModule(context, &ResolveRequireFacadeTarget)
.FromMaybe(false);
}
if (!linked) {
throw NativeScriptException(
tc, "Cannot link the require() facade for " + targetCanonicalPath);
}
// Three re-export statements over an already-evaluated module: trivially
// synchronous, so the strict policy's settled-promise requirement holds.
ModuleEvaluationOptions evalOptions;
evalOptions.policy = ModuleEvaluationPolicy::kSyncStrict;
EvaluateModuleGraph(isolate, context, facade, facadeUrl, evalOptions);
// The facade is deliberately absent from the registry and the identity-hash
// index: nothing resolves to it by name, and its source has no import.meta or
// dynamic import, so no host callback ever needs to find it.
RequireFacadeEntry entry;
entry.target.Reset(isolate, target);
entry.facade.Reset(isolate, facade);
state->requireFacadesByTargetHash[target->GetIdentityHash()].push_back(
std::move(entry));
return hs.Escape(facade);
}
void IndexModuleForIsolate(v8::Isolate* isolate, const std::string& canonicalKey,
v8::Local<v8::Module> mod) {
auto* state = ModuleLoaderStateFor(isolate);
if (state == nullptr) return;
IndexRegisteredModule(*state, canonicalKey, mod);
}
void UnindexModuleForIsolate(v8::Isolate* isolate,
const std::string& canonicalKey) {
auto* state = ModuleLoaderStateFor(isolate);
if (state == nullptr) return;
UnindexRegistryKey(*state, isolate, canonicalKey);
}
static bool IsVolatileUrl(const LoaderVocabulary& vocabulary,
const std::string& url);
// ─────────────────────────────────────────────────────────────
// AdoptThenable
//
// Turn any thenable value into a real v8::Promise. Promises returned by
// V8 itself (Module::Evaluate) are genuine and take the fast path;
// user-space thenables (e.g. Proxy'd Promises) fail v8::Value::IsPromise
// but adopting them via Promise::Resolver::New + Resolve preserves their
// state.
static v8::MaybeLocal<v8::Promise> AdoptThenable(v8::Isolate* isolate,
v8::Local<v8::Context> context,
v8::Local<v8::Value> value) {
if (value.IsEmpty()) return v8::MaybeLocal<v8::Promise>();
if (value->IsPromise()) return value.As<v8::Promise>();
if (!value->IsObject()) return v8::MaybeLocal<v8::Promise>();
v8::Local<v8::Value> thenVal;
if (!value.As<v8::Object>()
->Get(context, ArgConverter::ConvertToV8String(isolate, "then"))
.ToLocal(&thenVal) ||
!thenVal->IsFunction()) {
return v8::MaybeLocal<v8::Promise>();
}
v8::Local<v8::Promise::Resolver> adopter;
if (!v8::Promise::Resolver::New(context).ToLocal(&adopter) ||
adopter->Resolve(context, value).IsNothing()) {
return v8::MaybeLocal<v8::Promise>();
}
return adopter->GetPromise();
}
// ─────────────────────────────────────────────────────────────
// Compile helpers
// "message (line L:C)" for a caught exception, or empty. The line/column are
// the part no caller can reconstruct from a failure code.
static std::string DescribeCaughtError(v8::Isolate* isolate,
v8::Local<v8::Context> context,
const v8::TryCatch& tc) {
if (!tc.HasCaught()) return std::string();
v8::Local<v8::Message> message = tc.Message();
if (message.IsEmpty()) return std::string();
v8::String::Utf8Value text(isolate, message->Get());
std::string described = *text ? *text : "";
int line = message->GetLineNumber(context).FromMaybe(0);
if (line > 0) {
described += " (line " + std::to_string(line) + ":" +
std::to_string(message->GetStartColumn()) + ")";
}
return described;
}
// Compile-only variant used inside ResolveModuleCallback. 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.
//
// On compile failure the exception is left PENDING, the same contract as
// ModuleInternal::CompileFileEsModule: it names the file, line and column,
// which nothing downstream can reconstruct. A caller that cannot let it
// propagate must consume it through its own TryCatch and route the text into
// its own failure channel — never drop it.
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);
auto* moduleState = ModuleLoaderStateFor(isolate);
if (moduleState == nullptr) {
return v8::MaybeLocal<v8::Module>();
}
auto& registry = moduleState->registry;
const std::string registryKey = CanonicalizeRegistryKey(urlStr);
// Checked before compiling: recompiling a key that is already registered
// would mint a second module identity while importers hold the first.
auto itExisting = registry.find(registryKey);
if (itExisting != registry.end()) {
v8::Local<v8::Module> existing = itExisting->second.Get(isolate);
if (!existing.IsEmpty()) {
return hs.Escape(existing);
}
}
v8::Local<v8::String> sourceText =
ArgConverter::ConvertToV8String(isolate, code);
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(urlV8, 0, 0, false, -1, v8::Local<v8::Value>(),
false, false, true /* is_module */);
v8::ScriptCompiler::Source src(sourceText, origin);
v8::Local<v8::Module> mod;
{
v8::TryCatch tcCompile(isolate);
if (!v8::ScriptCompiler::CompileModule(isolate, &src).ToLocal(&mod)) {
TNS_DEBUG(Esm, "[http-esm][compile][fail] %s %s", urlStr.c_str(),
DescribeCaughtError(isolate, context, tcCompile).c_str());
tcCompile.ReThrow();
return v8::MaybeLocal<v8::Module>();
}
}
UnindexRegistryKey(*moduleState, isolate, registryKey);
registry[registryKey].Reset(isolate, mod);
IndexRegisteredModule(*moduleState, registryKey, mod);
return hs.Escape(mod);
}
// Returns null once teardown has begun.
ModuleHandleMap* ModuleRegistryFor(v8::Isolate* isolate) {
auto* state = ModuleLoaderStateFor(isolate);
return state == nullptr ? nullptr : &state->registry;
}
// Neutralize any in-flight async graph loads for `isolate`: their fetch
// completions check the dead flag before touching V8, and their context
// Globals are Reset here, while the isolate is still alive. The rest of the
// loader state is destroyed with the isolate's RuntimeState.
void QuiesceModuleLoadsForIsolate(v8::Isolate* isolate) {
KillAsyncGraphLoadsForIsolate(isolate);
}
// The calling isolate's vocabulary, or null once teardown has begun.
static LoaderVocabulary* VocabularyForCurrentIsolate() {
auto* state = ModuleLoaderStateFor(v8::Isolate::TryGetCurrent());
return state != nullptr ? &state->vocabulary : nullptr;
}
std::string CanonicalizeRegistryKey(const std::string& key) {
if (key.empty()) return key;
std::string registryKey;
const char* classification = "path";
bool traceEvenWithoutChange = false;
// Repair-first, exactly like IsHttpModulePath: a collapsed scheme
// separator (`http:/host/...`) must key as the URL it routes as, or the
// loader registers a module under a key the probes and evictions of the
// raw string can never find.
const std::string repaired = NormalizeHttpModuleUrl(key);
if (StartsWith(repaired, "http://") || StartsWith(repaired, "https://")) {
registryKey = CanonicalizeHttpUrlKey(repaired);
classification = "http";
} else if (StartsWith(key, "file://")) {
registryKey = NormalizePath(FileURLToPath(key));
classification = "file-url";
} else if (StartsWith(key, "blob:")) {
registryKey = key;
classification = "blob";
traceEvenWithoutChange = true;
} else {
// Preserve non-filesystem module namespaces such as node:
// so synthetic/in-memory modules keep their exact registry identity.
size_t schemePos = key.find(':');
size_t slashPos = key.find('/');
if (schemePos != std::string::npos &&
(slashPos == std::string::npos || schemePos < slashPos)) {
registryKey = key;
classification = "custom-scheme";
traceEvenWithoutChange = true;
} else {
registryKey = NormalizePath(key);
}
}
if (traceEvenWithoutChange || registryKey != key) {
TNS_DEBUG(Esm, "[resolver][registry-key][%s] raw=%s key=%s", classification,
key.c_str(), registryKey.c_str());
}
return registryKey;
}
v8::MaybeLocal<v8::Module> LoadHttpModuleForUrl(v8::Isolate* isolate,
v8::Local<v8::Context> context,
const std::string& requestedUrl) {
auto* moduleState = ModuleLoaderStateFor(isolate);
if (moduleState == nullptr) {
return v8::MaybeLocal<v8::Module>();
}
auto& registry = moduleState->registry;
const std::string registryKey = CanonicalizeHttpUrlKey(requestedUrl);
TNS_DEBUG(Esm, "[http-esm][load][begin] request=%s key=%s",
requestedUrl.c_str(), registryKey.c_str());
auto itExisting = registry.find(registryKey);
if (itExisting != registry.end()) {
v8::Local<v8::Module> existing = itExisting->second.Get(isolate);
if (!existing.IsEmpty() && existing->GetStatus() != v8::Module::kErrored) {
TNS_DEBUG(Esm, "[http-esm][load][cache-hit] key=%s", registryKey.c_str());
return v8::MaybeLocal<v8::Module>(existing);
}
TNS_DEBUG(Esm, "[http-esm][load][drop-errored] key=%s", registryKey.c_str());
RemoveModuleFromRegistry(isolate, registryKey);
}
// Reaching this point means the graph walk did not discover this URL, so the
// module is about to be fetched synchronously, blocking the JS thread for a
// whole round trip. That is an invariant violation, not a mode — always
// visible, in every build, so it cannot hide behind a disabled trace
// category. The fallback itself stays: correctness first, diagnosis loud.
DEBUG_WRITE_FORCE(
"NativeScript: module graph walk missed %s — falling back to a blocking "
"synchronous fetch. This should not happen; please report it.",
requestedUrl.c_str());
ModuleFetchResult fetched;
if (!HttpFetchModule(requestedUrl, registryKey, fetched)) {
TNS_DEBUG(Esm, "[http-esm][load][fetch-fail] request=%s key=%s status=%d",
requestedUrl.c_str(), registryKey.c_str(), fetched.status);
// The classifier's reason names the URL and the cause (status, MIME or
// transport); a generic message here would lose all of it. V8 requires an
// exception whenever a resolve callback returns empty, so this is thrown
// in every build.
isolate->ThrowException(v8::Exception::Error(
ArgConverter::ConvertToV8String(isolate, fetched.failureReason)));
return v8::MaybeLocal<v8::Module>();
}
if (fetched.kind == ModuleResponseKind::kJson) {
return CompileJsonTextAsEsModule(isolate, context, fetched.body, registryKey,
requestedUrl);
}
v8::Local<v8::Module> loaded;
{
v8::TryCatch tcCompile(isolate);
if (!CompileModuleForResolveRegisterOnly(isolate, context, fetched.body,
registryKey)
.ToLocal(&loaded)) {
TNS_DEBUG(Esm, "[http-esm][load][compile-fail] request=%s key=%s bytes=%zu",
requestedUrl.c_str(), registryKey.c_str(),
fetched.body.size());
if (tcCompile.HasCaught()) {
// The compile error names the module, line and column; replacing it
// with a generic "compile failed" would strictly lose information.
tcCompile.ReThrow();
} else {
std::string msg = "HTTP import compile failed: " + requestedUrl;
isolate->ThrowException(v8::Exception::Error(
ArgConverter::ConvertToV8String(isolate, msg)));
}
return v8::MaybeLocal<v8::Module>();
}
}
TNS_DEBUG(Esm, "[http-esm][load][ok] request=%s key=%s type=%s bytes=%zu",
requestedUrl.c_str(), registryKey.c_str(),
fetched.contentType.c_str(), fetched.body.size());
return loaded;
}
// ─────────────────────────────────────────────────────────────
// Import map helpers
// Read one imports-shaped section. Every rejection names the offending key so
// a bad map is fixable from the message alone.
static bool ParseImportMapEntries(v8::Isolate* isolate, v8::Local<v8::Context> context,
v8::Local<v8::Object> source,
const std::string& sectionLabel,
ImportMapEntries* out, std::string* error) {
v8::Local<v8::Array> keys;
if (!source->GetOwnPropertyNames(context).ToLocal(&keys)) {
*error = sectionLabel + ": could not be read";
return false;
}
for (uint32_t i = 0; i < keys->Length(); i++) {
v8::Local<v8::Value> keyVal;
if (!keys->Get(context, i).ToLocal(&keyVal) || !keyVal->IsString()) {
*error = sectionLabel + ": every key must be a string";
return false;
}
v8::String::Utf8Value keyUtf8(isolate, keyVal);
if (!*keyUtf8) {
*error = sectionLabel + ": every key must be a string";
return false;
}
const std::string specifier(*keyUtf8);
if (specifier.empty()) {
*error = sectionLabel + ": a specifier key must not be empty";
return false;
}
v8::Local<v8::Value> value;
if (!source->Get(context, keyVal).ToLocal(&value) || !value->IsString()) {
*error = sectionLabel + ": the target for '" + specifier + "' must be a string";
return false;
}
v8::String::Utf8Value valueUtf8(isolate, value);
if (!*valueUtf8) {
*error = sectionLabel + ": the target for '" + specifier + "' must be a string";
return false;
}
const std::string target(*valueUtf8);
if (target.empty()) {
*error = sectionLabel + ": the target for '" + specifier + "' must not be empty";
return false;
}
// A trailing-slash key maps a whole subtree, so its target must name one
// too — otherwise the remainder would be pasted onto a file path.
if (specifier.back() == '/' && target.back() != '/') {
*error = sectionLabel + ": the target for '" + specifier +
"' must end with '/' because the specifier key does";
return false;
}
(*out)[specifier] = target;
}
return true;
}
// Parse without touching the live map. On any failure `error` explains what is
// wrong and `out` is meaningless — the caller keeps whatever it already had.
// V8's JSON parser stands in for iOS's NSJSONSerialization: escapes, nesting
// and malformed input are handled by the engine rather than a hand-rolled
// scanner, and this always runs on the isolate's own thread.
static bool ParseImportMap(v8::Isolate* isolate, const std::string& json,
ParsedImportMap* out, std::string* error) {
if (json.empty()) {
*error = "an import map must be a non-empty JSON object";
return false;
}
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::TryCatch tc(isolate);
v8::Local<v8::Value> parsed;
if (!v8::JSON::Parse(context, ArgConverter::ConvertToV8String(isolate, json))
.ToLocal(&parsed)) {
std::string detail = DescribeCaughtError(isolate, context, tc);
*error = "an import map must be valid JSON" + (detail.empty() ? "" : ": " + detail);
return false;
}
if (!parsed->IsObject() || parsed->IsArray()) {
*error = "an import map must be a JSON object";
return false;
}
v8::Local<v8::Object> top = parsed.As<v8::Object>();
// Only the map's OWN keys are sections; reading through the prototype would
// let a polluted Object.prototype smuggle one in.
v8::Local<v8::Array> sections;
if (!top->GetOwnPropertyNames(context).ToLocal(§ions)) {
*error = "an import map must be a JSON object";
return false;
}
bool hasImports = false;
bool hasScopes = false;
for (uint32_t i = 0; i < sections->Length(); i++) {
v8::Local<v8::Value> sectionVal;
std::string name;
if (sections->Get(context, i).ToLocal(§ionVal) && sectionVal->IsString()) {
v8::String::Utf8Value utf8(isolate, sectionVal);
if (*utf8) name = *utf8;
}
if (name == "imports") {
hasImports = true;
} else if (name == "scopes") {
hasScopes = true;
} else {
*error = "unsupported import-map section '" + name +
"'; only \"imports\" and \"scopes\" are supported";
return false;
}
}
v8::Local<v8::Value> imports;
if (hasImports &&
top->Get(context, ArgConverter::ConvertToV8String(isolate, "imports")).ToLocal(&imports) &&
!imports->IsUndefined()) {
if (!imports->IsObject() || imports->IsArray()) {
*error = "the \"imports\" section must be an object";
return false;
}
if (!ParseImportMapEntries(isolate, context, imports.As<v8::Object>(), "imports",
&out->imports, error)) {
return false;
}
}
v8::Local<v8::Value> scopes;
if (hasScopes &&
top->Get(context, ArgConverter::ConvertToV8String(isolate, "scopes")).ToLocal(&scopes) &&
!scopes->IsUndefined()) {
if (!scopes->IsObject() || scopes->IsArray()) {
*error = "the \"scopes\" section must be an object";
return false;
}
v8::Local<v8::Object> scopesObj = scopes.As<v8::Object>();
v8::Local<v8::Array> scopeKeys;
if (!scopesObj->GetOwnPropertyNames(context).ToLocal(&scopeKeys)) {
*error = "the \"scopes\" section must be an object";
return false;
}
for (uint32_t i = 0; i < scopeKeys->Length(); i++) {
v8::Local<v8::Value> scopeKeyVal;
if (!scopeKeys->Get(context, i).ToLocal(&scopeKeyVal) || !scopeKeyVal->IsString()) {
*error = "scopes: every scope key must be a string";
return false;
}
v8::String::Utf8Value scopeUtf8(isolate, scopeKeyVal);
const std::string scopePrefix(*scopeUtf8 ? *scopeUtf8 : "");
if (scopePrefix.empty()) {
*error = "scopes: a scope key must not be empty";
return false;
}
v8::Local<v8::Value> scopeMap;
if (!scopesObj->Get(context, scopeKeyVal).ToLocal(&scopeMap) || !scopeMap->IsObject() ||
scopeMap->IsArray()) {
*error = "scopes: the map for scope '" + scopePrefix + "' must be an object";
return false;
}
ImportMapEntries entries;
if (!ParseImportMapEntries(isolate, context, scopeMap.As<v8::Object>(),
"scope '" + scopePrefix + "'", &entries, error)) {
return false;
}
out->scopes.emplace_back(scopePrefix, std::move(entries));
}
}
// Most specific first: a longer prefix is the more specific scope, and the
// key comparison keeps the order deterministic for equal-length prefixes.
std::sort(out->scopes.begin(), out->scopes.end(),
[](const std::pair<std::string, ImportMapEntries>& a,
const std::pair<std::string, ImportMapEntries>& b) {
if (a.first.size() != b.first.size()) {
return a.first.size() > b.first.size();
}
return a.first > b.first;
});
return true;
}
// Swaps in an already-parsed map. Split from SetImportMap so configureLoader
// can validate every section before installing any of them.
static bool InstallParsedImportMap(ParsedImportMap parsedMap, std::string* error) {
LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate();
if (vocabulary == nullptr) {
if (error != nullptr) {
*error = "the isolate is shutting down";
}
return false;
}
vocabulary->importMap = std::move(parsedMap);
TNS_DEBUG(Esm, "[import-map] loaded %lu entries, %lu scopes",
(unsigned long)vocabulary->importMap.imports.size(),
(unsigned long)vocabulary->importMap.scopes.size());
return true;
}
bool SetImportMap(const std::string& json, std::string* error) {
// Parse-validate-swap: the live vocabulary is replaced only once a complete
// map has been built, so a rejected update leaves resolution exactly as it
// was rather than silently emptying it.
ParsedImportMap parsedMap;
std::string localError;
std::string* sink = error != nullptr ? error : &localError;
if (!ParseImportMap(v8::Isolate::GetCurrent(), json, &parsedMap, sink)) {
return false;
}
return InstallParsedImportMap(std::move(parsedMap), sink);
}
void SetVolatilePatterns(const std::vector<std::string>& patterns) {
LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate();
if (vocabulary == nullptr) return;
vocabulary->volatilePatterns = patterns;
TNS_DEBUG(Esm, "[import-map] volatile patterns: %lu",
(unsigned long)vocabulary->volatilePatterns.size());
}
LoaderVocabulary CaptureLoaderVocabulary(v8::Isolate* isolate) {
auto* state = ModuleLoaderStateFor(isolate);
return state != nullptr ? state->vocabulary : LoaderVocabulary();
}
void InstallLoaderVocabulary(v8::Isolate* isolate, LoaderVocabulary vocabulary) {
auto* state = ModuleLoaderStateFor(isolate);
if (state == nullptr) return;
state->vocabulary = std::move(vocabulary);
TNS_DEBUG(Esm,
"[import-map] inherited %lu entries, %lu scopes, %lu volatile patterns",
(unsigned long)state->vocabulary.importMap.imports.size(),
(unsigned long)state->vocabulary.importMap.scopes.size(),
(unsigned long)state->vocabulary.volatilePatterns.size());
}
const CanonicalizationConfig* CanonicalizationConfigForCurrentIsolate() {
const LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate();
if (vocabulary == nullptr || !vocabulary->canonicalizationConfigured) {
return nullptr;
}
return &vocabulary->canonicalization;
}
void SetCanonicalizationConfig(CanonicalizationConfig config) {
LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate();
if (vocabulary == nullptr) return;
vocabulary->canonicalization = std::move(config);
vocabulary->canonicalizationConfigured = true;
TNS_DEBUG(Esm, "[ns:module configureLoader] canonicalization set (strip=%lu "
"devPrefixes=%lu preserve=%lu)",