Skip to main content

fallow_extract/
sfc.rs

1//! Vue/Svelte Single File Component (SFC) script and style extraction.
2//!
3//! Extracts `<script>` block content from `.vue` and `.svelte` files using regex,
4//! handling `lang`, `src`, and `generic` attributes, and filtering HTML comments.
5//! Also extracts `<style>` block sources (`@import` / `@use` / `@forward` /
6//! `@plugin` and `<style src="...">`) so referenced CSS / SCSS files become
7//! reachable from the component, preventing false `unused-files` reports on
8//! co-located styles.
9
10use std::path::Path;
11use std::sync::LazyLock;
12
13use oxc_allocator::Allocator;
14use oxc_ast_visit::Visit;
15use oxc_parser::Parser;
16use oxc_span::SourceType;
17use rustc_hash::{FxHashMap, FxHashSet};
18
19use crate::asset_url::normalize_asset_url;
20use crate::parse::compute_import_binding_usage;
21use crate::sfc_template::{SfcKind, collect_template_usage_with_bound_targets};
22use crate::visitor::ModuleInfoExtractor;
23use crate::{ImportInfo, ImportedName, ModuleInfo};
24use fallow_types::discover::FileId;
25use fallow_types::extract::{FunctionComplexity, byte_offset_to_line_col, compute_line_offsets};
26use oxc_span::Span;
27
28/// Regex to extract `<script>` block content from Vue/Svelte SFCs.
29/// The attrs pattern handles `>` inside quoted attribute values (e.g., `generic="T extends Foo<Bar>"`).
30static SCRIPT_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
31    regex::Regex::new(
32        r#"(?is)<script\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>(?P<body>[\s\S]*?)</script>"#,
33    )
34    .expect("valid regex")
35});
36
37/// Regex to extract the `lang` attribute value from a script tag.
38static LANG_ATTR_RE: LazyLock<regex::Regex> =
39    LazyLock::new(|| regex::Regex::new(r#"lang\s*=\s*["'](\w+)["']"#).expect("valid regex"));
40
41/// Regex to extract the `src` attribute value from a script tag.
42/// Requires whitespace (or start of string) before `src` to avoid matching `data-src` etc.
43static SRC_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
44    regex::Regex::new(r#"(?:^|\s)src\s*=\s*["']([^"']+)["']"#).expect("valid regex")
45});
46
47/// Regex to detect Vue's bare `setup` attribute.
48static SETUP_ATTR_RE: LazyLock<regex::Regex> =
49    LazyLock::new(|| regex::Regex::new(r"(?:^|\s)setup(?:\s|$)").expect("valid regex"));
50
51/// Regex to detect Svelte's `context="module"` attribute.
52static CONTEXT_MODULE_ATTR_RE: LazyLock<regex::Regex> =
53    LazyLock::new(|| regex::Regex::new(r#"context\s*=\s*["']module["']"#).expect("valid regex"));
54
55/// Regex to extract Vue's `generic="..."` attribute value (script-setup
56/// generics). Matches the contents between the quotes and stops at the
57/// closing quote, mirroring `LANG_ATTR_RE`.
58static VUE_GENERIC_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
59    regex::Regex::new(r#"(?:^|\s)generic\s*=\s*"([^"]*)"|(?:^|\s)generic\s*=\s*'([^']*)'"#)
60        .expect("valid regex")
61});
62
63/// Regex to extract Svelte's `generics="..."` attribute value (Svelte 4
64/// generic script attribute, repurposed by some Svelte 5 code).
65static SVELTE_GENERICS_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
66    regex::Regex::new(r#"(?:^|\s)generics\s*=\s*"([^"]*)"|(?:^|\s)generics\s*=\s*'([^']*)'"#)
67        .expect("valid regex")
68});
69
70/// Regex to match HTML comments for filtering script blocks inside comments.
71static HTML_COMMENT_RE: LazyLock<regex::Regex> =
72    LazyLock::new(|| regex::Regex::new(r"(?s)<!--.*?-->").expect("valid regex"));
73
74/// Regex to extract `<style>` block content from Vue/Svelte SFCs.
75/// Mirrors `SCRIPT_BLOCK_RE`: handles `>` inside quoted attribute values and
76/// captures the body so `@import` / `@use` / `@forward` directives can be parsed.
77static STYLE_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
78    regex::Regex::new(
79        r#"(?is)<style\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>(?P<body>[\s\S]*?)</style>"#,
80    )
81    .expect("valid regex")
82});
83
84/// An extracted `<script>` block from a Vue or Svelte SFC.
85pub struct SfcScript {
86    /// The script body text.
87    pub body: String,
88    /// Whether the script uses TypeScript (`lang="ts"` or `lang="tsx"`).
89    pub is_typescript: bool,
90    /// Whether the script uses JSX syntax (`lang="tsx"` or `lang="jsx"`).
91    pub is_jsx: bool,
92    /// Byte offset of the script body within the full SFC source.
93    pub byte_offset: usize,
94    /// External script source path from `src` attribute.
95    pub src: Option<String>,
96    /// Whether this script is a Vue `<script setup>` block.
97    pub is_setup: bool,
98    /// Whether this script is a Svelte module-context block.
99    pub is_context_module: bool,
100    /// Type-parameter list from a `generic="..."` (Vue) or `generics="..."`
101    /// (Svelte) attribute on the script tag. Holds the bare constraint, no
102    /// surrounding angle brackets, e.g. `T extends Test<boolean>`.
103    pub generic_attr: Option<String>,
104}
105
106/// Extract all `<script>` blocks from a Vue/Svelte SFC source string.
107pub fn extract_sfc_scripts(source: &str) -> Vec<SfcScript> {
108    // Build HTML comment ranges to filter out <script> blocks inside comments.
109    // Using ranges instead of source replacement avoids corrupting script body content
110    // (e.g., string literals containing "<!--" would be destroyed by replacement).
111    let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
112        .find_iter(source)
113        .map(|m| (m.start(), m.end()))
114        .collect();
115
116    SCRIPT_BLOCK_RE
117        .captures_iter(source)
118        .filter(|cap| {
119            let start = cap.get(0).map_or(0, |m| m.start());
120            !comment_ranges
121                .iter()
122                .any(|&(cs, ce)| start >= cs && start < ce)
123        })
124        .map(|cap| {
125            let attrs = cap.name("attrs").map_or("", |m| m.as_str());
126            let body_match = cap.name("body");
127            let byte_offset = body_match.map_or(0, |m| m.start());
128            let body = body_match.map_or("", |m| m.as_str()).to_string();
129            let lang = LANG_ATTR_RE
130                .captures(attrs)
131                .and_then(|c| c.get(1))
132                .map(|m| m.as_str());
133            let is_typescript = matches!(lang, Some("ts" | "tsx"));
134            let is_jsx = matches!(lang, Some("tsx" | "jsx"));
135            let src = SRC_ATTR_RE
136                .captures(attrs)
137                .and_then(|c| c.get(1))
138                .map(|m| m.as_str().to_string());
139            let is_setup = SETUP_ATTR_RE.is_match(attrs);
140            let is_context_module = CONTEXT_MODULE_ATTR_RE.is_match(attrs);
141            let generic_attr = VUE_GENERIC_ATTR_RE
142                .captures(attrs)
143                .or_else(|| SVELTE_GENERICS_ATTR_RE.captures(attrs))
144                .and_then(|cap| cap.get(1).or_else(|| cap.get(2)))
145                .map(|m| m.as_str().to_string())
146                .filter(|value| !value.trim().is_empty());
147            SfcScript {
148                body,
149                is_typescript,
150                is_jsx,
151                byte_offset,
152                src,
153                is_setup,
154                is_context_module,
155                generic_attr,
156            }
157        })
158        .collect()
159}
160
161/// An extracted `<style>` block from a Vue or Svelte SFC.
162pub struct SfcStyle {
163    /// The style body text (CSS / SCSS / Sass / Less / Stylus / PostCSS source).
164    pub body: String,
165    /// The `lang` attribute value (`scss`, `sass`, `less`, `stylus`, `postcss`, ...).
166    /// `None` for plain `<style>` (CSS).
167    pub lang: Option<String>,
168    /// External style source path from the `src` attribute (`<style src="./theme.scss">`).
169    pub src: Option<String>,
170}
171
172/// Extract all `<style>` blocks from a Vue/Svelte SFC source string.
173///
174/// Mirrors [`extract_sfc_scripts`]: filters blocks inside HTML comments and
175/// captures the `lang` and `src` attributes so the caller can route the body to
176/// the right preprocessor's import scanner (currently only CSS / SCSS / Sass) or
177/// seed the `src` reference as a side-effect import.
178pub fn extract_sfc_styles(source: &str) -> Vec<SfcStyle> {
179    let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
180        .find_iter(source)
181        .map(|m| (m.start(), m.end()))
182        .collect();
183
184    STYLE_BLOCK_RE
185        .captures_iter(source)
186        .filter(|cap| {
187            let start = cap.get(0).map_or(0, |m| m.start());
188            !comment_ranges
189                .iter()
190                .any(|&(cs, ce)| start >= cs && start < ce)
191        })
192        .map(|cap| {
193            let attrs = cap.name("attrs").map_or("", |m| m.as_str());
194            let body = cap.name("body").map_or("", |m| m.as_str()).to_string();
195            let lang = LANG_ATTR_RE
196                .captures(attrs)
197                .and_then(|c| c.get(1))
198                .map(|m| m.as_str().to_string());
199            let src = SRC_ATTR_RE
200                .captures(attrs)
201                .and_then(|c| c.get(1))
202                .map(|m| m.as_str().to_string());
203            SfcStyle { body, lang, src }
204        })
205        .collect()
206}
207
208/// Check if a file path is a Vue or Svelte SFC (`.vue` or `.svelte`).
209#[must_use]
210pub fn is_sfc_file(path: &Path) -> bool {
211    path.extension()
212        .and_then(|e| e.to_str())
213        .is_some_and(|ext| ext == "vue" || ext == "svelte")
214}
215
216/// Parse an SFC file by extracting and combining all `<script>` and `<style>` blocks.
217pub(crate) fn parse_sfc_to_module(
218    file_id: FileId,
219    path: &Path,
220    source: &str,
221    content_hash: u64,
222    need_complexity: bool,
223) -> ModuleInfo {
224    let scripts = extract_sfc_scripts(source);
225    let styles = extract_sfc_styles(source);
226    let kind = sfc_kind(path);
227    let mut combined = empty_sfc_module(file_id, source, content_hash);
228    let mut template_visible_imports: FxHashSet<String> = FxHashSet::default();
229    let mut template_visible_bound_targets: FxHashMap<String, String> = FxHashMap::default();
230
231    for script in &scripts {
232        merge_script_into_module(
233            kind,
234            script,
235            &mut combined,
236            &mut template_visible_imports,
237            &mut template_visible_bound_targets,
238            need_complexity,
239        );
240    }
241
242    for style in &styles {
243        merge_style_into_module(style, &mut combined);
244    }
245
246    apply_template_usage(
247        kind,
248        source,
249        &template_visible_imports,
250        &template_visible_bound_targets,
251        &mut combined,
252    );
253    combined.unused_import_bindings.sort_unstable();
254    combined.unused_import_bindings.dedup();
255    combined.type_referenced_import_bindings.sort_unstable();
256    combined.type_referenced_import_bindings.dedup();
257    combined.value_referenced_import_bindings.sort_unstable();
258    combined.value_referenced_import_bindings.dedup();
259
260    combined
261}
262
263fn sfc_kind(path: &Path) -> SfcKind {
264    if path.extension().and_then(|ext| ext.to_str()) == Some("vue") {
265        SfcKind::Vue
266    } else {
267        SfcKind::Svelte
268    }
269}
270
271fn empty_sfc_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
272    // For SFC files, use string scanning for suppression comments since script block
273    // byte offsets don't correspond to the original file positions.
274    let suppressions = crate::suppress::parse_suppressions_from_source(source);
275
276    ModuleInfo {
277        file_id,
278        exports: Vec::new(),
279        imports: Vec::new(),
280        re_exports: Vec::new(),
281        dynamic_imports: Vec::new(),
282        dynamic_import_patterns: Vec::new(),
283        require_calls: Vec::new(),
284        member_accesses: Vec::new(),
285        whole_object_uses: Vec::new(),
286        has_cjs_exports: false,
287        content_hash,
288        suppressions,
289        unused_import_bindings: Vec::new(),
290        type_referenced_import_bindings: Vec::new(),
291        value_referenced_import_bindings: Vec::new(),
292        line_offsets: compute_line_offsets(source),
293        complexity: Vec::new(),
294        flag_uses: Vec::new(),
295        class_heritage: vec![],
296        local_type_declarations: Vec::new(),
297        public_signature_type_references: Vec::new(),
298        namespace_object_aliases: Vec::new(),
299    }
300}
301
302fn merge_script_into_module(
303    kind: SfcKind,
304    script: &SfcScript,
305    combined: &mut ModuleInfo,
306    template_visible_imports: &mut FxHashSet<String>,
307    template_visible_bound_targets: &mut FxHashMap<String, String>,
308    need_complexity: bool,
309) {
310    if let Some(src) = &script.src {
311        add_script_src_import(combined, src);
312    }
313
314    let allocator = Allocator::default();
315    let parser_return =
316        Parser::new(&allocator, &script.body, source_type_for_script(script)).parse();
317    let mut extractor = ModuleInfoExtractor::new();
318    extractor.visit_program(&parser_return.program);
319
320    // The script-tag `generic="..."` (Vue) / `generics="..."` (Svelte)
321    // constraint lives on the tag, not in the script body. Imports referenced
322    // only inside it would be classified as unused without this augmentation.
323    // Append a synthetic `type _<...> = unknown;` declaration so oxc_semantic
324    // sees those references and routes the bindings into `type_referenced`.
325    let augmented_body = build_generic_attr_probe_source(script);
326    let binding_usage = if let Some(augmented) = augmented_body.as_deref() {
327        let augmented_return =
328            Parser::new(&allocator, augmented, source_type_for_script(script)).parse();
329        compute_import_binding_usage(&augmented_return.program, &extractor.imports)
330    } else {
331        compute_import_binding_usage(&parser_return.program, &extractor.imports)
332    };
333    combined
334        .unused_import_bindings
335        .extend(binding_usage.unused.iter().cloned());
336    combined
337        .type_referenced_import_bindings
338        .extend(binding_usage.type_referenced.iter().cloned());
339    combined
340        .value_referenced_import_bindings
341        .extend(binding_usage.value_referenced.iter().cloned());
342    if need_complexity {
343        combined.complexity.extend(translate_script_complexity(
344            script,
345            &parser_return.program,
346            &combined.line_offsets,
347        ));
348    }
349
350    if is_template_visible_script(kind, script) {
351        template_visible_imports.extend(
352            extractor
353                .imports
354                .iter()
355                .filter(|import| !import.local_name.is_empty())
356                .map(|import| import.local_name.clone()),
357        );
358        template_visible_bound_targets.extend(
359            extractor
360                .binding_target_names()
361                .iter()
362                .filter(|(local, _)| !local.starts_with("this."))
363                .map(|(local, target)| (local.clone(), target.clone())),
364        );
365    }
366
367    extractor.merge_into(combined);
368}
369
370fn translate_script_complexity(
371    script: &SfcScript,
372    program: &oxc_ast::ast::Program<'_>,
373    sfc_line_offsets: &[u32],
374) -> Vec<FunctionComplexity> {
375    let script_line_offsets = compute_line_offsets(&script.body);
376    let mut complexity = crate::complexity::compute_complexity(program, &script_line_offsets);
377    let (body_start_line, body_start_col) =
378        byte_offset_to_line_col(sfc_line_offsets, script.byte_offset as u32);
379
380    for function in &mut complexity {
381        function.line = body_start_line + function.line.saturating_sub(1);
382        if function.line == body_start_line {
383            function.col += body_start_col;
384        }
385    }
386
387    complexity
388}
389
390fn add_script_src_import(module: &mut ModuleInfo, source: &str) {
391    // Normalize bare filenames (e.g., `<script src="logic.ts">`) so the
392    // resolver treats them as file-relative references, not npm packages.
393    module.imports.push(ImportInfo {
394        source: normalize_asset_url(source),
395        imported_name: ImportedName::SideEffect,
396        local_name: String::new(),
397        is_type_only: false,
398        from_style: false,
399        span: Span::default(),
400        source_span: Span::default(),
401    });
402}
403
404/// `lang` attribute values whose body we know how to scan for `@import` /
405/// `@use` / `@forward` / `@plugin` directives. Plain `<style>` (no `lang`) is treated as
406/// CSS. `less`, `stylus`, and `postcss` bodies are NOT scanned because their
407/// import syntax differs (`@import (reference)` modifiers, etc.); their
408/// `<style src="...">` references are still seeded.
409fn style_lang_is_scss(lang: Option<&str>) -> bool {
410    matches!(lang, Some("scss" | "sass"))
411}
412
413fn style_lang_is_css_like(lang: Option<&str>) -> bool {
414    lang.is_none() || matches!(lang, Some("css"))
415}
416
417fn merge_style_into_module(style: &SfcStyle, combined: &mut ModuleInfo) {
418    // <style src="./theme.scss"> is symmetric to <script src="...">: seed the
419    // referenced file as a side-effect import. The resolver still applies SCSS
420    // partial / include-path / node_modules fallbacks because `from_style` is
421    // set on the import.
422    if let Some(src) = &style.src {
423        combined.imports.push(ImportInfo {
424            source: normalize_asset_url(src),
425            imported_name: ImportedName::SideEffect,
426            local_name: String::new(),
427            is_type_only: false,
428            from_style: true,
429            span: Span::default(),
430            source_span: Span::default(),
431        });
432    }
433
434    let lang = style.lang.as_deref();
435    let is_scss = style_lang_is_scss(lang);
436    let is_css_like = style_lang_is_css_like(lang);
437    if !is_scss && !is_css_like {
438        return;
439    }
440
441    for source in crate::css::extract_css_import_sources(&style.body, is_scss) {
442        combined.imports.push(ImportInfo {
443            source: source.normalized,
444            imported_name: if source.is_plugin {
445                ImportedName::Default
446            } else {
447                ImportedName::SideEffect
448            },
449            local_name: String::new(),
450            is_type_only: false,
451            from_style: true,
452            span: Span::default(),
453            source_span: Span::default(),
454        });
455    }
456}
457
458fn source_type_for_script(script: &SfcScript) -> SourceType {
459    match (script.is_typescript, script.is_jsx) {
460        (true, true) => SourceType::tsx(),
461        (true, false) => SourceType::ts(),
462        (false, true) => SourceType::jsx(),
463        (false, false) => SourceType::mjs(),
464    }
465}
466
467/// Build an augmented script body that pins the `generic="..."` constraint as
468/// a synthetic local type alias. The alias is unexported and uses a sentinel
469/// name so it can't collide with user code. Returns `None` when there is no
470/// generic attribute to pin (the common case), so callers fall back to the
471/// raw body without paying for a second parse.
472fn build_generic_attr_probe_source(script: &SfcScript) -> Option<String> {
473    let constraint = script.generic_attr.as_deref()?.trim();
474    if constraint.is_empty() {
475        return None;
476    }
477    Some(format!(
478        "{}\n;type __FALLOW_GENERIC_ATTR_PROBE<{}> = unknown;\n",
479        script.body, constraint,
480    ))
481}
482
483fn apply_template_usage(
484    kind: SfcKind,
485    source: &str,
486    template_visible_imports: &FxHashSet<String>,
487    template_visible_bound_targets: &FxHashMap<String, String>,
488    combined: &mut ModuleInfo,
489) {
490    if template_visible_imports.is_empty() && template_visible_bound_targets.is_empty() {
491        return;
492    }
493
494    let template_usage = collect_template_usage_with_bound_targets(
495        kind,
496        source,
497        template_visible_imports,
498        template_visible_bound_targets,
499    );
500    combined
501        .unused_import_bindings
502        .retain(|binding| !template_usage.used_bindings.contains(binding));
503    combined
504        .member_accesses
505        .extend(template_usage.member_accesses);
506    combined
507        .whole_object_uses
508        .extend(template_usage.whole_object_uses);
509}
510
511fn is_template_visible_script(kind: SfcKind, script: &SfcScript) -> bool {
512    match kind {
513        SfcKind::Vue => script.is_setup,
514        SfcKind::Svelte => !script.is_context_module,
515    }
516}
517
518// SFC tests exercise regex-based HTML string extraction — no unsafe code,
519// no Miri-specific value. Oxc parser tests are additionally ~1000x slower.
520#[cfg(all(test, not(miri)))]
521mod tests {
522    use super::*;
523
524    // ── is_sfc_file ──────────────────────────────────────────────
525
526    #[test]
527    fn is_sfc_file_vue() {
528        assert!(is_sfc_file(Path::new("App.vue")));
529    }
530
531    #[test]
532    fn is_sfc_file_svelte() {
533        assert!(is_sfc_file(Path::new("Counter.svelte")));
534    }
535
536    #[test]
537    fn is_sfc_file_rejects_ts() {
538        assert!(!is_sfc_file(Path::new("utils.ts")));
539    }
540
541    #[test]
542    fn is_sfc_file_rejects_jsx() {
543        assert!(!is_sfc_file(Path::new("App.jsx")));
544    }
545
546    #[test]
547    fn is_sfc_file_rejects_astro() {
548        assert!(!is_sfc_file(Path::new("Layout.astro")));
549    }
550
551    // ── extract_sfc_scripts: single script block ─────────────────
552
553    #[test]
554    fn single_plain_script() {
555        let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
556        assert_eq!(scripts.len(), 1);
557        assert_eq!(scripts[0].body, "const x = 1;");
558        assert!(!scripts[0].is_typescript);
559        assert!(!scripts[0].is_jsx);
560        assert!(scripts[0].src.is_none());
561    }
562
563    #[test]
564    fn single_ts_script() {
565        let scripts = extract_sfc_scripts(r#"<script lang="ts">const x: number = 1;</script>"#);
566        assert_eq!(scripts.len(), 1);
567        assert!(scripts[0].is_typescript);
568        assert!(!scripts[0].is_jsx);
569    }
570
571    #[test]
572    fn single_tsx_script() {
573        let scripts = extract_sfc_scripts(r#"<script lang="tsx">const el = <div />;</script>"#);
574        assert_eq!(scripts.len(), 1);
575        assert!(scripts[0].is_typescript);
576        assert!(scripts[0].is_jsx);
577    }
578
579    #[test]
580    fn single_jsx_script() {
581        let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
582        assert_eq!(scripts.len(), 1);
583        assert!(!scripts[0].is_typescript);
584        assert!(scripts[0].is_jsx);
585    }
586
587    // ── Multiple script blocks ───────────────────────────────────
588
589    #[test]
590    fn two_script_blocks() {
591        let source = r#"
592<script lang="ts">
593export default {};
594</script>
595<script setup lang="ts">
596const count = 0;
597</script>
598"#;
599        let scripts = extract_sfc_scripts(source);
600        assert_eq!(scripts.len(), 2);
601        assert!(scripts[0].body.contains("export default"));
602        assert!(scripts[1].body.contains("count"));
603    }
604
605    // ── <script setup> ───────────────────────────────────────────
606
607    #[test]
608    fn script_setup_extracted() {
609        let scripts =
610            extract_sfc_scripts(r#"<script setup lang="ts">import { ref } from 'vue';</script>"#);
611        assert_eq!(scripts.len(), 1);
612        assert!(scripts[0].body.contains("import"));
613        assert!(scripts[0].is_typescript);
614    }
615
616    // ── <script src="..."> external script ───────────────────────
617
618    #[test]
619    fn script_src_detected() {
620        let scripts = extract_sfc_scripts(r#"<script src="./component.ts" lang="ts"></script>"#);
621        assert_eq!(scripts.len(), 1);
622        assert_eq!(scripts[0].src.as_deref(), Some("./component.ts"));
623    }
624
625    #[test]
626    fn data_src_not_treated_as_src() {
627        let scripts =
628            extract_sfc_scripts(r#"<script lang="ts" data-src="./nope.ts">const x = 1;</script>"#);
629        assert_eq!(scripts.len(), 1);
630        assert!(scripts[0].src.is_none());
631    }
632
633    // ── HTML comment filtering ───────────────────────────────────
634
635    #[test]
636    fn script_inside_html_comment_filtered() {
637        let source = r#"
638<!-- <script lang="ts">import { bad } from 'bad';</script> -->
639<script lang="ts">import { good } from 'good';</script>
640"#;
641        let scripts = extract_sfc_scripts(source);
642        assert_eq!(scripts.len(), 1);
643        assert!(scripts[0].body.contains("good"));
644    }
645
646    #[test]
647    fn spanning_comment_filters_script() {
648        let source = r#"
649<!-- disabled:
650<script lang="ts">import { bad } from 'bad';</script>
651-->
652<script lang="ts">const ok = true;</script>
653"#;
654        let scripts = extract_sfc_scripts(source);
655        assert_eq!(scripts.len(), 1);
656        assert!(scripts[0].body.contains("ok"));
657    }
658
659    #[test]
660    fn string_containing_comment_markers_not_corrupted() {
661        // A string in the script body containing <!-- should not cause filtering issues
662        let source = r#"
663<script setup lang="ts">
664const marker = "<!-- not a comment -->";
665import { ref } from 'vue';
666</script>
667"#;
668        let scripts = extract_sfc_scripts(source);
669        assert_eq!(scripts.len(), 1);
670        assert!(scripts[0].body.contains("import"));
671    }
672
673    // ── Generic attributes with > in quoted values ───────────────
674
675    #[test]
676    fn generic_attr_with_angle_bracket() {
677        let source =
678            r#"<script setup lang="ts" generic="T extends Foo<Bar>">const x = 1;</script>"#;
679        let scripts = extract_sfc_scripts(source);
680        assert_eq!(scripts.len(), 1);
681        assert_eq!(scripts[0].body, "const x = 1;");
682    }
683
684    #[test]
685    fn nested_generic_attr() {
686        let source = r#"<script setup lang="ts" generic="T extends Map<string, Set<number>>">const x = 1;</script>"#;
687        let scripts = extract_sfc_scripts(source);
688        assert_eq!(scripts.len(), 1);
689        assert_eq!(scripts[0].body, "const x = 1;");
690    }
691
692    // ── lang attribute with single quotes ────────────────────────
693
694    #[test]
695    fn lang_single_quoted() {
696        let scripts = extract_sfc_scripts("<script lang='ts'>const x = 1;</script>");
697        assert_eq!(scripts.len(), 1);
698        assert!(scripts[0].is_typescript);
699    }
700
701    // ── Case-insensitive matching ────────────────────────────────
702
703    #[test]
704    fn uppercase_script_tag() {
705        let scripts = extract_sfc_scripts(r#"<SCRIPT lang="ts">const x = 1;</SCRIPT>"#);
706        assert_eq!(scripts.len(), 1);
707        assert!(scripts[0].is_typescript);
708    }
709
710    // ── Edge cases ───────────────────────────────────────────────
711
712    #[test]
713    fn no_script_block() {
714        let scripts = extract_sfc_scripts("<template><div>Hello</div></template>");
715        assert!(scripts.is_empty());
716    }
717
718    #[test]
719    fn empty_script_body() {
720        let scripts = extract_sfc_scripts(r#"<script lang="ts"></script>"#);
721        assert_eq!(scripts.len(), 1);
722        assert!(scripts[0].body.is_empty());
723    }
724
725    #[test]
726    fn whitespace_only_script() {
727        let scripts = extract_sfc_scripts("<script lang=\"ts\">\n  \n</script>");
728        assert_eq!(scripts.len(), 1);
729        assert!(scripts[0].body.trim().is_empty());
730    }
731
732    #[test]
733    fn byte_offset_is_set() {
734        let source = r#"<template><div/></template><script lang="ts">code</script>"#;
735        let scripts = extract_sfc_scripts(source);
736        assert_eq!(scripts.len(), 1);
737        // The byte_offset should point to where "code" starts in the source
738        let offset = scripts[0].byte_offset;
739        assert_eq!(&source[offset..offset + 4], "code");
740    }
741
742    #[test]
743    fn script_with_extra_attributes() {
744        let scripts = extract_sfc_scripts(
745            r#"<script lang="ts" id="app" type="module" data-custom="val">const x = 1;</script>"#,
746        );
747        assert_eq!(scripts.len(), 1);
748        assert!(scripts[0].is_typescript);
749        assert!(scripts[0].src.is_none());
750    }
751
752    // ── Full parse tests (Oxc parser ~1000x slower under Miri) ──
753
754    #[test]
755    fn multiple_script_blocks_exports_combined() {
756        let source = r#"
757<script lang="ts">
758export const version = '1.0';
759</script>
760<script setup lang="ts">
761import { ref } from 'vue';
762const count = ref(0);
763</script>
764"#;
765        let info = parse_sfc_to_module(FileId(0), Path::new("Dual.vue"), source, 0, false);
766        // The non-setup block exports `version`
767        assert!(
768            info.exports
769                .iter()
770                .any(|e| matches!(&e.name, crate::ExportName::Named(n) if n == "version")),
771            "export from <script> block should be extracted"
772        );
773        // The setup block imports `ref` from 'vue'
774        assert!(
775            info.imports.iter().any(|i| i.source == "vue"),
776            "import from <script setup> block should be extracted"
777        );
778    }
779
780    // ── lang="tsx" detection ────────────────────────────────────
781
782    #[test]
783    fn lang_tsx_detected_as_typescript_jsx() {
784        let scripts =
785            extract_sfc_scripts(r#"<script lang="tsx">const el = <div>{x}</div>;</script>"#);
786        assert_eq!(scripts.len(), 1);
787        assert!(scripts[0].is_typescript, "lang=tsx should be typescript");
788        assert!(scripts[0].is_jsx, "lang=tsx should be jsx");
789    }
790
791    // ── HTML comment filtering of script blocks ─────────────────
792
793    #[test]
794    fn multiline_html_comment_filters_all_script_blocks_inside() {
795        let source = r#"
796<!--
797  This whole section is disabled:
798  <script lang="ts">import { bad1 } from 'bad1';</script>
799  <script lang="ts">import { bad2 } from 'bad2';</script>
800-->
801<script lang="ts">import { good } from 'good';</script>
802"#;
803        let scripts = extract_sfc_scripts(source);
804        assert_eq!(scripts.len(), 1);
805        assert!(scripts[0].body.contains("good"));
806    }
807
808    // ── <script src="..."> generates side-effect import ─────────
809
810    #[test]
811    fn script_src_generates_side_effect_import() {
812        let info = parse_sfc_to_module(
813            FileId(0),
814            Path::new("External.vue"),
815            r#"<script src="./external-logic.ts" lang="ts"></script>"#,
816            0,
817            false,
818        );
819        assert!(
820            info.imports
821                .iter()
822                .any(|i| i.source == "./external-logic.ts"
823                    && matches!(i.imported_name, ImportedName::SideEffect)),
824            "script src should generate a side-effect import"
825        );
826    }
827
828    // ── Additional coverage ─────────────────────────────────────
829
830    #[test]
831    fn parse_sfc_no_script_returns_empty_module() {
832        let info = parse_sfc_to_module(
833            FileId(0),
834            Path::new("Empty.vue"),
835            "<template><div>Hello</div></template>",
836            42,
837            false,
838        );
839        assert!(info.imports.is_empty());
840        assert!(info.exports.is_empty());
841        assert_eq!(info.content_hash, 42);
842        assert_eq!(info.file_id, FileId(0));
843    }
844
845    #[test]
846    fn parse_sfc_has_line_offsets() {
847        let info = parse_sfc_to_module(
848            FileId(0),
849            Path::new("LineOffsets.vue"),
850            r#"<script lang="ts">const x = 1;</script>"#,
851            0,
852            false,
853        );
854        assert!(!info.line_offsets.is_empty());
855    }
856
857    #[test]
858    fn parse_sfc_has_suppressions() {
859        let info = parse_sfc_to_module(
860            FileId(0),
861            Path::new("Suppressions.vue"),
862            r#"<script lang="ts">
863// fallow-ignore-file
864export const foo = 1;
865</script>"#,
866            0,
867            false,
868        );
869        assert!(!info.suppressions.is_empty());
870    }
871
872    #[test]
873    fn source_type_jsx_detection() {
874        let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
875        assert_eq!(scripts.len(), 1);
876        assert!(!scripts[0].is_typescript);
877        assert!(scripts[0].is_jsx);
878    }
879
880    #[test]
881    fn source_type_plain_js_detection() {
882        let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
883        assert_eq!(scripts.len(), 1);
884        assert!(!scripts[0].is_typescript);
885        assert!(!scripts[0].is_jsx);
886    }
887
888    #[test]
889    fn is_sfc_file_rejects_no_extension() {
890        assert!(!is_sfc_file(Path::new("Makefile")));
891    }
892
893    #[test]
894    fn is_sfc_file_rejects_mdx() {
895        assert!(!is_sfc_file(Path::new("post.mdx")));
896    }
897
898    #[test]
899    fn is_sfc_file_rejects_css() {
900        assert!(!is_sfc_file(Path::new("styles.css")));
901    }
902
903    #[test]
904    fn multiple_script_blocks_both_have_offsets() {
905        let source = r#"<script lang="ts">const a = 1;</script>
906<script setup lang="ts">const b = 2;</script>"#;
907        let scripts = extract_sfc_scripts(source);
908        assert_eq!(scripts.len(), 2);
909        // Both scripts should have valid byte offsets
910        let offset0 = scripts[0].byte_offset;
911        let offset1 = scripts[1].byte_offset;
912        assert_eq!(
913            &source[offset0..offset0 + "const a = 1;".len()],
914            "const a = 1;"
915        );
916        assert_eq!(
917            &source[offset1..offset1 + "const b = 2;".len()],
918            "const b = 2;"
919        );
920    }
921
922    #[test]
923    fn script_with_src_and_lang() {
924        // src + lang should both be detected
925        let scripts = extract_sfc_scripts(r#"<script src="./logic.ts" lang="tsx"></script>"#);
926        assert_eq!(scripts.len(), 1);
927        assert_eq!(scripts[0].src.as_deref(), Some("./logic.ts"));
928        assert!(scripts[0].is_typescript);
929        assert!(scripts[0].is_jsx);
930    }
931
932    // ── extract_sfc_styles (issue #195 Case B) ──
933
934    #[test]
935    fn extract_style_block_lang_scss() {
936        let source = r#"<template/><style lang="scss">@import 'Foo';</style>"#;
937        let styles = extract_sfc_styles(source);
938        assert_eq!(styles.len(), 1);
939        assert_eq!(styles[0].lang.as_deref(), Some("scss"));
940        assert!(styles[0].body.contains("@import"));
941        assert!(styles[0].src.is_none());
942    }
943
944    #[test]
945    fn extract_style_block_with_src() {
946        let source = r#"<style src="./theme.scss" lang="scss"></style>"#;
947        let styles = extract_sfc_styles(source);
948        assert_eq!(styles.len(), 1);
949        assert_eq!(styles[0].src.as_deref(), Some("./theme.scss"));
950        assert_eq!(styles[0].lang.as_deref(), Some("scss"));
951    }
952
953    #[test]
954    fn extract_style_block_plain_no_lang() {
955        let source = r"<style>.foo { color: red; }</style>";
956        let styles = extract_sfc_styles(source);
957        assert_eq!(styles.len(), 1);
958        assert!(styles[0].lang.is_none());
959    }
960
961    #[test]
962    fn extract_multiple_style_blocks() {
963        let source = r#"<style lang="scss">@import 'a';</style>
964<style scoped lang="scss">@import 'b';</style>"#;
965        let styles = extract_sfc_styles(source);
966        assert_eq!(styles.len(), 2);
967    }
968
969    #[test]
970    fn style_block_inside_html_comment_filtered() {
971        let source = r#"<!-- <style lang="scss">@import 'bad';</style> -->
972<style lang="scss">@import 'good';</style>"#;
973        let styles = extract_sfc_styles(source);
974        assert_eq!(styles.len(), 1);
975        assert!(styles[0].body.contains("good"));
976    }
977
978    #[test]
979    fn parse_sfc_extracts_style_imports_with_from_style_flag() {
980        let info = parse_sfc_to_module(
981            FileId(0),
982            Path::new("Foo.vue"),
983            r#"<template/><style lang="scss">@import 'Foo';</style>"#,
984            0,
985            false,
986        );
987        let style_import = info
988            .imports
989            .iter()
990            .find(|i| i.source == "./Foo")
991            .expect("scss @import 'Foo' should be normalized to ./Foo");
992        assert!(
993            style_import.from_style,
994            "imports from <style> blocks must carry from_style=true so the resolver \
995             enables SCSS partial fallback for the SFC importer"
996        );
997        assert!(matches!(
998            style_import.imported_name,
999            ImportedName::SideEffect
1000        ));
1001    }
1002
1003    #[test]
1004    fn parse_sfc_extracts_style_plugin_as_default_import() {
1005        let info = parse_sfc_to_module(
1006            FileId(0),
1007            Path::new("Foo.vue"),
1008            r#"<template/><style>@plugin "./tailwind-plugin.js";</style>"#,
1009            0,
1010            false,
1011        );
1012        let plugin_import = info
1013            .imports
1014            .iter()
1015            .find(|i| i.source == "./tailwind-plugin.js")
1016            .expect("style @plugin should create an import");
1017        assert!(plugin_import.from_style);
1018        assert!(matches!(plugin_import.imported_name, ImportedName::Default));
1019    }
1020
1021    #[test]
1022    fn parse_sfc_extracts_style_src_with_from_style_flag() {
1023        let info = parse_sfc_to_module(
1024            FileId(0),
1025            Path::new("Bar.vue"),
1026            r#"<style src="./Bar.scss" lang="scss"></style>"#,
1027            0,
1028            false,
1029        );
1030        let style_src = info
1031            .imports
1032            .iter()
1033            .find(|i| i.source == "./Bar.scss")
1034            .expect("<style src=\"./Bar.scss\"> should produce a side-effect import");
1035        assert!(style_src.from_style);
1036    }
1037
1038    #[test]
1039    fn parse_sfc_skips_unsupported_style_lang_body_but_keeps_src() {
1040        // <style lang="postcss"> body is NOT scanned (custom directives); src is still seeded.
1041        let info = parse_sfc_to_module(
1042            FileId(0),
1043            Path::new("Baz.vue"),
1044            r#"<style lang="postcss" src="./Baz.pcss">@custom-rule "skipped";</style>"#,
1045            0,
1046            false,
1047        );
1048        assert!(
1049            info.imports.iter().any(|i| i.source == "./Baz.pcss"),
1050            "src reference should still be seeded for unsupported lang"
1051        );
1052        assert!(
1053            !info.imports.iter().any(|i| i.source.contains("skipped")),
1054            "postcss body should not be scanned for @import directives"
1055        );
1056    }
1057}