-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathVM.cpp
More file actions
3578 lines (3050 loc) · 106 KB
/
VM.cpp
File metadata and controls
3578 lines (3050 loc) · 106 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 "VM.h"
#include <climits>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <memory>
#include <regex>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "js_native_api.h"
#include "native_api_util.h"
#if defined(TARGET_ENGINE_V8)
#include "v8-api.h"
#elif defined(TARGET_ENGINE_QUICKJS)
#include "quickjs.h"
#include "quicks-runtime.h"
#endif
namespace nativescript {
namespace {
constexpr char kContextSymbolName[] = "nativescript.vm.context";
constexpr char kDefaultFilename[] = "vm.js";
constexpr char kDefaultModuleIdentifier[] = "vm:module";
bool IsNullOrUndefined(napi_env env, napi_value value) {
if (value == nullptr) {
return true;
}
napi_valuetype type;
if (napi_typeof(env, value, &type) != napi_ok) {
return false;
}
return type == napi_null || type == napi_undefined;
}
bool IsObjectLike(napi_env env, napi_value value) {
if (value == nullptr) {
return false;
}
napi_valuetype type;
if (napi_typeof(env, value, &type) != napi_ok) {
return false;
}
return type == napi_object || type == napi_function;
}
bool CoerceToString(napi_env env, napi_value value, std::string& out) {
napi_value coerced;
if (napi_coerce_to_string(env, value, &coerced) != napi_ok) {
return false;
}
size_t length = 0;
if (napi_get_value_string_utf8(env, coerced, nullptr, 0, &length) !=
napi_ok) {
return false;
}
std::vector<char> buffer(length + 1);
if (napi_get_value_string_utf8(env, coerced, buffer.data(), buffer.size(),
nullptr) != napi_ok) {
return false;
}
out.assign(buffer.data(), length);
return true;
}
bool ReadOptionalStringProperty(napi_env env, napi_value object,
const char* property, std::string& out) {
if (IsNullOrUndefined(env, object)) {
return false;
}
bool hasProperty = false;
if (napi_has_named_property(env, object, property, &hasProperty) != napi_ok ||
!hasProperty) {
return false;
}
napi_value value;
if (napi_get_named_property(env, object, property, &value) != napi_ok) {
return false;
}
return CoerceToString(env, value, out);
}
bool ReadOptionalProperty(napi_env env, napi_value object, const char* property,
napi_value* out) {
if (IsNullOrUndefined(env, object)) {
return false;
}
bool hasProperty = false;
if (napi_has_named_property(env, object, property, &hasProperty) != napi_ok ||
!hasProperty) {
return false;
}
return napi_get_named_property(env, object, property, out) == napi_ok;
}
std::string ReadIdentifierOption(
napi_env env, napi_value options,
const std::string& fallback = kDefaultModuleIdentifier) {
std::string identifier;
if (ReadOptionalStringProperty(env, options, "identifier", identifier) &&
!identifier.empty()) {
return identifier;
}
if (ReadOptionalStringProperty(env, options, "filename", identifier) &&
!identifier.empty()) {
return identifier;
}
if (!identifier.empty()) {
return identifier;
}
return fallback;
}
napi_value CreateUint8ArrayCopy(napi_env env, const uint8_t* data,
size_t length) {
void* bufferData = nullptr;
napi_value arrayBuffer;
if (napi_create_arraybuffer(env, length, &bufferData, &arrayBuffer) !=
napi_ok) {
return nullptr;
}
if (length > 0 && data != nullptr) {
memcpy(bufferData, data, length);
}
napi_value typedArray;
if (napi_create_typedarray(env, napi_uint8_array, length, arrayBuffer, 0,
&typedArray) != napi_ok) {
return nullptr;
}
return typedArray;
}
napi_value CreateStringArray(napi_env env,
const std::vector<std::string>& values) {
napi_value array;
if (napi_create_array_with_length(env, values.size(), &array) != napi_ok) {
return nullptr;
}
for (size_t index = 0; index < values.size(); ++index) {
napi_value entry;
if (napi_create_string_utf8(env, values[index].c_str(),
values[index].size(), &entry) != napi_ok ||
napi_set_element(env, array, index, entry) != napi_ok) {
return nullptr;
}
}
return array;
}
bool GetStringArray(napi_env env, napi_value value,
std::vector<std::string>& out) {
bool isArray = false;
if (napi_is_array(env, value, &isArray) != napi_ok || !isArray) {
return false;
}
uint32_t length = 0;
if (napi_get_array_length(env, value, &length) != napi_ok) {
return false;
}
out.clear();
out.reserve(length);
for (uint32_t index = 0; index < length; ++index) {
napi_value element;
std::string text;
if (napi_get_element(env, value, index, &element) != napi_ok ||
!CoerceToString(env, element, text)) {
return false;
}
out.push_back(text);
}
return true;
}
bool CreatePromiseSettledWithUndefined(napi_env env, bool rejected,
napi_value reasonOrValue,
napi_value* result) {
napi_deferred deferred;
if (napi_create_promise(env, &deferred, result) != napi_ok) {
return false;
}
napi_value undefined;
napi_get_undefined(env, &undefined);
if (rejected) {
return napi_reject_deferred(
env, deferred,
reasonOrValue != nullptr ? reasonOrValue : undefined) == napi_ok;
}
return napi_resolve_deferred(
env, deferred,
reasonOrValue != nullptr ? reasonOrValue : undefined) == napi_ok;
}
std::vector<std::string> ExtractModuleDependencySpecifiers(
const std::string& source) {
static const std::regex kImportFromPattern(
R"((?:^|[\r\n])\s*import\s+[^;]*?\s+from\s+['"]([^'"]+)['"])",
std::regex::ECMAScript);
static const std::regex kImportOnlyPattern(
R"((?:^|[\r\n])\s*import\s+['"]([^'"]+)['"])", std::regex::ECMAScript);
std::vector<std::string> specifiers;
std::unordered_set<std::string> seen;
for (std::sregex_iterator
it(source.begin(), source.end(), kImportFromPattern),
end;
it != end; ++it) {
const std::string specifier = (*it)[1].str();
if (seen.insert(specifier).second) {
specifiers.push_back(specifier);
}
}
for (std::sregex_iterator
it(source.begin(), source.end(), kImportOnlyPattern),
end;
it != end; ++it) {
const std::string specifier = (*it)[1].str();
if (seen.insert(specifier).second) {
specifiers.push_back(specifier);
}
}
return specifiers;
}
std::string ReadFilenameOption(napi_env env, napi_value options,
const std::string& fallback = kDefaultFilename) {
if (IsNullOrUndefined(env, options)) {
return fallback;
}
napi_valuetype type;
if (napi_typeof(env, options, &type) != napi_ok) {
return fallback;
}
if (type == napi_string) {
std::string filename;
if (CoerceToString(env, options, filename) && !filename.empty()) {
return filename;
}
return fallback;
}
if (type != napi_object) {
return fallback;
}
bool hasFilename = false;
if (napi_has_named_property(env, options, "filename", &hasFilename) !=
napi_ok ||
!hasFilename) {
return fallback;
}
napi_value filenameValue;
if (napi_get_named_property(env, options, "filename", &filenameValue) !=
napi_ok) {
return fallback;
}
std::string filename;
if (CoerceToString(env, filenameValue, filename) && !filename.empty()) {
return filename;
}
return fallback;
}
napi_value GetContextSymbol(napi_env env) {
napi_value global;
napi_value symbolCtor;
napi_value symbolFor;
napi_value description;
napi_value symbol;
napi_get_global(env, &global);
napi_get_named_property(env, global, "Symbol", &symbolCtor);
napi_get_named_property(env, symbolCtor, "for", &symbolFor);
napi_create_string_utf8(env, kContextSymbolName, NAPI_AUTO_LENGTH,
&description);
napi_call_function(env, symbolCtor, symbolFor, 1, &description, &symbol);
return symbol;
}
struct ContextState {
#if defined(TARGET_ENGINE_V8)
v8::Global<v8::Context> context;
#elif defined(TARGET_ENGINE_QUICKJS)
JSRuntime* runtime = nullptr;
JSContext* context = nullptr;
#endif
std::unordered_set<std::string> baselineKeys;
~ContextState() {
#if defined(TARGET_ENGINE_V8)
context.Reset();
#elif defined(TARGET_ENGINE_QUICKJS)
if (context != nullptr) {
JS_FreeContext(context);
context = nullptr;
}
#endif
}
};
struct ScriptState {
std::string source;
std::string filename;
};
enum class ModuleKind {
kSourceText,
kSynthetic,
};
struct ModuleState {
napi_env env = nullptr;
ModuleKind kind = ModuleKind::kSourceText;
std::string identifier;
std::vector<std::string> dependencySpecifiers;
std::vector<std::string> exportNames;
std::vector<ModuleState*> linkedModules;
napi_ref contextRef = nullptr;
ContextState* contextState = nullptr;
napi_ref errorRef = nullptr;
#if defined(TARGET_ENGINE_V8)
v8::Global<v8::Module> module;
#elif defined(TARGET_ENGINE_QUICKJS)
JSRuntime* runtime = nullptr;
JSContext* context = nullptr;
JSValue moduleValue = JS_UNDEFINED;
std::unordered_map<std::string, JSValue> syntheticExports;
bool linked = false;
bool evaluating = false;
bool evaluated = false;
bool errored = false;
std::string errorMessage;
#endif
};
#if defined(TARGET_ENGINE_V8)
std::unordered_map<int, ModuleState*>& GetV8ModuleRegistry();
#elif defined(TARGET_ENGINE_QUICKJS)
struct QuickJSModuleRegistry {
bool installed = false;
std::unordered_map<std::string, ModuleState*> modulesById;
std::unordered_map<JSModuleDef*, ModuleState*> modulesByDef;
std::unordered_map<std::string, std::string> resolutions;
};
std::unordered_map<JSRuntime*, QuickJSModuleRegistry>&
GetQuickJSModuleRegistries();
std::string MakeQuickJSResolutionKey(const std::string& base,
const std::string& specifier);
QuickJSModuleRegistry& EnsureQuickJSModuleRegistry(JSRuntime* runtime);
std::string GetQuickJSModuleStatusString(ModuleState* state);
bool EnsureQuickJSImportMeta(ModuleState* state);
bool EnsureQuickJSLinked(napi_env env, ModuleState* state);
bool CacheQuickJSError(napi_env env, ModuleState* state, JSValue exception);
bool CreateQuickJSSourceTextModule(napi_env env, const std::string& sourceText,
napi_value options, napi_value* result);
bool CreateQuickJSSyntheticModule(napi_env env,
const std::vector<std::string>& exportNames,
napi_value options, napi_value* result);
void CleanupQuickJSModuleState(ModuleState* state);
bool ApplyQuickJSSyntheticExports(ModuleState* state);
#endif
void FinalizeContextState(napi_env env, void* data, void* /*hint*/) {
delete static_cast<ContextState*>(data);
}
void FinalizeScriptState(napi_env env, void* data, void* /*hint*/) {
delete static_cast<ScriptState*>(data);
}
void FinalizeModuleState(napi_env env, void* data, void* /*hint*/) {
ModuleState* state = static_cast<ModuleState*>(data);
if (state == nullptr) {
return;
}
if (state->contextRef != nullptr) {
napi_delete_reference(env, state->contextRef);
state->contextRef = nullptr;
}
if (state->errorRef != nullptr) {
napi_delete_reference(env, state->errorRef);
state->errorRef = nullptr;
}
#if defined(TARGET_ENGINE_V8)
auto& registry = GetV8ModuleRegistry();
for (auto it = registry.begin(); it != registry.end();) {
if (it->second == state) {
it = registry.erase(it);
} else {
++it;
}
}
state->module.Reset();
#elif defined(TARGET_ENGINE_QUICKJS)
CleanupQuickJSModuleState(state);
#endif
delete state;
}
bool GetContextState(napi_env env, napi_value sandbox, ContextState** out) {
*out = nullptr;
if (!IsObjectLike(env, sandbox)) {
return false;
}
napi_value symbol = GetContextSymbol(env);
bool hasState = false;
if (napi_has_property(env, sandbox, symbol, &hasState) != napi_ok ||
!hasState) {
return false;
}
napi_value stateValue;
if (napi_get_property(env, sandbox, symbol, &stateValue) != napi_ok) {
return false;
}
void* rawState = nullptr;
if (napi_get_value_external(env, stateValue, &rawState) != napi_ok ||
rawState == nullptr) {
return false;
}
*out = static_cast<ContextState*>(rawState);
return true;
}
bool RequireContextState(napi_env env, napi_value sandbox, ContextState** out) {
if (GetContextState(env, sandbox, out)) {
return true;
}
napi_throw_type_error(env, nullptr,
"The \"contextifiedObject\" argument must be a vm "
"context created by vm.createContext()");
return false;
}
bool ReadModuleContextOption(napi_env env, napi_value options,
ContextState** outState,
napi_value* outContextObject) {
*outState = nullptr;
if (outContextObject != nullptr) {
*outContextObject = nullptr;
}
napi_value contextValue;
if (!ReadOptionalProperty(env, options, "context", &contextValue) ||
IsNullOrUndefined(env, contextValue)) {
return true;
}
if (!RequireContextState(env, contextValue, outState)) {
return false;
}
if (outContextObject != nullptr) {
*outContextObject = contextValue;
}
return true;
}
bool CreateModuleHandle(napi_env env, ModuleState* state, napi_value* result) {
return napi_create_external(env, state, FinalizeModuleState, nullptr,
result) == napi_ok;
}
bool GetModuleState(napi_env env, napi_value value, ModuleState** out) {
*out = nullptr;
void* raw = nullptr;
if (napi_get_value_external(env, value, &raw) != napi_ok || raw == nullptr) {
napi_throw_type_error(env, nullptr, "Invalid vm.Module handle");
return false;
}
*out = static_cast<ModuleState*>(raw);
return true;
}
bool SetModuleError(napi_env env, ModuleState* state, napi_value error) {
if (state->errorRef != nullptr) {
napi_delete_reference(env, state->errorRef);
state->errorRef = nullptr;
}
if (IsNullOrUndefined(env, error)) {
return true;
}
return napi_create_reference(env, error, 1, &state->errorRef) == napi_ok;
}
napi_value GetStoredModuleError(napi_env env, ModuleState* state) {
if (state->errorRef == nullptr) {
napi_value undefined;
napi_get_undefined(env, &undefined);
return undefined;
}
napi_value error;
if (napi_get_reference_value(env, state->errorRef, &error) != napi_ok) {
return nullptr;
}
return error;
}
napi_value GetStoredModuleContext(napi_env env, ModuleState* state) {
if (state->contextRef == nullptr) {
napi_value undefined;
napi_get_undefined(env, &undefined);
return undefined;
}
napi_value context;
if (napi_get_reference_value(env, state->contextRef, &context) != napi_ok) {
return nullptr;
}
return context;
}
#if defined(TARGET_ENGINE_V8)
std::vector<std::string> CollectV8OwnStringKeys(v8::Isolate* isolate,
v8::Local<v8::Context> context,
v8::Local<v8::Object> object) {
std::vector<std::string> result;
v8::Local<v8::Array> names;
if (!object->GetOwnPropertyNames(context).ToLocal(&names)) {
return result;
}
const uint32_t length = names->Length();
result.reserve(length);
for (uint32_t index = 0; index < length; ++index) {
v8::Local<v8::Value> key;
if (!names->Get(context, index).ToLocal(&key) || !key->IsString()) {
continue;
}
v8::String::Utf8Value utf8(isolate, key);
if (*utf8 == nullptr) {
continue;
}
result.emplace_back(*utf8, utf8.length());
}
return result;
}
std::unordered_set<std::string> ToKeySet(const std::vector<std::string>& keys) {
return std::unordered_set<std::string>(keys.begin(), keys.end());
}
#if defined(TARGET_ENGINE_QUICKJS)
struct QuickJSModuleRegistry {
bool installed = false;
std::unordered_map<std::string, ModuleState*> modulesById;
std::unordered_map<std::string, std::string> resolutions;
};
std::unordered_map<JSRuntime*, QuickJSModuleRegistry>&
GetQuickJSModuleRegistries() {
static std::unordered_map<JSRuntime*, QuickJSModuleRegistry> registries;
return registries;
}
std::string MakeQuickJSResolutionKey(const std::string& base,
const std::string& specifier) {
return base + "\n" + specifier;
}
char* NormalizeQuickJSVmModule(JSContext* ctx, const char* base_name,
const char* name, void* opaque) {
QuickJSModuleRegistry* registry = static_cast<QuickJSModuleRegistry*>(opaque);
if (registry == nullptr) {
return js_strdup(ctx, name);
}
const std::string base = base_name != nullptr ? base_name : "";
const auto it =
registry->resolutions.find(MakeQuickJSResolutionKey(base, name));
if (it != registry->resolutions.end()) {
return js_strdup(ctx, it->second.c_str());
}
return js_strdup(ctx, name);
}
JSModuleDef* LoadQuickJSVmModule(JSContext* /*ctx*/, const char* module_name,
void* opaque) {
QuickJSModuleRegistry* registry = static_cast<QuickJSModuleRegistry*>(opaque);
if (registry == nullptr) {
return nullptr;
}
const auto it = registry->modulesById.find(module_name);
if (it == registry->modulesById.end() || it->second == nullptr) {
return nullptr;
}
return static_cast<JSModuleDef*>(JS_VALUE_GET_PTR(it->second->moduleValue));
}
QuickJSModuleRegistry& EnsureQuickJSModuleRegistry(JSRuntime* runtime) {
auto& registries = GetQuickJSModuleRegistries();
QuickJSModuleRegistry& registry = registries[runtime];
if (!registry.installed) {
JS_SetModuleLoaderFunc(runtime, &NormalizeQuickJSVmModule,
&LoadQuickJSVmModule, ®istry);
registry.installed = true;
}
return registry;
}
std::string GetQuickJSModuleStatusString(ModuleState* state) {
if (state->errored) {
return "errored";
}
if (state->evaluating) {
return "evaluating";
}
if (state->evaluated) {
return "evaluated";
}
if (state->linked) {
return "linked";
}
return "unlinked";
}
bool EnsureQuickJSImportMeta(ModuleState* state) {
JSModuleDef* module =
static_cast<JSModuleDef*>(JS_VALUE_GET_PTR(state->moduleValue));
JSValue meta = JS_GetImportMeta(state->context, module);
if (JS_IsException(meta)) {
return false;
}
if (JS_DefinePropertyValueStr(
state->context, meta, "url",
JS_NewString(state->context, state->identifier.c_str()),
JS_PROP_C_W_E) < 0 ||
JS_DefinePropertyValueStr(state->context, meta, "main", JS_FALSE,
JS_PROP_C_W_E) < 0) {
JS_FreeValue(state->context, meta);
return false;
}
JS_FreeValue(state->context, meta);
return true;
}
bool EnsureQuickJSLinked(napi_env env, ModuleState* state) {
if (state->linked) {
return true;
}
if (JS_ResolveModule(state->context, state->moduleValue) < 0) {
state->errored = true;
state->errorMessage = GetQuickJSExceptionMessage(
state->context, JS_GetException(state->context));
napi_throw_error(env, nullptr, state->errorMessage.c_str());
return false;
}
state->linked = true;
return true;
}
bool CacheQuickJSError(napi_env env, ModuleState* state, JSValue exception) {
JSContext* mainContext = qjs_get_context(env);
JSValue cloned = CloneQuickJSValue(state->context, mainContext, exception);
JS_FreeValue(state->context, exception);
if (JS_IsException(cloned)) {
state->errorMessage =
GetQuickJSExceptionMessage(mainContext, JS_GetException(mainContext));
napi_throw_error(env, nullptr, state->errorMessage.c_str());
return false;
}
napi_value error;
if (qjs_create_scoped_value(env, cloned, &error) != napi_ok ||
!SetModuleError(env, state, error)) {
return false;
}
return true;
}
bool CreateQuickJSSourceTextModule(napi_env env, const std::string& sourceText,
napi_value options, napi_value* result) {
ContextState* contextState = nullptr;
napi_value contextObject = nullptr;
if (!ReadModuleContextOption(env, options, &contextState, &contextObject)) {
return false;
}
JSContext* context =
contextState != nullptr ? contextState->context : qjs_get_context(env);
JSRuntime* runtime = JS_GetRuntime(context);
QuickJSModuleRegistry& registry = EnsureQuickJSModuleRegistry(runtime);
const std::string identifier = ReadIdentifierOption(env, options);
JSValue moduleValue = JS_Eval(
context, sourceText.c_str(), sourceText.size(), identifier.c_str(),
JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY |
JS_EVAL_FLAG_COMPILE_ONLY_NO_RESOLVE);
if (JS_IsException(moduleValue)) {
return ThrowLatestQuickJSException(env, context);
}
std::unique_ptr<ModuleState> state(new ModuleState());
state->env = env;
state->kind = ModuleKind::kSourceText;
state->identifier = identifier;
state->contextState = contextState;
state->runtime = runtime;
state->context = context;
state->moduleValue = moduleValue;
state->dependencySpecifiers = ExtractModuleDependencySpecifiers(sourceText);
if (contextObject != nullptr &&
napi_create_reference(env, contextObject, 1, &state->contextRef) !=
napi_ok) {
return false;
}
registry.modulesById[identifier] = state.get();
registry
.modulesByDef[static_cast<JSModuleDef*>(JS_VALUE_GET_PTR(moduleValue))] =
state.get();
if (!CreateModuleHandle(env, state.get(), result)) {
return false;
}
state.release();
return true;
}
bool ApplyQuickJSSyntheticExports(ModuleState* state) {
JSModuleDef* moduleDef =
static_cast<JSModuleDef*>(JS_VALUE_GET_PTR(state->moduleValue));
for (const auto& exportName : state->exportNames) {
JSValue exportValue = JS_UNDEFINED;
auto valueIt = state->syntheticExports.find(exportName);
if (valueIt != state->syntheticExports.end()) {
exportValue = JS_DupValue(state->context, valueIt->second);
}
if (JS_SetModuleExport(state->context, moduleDef, exportName.c_str(),
exportValue) < 0) {
return false;
}
}
return true;
}
int InitializeQuickJSSyntheticModule(JSContext* ctx, JSModuleDef* moduleDef) {
auto& registries = GetQuickJSModuleRegistries();
auto registryIt = registries.find(JS_GetRuntime(ctx));
if (registryIt == registries.end()) {
return -1;
}
auto stateIt = registryIt->second.modulesByDef.find(moduleDef);
if (stateIt == registryIt->second.modulesByDef.end() ||
stateIt->second == nullptr) {
return -1;
}
return ApplyQuickJSSyntheticExports(stateIt->second) ? 0 : -1;
}
bool CreateQuickJSSyntheticModule(napi_env env,
const std::vector<std::string>& exportNames,
napi_value options, napi_value* result) {
ContextState* contextState = nullptr;
napi_value contextObject = nullptr;
if (!ReadModuleContextOption(env, options, &contextState, &contextObject)) {
return false;
}
JSContext* context =
contextState != nullptr ? contextState->context : qjs_get_context(env);
JSRuntime* runtime = JS_GetRuntime(context);
QuickJSModuleRegistry& registry = EnsureQuickJSModuleRegistry(runtime);
const std::string identifier = ReadIdentifierOption(env, options);
JSModuleDef* moduleDef = JS_NewCModule(context, identifier.c_str(),
&InitializeQuickJSSyntheticModule);
if (moduleDef == nullptr) {
return ThrowLatestQuickJSException(env, context);
}
for (const auto& exportName : exportNames) {
if (JS_AddModuleExport(context, moduleDef, exportName.c_str()) < 0) {
return ThrowLatestQuickJSException(env, context);
}
}
std::unique_ptr<ModuleState> state(new ModuleState());
state->env = env;
state->kind = ModuleKind::kSynthetic;
state->identifier = identifier;
state->contextState = contextState;
state->runtime = runtime;
state->context = context;
state->exportNames = exportNames;
state->moduleValue = JS_DupValue(context, JS_MKPTR(JS_TAG_MODULE, moduleDef));
if (contextObject != nullptr &&
napi_create_reference(env, contextObject, 1, &state->contextRef) !=
napi_ok) {
return false;
}
registry.modulesById[identifier] = state.get();
registry.modulesByDef[moduleDef] = state.get();
if (!EnsureQuickJSLinked(env, state.get())) {
return false;
}
if (!CreateModuleHandle(env, state.get(), result)) {
return false;
}
state.release();
return true;
}
#endif
std::unordered_map<int, ModuleState*>& GetV8ModuleRegistry() {
static std::unordered_map<int, ModuleState*> registry;
return registry;
}
v8::Local<v8::Context> GetV8ModuleContext(napi_env env, ModuleState* state) {
return state->contextState != nullptr
? state->contextState->context.Get(env->isolate)
: env->context();
}
std::string GetV8ModuleStatusString(v8::Module::Status status) {
switch (status) {
case v8::Module::kUninstantiated:
return "unlinked";
case v8::Module::kInstantiating:
return "linking";
case v8::Module::kInstantiated:
return "linked";
case v8::Module::kEvaluating:
return "evaluating";
case v8::Module::kEvaluated:
return "evaluated";
case v8::Module::kErrored:
return "errored";
}
return "unlinked";
}
bool SetV8ModuleRegistryEntry(v8::Local<v8::Module> module,
ModuleState* state) {
GetV8ModuleRegistry()[module->GetIdentityHash()] = state;
return true;
}
v8::MaybeLocal<v8::Module> ResolveV8VmModuleByIndex(
v8::Local<v8::Context> context, size_t index,
v8::Local<v8::Module> referrer) {
auto& registry = GetV8ModuleRegistry();
auto it = registry.find(referrer->GetIdentityHash());
if (it == registry.end() || it->second == nullptr) {
return v8::MaybeLocal<v8::Module>();
}
ModuleState* referrerState = it->second;
if (index >= referrerState->linkedModules.size() ||
referrerState->linkedModules[index] == nullptr) {
return v8::MaybeLocal<v8::Module>();
}
v8::Isolate* isolate = v8::Isolate::GetCurrent();
return referrerState->linkedModules[index]->module.Get(isolate);
}
v8::MaybeLocal<v8::Value> EvaluateV8SyntheticModule(
v8::Local<v8::Context> context, v8::Local<v8::Module> /*module*/) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Promise::Resolver> resolver =
v8::Promise::Resolver::New(context).ToLocalChecked();
resolver->Resolve(context, v8::Undefined(isolate)).ToChecked();
return resolver->GetPromise();
}
bool ExtractV8DependencySpecifiers(v8::Isolate* isolate,
v8::Local<v8::Module> module,
std::vector<std::string>& out) {
out.clear();
v8::Local<v8::FixedArray> requests = module->GetModuleRequests();
const int length = requests->Length();
out.reserve(length);
for (int index = 0; index < length; ++index) {
v8::Local<v8::Data> entry =
requests->Get(isolate->GetCurrentContext(), index);
v8::Local<v8::String> specifier =
v8::ModuleRequest::Cast(*entry)->GetSpecifier();
v8::String::Utf8Value text(isolate, specifier);
if (*text == nullptr) {
return false;
}
out.emplace_back(*text, text.length());
}
return true;
}
std::vector<std::string> CollectV8ModuleExportNames(napi_env env,
ModuleState* state) {
v8::Isolate* isolate = env->isolate;
v8::EscapableHandleScope scope(isolate);
v8::Local<v8::Context> context = GetV8ModuleContext(env, state);
v8::Context::Scope contextScope(context);
v8::Local<v8::Module> module = state->module.Get(isolate);
if (module.IsEmpty() || module->GetStatus() < v8::Module::kInstantiated) {
return {};
}
v8::Local<v8::Object> ns = module->GetModuleNamespace().As<v8::Object>();
return CollectV8OwnStringKeys(isolate, context, ns);
}
bool ThrowV8ModuleException(napi_env env, ModuleState* state) {
v8::Isolate* isolate = env->isolate;
v8::HandleScope scope(isolate);
v8::Local<v8::Module> module = state->module.Get(isolate);
napi_throw(env, v8impl::JsValueFromV8LocalValue(module->GetException()));
return false;
}
bool CacheV8ModuleError(napi_env env, ModuleState* state) {
v8::Isolate* isolate = env->isolate;
v8::HandleScope scope(isolate);
v8::Local<v8::Module> module = state->module.Get(isolate);
return SetModuleError(