-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript_module.rs
More file actions
2276 lines (2005 loc) · 87.8 KB
/
Copy pathscript_module.rs
File metadata and controls
2276 lines (2005 loc) · 87.8 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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! The script module mod contains common traits and structs
//! related to `type=module` for script thread or worker threads.
use std::cell::{OnceCell, RefCell};
use std::ffi::CStr;
use std::fmt::Debug;
use std::ptr::NonNull;
use std::rc::Rc;
use std::{mem, ptr};
use encoding_rs::UTF_8;
use headers::{HeaderMapExt, ReferrerPolicy as ReferrerPolicyHeader};
use html5ever::local_name;
use hyper_serde::Serde;
use indexmap::IndexMap;
use indexmap::map::Entry;
use js::context::JSContext;
use js::conversions::jsstr_to_string;
use js::gc::MutableHandleValue;
use js::jsapi::{
CallArgs, CompileJsonModule1, CompileModule1, ExceptionStackBehavior,
GetFunctionNativeReserved, GetModuleResolveHook, Handle as RawHandle,
HandleValue as RawHandleValue, Heap, JS_ClearPendingException, JS_GetFunctionObject,
JSAutoRealm, JSContext as RawJSContext, JSObject, JSPROP_ENUMERATE, JSRuntime,
ModuleErrorBehaviour, ModuleType, SetFunctionNativeReserved, SetModuleDynamicImportHook,
SetModuleMetadataHook, SetModulePrivate, SetModuleResolveHook, SetScriptPrivateReferenceHooks,
ThrowOnModuleEvaluationFailure, Value,
};
use js::jsval::{JSVal, PrivateValue, UndefinedValue};
use js::realm::{AutoRealm, CurrentRealm};
use js::rust::wrappers::{JS_GetPendingException, JS_SetPendingException, ModuleEvaluate};
use js::rust::wrappers2::{
DefineFunctionWithReserved, GetModuleRequestSpecifier, GetModuleRequestType,
JS_DefineProperty4, JS_NewStringCopyN, ModuleLink,
};
use js::rust::{
CompileOptionsWrapper, Handle, HandleObject as RustHandleObject, HandleValue, ToString,
transform_str_to_source_text,
};
use mime::Mime;
use net_traits::http_status::HttpStatus;
use net_traits::mime_classifier::MimeClassifier;
use net_traits::policy_container::PolicyContainer;
use net_traits::request::{
CredentialsMode, Destination, InsecureRequestsPolicy, ParserMetadata, Referrer, RequestBuilder,
RequestClient, RequestId, RequestMode,
};
use net_traits::response::HttpsState;
use net_traits::{FetchMetadata, Metadata, NetworkError, ReferrerPolicy, ResourceFetchTiming};
use script_bindings::cformat;
use script_bindings::domstring::BytesView;
use script_bindings::error::Fallible;
use script_bindings::settings_stack::run_a_callback;
use script_bindings::trace::CustomTraceable;
use serde_json::{Map as JsonMap, Value as JsonValue};
use servo_base::id::PipelineId;
use servo_config::pref;
use servo_url::{ImmutableOrigin, ServoUrl};
use crate::DomTypeHolder;
use crate::document_loader::LoadType;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::WindowBinding::Window_Binding::WindowMethods;
use crate::dom::bindings::conversions::SafeToJSValConvertible;
use crate::dom::bindings::error::{
Error, ErrorToJsval, report_pending_exception, throw_dom_exception,
};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::{DomGlobal, DomObject};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::trace::RootedTraceableBox;
use crate::dom::csp::{GlobalCspReporting, Violation};
use crate::dom::document::Document;
use crate::dom::element::Element;
use crate::dom::globalscope::GlobalScope;
use crate::dom::html::htmlscriptelement::{
HTMLScriptElement, SCRIPT_JS_MIMES, Script, substitute_with_local_script,
};
use crate::dom::node::NodeTraits;
use crate::dom::performance::performanceresourcetiming::InitiatorType;
use crate::dom::promise::Promise;
use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler};
use crate::dom::types::{Console, DedicatedWorkerGlobalScope, WorkerGlobalScope};
use crate::dom::window::Window;
use crate::module_loading::{
LoadState, Payload, host_load_imported_module, load_requested_modules,
};
use crate::network_listener::{
self, FetchResponseListener, NetworkListener, ResourceTimingListener,
};
use crate::realms::{InRealm, enter_realm};
use crate::script_runtime::{CanGc, IntroductionType, JSContext as SafeJSContext};
use crate::task::NonSendTaskBox;
pub(crate) fn gen_type_error(global: &GlobalScope, error: Error, can_gc: CanGc) -> RethrowError {
rooted!(in(*GlobalScope::get_cx()) let mut thrown = UndefinedValue());
error.to_jsval(GlobalScope::get_cx(), global, thrown.handle_mut(), can_gc);
RethrowError(RootedTraceableBox::from_box(Heap::boxed(thrown.get())))
}
#[derive(JSTraceable)]
pub(crate) struct ModuleObject(RootedTraceableBox<Heap<*mut JSObject>>);
impl ModuleObject {
pub(crate) fn new(obj: RustHandleObject) -> ModuleObject {
ModuleObject(RootedTraceableBox::from_box(Heap::boxed(obj.get())))
}
pub(crate) fn handle(&'_ self) -> js::gc::HandleObject<'_> {
self.0.handle()
}
}
#[derive(JSTraceable)]
pub(crate) struct RethrowError(RootedTraceableBox<Heap<JSVal>>);
impl RethrowError {
pub(crate) fn new(val: Box<Heap<JSVal>>) -> Self {
Self(RootedTraceableBox::from_box(val))
}
#[expect(unsafe_code)]
pub(crate) fn from_pending_exception(cx: SafeJSContext) -> Self {
rooted!(in(*cx) let mut exception = UndefinedValue());
assert!(unsafe { JS_GetPendingException(*cx, exception.handle_mut()) });
unsafe { JS_ClearPendingException(*cx) };
Self::new(Heap::boxed(exception.get()))
}
pub(crate) fn handle(&self) -> Handle<'_, JSVal> {
self.0.handle()
}
}
impl Debug for RethrowError {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
"RethrowError(...)".fmt(fmt)
}
}
impl Clone for RethrowError {
fn clone(&self) -> Self {
Self(RootedTraceableBox::from_box(Heap::boxed(self.0.get())))
}
}
pub(crate) struct ModuleScript {
pub(crate) base_url: ServoUrl,
pub(crate) options: ScriptFetchOptions,
pub(crate) owner: Option<ModuleOwner>,
}
impl ModuleScript {
pub(crate) fn new(
base_url: ServoUrl,
options: ScriptFetchOptions,
owner: Option<ModuleOwner>,
) -> Self {
ModuleScript {
base_url,
options,
owner,
}
}
}
pub(crate) type ModuleRequest = (ServoUrl, ModuleType);
#[derive(Clone, JSTraceable)]
pub(crate) enum ModuleStatus {
Fetching(DomRefCell<Option<Rc<Promise>>>),
Loaded(Option<Rc<ModuleTree>>),
}
#[derive(JSTraceable, MallocSizeOf)]
pub(crate) struct ModuleTree {
#[no_trace]
url: ServoUrl,
#[ignore_malloc_size_of = "mozjs"]
record: OnceCell<ModuleObject>,
#[ignore_malloc_size_of = "mozjs"]
parse_error: OnceCell<RethrowError>,
#[ignore_malloc_size_of = "mozjs"]
rethrow_error: DomRefCell<Option<RethrowError>>,
#[no_trace]
loaded_modules: DomRefCell<IndexMap<String, ServoUrl>>,
}
impl ModuleTree {
pub(crate) fn get_url(&self) -> ServoUrl {
self.url.clone()
}
pub(crate) fn get_record(&self) -> Option<&ModuleObject> {
self.record.get()
}
pub(crate) fn get_parse_error(&self) -> Option<&RethrowError> {
self.parse_error.get()
}
pub(crate) fn get_rethrow_error(&self) -> &DomRefCell<Option<RethrowError>> {
&self.rethrow_error
}
pub(crate) fn set_rethrow_error(&self, rethrow_error: RethrowError) {
*self.rethrow_error.borrow_mut() = Some(rethrow_error);
}
pub(crate) fn find_descendant_inside_module_map(
&self,
global: &GlobalScope,
specifier: &String,
module_type: ModuleType,
) -> Option<Rc<ModuleTree>> {
self.loaded_modules
.borrow()
.get(specifier)
.and_then(|url| global.get_module_map_entry(&(url.clone(), module_type)))
.and_then(|status| match status {
ModuleStatus::Fetching(_) => None,
ModuleStatus::Loaded(module_tree) => module_tree,
})
}
pub(crate) fn insert_module_dependency(
&self,
module: &Rc<ModuleTree>,
module_request_specifier: String,
) {
// Store the url which is used to retrieve the module from module map when needed.
let url = module.url.clone();
match self
.loaded_modules
.borrow_mut()
.entry(module_request_specifier)
{
// a. If referrer.[[LoadedModules]] contains a LoadedModuleRequest Record record such that
// ModuleRequestsEqual(record, moduleRequest) is true, then
Entry::Occupied(entry) => {
// i. Assert: record.[[Module]] and result.[[Value]] are the same Module Record.
assert_eq!(*entry.get(), url);
},
// b. Else,
Entry::Vacant(entry) => {
// i. Append the LoadedModuleRequest Record { [[Specifier]]: moduleRequest.[[Specifier]],
// [[Attributes]]: moduleRequest.[[Attributes]], [[Module]]: result.[[Value]] } to referrer.[[LoadedModules]].
entry.insert(url);
},
}
}
}
pub(crate) struct ModuleSource {
pub source: Rc<DOMString>,
pub unminified_dir: Option<String>,
pub external: bool,
pub url: ServoUrl,
}
impl crate::unminify::ScriptSource for ModuleSource {
fn unminified_dir(&self) -> Option<String> {
self.unminified_dir.clone()
}
fn extract_bytes(&self) -> BytesView<'_> {
self.source.as_bytes()
}
fn rewrite_source(&mut self, source: Rc<DOMString>) {
self.source = source;
}
fn url(&self) -> ServoUrl {
self.url.clone()
}
fn is_external(&self) -> bool {
self.external
}
}
impl ModuleTree {
#[expect(unsafe_code)]
#[expect(clippy::too_many_arguments)]
/// <https://html.spec.whatwg.org/multipage/#creating-a-javascript-module-script>
/// Although the CanGc argument appears unused, it represents the GC operations that
/// can occur as part of compiling a script.
fn create_a_javascript_module_script(
source: Rc<DOMString>,
owner: ModuleOwner,
url: &ServoUrl,
options: ScriptFetchOptions,
external: bool,
line_number: u32,
introduction_type: Option<&'static CStr>,
_can_gc: CanGc,
) -> Self {
let cx = GlobalScope::get_cx();
let global = owner.global();
let _ac = JSAutoRealm::new(*cx, *global.reflector().get_jsobject());
// Step 2. Let script be a new module script that this algorithm will subsequently initialize.
// Step 6. Set script's parse error and error to rethrow to null.
let module = ModuleTree {
url: url.clone(),
record: OnceCell::new(),
parse_error: OnceCell::new(),
rethrow_error: DomRefCell::new(None),
loaded_modules: DomRefCell::new(IndexMap::new()),
};
let compile_options = fill_module_compile_options(cx, url, introduction_type, line_number);
let mut module_source = ModuleSource {
source,
unminified_dir: global.unminified_js_dir(),
external,
url: url.clone(),
};
crate::unminify::unminify_js(&mut module_source);
unsafe {
// Step 7. Let result be ParseModule(source, settings's realm, script).
rooted!(in(*cx) let mut module_script: *mut JSObject = std::ptr::null_mut());
module_script.set(CompileModule1(
*cx,
compile_options.ptr,
&mut transform_str_to_source_text(&module_source.source.str()),
));
// Step 8. If result is a list of errors, then:
if module_script.is_null() {
warn!("fail to compile module script of {}", url);
// Step 8.1. Set script's parse error to result[0].
let _ = module
.parse_error
.set(RethrowError::from_pending_exception(cx));
// Step 8.2. Return script.
return module;
}
// Step 3. Set script's settings object to settings.
// Step 4. Set script's base URL to baseURL.
// Step 5. Set script's fetch options to options.
let module_script_data = Rc::new(ModuleScript::new(url.clone(), options, Some(owner)));
SetModulePrivate(
module_script.get(),
&PrivateValue(Rc::into_raw(module_script_data) as *const _),
);
// Step 9. Set script's record to result.
let _ = module.record.set(ModuleObject::new(module_script.handle()));
}
// Step 10. Return script.
module
}
#[expect(unsafe_code)]
/// <https://html.spec.whatwg.org/multipage/#creating-a-json-module-script>
/// Although the CanGc argument appears unused, it represents the GC operations that
/// can occur as part of compiling a script.
fn create_a_json_module_script(
source: &str,
global: &GlobalScope,
url: &ServoUrl,
introduction_type: Option<&'static CStr>,
_can_gc: CanGc,
) -> Self {
let cx = GlobalScope::get_cx();
let _ac = JSAutoRealm::new(*cx, *global.reflector().get_jsobject());
// Step 1. Let script be a new module script that this algorithm will subsequently initialize.
// Step 4. Set script's parse error and error to rethrow to null.
let module = ModuleTree {
url: url.clone(),
record: OnceCell::new(),
parse_error: OnceCell::new(),
rethrow_error: DomRefCell::new(None),
loaded_modules: DomRefCell::new(IndexMap::new()),
};
// Step 2. Set script's settings object to settings.
// Step 3. Set script's base URL and fetch options to null.
// Note: We don't need to call `SetModulePrivate` for json scripts
let compile_options = fill_module_compile_options(cx, url, introduction_type, 1);
rooted!(in(*cx) let mut module_script: *mut JSObject = std::ptr::null_mut());
unsafe {
// Step 5. Let result be ParseJSONModule(source).
module_script.set(CompileJsonModule1(
*cx,
compile_options.ptr,
&mut transform_str_to_source_text(source),
));
}
// If this throws an exception, catch it, and set script's parse error to that exception, and return script.
if module_script.is_null() {
warn!("fail to compile module script of {}", url);
let _ = module
.parse_error
.set(RethrowError::from_pending_exception(cx));
return module;
}
// Step 6. Set script's record to result.
let _ = module.record.set(ModuleObject::new(module_script.handle()));
// Step 7. Return script.
module
}
/// Execute the provided module, storing the evaluation return value in the provided
/// mutable handle. Although the CanGc appears unused, it represents the GC operations
/// possible when evluating arbitrary JS.
#[expect(unsafe_code)]
pub(crate) fn execute_module(
&self,
global: &GlobalScope,
module_record: js::gc::HandleObject,
mut eval_result: MutableHandleValue,
_can_gc: CanGc,
) -> Result<(), RethrowError> {
let cx = GlobalScope::get_cx();
let _ac = JSAutoRealm::new(*cx, *global.reflector().get_jsobject());
unsafe {
let ok = ModuleEvaluate(*cx, module_record, eval_result.reborrow());
assert!(ok, "module evaluation failed");
rooted!(in(*cx) let mut evaluation_promise = ptr::null_mut::<JSObject>());
if eval_result.is_object() {
evaluation_promise.set(eval_result.to_object());
}
let throw_result = ThrowOnModuleEvaluationFailure(
*cx,
evaluation_promise.handle().into(),
ModuleErrorBehaviour::ThrowModuleErrorsSync,
);
if !throw_result {
warn!("fail to evaluate module");
rooted!(in(*cx) let mut exception = UndefinedValue());
assert!(JS_GetPendingException(*cx, exception.handle_mut()));
JS_ClearPendingException(*cx);
Err(RethrowError(RootedTraceableBox::from_box(Heap::boxed(
exception.get(),
))))
} else {
debug!("module evaluated successfully");
Ok(())
}
}
}
#[expect(unsafe_code)]
pub(crate) fn report_error(&self, global: &GlobalScope, can_gc: CanGc) {
let module_error = self.rethrow_error.borrow();
if let Some(exception) = &*module_error {
let ar = enter_realm(global);
unsafe {
JS_SetPendingException(
*GlobalScope::get_cx(),
exception.handle(),
ExceptionStackBehavior::Capture,
);
}
report_pending_exception(GlobalScope::get_cx(), InRealm::Entered(&ar), can_gc);
}
}
/// <https://html.spec.whatwg.org/multipage/#resolve-a-module-specifier>
pub(crate) fn resolve_module_specifier(
global: &GlobalScope,
script: Option<&ModuleScript>,
specifier: DOMString,
) -> Fallible<ServoUrl> {
// Step 1~3 to get settingsObject and baseURL
let script_global = script.and_then(|s| s.owner.as_ref().map(|o| o.global()));
// Step 1. Let settingsObject and baseURL be null.
let (global, base_url): (&GlobalScope, &ServoUrl) = match script {
// Step 2. If referringScript is not null, then:
// Set settingsObject to referringScript's settings object.
// Set baseURL to referringScript's base URL.
Some(s) => (script_global.as_ref().map_or(global, |g| g), &s.base_url),
// Step 3. Otherwise:
// Set settingsObject to the current settings object.
// Set baseURL to settingsObject's API base URL.
// FIXME(#37553): Is this the correct current settings object?
None => (global, &global.api_base_url()),
};
// Step 4. Let importMap be an empty import map.
// Step 5. If settingsObject's global object implements Window, then set importMap to settingsObject's
// global object's import map.
let import_map = if global.is::<Window>() {
Some(global.import_map())
} else {
None
};
let specifier = &specifier.str();
// Step 6. Let serializedBaseURL be baseURL, serialized.
let serialized_base_url = base_url.as_str();
// Step 7. Let asURL be the result of resolving a URL-like module specifier given specifier and baseURL.
let as_url = Self::resolve_url_like_module_specifier(specifier, base_url);
// Step 8. Let normalizedSpecifier be the serialization of asURL, if asURL is non-null;
// otherwise, specifier.
let normalized_specifier = match &as_url {
Some(url) => url.as_str(),
None => specifier,
};
// Step 9. Let result be a URL-or-null, initially null.
let mut result = None;
if let Some(map) = import_map {
// Step 10. For each scopePrefix → scopeImports of importMap's scopes:
for (prefix, imports) in &map.scopes {
// Step 10.1 If scopePrefix is serializedBaseURL, or if scopePrefix ends with U+002F (/)
// and scopePrefix is a code unit prefix of serializedBaseURL, then:
let prefix = prefix.as_str();
if prefix == serialized_base_url ||
(serialized_base_url.starts_with(prefix) && prefix.ends_with('\u{002f}'))
{
// Step 10.1.1 Let scopeImportsMatch be the result of resolving an imports match
// given normalizedSpecifier, asURL, and scopeImports.
let scope_imports_match =
resolve_imports_match(normalized_specifier, as_url.as_ref(), imports)?;
// Step 10.1.2 If scopeImportsMatch is not null, then set result to scopeImportsMatch, and break.
if scope_imports_match.is_some() {
result = scope_imports_match;
break;
}
}
}
// Step 11. If result is null, set result to the result of resolving an imports match given
// normalizedSpecifier, asURL, and importMap's imports.
if result.is_none() {
result =
resolve_imports_match(normalized_specifier, as_url.as_ref(), &map.imports)?;
}
}
// Step 12. If result is null, set it to asURL.
if result.is_none() {
result = as_url.clone();
}
// Step 13. If result is not null, then:
match result {
Some(result) => {
// Step 13.1 Add module to resolved module set given settingsObject, serializedBaseURL,
// normalizedSpecifier, and asURL.
global.add_module_to_resolved_module_set(
serialized_base_url,
normalized_specifier,
as_url.clone(),
);
// Step 13.2 Return result.
Ok(result)
},
// Step 14. Throw a TypeError indicating that specifier was a bare specifier,
// but was not remapped to anything by importMap.
None => Err(Error::Type(
c"Specifier was a bare specifier, but was not remapped to anything by importMap."
.to_owned(),
)),
}
}
/// <https://html.spec.whatwg.org/multipage/#resolving-a-url-like-module-specifier>
fn resolve_url_like_module_specifier(specifier: &str, base_url: &ServoUrl) -> Option<ServoUrl> {
// Step 1. If specifier starts with "/", "./", or "../", then:
if specifier.starts_with('/') || specifier.starts_with("./") || specifier.starts_with("../")
{
// Step 1.1. Let url be the result of URL parsing specifier with baseURL.
return ServoUrl::parse_with_base(Some(base_url), specifier).ok();
}
// Step 2. Let url be the result of URL parsing specifier (with no base URL).
ServoUrl::parse(specifier).ok()
}
}
#[derive(JSTraceable, MallocSizeOf)]
pub(crate) struct ModuleHandler {
#[ignore_malloc_size_of = "Measuring trait objects is hard"]
task: DomRefCell<Option<Box<dyn NonSendTaskBox>>>,
}
impl ModuleHandler {
pub(crate) fn new_boxed(task: Box<dyn NonSendTaskBox>) -> Box<dyn Callback> {
Box::new(Self {
task: DomRefCell::new(Some(task)),
})
}
}
impl Callback for ModuleHandler {
fn callback(&self, cx: &mut CurrentRealm, _v: HandleValue) {
let task = self.task.borrow_mut().take().unwrap();
task.run_box(cx);
}
}
/// The owner of the module
/// It can be `worker` or `script` element
#[derive(Clone, JSTraceable)]
pub(crate) enum ModuleOwner {
Worker(Trusted<WorkerGlobalScope>),
Window(Trusted<HTMLScriptElement>),
DynamicModule(Trusted<GlobalScope>),
}
impl ModuleOwner {
pub(crate) fn global(&self) -> DomRoot<GlobalScope> {
match &self {
ModuleOwner::Worker(scope) => scope.root().global(),
ModuleOwner::Window(script) => (*script.root()).global(),
ModuleOwner::DynamicModule(dynamic_module) => (*dynamic_module.root()).global(),
}
}
fn notify_owner_to_finish(&self, cx: &mut JSContext, module_tree: Option<Rc<ModuleTree>>) {
match &self {
ModuleOwner::Worker(scope) => {
scope
.root()
.on_complete(cx, module_tree.map(Script::Module));
},
ModuleOwner::DynamicModule(_) => {},
ModuleOwner::Window(script) => {
let script = script.root();
let document = script.owner_document();
let load = match module_tree {
Some(module_tree) => Ok(Script::Module(module_tree)),
None => Err(()),
};
let asynch = script
.upcast::<Element>()
.has_attribute(&local_name!("async"));
if !asynch && script.get_parser_inserted() {
document.deferred_script_loaded(cx, &script, load);
} else if !asynch && !script.get_non_blocking() {
document.asap_in_order_script_loaded(cx, &script, load);
} else {
document.asap_script_loaded(cx, &script, load);
};
},
}
}
}
#[derive(Clone)]
pub(crate) struct ModuleFetchClient {
pub insecure_requests_policy: InsecureRequestsPolicy,
pub has_trustworthy_ancestor_origin: bool,
pub policy_container: PolicyContainer,
pub client: RequestClient,
pub pipeline_id: PipelineId,
pub origin: ImmutableOrigin,
pub https_state: HttpsState,
}
impl ModuleFetchClient {
pub(crate) fn from_global_scope(global: &GlobalScope) -> Self {
Self {
insecure_requests_policy: global.insecure_requests_policy(),
has_trustworthy_ancestor_origin: global.has_trustworthy_ancestor_or_current_origin(),
policy_container: global.policy_container(),
client: global.request_client(),
pipeline_id: global.pipeline_id(),
origin: global.origin().immutable().clone(),
https_state: global.get_https_state(),
}
}
}
/// The context required for asynchronously loading an external module script source.
struct ModuleContext {
/// The owner of the module that initiated the request.
owner: ModuleOwner,
/// The response body received to date.
data: Vec<u8>,
/// The response metadata received to date.
metadata: Option<Metadata>,
/// Url and type of the requested module.
module_request: ModuleRequest,
/// Options for the current script fetch
options: ScriptFetchOptions,
/// Indicates whether the request failed, and why
status: Result<(), NetworkError>,
/// `introductionType` value to set in the `CompileOptionsWrapper`.
introduction_type: Option<&'static CStr>,
/// <https://html.spec.whatwg.org/multipage/#policy-container>
policy_container: Option<PolicyContainer>,
}
impl FetchResponseListener for ModuleContext {
// TODO(cybai): Perhaps add custom steps to perform fetch here?
fn process_request_body(&mut self, _: RequestId) {}
fn process_response(
&mut self,
_: &mut js::context::JSContext,
_: RequestId,
metadata: Result<FetchMetadata, NetworkError>,
) {
self.metadata = metadata.ok().map(|meta| match meta {
FetchMetadata::Unfiltered(m) => m,
FetchMetadata::Filtered { unsafe_, .. } => unsafe_,
});
let status = self
.metadata
.as_ref()
.map(|m| m.status.clone())
.unwrap_or_else(HttpStatus::new_error);
self.status = {
if status.is_error() {
Err(NetworkError::ResourceLoadError(
"No http status code received".to_owned(),
))
} else if status.is_success() {
Ok(())
} else {
Err(NetworkError::ResourceLoadError(format!(
"HTTP error code {}",
status.code()
)))
}
};
}
fn process_response_chunk(
&mut self,
_: &mut js::context::JSContext,
_: RequestId,
mut chunk: Vec<u8>,
) {
if self.status.is_ok() {
self.data.append(&mut chunk);
}
}
/// <https://html.spec.whatwg.org/multipage/#fetch-a-single-module-script>
/// Step 13
fn process_response_eof(
mut self,
cx: &mut js::context::JSContext,
_: RequestId,
response: Result<(), NetworkError>,
timing: ResourceFetchTiming,
) {
let global = self.owner.global();
let (url, module_type) = &self.module_request;
if let ModuleOwner::Window(_) = self.owner {
let window = global.downcast::<Window>().unwrap();
window
.Document()
.finish_load(LoadType::Script(url.clone()), cx);
}
network_listener::submit_timing(cx, &self, &response, &timing);
let Some(ModuleStatus::Fetching(pending)) =
global.get_module_map_entry(&self.module_request)
else {
return error!("Processing response for a non pending module request");
};
let promise = pending
.borrow_mut()
.take()
.expect("Need promise to process response");
// Step 1. If any of the following are true: bodyBytes is null or failure; or response's status is not an ok status,
// then set moduleMap[(url, moduleType)] to null, run onComplete given null, and abort these steps.
if let (Err(error), _) | (_, Err(error)) = (response.as_ref(), self.status.as_ref()) {
error!("Fetching module script failed {:?}", error);
global.set_module_map(self.module_request, ModuleStatus::Loaded(None));
return promise.resolve_native(&(), CanGc::from_cx(cx));
}
let metadata = self.metadata.take().unwrap();
// The processResponseConsumeBody steps defined inside
// [run a worker](https://html.spec.whatwg.org/multipage/#run-a-worker)
if let Some(policy_container) = self.policy_container {
let workerscope = global.downcast::<WorkerGlobalScope>().expect(
"We only need a policy container when initializing a worker's globalscope.",
);
workerscope.process_response_for_workerscope(&metadata, &policy_container);
}
let final_url = metadata.final_url;
// Step 2. Let mimeType be the result of extracting a MIME type from response's header list.
let mime_type: Option<Mime> = metadata.content_type.map(Serde::into_inner).map(Into::into);
// Step 3. Let moduleScript be null.
let mut module_script = None;
// Step 4. Let referrerPolicy be the result of parsing the `Referrer-Policy` header given response. [REFERRERPOLICY]
let referrer_policy = metadata
.headers
.and_then(|headers| headers.typed_get::<ReferrerPolicyHeader>())
.into();
// Step 5. If referrerPolicy is not the empty string, set options's referrer policy to referrerPolicy.
if referrer_policy != ReferrerPolicy::EmptyString {
self.options.referrer_policy = referrer_policy;
}
// TODO Step 6. If mimeType's essence is "application/wasm" and moduleType is "javascript-or-wasm", then set
// moduleScript to the result of creating a WebAssembly module script given bodyBytes, settingsObject, response's URL, and options.
// TODO handle CSS module scripts on the next mozjs ESR bump.
if let Some(mime) = mime_type {
// Step 7.1 Let sourceText be the result of UTF-8 decoding bodyBytes.
let (mut source_text, _) = UTF_8.decode_with_bom_removal(&self.data);
// Step 7.2 If mimeType is a JavaScript MIME type and moduleType is "javascript-or-wasm", then set moduleScript
// to the result of creating a JavaScript module script given sourceText, settingsObject, response's URL, and options.
if SCRIPT_JS_MIMES.contains(&mime.essence_str()) &&
matches!(module_type, ModuleType::JavaScript)
{
if let Some(window) = global.downcast::<Window>() {
substitute_with_local_script(window, &mut source_text, final_url.clone());
}
let module_tree = Rc::new(ModuleTree::create_a_javascript_module_script(
Rc::new(DOMString::from(source_text.clone())),
self.owner.clone(),
&final_url,
self.options,
true,
1,
self.introduction_type,
CanGc::from_cx(cx),
));
module_script = Some(module_tree);
}
// Step 7.4 If mimeType is a JSON MIME type and moduleType is "json",
// then set moduleScript to the result of creating a JSON module script given sourceText and settingsObject.
if MimeClassifier::is_json(&mime) && matches!(module_type, ModuleType::JSON) {
let module_tree = Rc::new(ModuleTree::create_a_json_module_script(
&source_text,
&global,
&final_url,
self.introduction_type,
CanGc::from_cx(cx),
));
module_script = Some(module_tree);
}
}
// Step 8. Set moduleMap[(url, moduleType)] to moduleScript, and run onComplete given moduleScript.
global.set_module_map(self.module_request, ModuleStatus::Loaded(module_script));
promise.resolve_native(&(), CanGc::from_cx(cx));
}
fn process_csp_violations(&mut self, _request_id: RequestId, violations: Vec<Violation>) {
match &self.owner {
ModuleOwner::Worker(scope) => {
if let Some(scope) = scope.root().downcast::<DedicatedWorkerGlobalScope>() {
scope.report_csp_violations(violations);
}
},
_ => {
let global = &self.resource_timing_global();
global.report_csp_violations(violations, None, None);
},
};
}
}
impl ResourceTimingListener for ModuleContext {
fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
let initiator_type = InitiatorType::LocalName("module".to_string());
let (url, _) = &self.module_request;
(initiator_type, url.clone())
}
fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
self.owner.global()
}
}
#[expect(unsafe_code)]
#[expect(non_snake_case)]
/// A function to register module hooks (e.g. listening on resolving modules,
/// getting module metadata, getting script private reference and resolving dynamic import)
pub(crate) unsafe fn EnsureModuleHooksInitialized(rt: *mut JSRuntime) {
unsafe {
if GetModuleResolveHook(rt).is_some() {
return;
}
SetModuleResolveHook(rt, Some(HostResolveImportedModule));
SetModuleMetadataHook(rt, Some(HostPopulateImportMeta));
SetScriptPrivateReferenceHooks(
rt,
Some(host_add_ref_top_level_script),
Some(host_release_top_level_script),
);
SetModuleDynamicImportHook(rt, Some(host_import_module_dynamically));
}
}
#[expect(unsafe_code)]
unsafe extern "C" fn host_add_ref_top_level_script(value: *const Value) {
let val = unsafe { Rc::from_raw((*value).to_private() as *const ModuleScript) };
mem::forget(val.clone());
mem::forget(val);
}
#[expect(unsafe_code)]
unsafe extern "C" fn host_release_top_level_script(value: *const Value) {
let _val = unsafe { Rc::from_raw((*value).to_private() as *const ModuleScript) };
}
#[expect(unsafe_code)]
/// <https://tc39.es/ecma262/#sec-hostimportmoduledynamically>
/// <https://html.spec.whatwg.org/multipage/#hostimportmoduledynamically(referencingscriptormodule,-specifier,-promisecapability)>
pub(crate) unsafe extern "C" fn host_import_module_dynamically(
cx: *mut RawJSContext,
reference_private: RawHandleValue,
specifier: RawHandle<*mut JSObject>,
promise: RawHandle<*mut JSObject>,
) -> bool {
// Safety: it is safe to construct a JSContext from engine hook.
let mut cx = unsafe { JSContext::from_ptr(NonNull::new(cx).unwrap()) };
let cx = &mut cx;
let promise = Promise::new_with_js_promise(unsafe { Handle::from_raw(promise) }, cx.into());
let jsstr = unsafe { GetModuleRequestSpecifier(cx, Handle::from_raw(specifier)) };
let module_type = unsafe { GetModuleRequestType(cx, Handle::from_raw(specifier)) };
let specifier = unsafe { jsstr_to_string(cx.raw_cx(), NonNull::new(jsstr).unwrap()) };
let mut realm = CurrentRealm::assert(cx);
let payload = Payload::PromiseRecord(promise);
host_load_imported_module(
&mut realm,
None,
reference_private,
specifier,
module_type,
None,
payload,
);
true
}
#[derive(Clone, Debug, JSTraceable, MallocSizeOf)]
/// <https://html.spec.whatwg.org/multipage/#script-fetch-options>
pub(crate) struct ScriptFetchOptions {
pub(crate) integrity_metadata: String,
#[no_trace]
pub(crate) credentials_mode: CredentialsMode,
pub(crate) cryptographic_nonce: String,
#[no_trace]
pub(crate) parser_metadata: ParserMetadata,
#[no_trace]
pub(crate) referrer_policy: ReferrerPolicy,
}
impl ScriptFetchOptions {
/// <https://html.spec.whatwg.org/multipage/#default-classic-script-fetch-options>
pub(crate) fn default_classic_script() -> ScriptFetchOptions {
Self {
cryptographic_nonce: String::new(),
integrity_metadata: String::new(),
parser_metadata: ParserMetadata::NotParserInserted,