Skip to main content

blitz_script/
document_scripts.rs

1use blitz_dom::node::NodeFlags;
2use blitz_dom::{BaseDocument, LocalName};
3
4/// A script found in the parsed document, in tree order.
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub(crate) struct DocumentScript {
7    /// Inline source, or an empty string when the script has an external source.
8    pub source: String,
9    /// The value of the `src` attribute, when present.
10    pub src: Option<String>,
11    /// How the script should be evaluated.
12    pub kind: ScriptKind,
13}
14
15/// The supported executable script forms.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum ScriptKind {
18    Classic,
19    Module,
20    ImportMap,
21}
22
23/// Discover external executable sources using the same admission rules as
24/// document execution. Parser-inert scripts and scripts inside template
25/// contents are excluded. Import maps are inline configuration, not external
26/// executable sources, so their `src` attributes are not returned.
27pub fn external_script_urls(document: &BaseDocument) -> Vec<url::Url> {
28    document_scripts(document)
29        .into_iter()
30        .filter(|script| script.kind != ScriptKind::ImportMap)
31        .filter_map(|script| script.src)
32        .filter_map(|source| document.url().join(&source).ok())
33        .collect()
34}
35
36/// Collect executable scripts from the document in DOM tree order.
37pub(crate) fn document_scripts(doc: &BaseDocument) -> Vec<DocumentScript> {
38    let mut scripts = Vec::new();
39    let mut pending = doc
40        .root_node()
41        .children
42        .iter()
43        .rev()
44        .copied()
45        .collect::<Vec<_>>();
46
47    while let Some(node_id) = pending.pop() {
48        let Some(node) = doc.get_node(node_id) else {
49            continue;
50        };
51
52        if let Some(element) = node.element_data() {
53            let is_html = element.name.ns.as_ref() == "http://www.w3.org/1999/xhtml";
54            let is_template = is_html && element.name.local.as_ref() == "template";
55            if is_template {
56                continue;
57            }
58
59            if is_html && element.name.local.as_ref() == "script" {
60                if node.flags.contains(NodeFlags::IS_PARSER_INERT_SCRIPT) {
61                    continue;
62                }
63
64                if let Some(kind) = script_kind(element) {
65                    let src = element.attr(LocalName::from("src")).map(ToOwned::to_owned);
66                    let source = if src.is_some() {
67                        String::new()
68                    } else {
69                        let mut source = String::new();
70                        node.write_text_content(&mut source);
71                        source
72                    };
73                    scripts.push(DocumentScript { source, src, kind });
74                }
75            }
76        }
77
78        pending.extend(node.children.iter().rev().copied());
79    }
80
81    scripts
82}
83
84fn script_kind(element: &blitz_dom::node::ElementData) -> Option<ScriptKind> {
85    let type_value = element.attr(LocalName::from("type"));
86    let kind = match type_value.map(trim_ascii_whitespace) {
87        Some(value) if value.eq_ignore_ascii_case("module") => ScriptKind::Module,
88        Some(value) if value.eq_ignore_ascii_case("importmap") => ScriptKind::ImportMap,
89        Some("") | None => {
90            let language = element.attr(LocalName::from("language"));
91            match language.map(trim_ascii_whitespace) {
92                Some(language) if !language.is_empty() => {
93                    let mut mime = String::from("text/");
94                    mime.push_str(language);
95                    if !is_javascript_mime_type(&mime) {
96                        return None;
97                    }
98                    ScriptKind::Classic
99                }
100                _ => ScriptKind::Classic,
101            }
102        }
103        Some(value) if is_javascript_mime_type(value) => ScriptKind::Classic,
104        Some(_) => return None,
105    };
106
107    if kind == ScriptKind::Classic && element.has_attr(LocalName::from("nomodule")) {
108        return None;
109    }
110
111    Some(kind)
112}
113
114fn is_javascript_mime_type(value: &str) -> bool {
115    let essence =
116        trim_ascii_whitespace(value.split_once(';').map_or(value, |(essence, _)| essence));
117
118    matches_ignore_ascii_case(
119        essence,
120        &[
121            "application/ecmascript",
122            "application/javascript",
123            "application/x-ecmascript",
124            "application/x-javascript",
125            "text/ecmascript",
126            "text/javascript",
127            "text/javascript1.0",
128            "text/javascript1.1",
129            "text/javascript1.2",
130            "text/javascript1.3",
131            "text/javascript1.4",
132            "text/javascript1.5",
133            "text/jscript",
134            "text/livescript",
135            "text/x-ecmascript",
136            "text/x-javascript",
137        ],
138    )
139}
140
141fn matches_ignore_ascii_case(value: &str, choices: &[&str]) -> bool {
142    choices
143        .iter()
144        .any(|choice| value.eq_ignore_ascii_case(choice))
145}
146
147fn trim_ascii_whitespace(value: &str) -> &str {
148    value.trim_matches(|character: char| character.is_ascii_whitespace())
149}