Skip to main content

fallow_extract/
sfc.rs

1//! Vue/Svelte Single File Component (SFC) script 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
6use std::path::Path;
7use std::sync::LazyLock;
8
9use oxc_allocator::Allocator;
10use oxc_ast_visit::Visit;
11use oxc_parser::Parser;
12use oxc_span::SourceType;
13
14use crate::visitor::ModuleInfoExtractor;
15use crate::{ImportInfo, ImportedName, ModuleInfo};
16use fallow_types::discover::FileId;
17use oxc_span::Span;
18
19/// Regex to extract `<script>` block content from Vue/Svelte SFCs.
20/// The attrs pattern handles `>` inside quoted attribute values (e.g., `generic="T extends Foo<Bar>"`).
21static SCRIPT_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
22    regex::Regex::new(
23        r#"(?is)<script\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>(?P<body>[\s\S]*?)</script>"#,
24    )
25    .expect("valid regex")
26});
27
28/// Regex to extract the `lang` attribute value from a script tag.
29static LANG_ATTR_RE: LazyLock<regex::Regex> =
30    LazyLock::new(|| regex::Regex::new(r#"lang\s*=\s*["'](\w+)["']"#).expect("valid regex"));
31
32/// Regex to extract the `src` attribute value from a script tag.
33/// Requires whitespace (or start of string) before `src` to avoid matching `data-src` etc.
34static SRC_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
35    regex::Regex::new(r#"(?:^|\s)src\s*=\s*["']([^"']+)["']"#).expect("valid regex")
36});
37
38/// Regex to match HTML comments for filtering script blocks inside comments.
39static HTML_COMMENT_RE: LazyLock<regex::Regex> =
40    LazyLock::new(|| regex::Regex::new(r"(?s)<!--.*?-->").expect("valid regex"));
41
42/// An extracted `<script>` block from a Vue or Svelte SFC.
43pub struct SfcScript {
44    /// The script body text.
45    pub body: String,
46    /// Whether the script uses TypeScript (`lang="ts"` or `lang="tsx"`).
47    pub is_typescript: bool,
48    /// Whether the script uses JSX syntax (`lang="tsx"` or `lang="jsx"`).
49    pub is_jsx: bool,
50    /// Byte offset of the script body within the full SFC source.
51    pub byte_offset: usize,
52    /// External script source path from `src` attribute.
53    pub src: Option<String>,
54}
55
56/// Extract all `<script>` blocks from a Vue/Svelte SFC source string.
57pub fn extract_sfc_scripts(source: &str) -> Vec<SfcScript> {
58    // Build HTML comment ranges to filter out <script> blocks inside comments.
59    // Using ranges instead of source replacement avoids corrupting script body content
60    // (e.g., string literals containing "<!--" would be destroyed by replacement).
61    let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
62        .find_iter(source)
63        .map(|m| (m.start(), m.end()))
64        .collect();
65
66    SCRIPT_BLOCK_RE
67        .captures_iter(source)
68        .filter(|cap| {
69            let start = cap.get(0).map_or(0, |m| m.start());
70            !comment_ranges
71                .iter()
72                .any(|&(cs, ce)| start >= cs && start < ce)
73        })
74        .map(|cap| {
75            let attrs = cap.name("attrs").map_or("", |m| m.as_str());
76            let body_match = cap.name("body");
77            let byte_offset = body_match.map_or(0, |m| m.start());
78            let body = body_match.map_or("", |m| m.as_str()).to_string();
79            let lang = LANG_ATTR_RE
80                .captures(attrs)
81                .and_then(|c| c.get(1))
82                .map(|m| m.as_str());
83            let is_typescript = matches!(lang, Some("ts" | "tsx"));
84            let is_jsx = matches!(lang, Some("tsx" | "jsx"));
85            let src = SRC_ATTR_RE
86                .captures(attrs)
87                .and_then(|c| c.get(1))
88                .map(|m| m.as_str().to_string());
89            SfcScript {
90                body,
91                is_typescript,
92                is_jsx,
93                byte_offset,
94                src,
95            }
96        })
97        .collect()
98}
99
100/// Check if a file path is a Vue or Svelte SFC (`.vue` or `.svelte`).
101pub fn is_sfc_file(path: &Path) -> bool {
102    path.extension()
103        .and_then(|e| e.to_str())
104        .is_some_and(|ext| ext == "vue" || ext == "svelte")
105}
106
107/// Parse an SFC file by extracting and combining all `<script>` blocks.
108pub(crate) fn parse_sfc_to_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
109    let scripts = extract_sfc_scripts(source);
110
111    // For SFC files, use string scanning for suppression comments since script block
112    // byte offsets don't correspond to the original file positions.
113    let suppressions = crate::suppress::parse_suppressions_from_source(source);
114
115    let mut combined = ModuleInfo {
116        file_id,
117        exports: Vec::new(),
118        imports: Vec::new(),
119        re_exports: Vec::new(),
120        dynamic_imports: Vec::new(),
121        dynamic_import_patterns: Vec::new(),
122        require_calls: Vec::new(),
123        member_accesses: Vec::new(),
124        whole_object_uses: Vec::new(),
125        has_cjs_exports: false,
126        content_hash,
127        suppressions,
128        line_offsets: fallow_types::extract::compute_line_offsets(source),
129    };
130
131    for script in &scripts {
132        if let Some(src) = &script.src {
133            combined.imports.push(ImportInfo {
134                source: src.clone(),
135                imported_name: ImportedName::SideEffect,
136                local_name: String::new(),
137                is_type_only: false,
138                span: Span::default(),
139            });
140        }
141
142        let source_type = match (script.is_typescript, script.is_jsx) {
143            (true, true) => SourceType::tsx(),
144            (true, false) => SourceType::ts(),
145            (false, true) => SourceType::jsx(),
146            (false, false) => SourceType::mjs(),
147        };
148        let allocator = Allocator::default();
149        let parser_return = Parser::new(&allocator, &script.body, source_type).parse();
150        let mut extractor = ModuleInfoExtractor::new();
151        extractor.visit_program(&parser_return.program);
152        extractor.merge_into(&mut combined);
153    }
154
155    combined
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    // ── is_sfc_file ──────────────────────────────────────────────
163
164    #[test]
165    fn is_sfc_file_vue() {
166        assert!(is_sfc_file(Path::new("App.vue")));
167    }
168
169    #[test]
170    fn is_sfc_file_svelte() {
171        assert!(is_sfc_file(Path::new("Counter.svelte")));
172    }
173
174    #[test]
175    fn is_sfc_file_rejects_ts() {
176        assert!(!is_sfc_file(Path::new("utils.ts")));
177    }
178
179    #[test]
180    fn is_sfc_file_rejects_jsx() {
181        assert!(!is_sfc_file(Path::new("App.jsx")));
182    }
183
184    #[test]
185    fn is_sfc_file_rejects_astro() {
186        assert!(!is_sfc_file(Path::new("Layout.astro")));
187    }
188
189    // ── extract_sfc_scripts: single script block ─────────────────
190
191    #[test]
192    fn single_plain_script() {
193        let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
194        assert_eq!(scripts.len(), 1);
195        assert_eq!(scripts[0].body, "const x = 1;");
196        assert!(!scripts[0].is_typescript);
197        assert!(!scripts[0].is_jsx);
198        assert!(scripts[0].src.is_none());
199    }
200
201    #[test]
202    fn single_ts_script() {
203        let scripts = extract_sfc_scripts(r#"<script lang="ts">const x: number = 1;</script>"#);
204        assert_eq!(scripts.len(), 1);
205        assert!(scripts[0].is_typescript);
206        assert!(!scripts[0].is_jsx);
207    }
208
209    #[test]
210    fn single_tsx_script() {
211        let scripts = extract_sfc_scripts(r#"<script lang="tsx">const el = <div />;</script>"#);
212        assert_eq!(scripts.len(), 1);
213        assert!(scripts[0].is_typescript);
214        assert!(scripts[0].is_jsx);
215    }
216
217    #[test]
218    fn single_jsx_script() {
219        let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
220        assert_eq!(scripts.len(), 1);
221        assert!(!scripts[0].is_typescript);
222        assert!(scripts[0].is_jsx);
223    }
224
225    // ── Multiple script blocks ───────────────────────────────────
226
227    #[test]
228    fn two_script_blocks() {
229        let source = r#"
230<script lang="ts">
231export default {};
232</script>
233<script setup lang="ts">
234const count = 0;
235</script>
236"#;
237        let scripts = extract_sfc_scripts(source);
238        assert_eq!(scripts.len(), 2);
239        assert!(scripts[0].body.contains("export default"));
240        assert!(scripts[1].body.contains("count"));
241    }
242
243    // ── <script setup> ───────────────────────────────────────────
244
245    #[test]
246    fn script_setup_extracted() {
247        let scripts =
248            extract_sfc_scripts(r#"<script setup lang="ts">import { ref } from 'vue';</script>"#);
249        assert_eq!(scripts.len(), 1);
250        assert!(scripts[0].body.contains("import"));
251        assert!(scripts[0].is_typescript);
252    }
253
254    // ── <script src="..."> external script ───────────────────────
255
256    #[test]
257    fn script_src_detected() {
258        let scripts = extract_sfc_scripts(r#"<script src="./component.ts" lang="ts"></script>"#);
259        assert_eq!(scripts.len(), 1);
260        assert_eq!(scripts[0].src.as_deref(), Some("./component.ts"));
261    }
262
263    #[test]
264    fn data_src_not_treated_as_src() {
265        let scripts =
266            extract_sfc_scripts(r#"<script lang="ts" data-src="./nope.ts">const x = 1;</script>"#);
267        assert_eq!(scripts.len(), 1);
268        assert!(scripts[0].src.is_none());
269    }
270
271    // ── HTML comment filtering ───────────────────────────────────
272
273    #[test]
274    fn script_inside_html_comment_filtered() {
275        let source = r#"
276<!-- <script lang="ts">import { bad } from 'bad';</script> -->
277<script lang="ts">import { good } from 'good';</script>
278"#;
279        let scripts = extract_sfc_scripts(source);
280        assert_eq!(scripts.len(), 1);
281        assert!(scripts[0].body.contains("good"));
282    }
283
284    #[test]
285    fn spanning_comment_filters_script() {
286        let source = r#"
287<!-- disabled:
288<script lang="ts">import { bad } from 'bad';</script>
289-->
290<script lang="ts">const ok = true;</script>
291"#;
292        let scripts = extract_sfc_scripts(source);
293        assert_eq!(scripts.len(), 1);
294        assert!(scripts[0].body.contains("ok"));
295    }
296
297    #[test]
298    fn string_containing_comment_markers_not_corrupted() {
299        // A string in the script body containing <!-- should not cause filtering issues
300        let source = r#"
301<script setup lang="ts">
302const marker = "<!-- not a comment -->";
303import { ref } from 'vue';
304</script>
305"#;
306        let scripts = extract_sfc_scripts(source);
307        assert_eq!(scripts.len(), 1);
308        assert!(scripts[0].body.contains("import"));
309    }
310
311    // ── Generic attributes with > in quoted values ───────────────
312
313    #[test]
314    fn generic_attr_with_angle_bracket() {
315        let source =
316            r#"<script setup lang="ts" generic="T extends Foo<Bar>">const x = 1;</script>"#;
317        let scripts = extract_sfc_scripts(source);
318        assert_eq!(scripts.len(), 1);
319        assert_eq!(scripts[0].body, "const x = 1;");
320    }
321
322    #[test]
323    fn nested_generic_attr() {
324        let source = r#"<script setup lang="ts" generic="T extends Map<string, Set<number>>">const x = 1;</script>"#;
325        let scripts = extract_sfc_scripts(source);
326        assert_eq!(scripts.len(), 1);
327        assert_eq!(scripts[0].body, "const x = 1;");
328    }
329
330    // ── lang attribute with single quotes ────────────────────────
331
332    #[test]
333    fn lang_single_quoted() {
334        let scripts = extract_sfc_scripts("<script lang='ts'>const x = 1;</script>");
335        assert_eq!(scripts.len(), 1);
336        assert!(scripts[0].is_typescript);
337    }
338
339    // ── Case-insensitive matching ────────────────────────────────
340
341    #[test]
342    fn uppercase_script_tag() {
343        let scripts = extract_sfc_scripts(r#"<SCRIPT lang="ts">const x = 1;</SCRIPT>"#);
344        assert_eq!(scripts.len(), 1);
345        assert!(scripts[0].is_typescript);
346    }
347
348    // ── Edge cases ───────────────────────────────────────────────
349
350    #[test]
351    fn no_script_block() {
352        let scripts = extract_sfc_scripts("<template><div>Hello</div></template>");
353        assert!(scripts.is_empty());
354    }
355
356    #[test]
357    fn empty_script_body() {
358        let scripts = extract_sfc_scripts(r#"<script lang="ts"></script>"#);
359        assert_eq!(scripts.len(), 1);
360        assert!(scripts[0].body.is_empty());
361    }
362
363    #[test]
364    fn whitespace_only_script() {
365        let scripts = extract_sfc_scripts("<script lang=\"ts\">\n  \n</script>");
366        assert_eq!(scripts.len(), 1);
367        assert!(scripts[0].body.trim().is_empty());
368    }
369
370    #[test]
371    fn byte_offset_is_set() {
372        let source = r#"<template><div/></template><script lang="ts">code</script>"#;
373        let scripts = extract_sfc_scripts(source);
374        assert_eq!(scripts.len(), 1);
375        // The byte_offset should point to where "code" starts in the source
376        let offset = scripts[0].byte_offset;
377        assert_eq!(&source[offset..offset + 4], "code");
378    }
379
380    #[test]
381    fn script_with_extra_attributes() {
382        let scripts = extract_sfc_scripts(
383            r#"<script lang="ts" id="app" type="module" data-custom="val">const x = 1;</script>"#,
384        );
385        assert_eq!(scripts.len(), 1);
386        assert!(scripts[0].is_typescript);
387        assert!(scripts[0].src.is_none());
388    }
389
390    // ── Multiple script blocks: exports from both ───────────────
391
392    #[test]
393    fn multiple_script_blocks_exports_combined() {
394        let source = r#"
395<script lang="ts">
396export const version = '1.0';
397</script>
398<script setup lang="ts">
399import { ref } from 'vue';
400const count = ref(0);
401</script>
402"#;
403        let info = parse_sfc_to_module(FileId(0), source, 0);
404        // The non-setup block exports `version`
405        assert!(
406            info.exports
407                .iter()
408                .any(|e| matches!(&e.name, crate::ExportName::Named(n) if n == "version")),
409            "export from <script> block should be extracted"
410        );
411        // The setup block imports `ref` from 'vue'
412        assert!(
413            info.imports.iter().any(|i| i.source == "vue"),
414            "import from <script setup> block should be extracted"
415        );
416    }
417
418    // ── lang="tsx" detection ────────────────────────────────────
419
420    #[test]
421    fn lang_tsx_detected_as_typescript_jsx() {
422        let scripts =
423            extract_sfc_scripts(r#"<script lang="tsx">const el = <div>{x}</div>;</script>"#);
424        assert_eq!(scripts.len(), 1);
425        assert!(scripts[0].is_typescript, "lang=tsx should be typescript");
426        assert!(scripts[0].is_jsx, "lang=tsx should be jsx");
427    }
428
429    // ── HTML comment filtering of script blocks ─────────────────
430
431    #[test]
432    fn multiline_html_comment_filters_all_script_blocks_inside() {
433        let source = r#"
434<!--
435  This whole section is disabled:
436  <script lang="ts">import { bad1 } from 'bad1';</script>
437  <script lang="ts">import { bad2 } from 'bad2';</script>
438-->
439<script lang="ts">import { good } from 'good';</script>
440"#;
441        let scripts = extract_sfc_scripts(source);
442        assert_eq!(scripts.len(), 1);
443        assert!(scripts[0].body.contains("good"));
444    }
445
446    // ── <script src="..."> generates side-effect import ─────────
447
448    #[test]
449    fn script_src_generates_side_effect_import() {
450        let info = parse_sfc_to_module(
451            FileId(0),
452            r#"<script src="./external-logic.ts" lang="ts"></script>"#,
453            0,
454        );
455        assert!(
456            info.imports
457                .iter()
458                .any(|i| i.source == "./external-logic.ts"
459                    && matches!(i.imported_name, ImportedName::SideEffect)),
460            "script src should generate a side-effect import"
461        );
462    }
463}