Skip to main content

script/dom/html/scripting/
htmlscriptelement.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::borrow::Cow;
6use std::cell::Cell;
7use std::ffi::CStr;
8use std::fs::read_to_string;
9use std::path::PathBuf;
10use std::rc::Rc;
11use std::sync::Arc;
12
13use bytes::{Bytes, BytesMut};
14use dom_struct::dom_struct;
15use encoding_rs::Encoding;
16use html5ever::{LocalName, Prefix, local_name};
17use js::context::JSContext;
18use js::offthread::compile_to_stencil_offthread;
19use js::rust::HandleObject;
20use net_traits::blob_url_store::UrlWithBlobClaim;
21use net_traits::request::{
22    CorsSettings, Destination, ParserMetadata, Referrer, RequestBuilder, RequestId,
23};
24use net_traits::{FetchMetadata, Metadata, NetworkError, ResourceFetchTiming};
25use pixels::CorsStatus;
26use script_bindings::cell::DomRefCell;
27use script_bindings::domstring::{DOMString, TracedDOMString};
28use script_bindings::trace::RootedTraceableBox;
29use servo_base::id::WebViewId;
30use servo_config::pref;
31use servo_url::ServoUrl;
32use style::attr::AttrValue;
33use style::str::{HTML_SPACE_CHARACTERS, StaticStringVec};
34use stylo_atoms::Atom;
35
36use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
37use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
38use crate::dom::bindings::codegen::Bindings::HTMLScriptElementBinding::HTMLScriptElementMethods;
39use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
40use crate::dom::bindings::codegen::UnionTypes::{
41    TrustedScriptOrString, TrustedScriptURLOrUSVString,
42};
43use crate::dom::bindings::error::Fallible;
44use crate::dom::bindings::inheritance::Castable;
45use crate::dom::bindings::refcounted::Trusted;
46use crate::dom::bindings::reflector::DomGlobal;
47use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
48use crate::dom::csp::{CspReporting, GlobalCspReporting, InlineCheckType, Violation};
49use crate::dom::document::Document;
50use crate::dom::domtokenlist::DOMTokenList;
51use crate::dom::element::attributes::storage::AttrRef;
52use crate::dom::element::{
53    AttributeMutation, Element, ElementCreator, cors_setting_for_element,
54    cors_settings_attribute_credential_mode, referrer_policy_for_element,
55    reflect_cross_origin_attribute, reflect_referrer_policy_attribute, set_cross_origin_attribute,
56};
57use crate::dom::event::eventtarget::EventTarget;
58use crate::dom::globalscope::GlobalScope;
59use crate::dom::html::htmlelement::HTMLElement;
60use crate::dom::node::virtualmethods::VirtualMethods;
61use crate::dom::node::{ChildrenMutation, CloneChildrenFlag, Node, NodeTraits, UnbindContext};
62use crate::dom::performance::performanceresourcetiming::InitiatorType;
63use crate::dom::trustedtypes::trustedscript::TrustedScript;
64use crate::dom::trustedtypes::trustedscripturl::TrustedScriptURL;
65use crate::dom::window::Window;
66use crate::event_loop::document_loader::{LoadBlocker, LoadType};
67use crate::fetch::fetch::{RequestWithGlobalScope, create_a_potential_cors_request_with_claim};
68use crate::fetch::network_listener::{self, FetchResponseListener, ResourceTimingListener};
69use crate::runtime::script_runtime::IntroductionType;
70use crate::scripting::fetching_options::ScriptFetchOptions;
71use crate::scripting::import_map::{ImportMap, parse_an_import_map_string, register_import_map};
72use crate::scripting::script_execution::{
73    ClassicScript, RethrowErrors, ScriptOptions, fill_compile_options,
74};
75use crate::scripting::script_module::{
76    ModuleTree, fetch_an_external_module_script, fetch_inline_module_script,
77};
78use crate::url::ensure_blob_referenced_by_url_is_kept_alive;
79
80#[dom_struct]
81pub(crate) struct HTMLScriptElement {
82    htmlelement: HTMLElement,
83
84    /// <https://html.spec.whatwg.org/multipage/#concept-script-delay-load>
85    delaying_the_load_event: DomRefCell<Option<LoadBlocker>>,
86
87    /// <https://html.spec.whatwg.org/multipage/#already-started>
88    already_started: Cell<bool>,
89
90    /// <https://html.spec.whatwg.org/multipage/#parser-inserted>
91    parser_inserted: Cell<bool>,
92
93    /// <https://html.spec.whatwg.org/multipage/#non-blocking>
94    ///
95    /// (currently unused)
96    non_blocking: Cell<bool>,
97
98    /// Document of the parser that created this element
99    /// <https://html.spec.whatwg.org/multipage/#parser-document>
100    parser_document: Dom<Document>,
101
102    /// Prevents scripts that move between documents during preparation from executing.
103    /// <https://html.spec.whatwg.org/multipage/#preparation-time-document>
104    preparation_time_document: MutNullableDom<Document>,
105
106    /// Track line line_number
107    line_number: u64,
108
109    /// <https://w3c.github.io/trusted-types/dist/spec/#htmlscriptelement-script-text>
110    script_text: DomRefCell<TracedDOMString>,
111
112    /// <https://html.spec.whatwg.org/multipage/#concept-script-external>
113    from_an_external_file: Cell<bool>,
114
115    /// <https://html.spec.whatwg.org/multipage/#dom-script-blocking>
116    blocking: MutNullableDom<DOMTokenList>,
117
118    /// Used to keep track whether we consider this script element render blocking during
119    /// `prepare`
120    marked_as_render_blocking: Cell<bool>,
121
122    /// <https://html.spec.whatwg.org/multipage/#concept-script-result>
123    result: DomRefCell<Option<TracedScriptResult>>,
124}
125
126impl HTMLScriptElement {
127    fn new_inherited(
128        local_name: LocalName,
129        prefix: Option<Prefix>,
130        document: &Document,
131        creator: ElementCreator,
132    ) -> HTMLScriptElement {
133        HTMLScriptElement {
134            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
135            already_started: Cell::new(false),
136            delaying_the_load_event: Default::default(),
137            parser_inserted: Cell::new(creator.is_parser_created()),
138            non_blocking: Cell::new(!creator.is_parser_created()),
139            parser_document: Dom::from_ref(document),
140            preparation_time_document: MutNullableDom::new(None),
141            line_number: creator.return_line_number(),
142            script_text: Default::default(),
143            from_an_external_file: Cell::new(false),
144            blocking: Default::default(),
145            marked_as_render_blocking: Default::default(),
146            result: DomRefCell::new(None),
147        }
148    }
149
150    pub(crate) fn new(
151        cx: &mut JSContext,
152        local_name: LocalName,
153        prefix: Option<Prefix>,
154        document: &Document,
155        proto: Option<HandleObject>,
156        creator: ElementCreator,
157    ) -> DomRoot<HTMLScriptElement> {
158        Node::reflect_node_with_proto(
159            cx,
160            Box::new(HTMLScriptElement::new_inherited(
161                local_name, prefix, document, creator,
162            )),
163            document,
164            proto,
165        )
166    }
167
168    /// Marks that element as delaying the load event or not.
169    ///
170    /// <https://html.spec.whatwg.org/multipage/#concept-script-delay-load>
171    /// <https://html.spec.whatwg.org/multipage/#delaying-the-load-event-flag>
172    fn delay_load_event(&self, document: &Document, url: ServoUrl) {
173        debug_assert!(self.delaying_the_load_event.borrow().is_none());
174
175        *self.delaying_the_load_event.borrow_mut() =
176            Some(LoadBlocker::new(document, LoadType::Script(url)));
177    }
178
179    /// Helper method to determine the script kind based on attributes and insertion context.
180    ///
181    /// This duplicates the script preparation logic from the HTML spec to determine the
182    /// script's active document without full preparation.
183    ///
184    /// <https://html.spec.whatwg.org/multipage/#prepare-the-script-element>
185    fn get_script_kind(&self, script_type: ScriptType) -> ExternalScriptKind {
186        let element = self.upcast::<Element>();
187
188        if element.has_attribute(&local_name!("async")) || self.non_blocking.get() {
189            ExternalScriptKind::Asap
190        } else if !self.parser_inserted.get() {
191            ExternalScriptKind::AsapInOrder
192        } else if element.has_attribute(&local_name!("defer")) || script_type == ScriptType::Module
193        {
194            ExternalScriptKind::Deferred
195        } else {
196            ExternalScriptKind::ParsingBlocking
197        }
198    }
199
200    /// <https://html.spec.whatwg.org/multipage/#prepare-the-script-element>
201    fn get_script_active_document(&self, script_kind: ExternalScriptKind) -> DomRoot<Document> {
202        match script_kind {
203            ExternalScriptKind::Asap => self.preparation_time_document.get().unwrap(),
204            ExternalScriptKind::AsapInOrder => self.preparation_time_document.get().unwrap(),
205            ExternalScriptKind::Deferred => self.parser_document.as_rooted(),
206            ExternalScriptKind::ParsingBlocking => self.parser_document.as_rooted(),
207        }
208    }
209
210    /// <https://html.spec.whatwg.org/multipage/#steps-to-run-when-the-result-is-ready>
211    fn finish_fetching_a_script(&self, cx: &mut JSContext, script_kind: ExternalScriptKind) {
212        let load = self
213            .result
214            .take()
215            .map(|result| result.map(Into::into))
216            .expect("Result must be ready to proceed");
217
218        // Step 2. If el's steps to run when the result is ready are not null, then run them.
219        match script_kind {
220            ExternalScriptKind::Asap => {
221                let document = self.preparation_time_document.get().unwrap();
222                document.asap_script_loaded(cx, self, load)
223            },
224            ExternalScriptKind::AsapInOrder => {
225                let document = self.preparation_time_document.get().unwrap();
226                document.asap_in_order_script_loaded(cx, self, load)
227            },
228            ExternalScriptKind::Deferred => {
229                let document = self.parser_document.as_rooted();
230                document.deferred_script_loaded(cx, self, load);
231            },
232            ExternalScriptKind::ParsingBlocking => {
233                let document = self.parser_document.as_rooted();
234                document.pending_parsing_blocking_script_loaded(self, load, cx);
235            },
236        }
237
238        // Step 4. Set el's delaying the load event to false.
239        LoadBlocker::terminate(cx, &self.delaying_the_load_event);
240    }
241}
242
243/// Supported script types as defined by
244/// <https://html.spec.whatwg.org/multipage/#javascript-mime-type>.
245pub(crate) static SCRIPT_JS_MIMES: StaticStringVec = &[
246    "application/ecmascript",
247    "application/javascript",
248    "application/x-ecmascript",
249    "application/x-javascript",
250    "text/ecmascript",
251    "text/javascript",
252    "text/javascript1.0",
253    "text/javascript1.1",
254    "text/javascript1.2",
255    "text/javascript1.3",
256    "text/javascript1.4",
257    "text/javascript1.5",
258    "text/jscript",
259    "text/livescript",
260    "text/x-ecmascript",
261    "text/x-javascript",
262];
263
264#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
265pub(crate) enum ScriptType {
266    Classic,
267    Module,
268    ImportMap,
269}
270
271#[derive(JSTraceable, MallocSizeOf)]
272#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
273pub(crate) enum TracedScript {
274    Classic(Box<ClassicScript>),
275    Module(#[conditional_malloc_size_of] Rc<ModuleTree>),
276}
277
278#[expect(clippy::large_enum_variant)]
279pub(crate) enum Script {
280    Classic(RootedTraceableBox<ClassicScript>),
281    Module(RootedTraceableBox<Rc<ModuleTree>>),
282    ImportMap(Fallible<ImportMap>),
283}
284
285pub(crate) type TracedScriptResult = Result<TracedScript, ()>;
286pub(crate) type ScriptResult = Result<Script, ()>;
287
288impl From<Script> for TracedScript {
289    fn from(value: Script) -> Self {
290        match value {
291            Script::Classic(classic) => TracedScript::Classic(classic.into_box()),
292            Script::Module(module) => TracedScript::Module(*module.into_box()),
293            Script::ImportMap(_) => {
294                unreachable!("Import maps are executed immediately, traced variant is not needed")
295            },
296        }
297    }
298}
299
300impl From<TracedScript> for Script {
301    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
302    fn from(value: TracedScript) -> Self {
303        match value {
304            TracedScript::Classic(classic) => {
305                Script::Classic(RootedTraceableBox::from_box(classic))
306            },
307            TracedScript::Module(module) => Script::Module(RootedTraceableBox::new(module)),
308        }
309    }
310}
311
312/// The context required for asynchronously loading an external script source.
313struct ClassicContext {
314    /// The element that initiated the request.
315    elem: Trusted<HTMLScriptElement>,
316    /// The kind of external script.
317    kind: ExternalScriptKind,
318    /// The (fallback) character encoding argument to the "fetch a classic
319    /// script" algorithm.
320    character_encoding: &'static Encoding,
321    /// The response body received to date.
322    data: BytesMut,
323    /// The response metadata received to date.
324    metadata: Option<Metadata>,
325    /// The initial URL requested.
326    url: UrlWithBlobClaim,
327    /// Indicates whether the request failed, and why
328    status: Result<(), NetworkError>,
329    /// The fetch options of the script
330    fetch_options: ScriptFetchOptions,
331    /// Used to set muted errors flag of classic scripts
332    response_was_cors_cross_origin: bool,
333}
334
335impl FetchResponseListener for ClassicContext {
336    // TODO(KiChjang): Perhaps add custom steps to perform fetch here?
337    fn process_request_body(&mut self, _: &GlobalScope, _: RequestId) {}
338
339    fn process_response(
340        &mut self,
341        _: &mut JSContext,
342        _: &GlobalScope,
343        _: RequestId,
344        metadata: Result<FetchMetadata, NetworkError>,
345    ) {
346        self.metadata = metadata.ok().map(|metadata| {
347            self.response_was_cors_cross_origin = metadata.cors_status() == CorsStatus::Unsafe;
348            metadata.into()
349        });
350
351        self.status = network_listener::check_response_status(self.metadata.as_ref());
352    }
353
354    fn process_response_chunk(
355        &mut self,
356        _: &mut JSContext,
357        _: &GlobalScope,
358        _: RequestId,
359        chunk: Bytes,
360    ) {
361        if self.status.is_ok() {
362            self.data.extend_from_slice(&chunk);
363        }
364    }
365
366    /// <https://html.spec.whatwg.org/multipage/#fetch-a-classic-script>
367    /// step 4-9
368    fn process_response_eof(
369        mut self,
370        cx: &mut JSContext,
371        global: &GlobalScope,
372        _: RequestId,
373        response: Result<(), NetworkError>,
374        timing: ResourceFetchTiming,
375    ) {
376        // Resource timing is expected to be available before "error" or "load" events are fired.
377        network_listener::submit_timing(cx, global, &self, &response, &timing);
378
379        let elem = self.elem.root();
380
381        match (response.as_ref(), self.status.as_ref()) {
382            (Err(error), _) | (_, Err(error)) => {
383                error!(
384                    "Fetching classic script failed {:?} ({:?})",
385                    error, self.url
386                );
387                // Step 6, response is an error.
388                *elem.result.borrow_mut() = Some(Err(()));
389                elem.finish_fetching_a_script(cx, self.kind);
390                return;
391            },
392            _ => {},
393        };
394
395        let metadata = self.metadata.take().unwrap();
396        let final_url = metadata.final_url;
397
398        // Step 5.3. Let potentialMIMETypeForEncoding be the result of extracting a MIME type given response's header list.
399        // Step 5.4. Set encoding to the result of legacy extracting an encoding given potentialMIMETypeForEncoding and encoding.
400        let encoding = metadata
401            .charset
402            .and_then(|encoding| Encoding::for_label(encoding.as_bytes()))
403            .unwrap_or(self.character_encoding);
404
405        // Step 5.5. Let sourceText be the result of decoding bodyBytes to Unicode, using encoding as the fallback encoding.
406        let (mut source_text, _, _) = encoding.decode(&self.data);
407
408        let global = elem.global();
409
410        if let Some(window) = global.downcast::<Window>() &&
411            let Some(script_source) = window.local_script_source()
412        {
413            substitute_with_local_script(script_source, &mut source_text, &final_url);
414        }
415
416        // Step 5.6. Let mutedErrors be true if response was CORS-cross-origin, and false otherwise.
417        let mut script_options = ScriptOptions::External;
418        script_options.set(
419            ScriptOptions::MutedErrors,
420            self.response_was_cors_cross_origin,
421        );
422
423        let fetch_options = self.fetch_options.clone();
424
425        if pref!(dom_script_asynch) {
426            let options = fill_compile_options(
427                cx,
428                final_url.as_str(),
429                script_options,
430                Some(IntroductionType::SRC_SCRIPT),
431                1,
432            );
433
434            let src = Arc::new(source_text.to_string());
435
436            let task_source = global
437                .task_manager()
438                .dom_manipulation_task_source()
439                .to_sendable();
440
441            let trusted = self.elem.clone();
442
443            let _offthread_token = compile_to_stencil_offthread(options.ptr, src, move |result| {
444                task_source.queue(task!(instantiate_stencil: move |cx| {
445                    let script_element = trusted.root();
446
447                    let script = ClassicScript::from_stencil(
448                        cx,
449                        result,
450                        final_url,
451                        script_options,
452                        fetch_options,
453                    );
454
455                    let load = Script::Classic(script);
456                    *script_element.result.borrow_mut() = Some(Ok(load.into()));
457                    script_element.finish_fetching_a_script(cx, self.kind);
458                }));
459
460                None
461            });
462
463            return;
464        }
465
466        // Step 5.7. Let script be the result of creating a classic script given
467        // sourceText, settingsObject, response's URL, options, mutedErrors, and url.
468        let script = global.create_a_classic_script(
469            cx,
470            source_text,
471            final_url,
472            script_options,
473            fetch_options,
474            Some(IntroductionType::SRC_SCRIPT),
475            1,
476        );
477
478        let load = Script::Classic(script);
479        *elem.result.borrow_mut() = Some(Ok(load.into()));
480        elem.finish_fetching_a_script(cx, self.kind);
481    }
482
483    fn process_csp_violations(
484        &mut self,
485        cx: &mut JSContext,
486        global: &GlobalScope,
487        _request_id: RequestId,
488        violations: Vec<Violation>,
489    ) {
490        let elem = self.elem.root();
491        global.report_csp_violations(cx, violations, Some(elem.upcast()), None);
492    }
493
494    fn process_content_length(&mut self, _request_id: RequestId, size: usize) {
495        self.data.reserve(size.saturating_sub(self.data.len()));
496    }
497}
498
499impl ResourceTimingListener for ClassicContext {
500    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
501        let initiator_type =
502            InitiatorType::LocalName(self.elem.root().upcast::<Element>().local_name().clone());
503        (initiator_type, self.url.url())
504    }
505}
506
507/// Steps 1-2 of <https://html.spec.whatwg.org/multipage/#fetch-a-classic-script>
508// This function is also used to prefetch a script in `script::dom::servoparser::prefetch`.
509#[allow(clippy::too_many_arguments)]
510pub(crate) fn script_fetch_request(
511    webview_id: WebViewId,
512    url: UrlWithBlobClaim,
513    cors_setting: Option<CorsSettings>,
514    options: ScriptFetchOptions,
515    referrer: Referrer,
516) -> RequestBuilder {
517    // We intentionally ignore options' credentials_mode member for classic scripts.
518    // The mode is initialized by create_a_potential_cors_request.
519    create_a_potential_cors_request_with_claim(
520        Some(webview_id),
521        url,
522        Destination::Script,
523        cors_setting,
524        None,
525        referrer,
526    )
527    .parser_metadata(options.parser_metadata)
528    .integrity_metadata(options.integrity_metadata.clone())
529    .referrer_policy(options.referrer_policy)
530    .cryptographic_nonce_metadata(options.cryptographic_nonce)
531}
532
533/// <https://html.spec.whatwg.org/multipage/#fetch-a-classic-script>
534fn fetch_a_classic_script(
535    script: &HTMLScriptElement,
536    kind: ExternalScriptKind,
537    url: UrlWithBlobClaim,
538    cors_setting: Option<CorsSettings>,
539    options: ScriptFetchOptions,
540    character_encoding: &'static Encoding,
541) {
542    // Step 1, 2.
543    let doc = script.owner_document();
544    let global = script.global();
545    let referrer = global.get_referrer();
546    let request = script_fetch_request(
547        doc.webview_id(),
548        url.clone(),
549        cors_setting,
550        options.clone(),
551        referrer,
552    )
553    .with_global_scope(&global);
554
555    // TODO: Step 3, Add custom steps to perform fetch
556
557    let context = ClassicContext {
558        elem: Trusted::new(script),
559        kind,
560        character_encoding,
561        data: BytesMut::new(),
562        metadata: None,
563        url,
564        status: Ok(()),
565        fetch_options: options,
566        response_was_cors_cross_origin: false,
567    };
568    doc.fetch_background(request, context);
569}
570
571impl HTMLScriptElement {
572    /// <https://w3c.github.io/trusted-types/dist/spec/#setting-slot-values-from-parser>
573    pub(crate) fn set_initial_script_text(&self) {
574        *self.script_text.borrow_mut() = self.text().traced();
575    }
576
577    /// <https://w3c.github.io/trusted-types/dist/spec/#prepare-script-text>
578    fn prepare_the_script_text(&self, cx: &mut JSContext) -> Fallible<()> {
579        // Step 1. If script’s script text value is not equal to its child text content,
580        // set script’s script text to the result of executing
581        // Get Trusted Type compliant string, with the following arguments:
582        if *self.script_text.borrow() != *self.text() {
583            let result = TrustedScript::get_trusted_type_compliant_string(
584                cx,
585                &self.owner_global(),
586                self.Text(),
587                "HTMLScriptElement text",
588            )?;
589            *self.script_text.safe_borrow_mut(cx.no_gc()) = result.traced();
590        }
591
592        Ok(())
593    }
594
595    fn has_render_blocking_attribute(&self) -> bool {
596        self.blocking
597            .get()
598            .is_some_and(|list| list.Contains(DOMString::from_static("render")))
599    }
600
601    /// <https://html.spec.whatwg.org/multipage/#potentially-render-blocking>
602    fn potentially_render_blocking(&self, script_type: ScriptType) -> bool {
603        // An element is potentially render-blocking if its blocking tokens set contains "render",
604        // or if it is implicitly potentially render-blocking, which will be defined at the individual elements.
605        // By default, an element is not implicitly potentially render-blocking.
606        if self.has_render_blocking_attribute() {
607            return true;
608        }
609        let element = self.upcast::<Element>();
610        // https://html.spec.whatwg.org/multipage/#script-processing-model:implicitly-potentially-render-blocking
611        // > A script element el is implicitly potentially render-blocking if el's type is "classic",
612        // > el is parser-inserted, and el does not have an async or defer attribute.
613        script_type == ScriptType::Classic &&
614            self.parser_inserted.get() &&
615            !element.has_attribute(&local_name!("async")) &&
616            !element.has_attribute(&local_name!("defer"))
617    }
618
619    /// <https://html.spec.whatwg.org/multipage/#prepare-the-script-element>
620    pub(crate) fn prepare(
621        &self,
622        cx: &mut JSContext,
623        introduction_type_override: Option<&'static CStr>,
624    ) {
625        let introduction_type =
626            introduction_type_override.or(Some(IntroductionType::INLINE_SCRIPT));
627
628        // Step 1. If el's already started is true, then return.
629        if self.already_started.get() {
630            return;
631        }
632
633        // Step 2. Let parser document be el's parser document.
634        // TODO
635
636        // Step 3. Set el's parser document to null.
637        let was_parser_inserted = self.parser_inserted.get();
638        self.parser_inserted.set(false);
639
640        // Step 4.
641        // If parser document is non-null and el does not have an async attribute, then set el's force async to true.
642        let element = self.upcast::<Element>();
643        let asynch = element.has_attribute(&local_name!("async"));
644        // Note: confusingly, this is done if the element does *not* have an "async" attribute.
645        if was_parser_inserted && !asynch {
646            self.non_blocking.set(true);
647        }
648
649        // Step 5. Execute the Prepare the script text algorithm on el.
650        // If that algorithm threw an error, then return.
651        if self.prepare_the_script_text(cx).is_err() {
652            return;
653        }
654        // Step 5a. Let source text be el’s script text value.
655        let text: Cow<'_, str> = Cow::Owned(String::from(self.script_text.borrow().str()));
656        // Step 6. If el has no src attribute, and source text is the empty string, then return.
657        if text.is_empty() && !element.has_attribute(&local_name!("src")) {
658            return;
659        }
660
661        // Step 7. If el is not connected, then return.
662        if !self.upcast::<Node>().is_connected() {
663            return;
664        }
665
666        let Some(script_type) = self.script_type() else {
667            // Step 12. Otherwise, return. (No script is executed, and el's type is left as null.)
668            return;
669        };
670
671        // Step 13.
672        // If parser document is non-null, then set el's parser document back to parser document and set el's force
673        // async to false.
674        if was_parser_inserted {
675            self.parser_inserted.set(true);
676            self.non_blocking.set(false);
677        }
678
679        // Step 14. Set el's already started to true.
680        self.already_started.set(true);
681
682        // Step 15. Set el's preparation-time document to its node document.
683        let doc = self.owner_document();
684        self.preparation_time_document.set(Some(&doc));
685
686        // Step 16.
687        // If parser document is non-null, and parser document is not equal to el's preparation-time document, then
688        // return.
689        if self.parser_inserted.get() && *self.parser_document != *doc {
690            return;
691        }
692
693        // Step 17. If scripting is disabled for el, then return.
694        if !doc.scripting_enabled() {
695            return;
696        }
697
698        // Step 18. If el has a nomodule content attribute and its type is "classic", then return.
699        if element.has_attribute(&local_name!("nomodule")) && script_type == ScriptType::Classic {
700            return;
701        }
702
703        let global = &doc.global();
704
705        // Step 19. CSP.
706        if !element.has_attribute(&local_name!("src")) &&
707            global.call_on_csp_list(|csp_list| {
708                csp_list.should_elements_inline_type_behavior_be_blocked(
709                    cx,
710                    global,
711                    element,
712                    InlineCheckType::Script,
713                    &text,
714                    self.line_number as u32,
715                )
716            })
717        {
718            warn!("Blocking inline script due to CSP");
719            return;
720        }
721
722        // Step 20. If el has an event attribute and a for attribute, and el's type is "classic", then:
723        if script_type == ScriptType::Classic {
724            let for_attribute = element.get_attribute_string_value(&local_name!("for"));
725            let event_attribute = element.get_attribute_string_value(&local_name!("event"));
726            if let (Some(for_attribute), Some(event_attribute)) = (for_attribute, event_attribute) {
727                let for_value = for_attribute.trim_matches(HTML_SPACE_CHARACTERS);
728                if !for_value.eq_ignore_ascii_case("window") {
729                    return;
730                }
731
732                let event_value = event_attribute.trim_matches(HTML_SPACE_CHARACTERS);
733                if !event_value.eq_ignore_ascii_case("onload") &&
734                    !event_value.eq_ignore_ascii_case("onload()")
735                {
736                    return;
737                }
738            }
739        }
740
741        // Step 21. If el has a charset attribute, then let encoding be the result of getting
742        // an encoding from the value of the charset attribute.
743        // If el does not have a charset attribute, or if getting an encoding failed,
744        // then let encoding be el's node document's the encoding.
745        let encoding = element
746            .get_attribute_string_value(&local_name!("charset"))
747            .and_then(|charset| Encoding::for_label(charset.as_bytes()))
748            .unwrap_or_else(|| doc.encoding());
749
750        // Step 22. CORS setting.
751        let cors_setting = cors_setting_for_element(element);
752
753        // Step 23. Let module script credentials mode be the CORS settings attribute credentials mode for el's crossorigin content attribute.
754        let module_credentials_mode = cors_settings_attribute_credential_mode(element);
755
756        // Step 24. Let cryptographic nonce be el's [[CryptographicNonce]] internal slot's value.
757        // If the element has a nonce content attribute but is not nonceable strip the nonce to prevent injection attacks.
758        // Elements without a nonce content attribute (e.g. JS-created with .nonce = "abc")
759        // use the internal slot directly — the nonceable check only applies to parser-created elements.
760        let cryptographic_nonce =
761            if element.is_nonceable() || !element.has_attribute(&local_name!("nonce")) {
762                element.nonce_value().trim().to_owned()
763            } else {
764                String::new()
765            };
766
767        // Step 25. If el has an integrity attribute, then let integrity metadata be that attribute's value.
768        // Otherwise, let integrity metadata be the empty string.
769        let integrity_val = element.get_attribute_string_value(&local_name!("integrity"));
770        let integrity_val_is_none = integrity_val.is_none();
771        let integrity_metadata = integrity_val.unwrap_or_default();
772
773        // Step 26. Let referrer policy be the current state of el's referrerpolicy content attribute.
774        let referrer_policy = referrer_policy_for_element(element);
775
776        // Step 27. Let fetch priority be the current state of el's fetchpriority content attribute.
777        let fetch_priority = self.FetchPriority().into();
778
779        // Step 28. Let parser metadata be "parser-inserted" if el is parser-inserted,
780        // and "not-parser-inserted" otherwise.
781        let parser_metadata = if self.parser_inserted.get() {
782            ParserMetadata::ParserInserted
783        } else {
784            ParserMetadata::NotParserInserted
785        };
786
787        // Step 29. Let options be a script fetch options whose
788        // cryptographic nonce is cryptographic nonce,
789        // integrity metadata is integrity metadata,
790        // parser metadata is parser metadata,
791        // credentials mode is module script credentials mode,
792        // referrer policy is referrer policy,
793        // and fetch priority is fetch priority.
794        let mut script_fetch_options = ScriptFetchOptions {
795            cryptographic_nonce,
796            integrity_metadata,
797            parser_metadata,
798            referrer_policy,
799            fetch_priority,
800            credentials_mode: module_credentials_mode,
801            render_blocking: false,
802        };
803
804        // Step 30. Let settings object be el's node document's relevant settings object.
805
806        let base_url = doc.base_url();
807
808        let kind = self.get_script_kind(script_type);
809        let delayed_document = self.get_script_active_document(kind);
810
811        let potentially_render_blocking = self.potentially_render_blocking(script_type);
812
813        // Step 31. If el has a src content attribute, then:
814        // Step 31.2. Let src be the value of el's src attribute.
815        if let Some(src) = element.get_attribute_string_value(&local_name!("src")) {
816            // Step 31.1. If el's type is "importmap".
817            if script_type == ScriptType::ImportMap {
818                // then queue an element task on the DOM manipulation task source
819                // given el to fire an event named error at el, and return.
820                self.queue_error_event();
821                return;
822            }
823
824            // Step 31.3. If src is the empty string.
825            if src.is_empty() {
826                self.queue_error_event();
827                return;
828            }
829
830            // Step 31.4. Set el's from an external file to true.
831            self.from_an_external_file.set(true);
832
833            // Step 31.5-31.6. Parse URL.
834            let url = match base_url.join(&src) {
835                Ok(url) => url,
836                Err(_) => {
837                    warn!("error parsing URL for script {}", src);
838                    self.queue_error_event();
839                    return;
840                },
841            };
842            let url = ensure_blob_referenced_by_url_is_kept_alive(global, url);
843
844            // Step 31.7. If el is potentially render-blocking, then block rendering on el.
845            if potentially_render_blocking && doc.allows_adding_render_blocking_elements() {
846                self.marked_as_render_blocking.set(true);
847                doc.increment_render_blocking_element_count();
848            }
849
850            // Step 31.8. Set el's delaying the load event to true.
851            self.delay_load_event(&delayed_document, url.url());
852
853            // Step 31.9. If el is currently render-blocking, then set options's render-blocking to true.
854            if self.marked_as_render_blocking.get() {
855                script_fetch_options.render_blocking = true;
856            }
857
858            // Step 31.11. Switch on el's type:
859            match script_type {
860                ScriptType::Classic => {
861                    // Step 31.11. Fetch a classic script.
862                    fetch_a_classic_script(
863                        self,
864                        kind,
865                        url,
866                        cors_setting,
867                        script_fetch_options,
868                        encoding,
869                    );
870                },
871                ScriptType::Module => {
872                    // If el does not have an integrity attribute, then set options's integrity metadata to
873                    // the result of resolving a module integrity metadata with url and settings object.
874                    if integrity_val_is_none {
875                        script_fetch_options.integrity_metadata = global
876                            .import_map()
877                            .resolve_a_module_integrity_metadata(&url.url());
878                    }
879
880                    let script = DomRoot::from_ref(self);
881
882                    // Step 31.11. Fetch an external module script graph.
883                    fetch_an_external_module_script(
884                        cx,
885                        url,
886                        global,
887                        script_fetch_options,
888                        move |cx, module_tree| {
889                            let load = module_tree
890                                .map(|module| Script::Module(RootedTraceableBox::new(module)))
891                                .ok_or(());
892                            *script.result.borrow_mut() = Some(load.map(Into::into));
893
894                            script.finish_fetching_a_script(cx, kind);
895                        },
896                    );
897                },
898                ScriptType::ImportMap => (),
899            }
900        } else {
901            // Step 32. If el does not have a src content attribute:
902
903            assert!(!text.is_empty());
904
905            // Step 32.2: Switch on el's type:
906            match script_type {
907                ScriptType::Classic => {
908                    // Step 32.2.1 Let script be the result of creating a classic script
909                    // using source text, settings object, base URL, and options.
910                    let script = self.global().create_a_classic_script(
911                        cx,
912                        text,
913                        base_url,
914                        ScriptOptions::empty(),
915                        script_fetch_options,
916                        introduction_type,
917                        self.line_number as u32,
918                    );
919                    let result = Ok(Script::Classic(script));
920
921                    if was_parser_inserted &&
922                        doc.get_current_parser()
923                            .is_some_and(|parser| parser.script_nesting_level() <= 1) &&
924                        doc.has_a_stylesheet_that_is_blocking_scripts()
925                    {
926                        // Step 34.2: classic, has no src, was parser-inserted, is blocked on stylesheet.
927                        doc.set_pending_parsing_blocking_script(self, Some(result));
928                    } else {
929                        // Step 34.3: otherwise.
930                        self.execute(cx, result);
931                    }
932                    return;
933                },
934                ScriptType::Module => {
935                    // Step 32.2.2.1 Set el's delaying the load event to true.
936                    self.delay_load_event(&delayed_document, base_url.clone());
937
938                    // Step 32.2.2.2 If el is potentially render-blocking, then:
939                    if potentially_render_blocking && doc.allows_adding_render_blocking_elements() {
940                        // Step 32.2.2.2.1 Block rendering on el.
941                        self.marked_as_render_blocking.set(true);
942                        doc.increment_render_blocking_element_count();
943
944                        // Step 32.2.2.2.2 Set options's render-blocking to true.
945                        script_fetch_options.render_blocking = true;
946                    }
947
948                    let script = DomRoot::from_ref(self);
949                    // Step 32.2.2.3 Fetch an inline module script graph, given source text, base
950                    // URL, settings object, options, and with the following steps given result:
951                    let module = fetch_inline_module_script(
952                        cx,
953                        global,
954                        text,
955                        base_url,
956                        script_fetch_options,
957                        self.line_number as u32,
958                        introduction_type,
959                        move |_, module_tree| {
960                            if module_tree.is_none() {
961                                *script.result.borrow_mut() = Some(Err(()));
962                            }
963                            let trusted = Trusted::new(&*script);
964
965                            // Queue an element task on the networking task source given el to perform the following steps:
966                            script
967                                .owner_global()
968                                .task_manager()
969                                .networking_task_source()
970                                .queue(task!(terminate_module_fetch: move |cx| {
971                                    // Mark as ready el given result.
972                                    let element = trusted.root();
973                                    element.finish_fetching_a_script(cx, kind);
974                                }));
975                        },
976                    );
977
978                    *self.result.borrow_mut() = Some(Ok(TracedScript::Module(*module.into_box())));
979                },
980                ScriptType::ImportMap => {
981                    // Step 32.1 Let result be the result of creating an import map
982                    // parse result given source text and base URL.
983                    let import_map_result = parse_an_import_map_string(cx, global, &text, base_url);
984                    let script = Script::ImportMap(import_map_result);
985
986                    // Step 34.3
987                    self.execute(cx, Ok(script));
988                    return;
989                },
990            }
991        }
992
993        // Step 33.2/33.3/33.4/33.5, substeps 1-2. Add el to the corresponding script list.
994        match kind {
995            ExternalScriptKind::Deferred => delayed_document.add_deferred_script(self),
996            ExternalScriptKind::ParsingBlocking => {
997                delayed_document.set_pending_parsing_blocking_script(self, None);
998            },
999            ExternalScriptKind::AsapInOrder => delayed_document.push_asap_in_order_script(self),
1000            ExternalScriptKind::Asap => delayed_document.add_asap_script(self),
1001        }
1002    }
1003
1004    /// <https://html.spec.whatwg.org/multipage/#execute-the-script-element>
1005    pub(crate) fn execute(&self, cx: &mut JSContext, result: ScriptResult) {
1006        // Step 1. Let document be el's node document.
1007        let doc = self.owner_document();
1008
1009        // Step 2. If el's preparation-time document is not equal to document, then return.
1010        if *doc != *self.preparation_time_document.get().unwrap() {
1011            return;
1012        }
1013
1014        // Step 3. Unblock rendering on el.
1015        if self.marked_as_render_blocking.replace(false) {
1016            self.marked_as_render_blocking.set(false);
1017            doc.decrement_render_blocking_element_count();
1018        }
1019
1020        let script = match result {
1021            // Step 4. If el's result is null, then fire an event named error at el, and return.
1022            Err(_) => {
1023                self.upcast::<EventTarget>().fire_event(cx, atom!("error"));
1024                return;
1025            },
1026
1027            Ok(script) => script,
1028        };
1029
1030        // Step 5.
1031        // If el's from an external file is true, or el's type is "module", then increment document's
1032        // ignore-destructive-writes counter.
1033        let neutralized_doc =
1034            if self.from_an_external_file.get() || matches!(script, Script::Module(_)) {
1035                let doc = self.owner_document();
1036                doc.incr_ignore_destructive_writes_counter();
1037                Some(doc)
1038            } else {
1039                None
1040            };
1041
1042        let document = self.owner_document();
1043
1044        match script {
1045            Script::Classic(script) => {
1046                // Step 6."classic".1. Let oldCurrentScript be the value to which document's currentScript object was most recently set.
1047                let old_script = document.GetCurrentScript();
1048
1049                // Step 6."classic".2. If el's root is not a shadow root,
1050                // then set document's currentScript attribute to el. Otherwise, set it to null.
1051                if self.upcast::<Node>().is_in_a_shadow_tree() {
1052                    document.set_current_script(None)
1053                } else {
1054                    document.set_current_script(Some(self))
1055                }
1056
1057                // Step 6."classic".3. Run the classic script given by el's result.
1058                _ = self.owner_global().run_a_classic_script(
1059                    cx,
1060                    script,
1061                    RethrowErrors::No,
1062                    None, // return_value
1063                );
1064
1065                // Step 6."classic".4. Set document's currentScript attribute to oldCurrentScript.
1066                document.set_current_script(old_script.as_deref());
1067            },
1068            Script::Module(module_tree) => {
1069                // TODO Step 6."module".1. Assert: document's currentScript attribute is null.
1070                document.set_current_script(None);
1071
1072                // Step 6."module".2. Run the module script given by el's result.
1073                self.owner_global()
1074                    .run_a_module_script(cx, module_tree, false);
1075            },
1076            Script::ImportMap(import_map) => {
1077                // Step 6."importmap".1. Register an import map given el's relevant global object and el's result.
1078                register_import_map(cx, &self.owner_global(), import_map);
1079            },
1080        }
1081
1082        // Step 7.
1083        // Decrement the ignore-destructive-writes counter of document, if it was incremented in the earlier step.
1084        if let Some(doc) = neutralized_doc {
1085            doc.decr_ignore_destructive_writes_counter();
1086        }
1087
1088        // Step 8. If el's from an external file is true, then fire an event named load at el.
1089        if self.from_an_external_file.get() {
1090            self.upcast::<EventTarget>().fire_event(cx, atom!("load"));
1091        }
1092    }
1093
1094    pub(crate) fn queue_error_event(&self) {
1095        self.owner_global()
1096            .task_manager()
1097            .dom_manipulation_task_source()
1098            .queue_simple_event(self.upcast(), atom!("error"));
1099    }
1100
1101    /// <https://html.spec.whatwg.org/multipage/#prepare-a-script> Steps 8-12.
1102    fn script_type(&self) -> Option<ScriptType> {
1103        let element = self.upcast::<Element>();
1104
1105        let type_attr = element.get_attribute_string_ref(&local_name!("type"));
1106        let language_attr = element.get_attribute_string_ref(&local_name!("language"));
1107
1108        match (type_attr, language_attr) {
1109            // Step 8. If any of the following are true:
1110            // el has a type attribute whose value is the empty string;
1111            // el has no type attribute but it has a language attribute and that attribute's value
1112            // is the empty string; or el has neither a type attribute nor a language attribute,
1113            // then let the script block's type string for this script element be "text/javascript".
1114            (Some(type_attribute), _) if type_attribute.is_empty() => Some(ScriptType::Classic),
1115            (None, Some(lang)) if lang.is_empty() => Some(ScriptType::Classic),
1116            (None, None) => Some(ScriptType::Classic),
1117            // Otherwise, el has a non-empty language attribute; let the script block's type string
1118            // be the concatenation of "text/" and the value of el's language attribute.
1119            (None, Some(lang)) => {
1120                let language_value = lang.as_attr_ref().value();
1121                let script_block_type_string = format!("text/{}", language_value.as_ref());
1122
1123                // Step 9. If the script block's type string is a JavaScript MIME type essence match,
1124                // or el has a type attribute whose value with leading and trailing ASCII whitespace
1125                // stripped is a JavaScript MIME type essence match, then set el's type to "classic".
1126                let is_a_javascript_mime = SCRIPT_JS_MIMES
1127                    .iter()
1128                    .any(|mime| script_block_type_string.eq_ignore_ascii_case(mime));
1129
1130                is_a_javascript_mime.then_some(ScriptType::Classic)
1131            },
1132            // Otherwise, if el has a type attribute, then let the script block's type string be the
1133            // value of that attribute.
1134            (Some(ty), _) => {
1135                // Step 10. Otherwise, if the script block's type string is an ASCII case-insensitive
1136                // match for the string "module", then set el's type to "module".
1137                if ty.eq_ignore_ascii_case("module") {
1138                    return Some(ScriptType::Module);
1139                }
1140
1141                // Step 11. Otherwise, if the script block's type string is an ASCII case-insensitive
1142                // match for the string "importmap", then set el's type to "importmap".
1143                if ty.eq_ignore_ascii_case("importmap") {
1144                    return Some(ScriptType::ImportMap);
1145                }
1146
1147                let type_attr_value = ty.as_attr_ref().value();
1148
1149                // Step 9. If the script block's type string is a JavaScript MIME type essence match,
1150                // or el has a type attribute whose value with leading and trailing ASCII whitespace
1151                // stripped is a JavaScript MIME type essence match, then set el's type to "classic".
1152                let is_a_javascript_mime = SCRIPT_JS_MIMES.iter().any(|mime| {
1153                    type_attr_value
1154                        .trim_matches(HTML_SPACE_CHARACTERS)
1155                        .eq_ignore_ascii_case(mime)
1156                });
1157
1158                is_a_javascript_mime.then_some(ScriptType::Classic)
1159            },
1160        }
1161    }
1162
1163    pub(crate) fn set_parser_inserted(&self, parser_inserted: bool) {
1164        self.parser_inserted.set(parser_inserted);
1165    }
1166
1167    pub(crate) fn set_already_started(&self, already_started: bool) {
1168        self.already_started.set(already_started);
1169    }
1170
1171    fn text(&self) -> DOMString {
1172        match self.Text() {
1173            TrustedScriptOrString::String(value) => value,
1174            TrustedScriptOrString::TrustedScript(trusted_script) => {
1175                DOMString::from(trusted_script.to_string())
1176            },
1177        }
1178    }
1179}
1180
1181impl VirtualMethods for HTMLScriptElement {
1182    fn super_type(&self) -> Option<&dyn VirtualMethods> {
1183        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
1184    }
1185
1186    fn attribute_mutated(
1187        &self,
1188        cx: &mut JSContext,
1189        attr: AttrRef<'_>,
1190        mutation: AttributeMutation,
1191    ) {
1192        self.super_type()
1193            .unwrap()
1194            .attribute_mutated(cx, attr, mutation);
1195        if *attr.local_name() == local_name!("src") {
1196            if let AttributeMutation::Set(_) = mutation &&
1197                !self.parser_inserted.get() &&
1198                self.upcast::<Node>().is_connected()
1199            {
1200                self.prepare(cx, Some(IntroductionType::INJECTED_SCRIPT));
1201            }
1202        } else if *attr.local_name() == local_name!("blocking") &&
1203            !self.has_render_blocking_attribute() &&
1204            self.marked_as_render_blocking.replace(false)
1205        {
1206            let document = self.owner_document();
1207            document.decrement_render_blocking_element_count();
1208        }
1209    }
1210
1211    /// <https://html.spec.whatwg.org/multipage/#script-processing-model:the-script-element-26>
1212    fn children_changed(&self, cx: &mut JSContext, mutation: &ChildrenMutation) {
1213        if let Some(s) = self.super_type() {
1214            s.children_changed(cx, mutation);
1215        }
1216
1217        if self.upcast::<Node>().is_connected() && !self.parser_inserted.get() {
1218            let script = DomRoot::from_ref(self);
1219            // This method can be invoked while there are script/layout blockers present
1220            // as DOM mutations have not yet settled. We use a delayed task to avoid
1221            // running any scripts until the DOM tree is safe for interactions.
1222            self.owner_document().add_delayed_task(
1223                task!(ScriptPrepare: |cx, script: DomRoot<HTMLScriptElement>| {
1224                    script.prepare(cx, Some(IntroductionType::INJECTED_SCRIPT));
1225                }),
1226            );
1227        }
1228    }
1229
1230    /// <https://html.spec.whatwg.org/multipage/#script-processing-model:the-script-element-20>
1231    fn post_connection_steps(&self, cx: &mut JSContext) {
1232        if let Some(s) = self.super_type() {
1233            s.post_connection_steps(cx);
1234        }
1235
1236        if self.upcast::<Node>().is_connected() && !self.parser_inserted.get() {
1237            self.prepare(cx, Some(IntroductionType::INJECTED_SCRIPT));
1238        }
1239    }
1240
1241    fn cloning_steps(
1242        &self,
1243        cx: &mut JSContext,
1244        copy: &Node,
1245        maybe_doc: Option<&Document>,
1246        clone_children: CloneChildrenFlag,
1247    ) {
1248        if let Some(s) = self.super_type() {
1249            s.cloning_steps(cx, copy, maybe_doc, clone_children);
1250        }
1251
1252        // https://html.spec.whatwg.org/multipage/#already-started
1253        if self.already_started.get() {
1254            copy.downcast::<HTMLScriptElement>()
1255                .unwrap()
1256                .set_already_started(true);
1257        }
1258    }
1259
1260    fn unbind_from_tree(&self, cx: &mut JSContext, context: &UnbindContext) {
1261        self.super_type().unwrap().unbind_from_tree(cx, context);
1262
1263        if self.marked_as_render_blocking.replace(false) {
1264            let document = self.owner_document();
1265            document.decrement_render_blocking_element_count();
1266        }
1267    }
1268}
1269
1270impl HTMLScriptElementMethods<crate::DomTypeHolder> for HTMLScriptElement {
1271    /// <https://html.spec.whatwg.org/multipage/#dom-script-src>
1272    fn Src(&self) -> TrustedScriptURLOrUSVString {
1273        let element = self.upcast::<Element>();
1274        element.get_trusted_type_url_attribute(&local_name!("src"))
1275    }
1276
1277    /// <https://w3c.github.io/trusted-types/dist/spec/#the-src-idl-attribute>
1278    fn SetSrc(&self, cx: &mut JSContext, value: TrustedScriptURLOrUSVString) -> Fallible<()> {
1279        let element = self.upcast::<Element>();
1280        let local_name = &local_name!("src");
1281        let value = TrustedScriptURL::get_trusted_type_compliant_string(
1282            cx,
1283            &element.owner_global(),
1284            value,
1285            &format!("HTMLScriptElement {}", local_name),
1286        )?;
1287        element.set_attribute(cx, local_name, AttrValue::String(value.str().to_owned()));
1288        Ok(())
1289    }
1290
1291    // https://html.spec.whatwg.org/multipage/#dom-script-type
1292    make_getter!(Type, "type");
1293    // https://html.spec.whatwg.org/multipage/#dom-script-type
1294    make_setter!(SetType, "type");
1295
1296    // https://html.spec.whatwg.org/multipage/#dom-script-charset
1297    make_getter!(Charset, "charset");
1298    // https://html.spec.whatwg.org/multipage/#dom-script-charset
1299    make_setter!(SetCharset, "charset");
1300
1301    /// <https://html.spec.whatwg.org/multipage/#dom-script-async>
1302    fn Async(&self) -> bool {
1303        self.non_blocking.get() ||
1304            self.upcast::<Element>()
1305                .has_attribute(&local_name!("async"))
1306    }
1307
1308    /// <https://html.spec.whatwg.org/multipage/#dom-script-async>
1309    fn SetAsync(&self, cx: &mut JSContext, value: bool) {
1310        self.non_blocking.set(false);
1311        self.upcast::<Element>()
1312            .set_bool_attribute(cx, &local_name!("async"), value);
1313    }
1314
1315    // https://html.spec.whatwg.org/multipage/#dom-script-defer
1316    make_bool_getter!(Defer, "defer");
1317    // https://html.spec.whatwg.org/multipage/#dom-script-defer
1318    make_bool_setter!(SetDefer, "defer");
1319
1320    /// <https://html.spec.whatwg.org/multipage/#attr-script-blocking>
1321    fn Blocking(&self, cx: &mut JSContext) -> DomRoot<DOMTokenList> {
1322        self.blocking.or_init(|| {
1323            DOMTokenList::new(
1324                cx,
1325                self.upcast(),
1326                &local_name!("blocking"),
1327                Some(vec![Atom::from("render")]),
1328            )
1329        })
1330    }
1331
1332    // https://html.spec.whatwg.org/multipage/#dom-script-nomodule
1333    make_bool_getter!(NoModule, "nomodule");
1334    // https://html.spec.whatwg.org/multipage/#dom-script-nomodule
1335    make_bool_setter!(SetNoModule, "nomodule");
1336
1337    // https://html.spec.whatwg.org/multipage/#dom-script-integrity
1338    make_getter!(Integrity, "integrity");
1339    // https://html.spec.whatwg.org/multipage/#dom-script-integrity
1340    make_setter!(SetIntegrity, "integrity");
1341
1342    // https://html.spec.whatwg.org/multipage/#dom-script-event
1343    make_getter!(Event, "event");
1344    // https://html.spec.whatwg.org/multipage/#dom-script-event
1345    make_setter!(SetEvent, "event");
1346
1347    // https://html.spec.whatwg.org/multipage/#dom-script-htmlfor
1348    make_getter!(HtmlFor, "for");
1349    // https://html.spec.whatwg.org/multipage/#dom-script-htmlfor
1350    make_setter!(SetHtmlFor, "for");
1351
1352    // <https://html.spec.whatwg.org/multipage/#attr-script-fetchpriority>
1353    make_enumerated_getter!(
1354        FetchPriority,
1355        "fetchpriority",
1356        "high" | "low" | "auto",
1357        missing => "auto",
1358        invalid => "auto"
1359    );
1360    // https://html.spec.whatwg.org/multipage/#attr-script-fetchpriority
1361    make_setter!(SetFetchPriority, "fetchpriority");
1362
1363    /// <https://html.spec.whatwg.org/multipage/#dom-script-crossorigin>
1364    fn GetCrossOrigin(&self) -> Option<DOMString> {
1365        reflect_cross_origin_attribute(self.upcast::<Element>())
1366    }
1367
1368    /// <https://html.spec.whatwg.org/multipage/#dom-script-crossorigin>
1369    fn SetCrossOrigin(&self, cx: &mut JSContext, value: Option<DOMString>) {
1370        set_cross_origin_attribute(cx, self.upcast::<Element>(), value);
1371    }
1372
1373    /// <https://html.spec.whatwg.org/multipage/#dom-script-referrerpolicy>
1374    fn ReferrerPolicy(&self) -> DOMString {
1375        reflect_referrer_policy_attribute(self.upcast::<Element>())
1376    }
1377
1378    // https://html.spec.whatwg.org/multipage/#dom-script-referrerpolicy
1379    make_setter!(SetReferrerPolicy, "referrerpolicy");
1380
1381    /// <https://w3c.github.io/trusted-types/dist/spec/#dom-htmlscriptelement-innertext>
1382    fn InnerText(&self, cx: &mut JSContext) -> TrustedScriptOrString {
1383        // Step 1: Return the result of running get the text steps with this.
1384        TrustedScriptOrString::String(self.upcast::<HTMLElement>().get_inner_outer_text(cx))
1385    }
1386
1387    /// <https://w3c.github.io/trusted-types/dist/spec/#the-innerText-idl-attribute>
1388    fn SetInnerText(&self, cx: &mut JSContext, input: TrustedScriptOrString) -> Fallible<()> {
1389        // Step 1: Let value be the result of calling Get Trusted Type compliant string with TrustedScript,
1390        // this's relevant global object, the given value, HTMLScriptElement innerText, and script.
1391        let value = TrustedScript::get_trusted_type_compliant_string(
1392            cx,
1393            &self.owner_global(),
1394            input,
1395            "HTMLScriptElement innerText",
1396        )?;
1397        *self.script_text.safe_borrow_mut(cx.no_gc()) = value.clone().traced();
1398        // Step 3: Run set the inner text steps with this and value.
1399        self.upcast::<HTMLElement>().set_inner_text(cx, value);
1400        Ok(())
1401    }
1402
1403    /// <https://html.spec.whatwg.org/multipage/#dom-script-text>
1404    fn Text(&self) -> TrustedScriptOrString {
1405        TrustedScriptOrString::String(self.upcast::<Node>().child_text_content())
1406    }
1407
1408    /// <https://w3c.github.io/trusted-types/dist/spec/#the-text-idl-attribute>
1409    fn SetText(&self, cx: &mut JSContext, value: TrustedScriptOrString) -> Fallible<()> {
1410        // Step 1: Let value be the result of calling Get Trusted Type compliant string with TrustedScript,
1411        // this's relevant global object, the given value, HTMLScriptElement text, and script.
1412        let value = TrustedScript::get_trusted_type_compliant_string(
1413            cx,
1414            &self.owner_global(),
1415            value,
1416            "HTMLScriptElement text",
1417        )?;
1418        // Step 2: Set this's script text value to the given value.
1419        *self.script_text.safe_borrow_mut(cx.no_gc()) = value.clone().traced();
1420        // Step 3: String replace all with the given value within this.
1421        Node::string_replace_all(cx, value, self.upcast::<Node>());
1422        Ok(())
1423    }
1424
1425    /// <https://w3c.github.io/trusted-types/dist/spec/#the-textContent-idl-attribute>
1426    fn GetTextContent(&self) -> Option<TrustedScriptOrString> {
1427        // Step 1: Return the result of running get text content with this.
1428        Some(TrustedScriptOrString::String(
1429            self.upcast::<Node>().GetTextContent()?,
1430        ))
1431    }
1432
1433    /// <https://w3c.github.io/trusted-types/dist/spec/#the-textContent-idl-attribute>
1434    fn SetTextContent(
1435        &self,
1436        cx: &mut JSContext,
1437        value: Option<TrustedScriptOrString>,
1438    ) -> Fallible<()> {
1439        // Step 1: Let value be the result of calling Get Trusted Type compliant string with TrustedScript,
1440        // this's relevant global object, the given value, HTMLScriptElement textContent, and script.
1441        let value = TrustedScript::get_trusted_type_compliant_string(
1442            cx,
1443            &self.owner_global(),
1444            value.unwrap_or(TrustedScriptOrString::String(DOMString::new())),
1445            "HTMLScriptElement textContent",
1446        )?;
1447        // Step 2: Set this's script text value to value.
1448        *self.script_text.safe_borrow_mut(cx.no_gc()) = value.clone().traced();
1449        // Step 3: Run set text content with this and value.
1450        self.upcast::<Node>()
1451            .set_text_content_for_element(cx, Some(value));
1452        Ok(())
1453    }
1454
1455    /// <https://html.spec.whatwg.org/multipage/#dom-script-supports>
1456    fn Supports(_window: &Window, type_: DOMString) -> bool {
1457        // The type argument has to exactly match these values,
1458        // we do not perform an ASCII case-insensitive match.
1459        matches!(&*type_.str(), "classic" | "module" | "importmap")
1460    }
1461}
1462
1463pub fn substitute_with_local_script(
1464    script_source: &str,
1465    script: &mut Cow<'_, str>,
1466    url: &ServoUrl,
1467) {
1468    let mut path = PathBuf::from(script_source);
1469    path = path.join(&url[url::Position::BeforeHost..url::Position::AfterPath]);
1470    debug!("Attempting to read script stored at: {:?}", path);
1471    match read_to_string(path.clone()) {
1472        Ok(local_script) => {
1473            debug!("Found script stored at: {:?}", path);
1474            *script = Cow::Owned(local_script);
1475        },
1476        Err(why) => warn!("Could not restore script from file {:?}", why),
1477    }
1478}
1479
1480#[derive(Clone, Copy)]
1481enum ExternalScriptKind {
1482    Deferred,
1483    ParsingBlocking,
1484    AsapInOrder,
1485    Asap,
1486}