forked from WebKit/WebKit
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathJSModuleLoader.cpp
More file actions
1309 lines (1100 loc) · 60.6 KB
/
Copy pathJSModuleLoader.cpp
File metadata and controls
1309 lines (1100 loc) · 60.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
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
/*
* Copyright (C) 2015-2021, 2026 Apple Inc. All rights reserved.
* Copyright (C) 2016 Yusuke Suzuki <utatane.tea@gmail.com>.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "JSModuleLoader.h"
#include "ProgramExecutable.h"
#include "BuiltinNames.h"
#include "Completion.h"
#include "GlobalObjectMethodTable.h"
#include "JSCInlines.h"
#include "JSMicrotask.h"
#include "JSModuleNamespaceObject.h"
#include "JSModuleRecord.h"
#include "JSPromise.h"
#include "JSSourceCode.h"
#include "JSWebAssembly.h"
#include "Microtask.h"
#include "ModuleAnalyzer.h"
#include "ModuleLoadingContext.h"
#include "ModuleRegistryEntry.h"
#include "Nodes.h"
#include "ObjectConstructor.h"
#include "Parser.h"
#include "ParserError.h"
#include "Symbol.h"
#include "SyntheticModuleRecord.h"
#include "TopExceptionScope.h"
#include "VMTrapsInlines.h"
#include <wtf/text/MakeString.h>
namespace JSC {
namespace JSModuleLoaderInternal {
static constexpr unsigned maximumResolutionFailures = 128;
}
static Identifier jsValueToSpecifier(JSGlobalObject* globalObject, JSValue value)
{
if (value.isSymbol())
return Identifier::fromUid(uncheckedDowncast<Symbol>(value)->privateName());
ASSERT(value.isString());
return asString(value)->toIdentifier(globalObject);
}
bool JSModuleLoader::isFetchError(JSGlobalObject* globalObject, ErrorInstance* error)
{
VM& vm = globalObject->vm();
return error->hasOwnProperty(globalObject, vm.propertyNames->builtinNames().moduleFetchFailureKindPrivateName());
}
// Web Platform Tests requires that import() promises reject with difference error object instances for fetch errors.
// It also requires that errors be cached. To satisfy both requirements, it's necessary to duplicate errors.
ErrorInstance* JSModuleLoader::duplicateTypeError(JSGlobalObject* globalObject, ErrorInstance* error)
{
ASSERT(error);
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
auto* copy = uncheckedDowncast<ErrorInstance>(createTypeErrorCopy(globalObject, error));
RETURN_IF_EXCEPTION(scope, nullptr);
auto copyField = [&](const Identifier& name) -> bool {
if (JSValue value = error->getDirect(vm, name)) {
copy->putDirect(vm, name, value);
RETURN_IF_EXCEPTION(scope, false);
}
return true;
};
const BuiltinNames& names = vm.propertyNames->builtinNames();
if (!copyField(names.moduleFetchFailureKindPrivateName()))
return nullptr;
if (!copyField(names.moduleFailureModuleRecordPrivateName()))
return nullptr;
if (!copyField(names.moduleFailureModuleKeyPrivateName()))
return nullptr;
if (!copyField(names.moduleFailureModuleTypePrivateName()))
return nullptr;
if (!copyField(names.moduleFailureKindPrivateName()))
return nullptr;
return copy;
}
ErrorInstance* JSModuleLoader::duplicateError(JSGlobalObject* globalObject, ErrorInstance* error)
{
ASSERT(error);
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
if (error->errorType() == ErrorType::TypeError)
RELEASE_AND_RETURN(scope, JSModuleLoader::duplicateTypeError(globalObject, error));
String message = error->sanitizedMessageString(globalObject);
RETURN_IF_EXCEPTION(scope, nullptr);
ErrorInstance* out = ErrorInstance::create(globalObject, WTF::move(message), error->errorType(), { }, { }, { });
RETURN_IF_EXCEPTION(scope, nullptr);
auto copyField = [&](const Identifier& name) -> bool {
if (JSValue value = error->getDirect(vm, name)) {
out->putDirect(vm, name, value);
RETURN_IF_EXCEPTION(scope, false);
}
return true;
};
const BuiltinNames& names = vm.propertyNames->builtinNames();
if (!copyField(names.moduleFetchFailureKindPrivateName()))
return nullptr;
if (!copyField(names.moduleFailureModuleRecordPrivateName()))
return nullptr;
if (!copyField(names.moduleFailureModuleKeyPrivateName()))
return nullptr;
if (!copyField(names.moduleFailureModuleTypePrivateName()))
return nullptr;
if (!copyField(names.moduleFailureKindPrivateName()))
return nullptr;
return out;
}
ErrorInstance* JSModuleLoader::maybeDuplicateFetchError(JSGlobalObject* globalObject, ErrorInstance* error)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
if (error->hasOwnProperty(globalObject, vm.propertyNames->builtinNames().moduleFetchFailureKindPrivateName())) {
error = JSModuleLoader::duplicateError(globalObject, error);
RETURN_IF_EXCEPTION(scope, nullptr);
}
RELEASE_AND_RETURN(scope, error);
}
JSModuleLoader::ModuleFailure::ModuleFailure(AbstractModuleRecord* source, ScriptFetchParameters::Type type, Kind kind)
: m_source(source)
, m_key(source->moduleKey())
, m_type(type)
, m_kind(kind)
{
}
JSModuleLoader::ModuleFailure::ModuleFailure(Identifier key, ScriptFetchParameters::Type type, Kind kind)
: m_source(nullptr)
, m_key(WTF::move(key))
, m_type(type)
, m_kind(kind)
{
}
bool JSModuleLoader::ModuleFailure::isEvaluationError(const Identifier& expectedSpecifier, ScriptFetchParameters::Type expectedType) const
{
return m_kind == ModuleFailure::Kind::Evaluation || (!m_key.isNull() && m_key != expectedSpecifier) || (m_type != ScriptFetchParameters::None && m_type != expectedType);
}
JSModuleLoader::ModuleFailure::operator bool() const
{
return m_source != nullptr || !m_key.isNull() || m_type != ScriptFetchParameters::Type::None || m_kind != ModuleFailure::Kind::Unknown;
}
JSModuleLoader::ModuleFailure JSModuleLoader::getErrorInfo(JSGlobalObject* globalObject, ErrorInstance* error)
{
VM& vm = globalObject->vm();
JSModuleLoader::ModuleFailure failure;
if (JSValue sourceValue = error->getDirect(vm, vm.propertyNames->builtinNames().moduleFailureModuleRecordPrivateName()))
failure.m_source = dynamicDowncast<AbstractModuleRecord>(sourceValue);
if (JSValue keyValue = error->getDirect(vm, vm.propertyNames->builtinNames().moduleFailureModuleKeyPrivateName()))
failure.m_key = jsValueToSpecifier(globalObject, keyValue);
if (JSValue typeValue = error->getDirect(vm, vm.propertyNames->builtinNames().moduleFailureModuleTypePrivateName()))
failure.m_type = static_cast<ScriptFetchParameters::Type>(typeValue.asInt32());
if (JSValue kindValue = error->getDirect(vm, vm.propertyNames->builtinNames().moduleFailureKindPrivateName()))
failure.m_kind = static_cast<JSModuleLoader::ModuleFailure::Kind>(kindValue.asInt32());
return failure;
}
void JSModuleLoader::attachErrorInfo(JSGlobalObject* globalObject, ErrorInstance* error, AbstractModuleRecord* source, const Identifier& key, ScriptFetchParameters::Type type, JSModuleLoader::ModuleFailure::Kind kind)
{
VM& vm = globalObject->vm();
if (source)
error->putDirect(vm, vm.propertyNames->builtinNames().moduleFailureModuleRecordPrivateName(), source);
if (!key.isNull())
error->putDirect(vm, vm.propertyNames->builtinNames().moduleFailureModuleKeyPrivateName(), identifierToJSValue(vm, key));
if (type != ScriptFetchParameters::Type::None)
error->putDirect(vm, vm.propertyNames->builtinNames().moduleFailureModuleTypePrivateName(), jsNumber(std::to_underlying(type)));
if (kind != JSModuleLoader::ModuleFailure::Kind::Unknown)
error->putDirect(vm, vm.propertyNames->builtinNames().moduleFailureKindPrivateName(), jsNumber(std::to_underlying(kind)));
}
bool JSModuleLoader::attachErrorInfo(JSGlobalObject* globalObject, Exception* exception, AbstractModuleRecord* source, const Identifier& key, ScriptFetchParameters::Type type, ModuleFailure::Kind kind)
{
if (auto* error = dynamicDowncast<ErrorInstance>(exception->value())) {
attachErrorInfo(globalObject, error, source, key, type, kind);
return true;
}
return false;
}
bool JSModuleLoader::attachErrorInfo(JSGlobalObject* globalObject, ThrowScope& scope, AbstractModuleRecord* source, const Identifier& key, ScriptFetchParameters::Type type, ModuleFailure::Kind kind)
{
if (Exception* exception = scope.exception())
return attachErrorInfo(globalObject, exception, source, key, type, kind);
return false;
}
const ClassInfo JSModuleLoader::s_info = { "ModuleLoader"_s, nullptr, nullptr, nullptr, CREATE_METHOD_TABLE(JSModuleLoader) };
JSModuleLoader::JSModuleLoader(VM& vm, Structure* structure)
: JSCell(vm, structure)
{
}
void JSModuleLoader::destroy(JSCell* cell)
{
SUPPRESS_MEMORY_UNSAFE_CAST auto* thisObject = static_cast<JSModuleLoader*>(cell);
thisObject->JSModuleLoader::~JSModuleLoader();
}
void JSModuleLoader::finishCreation(JSGlobalObject*, VM& vm)
{
Base::finishCreation(vm);
ASSERT(inherits(info()));
}
template<typename Visitor>
void JSModuleLoader::visitChildrenImpl(JSCell* cell, Visitor& visitor)
{
JSModuleLoader* thisObject = uncheckedDowncast<JSModuleLoader>(cell);
ASSERT_GC_OBJECT_INHERITS(thisObject, info());
Base::visitChildren(thisObject, visitor);
Locker locker { thisObject->cellLock() };
auto moduleMapValues = thisObject->m_moduleMap.values();
visitor.append(moduleMapValues.begin(), moduleMapValues.end());
auto resolutionFailuresValues = thisObject->m_resolutionFailures.values();
visitor.append(resolutionFailuresValues.begin(), resolutionFailuresValues.end());
for (auto& [key, loadedModule] : thisObject->m_loadedModules)
visitor.append(loadedModule.m_module);
}
DEFINE_VISIT_CHILDREN(JSModuleLoader);
// ------------------------------ Functions --------------------------------
static String printableModuleKey(JSGlobalObject* globalObject, JSValue key)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
if (key.isString() || key.isSymbol()) {
auto propertyName = key.toPropertyKey(globalObject);
scope.assertNoExceptionExceptTermination(); // This is OK since this function is just for debugging purpose.
return propertyName.impl();
}
return vm.propertyNames->emptyIdentifier.impl();
}
JSArray* JSModuleLoader::dependencyKeysIfEvaluated(JSGlobalObject* globalObject, const String& key)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
Identifier ident = Identifier::fromString(vm, key);
auto iter = m_moduleMap.find({ ident.impl(), ScriptFetchParameters::Type::JavaScript });
if (iter == m_moduleMap.end())
iter = m_moduleMap.find({ ident.impl(), ScriptFetchParameters::Type::WebAssembly });
if (iter == m_moduleMap.end())
RELEASE_AND_RETURN(scope, nullptr);
ModuleRegistryEntry* entry = iter->value.get();
AbstractModuleRecord* record = entry->record();
if (record == nullptr)
RELEASE_AND_RETURN(scope, nullptr);
if (auto status = entry->status(); status != ModuleRegistryEntry::Status::Fetched && status != ModuleRegistryEntry::Status::EvaluationFailed)
RELEASE_AND_RETURN(scope, nullptr);
if (auto* cyclic = dynamicDowncast<CyclicModuleRecord>(record); cyclic && cyclic->status() != CyclicModuleRecord::Status::Evaluated)
RELEASE_AND_RETURN(scope, nullptr);
const Vector<AbstractModuleRecord::ModuleRequest>& requests = record->requestedModules();
JSArray* array = constructEmptyArray(globalObject, nullptr, requests.size());
RETURN_IF_EXCEPTION(scope, nullptr);
for (unsigned index = 0; const AbstractModuleRecord::ModuleRequest& request : requests) {
Identifier resolved = resolve(globalObject, request.m_specifier, ident, nullptr, /* useImportMap */ true);
RETURN_IF_EXCEPTION(scope, nullptr);
array->putDirectIndex(globalObject, index++, identifierToJSValue(vm, resolved));
RETURN_IF_EXCEPTION(scope, nullptr);
}
RELEASE_AND_RETURN(scope, array);
}
void JSModuleLoader::provideFetch(JSGlobalObject* globalObject, const Identifier& key, ScriptFetchParameters::Type type, SourceCode&& sourceCode)
{
ModuleRegistryEntry* entry = ensureRegistered(globalObject, key, type);
if (entry->status() == ModuleRegistryEntry::Status::New)
entry->provideFetch(globalObject, WTF::move(sourceCode)); // can throw
}
void JSModuleLoader::provideFetch(JSGlobalObject* globalObject, const Identifier& key, ScriptFetchParameters::Type type, JSSourceCode* jsSourceCode)
{
ModuleRegistryEntry* entry = ensureRegistered(globalObject, key, type);
if (entry->status() == ModuleRegistryEntry::Status::New)
entry->provideFetch(globalObject, jsSourceCode); // can throw
}
JSPromise* JSModuleLoader::loadModule(JSGlobalObject* globalObject, const Identifier& specifier, RefPtr<ScriptFetchParameters> parameters, RefPtr<ScriptFetcher> scriptFetcher, OptionSet<ModuleLoadFlag> flags, int64_t referrerAsyncOrder)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSPromise* promise = nullptr;
ScriptFetchParameters::Type type = parameters ? parameters->type() : ScriptFetchParameters::Type::JavaScript;
#if USE(BUN_JSC_ADDITIONS)
// Preserve the caller's ScriptFetchParameters (HostDefined data) into the loading context
// before `parameters` is moved into fetch() below.
RefPtr<ScriptFetchParameters> contextParameters = parameters ? parameters : ScriptFetchParameters::create(type);
#endif
if (ModuleRegistryEntry* entry = getRegisteredMayBeNull(specifier, type)) {
JSValue error = entry->error(globalObject);
RETURN_IF_EXCEPTION(scope, nullptr);
if (error)
return JSPromise::rejectedPromise(globalObject, error);
if (entry->status() != ModuleRegistryEntry::Status::New)
promise = entry->ensureFetchPromise(globalObject);
}
if (!promise) {
promise = fetch(globalObject, identifierToJSValue(vm, specifier), WTF::move(parameters), scriptFetcher);
RETURN_IF_EXCEPTION(scope, nullptr);
}
#if USE(BUN_JSC_ADDITIONS)
AbstractModuleRecord::ModuleRequest request { specifier, WTF::move(contextParameters) };
#else
AbstractModuleRecord::ModuleRequest request { specifier, ScriptFetchParameters::create(type) };
#endif
auto* context = ModuleLoadingContext::create(vm, request, WTF::move(scriptFetcher), flags, referrerAsyncOrder);
JSPromise* intermediatePromise = JSPromise::create(vm, globalObject->promiseStructure());
intermediatePromise->markAsHandled();
promise->performPromiseThenWithInternalMicrotask(vm, InternalMicrotask::ModuleLoadTopSettled, intermediatePromise, context);
JSPromise* resultPromise = JSPromise::create(vm, globalObject->promiseStructure());
resultPromise->markAsHandled();
intermediatePromise->performPromiseThenWithInternalMicrotask(vm, InternalMicrotask::ModuleLoadTopRejected, resultPromise, context);
return resultPromise;
}
JSPromise* JSModuleLoader::linkAndEvaluateModule(JSGlobalObject* globalObject, const Identifier& moduleKey, RefPtr<ScriptFetchParameters> parameters, RefPtr<ScriptFetcher> scriptFetcher)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
ScriptFetchParameters::Type type = parameters ? parameters->type() : ScriptFetchParameters::Type::JavaScript;
ModuleRegistryEntry* entry = ensureRegistered(globalObject, moduleKey, type);
RETURN_IF_EXCEPTION(scope, nullptr);
AbstractModuleRecord* record = entry->record();
ASSERT(record);
JSValue error = entry->error(globalObject);
RETURN_IF_EXCEPTION(scope, nullptr);
if (error) {
scope.throwException(globalObject, error);
return nullptr;
}
record->link(globalObject, WTF::move(scriptFetcher));
if (Exception* exception = scope.exception()) {
attachErrorInfo(globalObject, scope, record, entry->key(), entry->moduleType(), ModuleFailure::Kind::Instantiation);
entry->setInstantiationError(globalObject, exception->value());
if (auto* cyclic = dynamicDowncast<CyclicModuleRecord>(record))
cyclic->setEvaluationError(vm, exception->value());
return nullptr;
}
JSPromise* promise = record->evaluate(globalObject);
RETURN_IF_EXCEPTION(scope, nullptr);
error = entry->error(globalObject);
RETURN_IF_EXCEPTION(scope, nullptr);
if (error) {
// At this point, the promise exists but won't be returned. However, it will be rejected later.
// To prevent an unhandled promise rejection error, we have to explicitly mark the promise as handled.
promise->markAsHandled();
scope.throwException(globalObject, error);
return nullptr;
}
return promise;
}
JSPromise* JSModuleLoader::requestImportModule(JSGlobalObject* globalObject, const Identifier& moduleName, const Identifier& referrer, RefPtr<ScriptFetchParameters> parameters, RefPtr<ScriptFetcher> scriptFetcher, bool deferred, int64_t referrerAsyncOrder)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
Identifier resolved = resolve(globalObject, moduleName, referrer, scriptFetcher, /* useImportMap */ true);
RETURN_IF_EXCEPTION(scope, nullptr);
OptionSet<ModuleLoadFlag> flags { ModuleLoadFlag::Evaluate, ModuleLoadFlag::Dynamic };
if (deferred)
flags.add(ModuleLoadFlag::Deferred);
JSPromise* promise = loadModule(globalObject, resolved, WTF::move(parameters), WTF::move(scriptFetcher), flags, referrerAsyncOrder);
RETURN_IF_EXCEPTION(scope, nullptr);
JSPromise* resultPromise = JSPromise::create(vm, globalObject->promiseStructure());
resultPromise->markAsHandled();
promise->performPromiseThenWithInternalMicrotask(vm, InternalMicrotask::ImportModuleNamespace, resultPromise, jsUndefined());
return resultPromise;
}
JSPromise* JSModuleLoader::importModule(JSGlobalObject* globalObject, JSString* moduleName, JSValue parameters, const SourceOrigin& referrer, bool deferred)
{
dataLogLnIf(Options::dumpModuleLoadingState(), "Loader [import] ", printableModuleKey(globalObject, moduleName));
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
auto attributes = retrieveImportAttributesFromDynamicImportOptions(globalObject, parameters, { vm.propertyNames->type.impl() });
RETURN_IF_EXCEPTION(scope, nullptr);
auto type = retrieveTypeImportAttribute(globalObject, attributes);
RETURN_IF_EXCEPTION(scope, nullptr);
RefPtr<ScriptFetchParameters> fetchParams;
if (type) {
#if USE(BUN_JSC_ADDITIONS)
if (type.value() == ScriptFetchParameters::Type::HostDefined)
fetchParams = ScriptFetchParameters::create(attributes.get(vm.propertyNames->type.impl()));
else
#endif
fetchParams = ScriptFetchParameters::create(type.value());
}
#if USE(BUN_JSC_ADDITIONS)
if (!attributes.isEmpty()) {
if (!fetchParams)
fetchParams = ScriptFetchParameters::create(ScriptFetchParameters::Type::None);
fetchParams->setAttributes(WTF::move(attributes));
}
#endif
if (globalObject->globalObjectMethodTable()->moduleLoaderImportModule)
RELEASE_AND_RETURN(scope, globalObject->globalObjectMethodTable()->moduleLoaderImportModule(globalObject, this, moduleName, WTF::move(fetchParams), referrer, deferred));
auto* promise = JSPromise::create(vm, globalObject->promiseStructure());
auto moduleNameString = moduleName->value(globalObject);
RETURN_IF_EXCEPTION(scope, promise->rejectWithCaughtException(vm, scope));
scope.release();
promise->reject(vm, createError(globalObject, makeString("Could not import the module '"_s, moduleNameString.data, "'."_s)));
return promise;
}
Identifier JSModuleLoader::resolve(JSGlobalObject* globalObject, JSValue name, JSValue referrer, RefPtr<ScriptFetcher> scriptFetcher, bool useImportMap)
{
dataLogLnIf(Options::dumpModuleLoadingState(), "Loader [resolve] ", printableModuleKey(globalObject, name));
if (globalObject->globalObjectMethodTable()->moduleLoaderResolve)
return globalObject->globalObjectMethodTable()->moduleLoaderResolve(globalObject, this, name, referrer, WTF::move(scriptFetcher), useImportMap);
return name.toPropertyKey(globalObject);
}
Identifier JSModuleLoader::resolve(JSGlobalObject* globalObject, const Identifier& name, const Identifier& referrer, RefPtr<ScriptFetcher> scriptFetcher, bool useImportMap)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue nameValue = name.isSymbol() || name.isNull() ? jsUndefined() : jsString(vm, name.string());
RETURN_IF_EXCEPTION(scope, { });
JSValue referrerValue = referrer.isSymbol() || referrer.isNull() ? jsUndefined() : jsString(vm, referrer.string());
RETURN_IF_EXCEPTION(scope, { });
RELEASE_AND_RETURN(scope, resolve(globalObject, nameValue, referrerValue, WTF::move(scriptFetcher), useImportMap));
}
JSPromise* JSModuleLoader::fetch(JSGlobalObject* globalObject, JSValue key, RefPtr<ScriptFetchParameters> parameters, RefPtr<ScriptFetcher> scriptFetcher)
{
dataLogLnIf(Options::dumpModuleLoadingState(), "Loader [fetch] ", printableModuleKey(globalObject, key));
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
if (globalObject->globalObjectMethodTable()->moduleLoaderFetch)
RELEASE_AND_RETURN(scope, globalObject->globalObjectMethodTable()->moduleLoaderFetch(globalObject, this, key, WTF::move(parameters), WTF::move(scriptFetcher)));
auto* promise = JSPromise::create(vm, globalObject->promiseStructure());
String moduleKey = key.toWTFString(globalObject);
RETURN_IF_EXCEPTION(scope, promise->rejectWithCaughtException(vm, scope));
scope.release();
promise->reject(vm, createError(globalObject, makeString("Could not open the module '"_s, moduleKey, "'."_s)));
return promise;
}
JSObject* JSModuleLoader::createImportMetaProperties(JSGlobalObject* globalObject, JSValue key, JSModuleRecord* moduleRecord, RefPtr<ScriptFetcher> scriptFetcher)
{
if (globalObject->globalObjectMethodTable()->moduleLoaderCreateImportMetaProperties)
return globalObject->globalObjectMethodTable()->moduleLoaderCreateImportMetaProperties(globalObject, this, key, moduleRecord, WTF::move(scriptFetcher));
return constructEmptyObject(globalObject->vm(), globalObject->nullPrototypeObjectStructure());
}
JSValue JSModuleLoader::evaluate(JSGlobalObject* globalObject, JSValue key, JSValue moduleRecordValue, RefPtr<ScriptFetcher> scriptFetcher, JSValue sentValue, JSValue resumeMode)
{
dataLogLnIf(Options::dumpModuleLoadingState(), "Loader [evaluate] ", printableModuleKey(globalObject, key));
if (globalObject->globalObjectMethodTable()->moduleLoaderEvaluate)
return globalObject->globalObjectMethodTable()->moduleLoaderEvaluate(globalObject, this, key, moduleRecordValue, WTF::move(scriptFetcher), sentValue, resumeMode);
return evaluateNonVirtual(globalObject, key, moduleRecordValue, nullptr, sentValue, resumeMode);
}
JSValue JSModuleLoader::evaluateNonVirtual(JSGlobalObject* globalObject, JSValue, JSValue moduleRecordValue, RefPtr<ScriptFetcher>, JSValue sentValue, JSValue resumeMode)
{
if (auto* moduleRecord = dynamicDowncast<AbstractModuleRecord>(moduleRecordValue))
return moduleRecord->evaluate(globalObject, sentValue, resumeMode);
return jsUndefined();
}
JSModuleNamespaceObject* JSModuleLoader::getModuleNamespaceObject(JSGlobalObject* globalObject, JSValue moduleRecordValue)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
auto* moduleRecord = dynamicDowncast<AbstractModuleRecord>(moduleRecordValue);
if (!moduleRecord) {
throwTypeError(globalObject, scope);
return nullptr;
}
RELEASE_AND_RETURN(scope, moduleRecord->getModuleNamespace(globalObject));
}
AbstractModuleRecord* JSModuleLoader::getImportedModule(AbstractModuleRecord* referrer, const AbstractModuleRecord::ModuleRequest& request)
{
// GetImportedModule(referrer, request)
// https://tc39.es/ecma262/#sec-GetImportedModule
// 1. Let records be a List consisting of each LoadedModuleRequest Record r of referrer.[[LoadedModules]] such that ModuleRequestsEqual(r, request) is true.
auto iter = referrer->loadedModules().find(ModuleMapKey { request.m_specifier.impl(), request.type() });
// 2. Assert: records has exactly one element, since LoadRequestedModules has completed successfully on referrer prior to invoking this abstract operation.
ASSERT(iter != referrer->loadedModules().end());
// 3. Let record be the sole element of records.
// 4. Return record.[[Module]].
return iter->value.m_module.get();
}
AbstractModuleRecord* JSModuleLoader::maybeGetImportedModule(AbstractModuleRecord* referrer, const Identifier& moduleKey)
{
for (const auto& [key, loadedModuleRequest] : referrer->loadedModules()) {
if (loadedModuleRequest.m_specifier == moduleKey)
return loadedModuleRequest.m_module.get();
}
return nullptr;
}
JSPromise* JSModuleLoader::hostLoadImportedModule(JSGlobalObject* globalObject, const ModuleReferrer& referrer, const ModuleRequest& moduleRequest, JSCell* payload, RefPtr<ScriptFetcher> scriptFetcher, bool useImportMap)
{
// HostLoadImportedModule(referrer, moduleRequest, loadState, payload)
// https://html.spec.whatwg.org/multipage/webappapis.html#hostloadimportedmodule
ASSERT(isModuleLoaderHostDefinedPayload(payload));
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
Identifier referrerKey;
CyclicModuleRecord* record = referrer.getModule();
if (record)
referrerKey = record->moduleKey();
ModuleRegistryEntry* mapEntry = nullptr;
const Identifier& specifier = moduleRequest.m_specifier;
auto type = moduleRequest.type();
if (specifier.isSymbol())
mapEntry = getRegisteredMayBeNull(specifier, type);
ModuleMapKey moduleMapKey { specifier.impl(), type };
ResolutionMapKey resolutionKey { referrerKey.impl(), specifier.impl() };
if (auto error = m_resolutionFailures.get(resolutionKey)) {
JSValue errorValue = error.get();
ASSERT(errorValue);
JSPromise* promise = JSPromise::create(vm, globalObject->promiseStructure());
promise->reject(vm, errorValue);
// 9.1. If loadState is not undefined and loadState.[[ErrorToRethrow]] is null, set loadState.[[ErrorToRethrow]] to resolutionError.
// (Unused.)
// 9.2. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, ThrowCompletion(resolutionError)).
finishLoadingImportedModule(globalObject, referrer, moduleRequest, payload, Exception::create(vm, errorValue), scriptFetcher);
// 9.3. Return.
RELEASE_AND_RETURN(scope, promise);
}
Identifier resolved;
if (!mapEntry) {
// 8. Let url be the result of resolving a module specifier given referencingScript and moduleRequest.[[Specifier]], catching any exceptions. If they throw an exception, let resolutionError be the thrown exception.
resolved = resolve(globalObject, specifier, referrerKey, scriptFetcher, useImportMap);
// 9. If the previous step threw an exception, then:
if (Exception* resolutionError = scope.exception()) {
attachErrorInfo(globalObject, resolutionError, nullptr, specifier, moduleRequest.type(), ModuleFailure::Kind::Instantiation);
// Cache the resolution error so subsequent calls for the same specifier return the same error object.
JSValue errorValue = resolutionError->value();
addResolutionFailure(vm, resolutionKey, errorValue);
JSPromise* promise = JSPromise::create(vm, globalObject->promiseStructure());
promise->rejectWithCaughtException(vm, scope);
// 9.1. If loadState is not undefined and loadState.[[ErrorToRethrow]] is null, set loadState.[[ErrorToRethrow]] to resolutionError.
// (Unused.)
// 9.2. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, ThrowCompletion(resolutionError)).
finishLoadingImportedModule(globalObject, referrer, moduleRequest, payload, Exception::create(vm, errorValue), scriptFetcher);
// 9.3. Return.
RELEASE_AND_RETURN(scope, promise);
}
moduleMapKey.first = resolved.impl();
if (auto iter = m_moduleMap.find(moduleMapKey); iter != m_moduleMap.end())
mapEntry = iter->value.get();
} else
resolved = specifier;
if (mapEntry) {
ASSERT(mapEntry->status() != ModuleRegistryEntry::Status::New);
// Only fetching errors should be checked here, not instantiation or evaluation errors.
// This allows fetch errors to propagate first because they're required to have priority.
// To avoid a race condition, instantiation errors need to be checked later, not here.
if (JSValue fetchError = mapEntry->fetchError()) {
if (auto* errorInstance = dynamicDowncast<ErrorInstance>(fetchError)) {
fetchError = JSModuleLoader::duplicateError(globalObject, errorInstance);
RETURN_IF_EXCEPTION(scope, nullptr);
}
finishLoadingImportedModule(globalObject, referrer, moduleRequest, payload, Exception::create(vm, fetchError), scriptFetcher);
RETURN_IF_EXCEPTION(scope, nullptr);
return JSPromise::rejectedPromise(globalObject, fetchError);
}
#if USE(BUN_JSC_ADDITIONS)
if (vm.m_synchronousModuleQueue && mapEntry->status() == ModuleRegistryEntry::Status::Fetching) {
// require(esm) hit a dependency that the surrounding async graph
// already started loading. Force the fetch+makeModule chain through
// synchronously so this graph can complete without yielding; the
// outer async path will see the entry as Fetched when it eventually
// drains and short-circuit.
JSPromise* fetchPromise = mapEntry->ensureFetchPromise(globalObject);
JSPromise* modulePromise = mapEntry->ensureModulePromise(globalObject);
if (modulePromise->status() == JSPromise::Status::Pending) {
if (fetchPromise->status() == JSPromise::Status::Pending) {
// Transpilation still in flight — re-issue through the
// embedder's synchronous fetch. fetchPromise was already
// pipeFrom()'d by the async path which set
// isFirstResolvingFunctionCalledFlag, so use the unguarded
// fulfill/reject. The ModuleRegistryFetchSettled reaction on
// fetchPromise lands on the sync queue and drives the rest of
// the chain (including loadPromise).
JSPromise* promise = fetch(globalObject, identifierToJSValue(vm, resolved), nullptr, scriptFetcher.copyRef());
RETURN_IF_EXCEPTION(scope, nullptr);
if (promise->status() == JSPromise::Status::Fulfilled)
fetchPromise->fulfillPromise(vm, promise->result());
else if (promise->status() == JSPromise::Status::Rejected)
fetchPromise->rejectPromise(vm, promise->result());
} else if (fetchPromise->status() == JSPromise::Status::Fulfilled) {
// fetchPromise already settled but its
// ModuleRegistryFetchSettled reaction is sitting on the
// *normal* microtask queue (it fired before we entered sync
// mode). Replay that step inline. The queued
// normal-microtask copy will see modulePromise already
// settled and bail in moduleRegistryFetchSettled's handler.
JSPromise* makePromise = makeModule(globalObject, resolved, uncheckedDowncast<JSSourceCode>(fetchPromise->result()));
RETURN_IF_EXCEPTION(scope, nullptr);
if (makePromise->status() == JSPromise::Status::Fulfilled) {
mapEntry->fetchComplete(globalObject, uncheckedDowncast<AbstractModuleRecord>(makePromise->result()));
modulePromise->fulfillPromise(vm, makePromise->result());
} else if (makePromise->status() == JSPromise::Status::Rejected)
modulePromise->rejectPromise(vm, makePromise->result());
}
// The reactions above were diverted to the sync queue but
// haven't *run* yet — they'll run when the caller's
// drainSynchronousModuleQueue loop reaches them. The
// loadPromise()/record() reads below therefore still see the
// pre-advance state, so fall through to the modulePromise path
// instead of returning the (still-Pending) cached loadPromise.
}
}
#endif
JSPromise* promise = mapEntry->loadPromise();
if (promise) {
if (mapEntry->record()) {
finishLoadingImportedModule(globalObject, referrer, moduleRequest, payload, mapEntry->record(), scriptFetcher);
RETURN_IF_EXCEPTION(scope, nullptr);
} else {
auto* context = ModuleLoadingContext::create(vm, ModuleLoadingContext::Step::Cached, referrer, moduleRequest, payload, mapEntry, scriptFetcher);
JSPromise* resultPromise = JSPromise::create(vm, globalObject->promiseStructure());
resultPromise->markAsHandled();
promise->performPromiseThenWithInternalMicrotask(vm, InternalMicrotask::ModuleLoadStep, resultPromise, context);
promise = resultPromise;
}
return promise;
}
} else {
mapEntry = ModuleRegistryEntry::create(vm, resolved, type, scriptFetcher);
Locker locker { cellLock() };
m_moduleMap.add(moduleMapKey, WriteBarrier<ModuleRegistryEntry>(vm, this, mapEntry));
}
if (mapEntry->status() == ModuleRegistryEntry::Status::New) {
JSPromise* promise = fetch(globalObject, identifierToJSValue(vm, resolved), moduleRequest.m_attributes, scriptFetcher);
RETURN_IF_EXCEPTION(scope, nullptr);
mapEntry->setStatus(ModuleRegistryEntry::Status::Fetching);
mapEntry->ensureFetchPromise(globalObject)->pipeFrom(vm, promise);
}
JSPromise* modulePromise = mapEntry->ensureModulePromise(globalObject);
RETURN_IF_EXCEPTION(scope, nullptr);
auto* context = ModuleLoadingContext::create(vm, ModuleLoadingContext::Step::Main, referrer, moduleRequest, payload, mapEntry, scriptFetcher);
JSPromise* loadPromise = JSPromise::create(vm, globalObject->promiseStructure());
loadPromise->markAsHandled();
modulePromise->performPromiseThenWithInternalMicrotask(vm, InternalMicrotask::ModuleLoadStep, loadPromise, context);
mapEntry->setLoadPromise(vm, loadPromise);
return loadPromise;
}
JSPromise* JSModuleLoader::loadModule(JSGlobalObject* globalObject, const ModuleReferrer& referrer, const ModuleRequest& moduleRequest, JSCell* payload, RefPtr<ScriptFetcher> scriptFetcher, OptionSet<ModuleLoadFlag> flags)
{
ASSERT(isModuleLoaderHostDefinedPayload(payload));
ASSERT(!flags.contains(ModuleLoadFlag::Dynamic));
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSPromise* promise = hostLoadImportedModule(globalObject, referrer, moduleRequest, payload, scriptFetcher, flags.contains(ModuleLoadFlag::UseImportMap));
RETURN_IF_EXCEPTION(scope, nullptr);
auto* context = ModuleLoadingContext::create(vm, moduleRequest, WTF::move(scriptFetcher), flags);
JSPromise* resultPromise = JSPromise::create(vm, globalObject->promiseStructure());
resultPromise->markAsHandled();
promise->performPromiseThenWithInternalMicrotask(vm, InternalMicrotask::ModuleLoadLinkEvaluateSettled, resultPromise, context);
resultPromise->performPromiseThenWithInternalMicrotask(vm, InternalMicrotask::ModuleLoadStoreError, nullptr, context);
return resultPromise;
}
void JSModuleLoader::innerModuleLoading(JSGlobalObject* globalObject, ModuleGraphLoadingState *state, AbstractModuleRecord* startModule)
{
// InnerModuleLoading(state, module)
// https://tc39.es/ecma262/#sec-InnerModuleLoading
//
// The spec phrases this recursively, with HostLoadImportedModule re-entering
// via FinishLoadingImportedModule -> ContinueModuleLoading. That re-entry
// happens once per import edge, but only one-per-module actually enters the
// step-2 loop body — the rest hit the visited check, decrement the counter
// and return. With dense `export * from` graphs (E >> V) the per-edge
// function entry / throw-scope / dynamicDowncast dominates. We instead drain
// a worklist on the state: ContinueModuleLoading enqueues, and the outermost
// call drains. Same observable [[Visited]] / [[PendingModulesCount]].
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
state->enqueueInnerLoad(startModule);
if (state->drainingInnerLoad())
RELEASE_AND_RETURN(scope, void());
state->setDrainingInnerLoad(true);
AbstractModuleRecord* module;
while ((module = state->takeInnerLoad())) {
// 1. Assert: state.[[IsLoading]] is true.
ASSERT(state->isLoading());
// 2. If module is a Cyclic Module Record, module.[[Status]] is NEW, and state.[[Visited]] does not contain module, then
// (containsVisited first — it's the cheap pointer-hash check that fails
// fast for the common already-seen case before we pay for the dyncast.)
if (!state->containsVisited(module)) {
if (auto* cyclic = dynamicDowncast<CyclicModuleRecord>(module); cyclic && cyclic->status() == CyclicModuleRecord::Status::New) {
// 2.a. Append module to state.[[Visited]].
state->appendVisited(vm, cyclic);
// 2.b. Let requestedModulesCount be the number of elements in module.[[RequestedModules]].
size_t requestedModulesCount = module->requestedModules().size();
// 2.c. Set state.[[PendingModulesCount]] to state.[[PendingModulesCount]] + requestedModulesCount.
state->setPendingModulesCount(state->pendingModulesCount() + requestedModulesCount);
// 2.d. For each ModuleRequest Record request of module.[[RequestedModules]], do
for (const AbstractModuleRecord::ModuleRequest& request : module->requestedModules()) {
// 2.d.i. If AllImportAttributesSupported(request.[[Attributes]]) is false, then
// 2.d.i.1. Let error be ThrowCompletion(a newly created SyntaxError object).
// 2.d.i.2. Perform ContinueModuleLoading(state, error).
// (Not possible.)
// 2.d.ii. Else if module.[[LoadedModules]] contains a LoadedModuleRequest Record record such that ModuleRequestsEqual(record, request) is true, then
if (auto iter = module->loadedModules().find(ModuleMapKey { request.m_specifier.impl(), request.type() }); iter != module->loadedModules().end()) {
// 2.d.ii.1. Perform InnerModuleLoading(state, record.[[Module]]).
AbstractModuleRecord* loaded = iter->value.m_module.get();
if (state->containsVisited(loaded))
state->setPendingModulesCount(state->pendingModulesCount() - 1);
else
state->enqueueInnerLoad(loaded);
if (!state->isLoading())
break;
continue;
}
// 2.d.iii. Else,
// 2.d.iii.1. Perform HostLoadImportedModule(module, request, state.[[HostDefined]], state).
unsigned loadedModulesCountBefore = module->loadedModules().size();
JSPromise* promise = hostLoadImportedModule(globalObject, cyclic, request, state, state->scriptFetcher(), true);
if (scope.exception()) [[unlikely]] {
state->setDrainingInnerLoad(false);
return;
}
// 2.d.iii.2. NOTE: HostLoadImportedModule will call FinishLoadingImportedModule, which re-enters the graph loading process through ContinueModuleLoading.
//
// If module.[[LoadedModules]] grew across the HostLoadImportedModule call, the requested
// module was loaded synchronously, which means it was already loaded before. In that case
// there is no need to attach a ModuleGraphLoadingError reaction, so we skip it.
bool needsErrorReaction = module->loadedModules().size() == loadedModulesCountBefore;
ASSERT(module->loadedModules().size() <= loadedModulesCountBefore + 1);
ASSERT(needsErrorReaction != module->loadedModules().contains(ModuleMapKey { request.m_specifier.impl(), request.type() }));
if (needsErrorReaction)
promise->performPromiseThenWithInternalMicrotask(vm, InternalMicrotask::ModuleGraphLoadingError, nullptr, state);
// 2.d.iv. If state.[[IsLoading]] is false, return UNUSED.
if (!state->isLoading())
break;
}
if (!state->isLoading()) {
state->setDrainingInnerLoad(false);
RELEASE_AND_RETURN(scope, void());
}
}
}
// 3. Assert: state.[[PendingModulesCount]] ≥ 1.
ASSERT(state->pendingModulesCount() >= 1);
// 4. Set state.[[PendingModulesCount]] to state.[[PendingModulesCount]] - 1.
state->setPendingModulesCount(state->pendingModulesCount() - 1);
// 5. If state.[[PendingModulesCount]] = 0, then
if (!state->pendingModulesCount()) {
// 5.a. Set state.[[IsLoading]] to false.
state->setIsLoading(false);
// 5.b. For each Cyclic Module Record loaded of state.[[Visited]], do
state->iterateVisited([](CyclicModuleRecord* loaded) {
// 5.b.i. If loaded.[[Status]] is NEW, set loaded.[[Status]] to UNLINKED.
if (loaded->status() == CyclicModuleRecord::Status::New)
loaded->setStatus(CyclicModuleRecord::Status::Unlinked);
});
// 5.c. Perform ! Call(state.[[PromiseCapability]].[[Resolve]], undefined, « undefined »).
state->promise()->fulfill(vm, module);
break;
}
}
// 6. Return UNUSED.
state->setDrainingInnerLoad(false);
scope.release();
}
void JSModuleLoader::finishLoadingImportedModule(JSGlobalObject* globalObject, const ModuleReferrer& referrer, const ModuleRequest& moduleRequest, JSCell* payload, ModuleCompletion result, RefPtr<ScriptFetcher> scriptFetcher)
{
// FinishLoadingImportedModule(referrer, moduleRequest, payload, result)
// https://tc39.es/ecma262/#sec-FinishLoadingImportedModule
ASSERT(isModuleLoaderHostDefinedPayload(payload));
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// 1. If result is a normal completion, then
if (auto* resultRecord = std::get_if<AbstractModuleRecord*>(&result)) {
JSCell* owner = nullptr;
auto& loadedModules = [&] -> ModuleMap<AbstractModuleRecord::LoadedModuleRequest> & {
if (CyclicModuleRecord* module = referrer.getModule()) {
owner = module;
return module->loadedModules();
}
ASSERT(referrer.isRealm());
owner = this;
return m_loadedModules;
}();
ASSERT(owner);
// 1.a. If referrer.[[LoadedModules]] contains a LoadedModuleRequest Record record such that ModuleRequestsEqual(record, moduleRequest) is true, then
if (auto iter = loadedModules.find(ModuleMapKey { moduleRequest.m_specifier.impl(), moduleRequest.type() }); iter != loadedModules.end()) {
// 1.a.i. Assert: record.[[Module]] and result.[[Value]] are the same Module Record.
ASSERT(iter->value.m_module.get() == *resultRecord);
// 1.b. Else,
} else {
// 1.b.i. Append the LoadedModuleRequest Record { [[Specifier]]: moduleRequest.[[Specifier]], [[Attributes]]: moduleRequest.[[Attributes]], [[Module]]: result.[[Value]] } to referrer.[[LoadedModules]].
ModuleMapKey key { moduleRequest.m_specifier.impl(), moduleRequest.type() };
Locker locker { owner->cellLock() };
AbstractModuleRecord::LoadedModuleRequest value { vm, moduleRequest, *resultRecord, owner };
loadedModules.add(WTF::move(key), WTF::move(value));
}
}
// 2. If payload is a GraphLoadingState Record, then
if (auto* state = dynamicDowncast<ModuleGraphLoadingState>(payload)) {
// 2.a. Perform ContinueModuleLoading(payload, result).
continueModuleLoading(globalObject, state, result);
RETURN_IF_EXCEPTION(scope, void());
// 3. Else,
} else {
// 3.a. Perform ContinueDynamicImport(payload, result).
auto* dynamicPayload = uncheckedDowncast<ModuleLoaderPayload>(payload);
continueDynamicImport(globalObject, dynamicPayload, result, WTF::move(scriptFetcher));
RETURN_IF_EXCEPTION(scope, void());
}
// 4. Return UNUSED.
scope.release();
}
void JSModuleLoader::continueModuleLoading(JSGlobalObject* globalObject, ModuleGraphLoadingState *state, ModuleCompletion moduleCompletion)
{
// ContinueModuleLoading(state, moduleCompletion)
// https://tc39.es/ecma262/#sec-ContinueModuleLoading
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// 1. If state.[[IsLoading]] is false, return UNUSED.
if (!state->isLoading())
RELEASE_AND_RETURN(scope, void());
// 2. If moduleCompletion is a normal completion, then
if (auto* module = std::get_if<AbstractModuleRecord*>(&moduleCompletion)) {
// 2.a. Perform InnerModuleLoading(state, moduleCompletion.[[Value]]).
// Per-edge fast path: most calls land here with a module that's already
// visited (E >> V); skip the dyncast+enqueue and just decrement.
if (state->containsVisited(*module)) {
ASSERT(state->pendingModulesCount() > 1 || !state->drainingInnerLoad());
state->setPendingModulesCount(state->pendingModulesCount() - 1);
if (!state->pendingModulesCount()) {
state->setIsLoading(false);
state->iterateVisited([](CyclicModuleRecord* loaded) {
if (loaded->status() == CyclicModuleRecord::Status::New)
loaded->setStatus(CyclicModuleRecord::Status::Unlinked);
});
state->promise()->fulfill(vm, *module);
}
} else if (state->drainingInnerLoad())
state->enqueueInnerLoad(*module);
else {
innerModuleLoading(globalObject, state, *module);
RETURN_IF_EXCEPTION(scope, void());
}
// 3. Else,