Skip to main content

fallow_extract/
html.rs

1//! HTML file parsing for script, stylesheet, and Angular template references.
2//!
3//! Extracts `<script src="...">` and `<link rel="stylesheet" href="...">` references
4//! from HTML files, creating graph edges so that referenced JS/CSS assets (and their
5//! transitive imports) are reachable from the HTML entry point.
6//!
7//! Also scans for Angular template syntax (`{{ }}`, `[prop]`, `(event)`, `@if`, etc.)
8//! and stores referenced identifiers as `MemberAccess` entries with a sentinel object,
9//! enabling the analysis phase to credit component class members used in external templates.
10
11use std::path::Path;
12use std::sync::LazyLock;
13
14use oxc_span::Span;
15
16use crate::asset_url::normalize_asset_url;
17use crate::sfc_template::angular::{self, ANGULAR_TPL_SENTINEL};
18use crate::{ImportInfo, ImportedName, MemberAccess, ModuleInfo};
19use fallow_types::discover::FileId;
20
21/// Regex to match HTML comments (`<!-- ... -->`) for stripping before extraction.
22static HTML_COMMENT_RE: LazyLock<regex::Regex> =
23    LazyLock::new(|| regex::Regex::new(r"(?s)<!--.*?-->").expect("valid regex"));
24
25/// Regex to extract `src` attribute from `<script>` tags.
26/// Matches both `<script src="...">` and `<script type="module" src="...">`.
27/// Uses `(?s)` so `.` matches newlines (multi-line attributes).
28static SCRIPT_SRC_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
29    regex::Regex::new(r#"(?si)<script\b(?:[^>"']|"[^"]*"|'[^']*')*?\bsrc\s*=\s*["']([^"']+)["']"#)
30        .expect("valid regex")
31});
32
33/// Regex to extract `href` attribute from `<link>` tags with `rel="stylesheet"` or
34/// `rel="modulepreload"`.
35/// Handles attributes in any order (rel before or after href).
36static LINK_HREF_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
37    regex::Regex::new(
38        r#"(?si)<link\b(?:[^>"']|"[^"]*"|'[^']*')*?\brel\s*=\s*["'](stylesheet|modulepreload)["'](?:[^>"']|"[^"]*"|'[^']*')*?\bhref\s*=\s*["']([^"']+)["']"#,
39    )
40    .expect("valid regex")
41});
42
43/// Regex for the reverse attribute order: href before rel.
44static LINK_HREF_REVERSE_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
45    regex::Regex::new(
46        r#"(?si)<link\b(?:[^>"']|"[^"]*"|'[^']*')*?\bhref\s*=\s*["']([^"']+)["'](?:[^>"']|"[^"]*"|'[^']*')*?\brel\s*=\s*["'](stylesheet|modulepreload)["']"#,
47    )
48    .expect("valid regex")
49});
50
51/// Check if a path is an HTML file.
52// Keep in sync with fallow_core::analyze::predicates::is_html_file (crate boundary prevents sharing)
53pub(crate) fn is_html_file(path: &Path) -> bool {
54    path.extension()
55        .and_then(|e| e.to_str())
56        .is_some_and(|ext| ext == "html")
57}
58
59/// Returns true if an HTML asset reference is a remote URL that should be skipped.
60pub(crate) fn is_remote_url(src: &str) -> bool {
61    src.starts_with("http://")
62        || src.starts_with("https://")
63        || src.starts_with("//")
64        || src.starts_with("data:")
65}
66
67/// Extract local (non-remote) asset references from HTML-like markup.
68///
69/// Returns the raw `src`/`href` strings (trimmed, remote URLs filtered). Shared
70/// between the HTML file parser and the JS/TS visitor's tagged template
71/// literal override so `` html`<script src="...">` `` in Hono/lit-html/htm
72/// layouts emits the same asset edges as a real `.html` file.
73pub(crate) fn collect_asset_refs(source: &str) -> Vec<String> {
74    let stripped = HTML_COMMENT_RE.replace_all(source, "");
75    let mut refs: Vec<String> = Vec::new();
76
77    for cap in SCRIPT_SRC_RE.captures_iter(&stripped) {
78        if let Some(m) = cap.get(1) {
79            let src = m.as_str().trim();
80            if !src.is_empty() && !is_remote_url(src) {
81                refs.push(src.to_string());
82            }
83        }
84    }
85
86    for cap in LINK_HREF_RE.captures_iter(&stripped) {
87        if let Some(m) = cap.get(2) {
88            let href = m.as_str().trim();
89            if !href.is_empty() && !is_remote_url(href) {
90                refs.push(href.to_string());
91            }
92        }
93    }
94    for cap in LINK_HREF_REVERSE_RE.captures_iter(&stripped) {
95        if let Some(m) = cap.get(1) {
96            let href = m.as_str().trim();
97            if !href.is_empty() && !is_remote_url(href) {
98                refs.push(href.to_string());
99            }
100        }
101    }
102
103    refs
104}
105
106/// Parse an HTML file, extracting script and stylesheet references as imports.
107pub(crate) fn parse_html_to_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
108    let suppressions = crate::suppress::parse_suppressions_from_source(source);
109
110    // Bare filenames (e.g., `src="app.js"`) are normalized to `./app.js` so
111    // the resolver doesn't misclassify them as npm packages.
112    let mut imports: Vec<ImportInfo> = collect_asset_refs(source)
113        .into_iter()
114        .map(|raw| ImportInfo {
115            source: normalize_asset_url(&raw),
116            imported_name: ImportedName::SideEffect,
117            local_name: String::new(),
118            is_type_only: false,
119            span: Span::default(),
120            source_span: Span::default(),
121        })
122        .collect();
123
124    // Deduplicate: the same asset may be referenced by both <script src> and
125    // <link rel="modulepreload" href> for the same path.
126    imports.sort_unstable_by(|a, b| a.source.cmp(&b.source));
127    imports.dedup_by(|a, b| a.source == b.source);
128
129    // Scan for Angular template syntax ({{ }}, [prop], (event), @if, etc.).
130    // Referenced identifiers are stored as MemberAccess entries with a sentinel
131    // object name so the analysis phase can bridge them to the component class.
132    let template_refs = angular::collect_angular_template_refs(source);
133    let member_accesses: Vec<MemberAccess> = template_refs
134        .into_iter()
135        .map(|name| MemberAccess {
136            object: ANGULAR_TPL_SENTINEL.to_string(),
137            member: name,
138        })
139        .collect();
140
141    ModuleInfo {
142        file_id,
143        exports: Vec::new(),
144        imports,
145        re_exports: Vec::new(),
146        dynamic_imports: Vec::new(),
147        dynamic_import_patterns: Vec::new(),
148        require_calls: Vec::new(),
149        member_accesses,
150        whole_object_uses: Vec::new(),
151        has_cjs_exports: false,
152        content_hash,
153        suppressions,
154        unused_import_bindings: Vec::new(),
155        type_referenced_import_bindings: Vec::new(),
156        value_referenced_import_bindings: Vec::new(),
157        line_offsets: fallow_types::extract::compute_line_offsets(source),
158        complexity: Vec::new(),
159        flag_uses: Vec::new(),
160        class_heritage: vec![],
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    // ── is_html_file ─────────────────────────────────────────────
169
170    #[test]
171    fn is_html_file_html() {
172        assert!(is_html_file(Path::new("index.html")));
173    }
174
175    #[test]
176    fn is_html_file_nested() {
177        assert!(is_html_file(Path::new("pages/about.html")));
178    }
179
180    #[test]
181    fn is_html_file_rejects_htm() {
182        assert!(!is_html_file(Path::new("index.htm")));
183    }
184
185    #[test]
186    fn is_html_file_rejects_js() {
187        assert!(!is_html_file(Path::new("app.js")));
188    }
189
190    #[test]
191    fn is_html_file_rejects_ts() {
192        assert!(!is_html_file(Path::new("app.ts")));
193    }
194
195    #[test]
196    fn is_html_file_rejects_vue() {
197        assert!(!is_html_file(Path::new("App.vue")));
198    }
199
200    // ── is_remote_url ────────────────────────────────────────────
201
202    #[test]
203    fn remote_url_http() {
204        assert!(is_remote_url("http://example.com/script.js"));
205    }
206
207    #[test]
208    fn remote_url_https() {
209        assert!(is_remote_url("https://cdn.example.com/style.css"));
210    }
211
212    #[test]
213    fn remote_url_protocol_relative() {
214        assert!(is_remote_url("//cdn.example.com/lib.js"));
215    }
216
217    #[test]
218    fn remote_url_data() {
219        assert!(is_remote_url("data:text/javascript;base64,abc"));
220    }
221
222    #[test]
223    fn local_relative_not_remote() {
224        assert!(!is_remote_url("./src/entry.js"));
225    }
226
227    #[test]
228    fn local_root_relative_not_remote() {
229        assert!(!is_remote_url("/src/entry.js"));
230    }
231
232    // ── parse_html_to_module: script src extraction ──────────────
233
234    #[test]
235    fn extracts_module_script_src() {
236        let info = parse_html_to_module(
237            FileId(0),
238            r#"<script type="module" src="./src/entry.js"></script>"#,
239            0,
240        );
241        assert_eq!(info.imports.len(), 1);
242        assert_eq!(info.imports[0].source, "./src/entry.js");
243    }
244
245    #[test]
246    fn extracts_plain_script_src() {
247        let info = parse_html_to_module(
248            FileId(0),
249            r#"<script src="./src/polyfills.js"></script>"#,
250            0,
251        );
252        assert_eq!(info.imports.len(), 1);
253        assert_eq!(info.imports[0].source, "./src/polyfills.js");
254    }
255
256    #[test]
257    fn extracts_multiple_scripts() {
258        let info = parse_html_to_module(
259            FileId(0),
260            r#"
261            <script type="module" src="./src/entry.js"></script>
262            <script src="./src/polyfills.js"></script>
263            "#,
264            0,
265        );
266        assert_eq!(info.imports.len(), 2);
267    }
268
269    #[test]
270    fn skips_inline_script() {
271        let info = parse_html_to_module(FileId(0), r#"<script>console.log("hello");</script>"#, 0);
272        assert!(info.imports.is_empty());
273    }
274
275    #[test]
276    fn skips_remote_script() {
277        let info = parse_html_to_module(
278            FileId(0),
279            r#"<script src="https://cdn.example.com/lib.js"></script>"#,
280            0,
281        );
282        assert!(info.imports.is_empty());
283    }
284
285    #[test]
286    fn skips_protocol_relative_script() {
287        let info = parse_html_to_module(
288            FileId(0),
289            r#"<script src="//cdn.example.com/lib.js"></script>"#,
290            0,
291        );
292        assert!(info.imports.is_empty());
293    }
294
295    // ── parse_html_to_module: link href extraction ───────────────
296
297    #[test]
298    fn extracts_stylesheet_link() {
299        let info = parse_html_to_module(
300            FileId(0),
301            r#"<link rel="stylesheet" href="./src/global.css" />"#,
302            0,
303        );
304        assert_eq!(info.imports.len(), 1);
305        assert_eq!(info.imports[0].source, "./src/global.css");
306    }
307
308    #[test]
309    fn extracts_modulepreload_link() {
310        let info = parse_html_to_module(
311            FileId(0),
312            r#"<link rel="modulepreload" href="./src/vendor.js" />"#,
313            0,
314        );
315        assert_eq!(info.imports.len(), 1);
316        assert_eq!(info.imports[0].source, "./src/vendor.js");
317    }
318
319    #[test]
320    fn extracts_link_with_reversed_attrs() {
321        let info = parse_html_to_module(
322            FileId(0),
323            r#"<link href="./src/global.css" rel="stylesheet" />"#,
324            0,
325        );
326        assert_eq!(info.imports.len(), 1);
327        assert_eq!(info.imports[0].source, "./src/global.css");
328    }
329
330    // ── Bare asset references normalized to relative paths ──────
331    // Regression tests for the same class of bug as #99 (Angular templateUrl).
332    // Browsers resolve `src="app.js"` and `href="styles.css"` relative to the
333    // HTML file, so emitting these as bare specifiers would misclassify them
334    // as unlisted npm packages.
335
336    #[test]
337    fn bare_script_src_normalized_to_relative() {
338        let info = parse_html_to_module(FileId(0), r#"<script src="app.js"></script>"#, 0);
339        assert_eq!(info.imports.len(), 1);
340        assert_eq!(info.imports[0].source, "./app.js");
341    }
342
343    #[test]
344    fn bare_module_script_src_normalized_to_relative() {
345        let info = parse_html_to_module(
346            FileId(0),
347            r#"<script type="module" src="main.ts"></script>"#,
348            0,
349        );
350        assert_eq!(info.imports.len(), 1);
351        assert_eq!(info.imports[0].source, "./main.ts");
352    }
353
354    #[test]
355    fn bare_stylesheet_link_href_normalized_to_relative() {
356        let info = parse_html_to_module(
357            FileId(0),
358            r#"<link rel="stylesheet" href="styles.css" />"#,
359            0,
360        );
361        assert_eq!(info.imports.len(), 1);
362        assert_eq!(info.imports[0].source, "./styles.css");
363    }
364
365    #[test]
366    fn bare_link_href_reversed_attrs_normalized_to_relative() {
367        let info = parse_html_to_module(
368            FileId(0),
369            r#"<link href="styles.css" rel="stylesheet" />"#,
370            0,
371        );
372        assert_eq!(info.imports.len(), 1);
373        assert_eq!(info.imports[0].source, "./styles.css");
374    }
375
376    #[test]
377    fn bare_modulepreload_link_href_normalized_to_relative() {
378        let info = parse_html_to_module(
379            FileId(0),
380            r#"<link rel="modulepreload" href="vendor.js" />"#,
381            0,
382        );
383        assert_eq!(info.imports.len(), 1);
384        assert_eq!(info.imports[0].source, "./vendor.js");
385    }
386
387    #[test]
388    fn bare_asset_with_subdir_normalized_to_relative() {
389        let info = parse_html_to_module(FileId(0), r#"<script src="assets/app.js"></script>"#, 0);
390        assert_eq!(info.imports.len(), 1);
391        assert_eq!(info.imports[0].source, "./assets/app.js");
392    }
393
394    #[test]
395    fn root_absolute_script_src_unchanged() {
396        // `/src/main.ts` is a web convention (Vite root-relative) and must
397        // stay absolute so the resolver's HTML special case applies.
398        let info = parse_html_to_module(FileId(0), r#"<script src="/src/main.ts"></script>"#, 0);
399        assert_eq!(info.imports.len(), 1);
400        assert_eq!(info.imports[0].source, "/src/main.ts");
401    }
402
403    #[test]
404    fn parent_relative_script_src_unchanged() {
405        let info = parse_html_to_module(
406            FileId(0),
407            r#"<script src="../shared/vendor.js"></script>"#,
408            0,
409        );
410        assert_eq!(info.imports.len(), 1);
411        assert_eq!(info.imports[0].source, "../shared/vendor.js");
412    }
413
414    #[test]
415    fn skips_preload_link() {
416        let info = parse_html_to_module(
417            FileId(0),
418            r#"<link rel="preload" href="./src/font.woff2" as="font" />"#,
419            0,
420        );
421        assert!(info.imports.is_empty());
422    }
423
424    #[test]
425    fn skips_icon_link() {
426        let info =
427            parse_html_to_module(FileId(0), r#"<link rel="icon" href="./favicon.ico" />"#, 0);
428        assert!(info.imports.is_empty());
429    }
430
431    #[test]
432    fn skips_remote_stylesheet() {
433        let info = parse_html_to_module(
434            FileId(0),
435            r#"<link rel="stylesheet" href="https://fonts.googleapis.com/css" />"#,
436            0,
437        );
438        assert!(info.imports.is_empty());
439    }
440
441    // ── HTML comment stripping ───────────────────────────────────
442
443    #[test]
444    fn skips_commented_out_script() {
445        let info = parse_html_to_module(
446            FileId(0),
447            r#"<!-- <script src="./old.js"></script> -->
448            <script src="./new.js"></script>"#,
449            0,
450        );
451        assert_eq!(info.imports.len(), 1);
452        assert_eq!(info.imports[0].source, "./new.js");
453    }
454
455    #[test]
456    fn skips_commented_out_link() {
457        let info = parse_html_to_module(
458            FileId(0),
459            r#"<!-- <link rel="stylesheet" href="./old.css" /> -->
460            <link rel="stylesheet" href="./new.css" />"#,
461            0,
462        );
463        assert_eq!(info.imports.len(), 1);
464        assert_eq!(info.imports[0].source, "./new.css");
465    }
466
467    // ── Multi-line attributes ────────────────────────────────────
468
469    #[test]
470    fn handles_multiline_script_tag() {
471        let info = parse_html_to_module(
472            FileId(0),
473            "<script\n  type=\"module\"\n  src=\"./src/entry.js\"\n></script>",
474            0,
475        );
476        assert_eq!(info.imports.len(), 1);
477        assert_eq!(info.imports[0].source, "./src/entry.js");
478    }
479
480    #[test]
481    fn handles_multiline_link_tag() {
482        let info = parse_html_to_module(
483            FileId(0),
484            "<link\n  rel=\"stylesheet\"\n  href=\"./src/global.css\"\n/>",
485            0,
486        );
487        assert_eq!(info.imports.len(), 1);
488        assert_eq!(info.imports[0].source, "./src/global.css");
489    }
490
491    // ── Full HTML document ───────────────────────────────────────
492
493    #[test]
494    fn full_vite_html() {
495        let info = parse_html_to_module(
496            FileId(0),
497            r#"<!doctype html>
498<html>
499  <head>
500    <link rel="stylesheet" href="./src/global.css" />
501    <link rel="icon" href="/favicon.ico" />
502  </head>
503  <body>
504    <div id="app"></div>
505    <script type="module" src="./src/entry.js"></script>
506  </body>
507</html>"#,
508            0,
509        );
510        assert_eq!(info.imports.len(), 2);
511        let sources: Vec<&str> = info.imports.iter().map(|i| i.source.as_str()).collect();
512        assert!(sources.contains(&"./src/global.css"));
513        assert!(sources.contains(&"./src/entry.js"));
514    }
515
516    // ── Edge cases ───────────────────────────────────────────────
517
518    #[test]
519    fn empty_html() {
520        let info = parse_html_to_module(FileId(0), "", 0);
521        assert!(info.imports.is_empty());
522    }
523
524    #[test]
525    fn html_with_no_assets() {
526        let info = parse_html_to_module(
527            FileId(0),
528            r"<!doctype html><html><body><h1>Hello</h1></body></html>",
529            0,
530        );
531        assert!(info.imports.is_empty());
532    }
533
534    #[test]
535    fn single_quoted_attributes() {
536        let info = parse_html_to_module(FileId(0), r"<script src='./src/entry.js'></script>", 0);
537        assert_eq!(info.imports.len(), 1);
538        assert_eq!(info.imports[0].source, "./src/entry.js");
539    }
540
541    #[test]
542    fn all_imports_are_side_effect() {
543        let info = parse_html_to_module(
544            FileId(0),
545            r#"<script src="./entry.js"></script>
546            <link rel="stylesheet" href="./style.css" />"#,
547            0,
548        );
549        for imp in &info.imports {
550            assert!(matches!(imp.imported_name, ImportedName::SideEffect));
551            assert!(imp.local_name.is_empty());
552            assert!(!imp.is_type_only);
553        }
554    }
555
556    #[test]
557    fn suppression_comments_extracted() {
558        let info = parse_html_to_module(
559            FileId(0),
560            "<!-- fallow-ignore-file -->\n<script src=\"./entry.js\"></script>",
561            0,
562        );
563        // HTML comments use <!-- --> not //, so suppression parsing
564        // from source text won't find standard JS-style comments.
565        // This is expected — HTML suppression is not supported.
566        assert_eq!(info.imports.len(), 1);
567    }
568
569    // ── Angular template scanning ──────────────────────────────
570
571    #[test]
572    fn angular_template_extracts_member_refs() {
573        let info = parse_html_to_module(
574            FileId(0),
575            "<h1>{{ title() }}</h1>\n\
576             <p [class.highlighted]=\"isHighlighted\">{{ greeting() }}</p>\n\
577             <button (click)=\"onButtonClick()\">Toggle</button>",
578            0,
579        );
580        let names: rustc_hash::FxHashSet<&str> = info
581            .member_accesses
582            .iter()
583            .filter(|a| a.object == ANGULAR_TPL_SENTINEL)
584            .map(|a| a.member.as_str())
585            .collect();
586        assert!(names.contains("title"), "should contain 'title'");
587        assert!(
588            names.contains("isHighlighted"),
589            "should contain 'isHighlighted'"
590        );
591        assert!(names.contains("greeting"), "should contain 'greeting'");
592        assert!(
593            names.contains("onButtonClick"),
594            "should contain 'onButtonClick'"
595        );
596    }
597
598    #[test]
599    fn plain_html_no_angular_refs() {
600        let info = parse_html_to_module(
601            FileId(0),
602            "<!doctype html><html><body><h1>Hello</h1></body></html>",
603            0,
604        );
605        assert!(info.member_accesses.is_empty());
606    }
607}