1use 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
28static 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
37static LANG_ATTR_RE: LazyLock<regex::Regex> =
39 LazyLock::new(|| regex::Regex::new(r#"lang\s*=\s*["'](\w+)["']"#).expect("valid regex"));
40
41static SRC_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
44 regex::Regex::new(r#"(?:^|\s)src\s*=\s*["']([^"']+)["']"#).expect("valid regex")
45});
46
47static SETUP_ATTR_RE: LazyLock<regex::Regex> =
49 LazyLock::new(|| regex::Regex::new(r"(?:^|\s)setup(?:\s|$)").expect("valid regex"));
50
51static CONTEXT_MODULE_ATTR_RE: LazyLock<regex::Regex> =
53 LazyLock::new(|| regex::Regex::new(r#"context\s*=\s*["']module["']"#).expect("valid regex"));
54
55static 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
63static 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
70static HTML_COMMENT_RE: LazyLock<regex::Regex> =
72 LazyLock::new(|| regex::Regex::new(r"(?s)<!--.*?-->").expect("valid regex"));
73
74static 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
84pub struct SfcScript {
86 pub body: String,
88 pub is_typescript: bool,
90 pub is_jsx: bool,
92 pub byte_offset: usize,
94 pub src: Option<String>,
96 pub is_setup: bool,
98 pub is_context_module: bool,
100 pub generic_attr: Option<String>,
104}
105
106pub fn extract_sfc_scripts(source: &str) -> Vec<SfcScript> {
108 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
161pub struct SfcStyle {
163 pub body: String,
165 pub lang: Option<String>,
168 pub src: Option<String>,
170}
171
172pub 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#[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
216pub(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 let parsed = 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 has_angular_component_template_url: false,
288 content_hash,
289 suppressions: parsed.suppressions,
290 unknown_suppression_kinds: parsed.unknown_kinds,
291 unused_import_bindings: Vec::new(),
292 type_referenced_import_bindings: Vec::new(),
293 value_referenced_import_bindings: Vec::new(),
294 line_offsets: compute_line_offsets(source),
295 complexity: Vec::new(),
296 flag_uses: Vec::new(),
297 class_heritage: vec![],
298 local_type_declarations: Vec::new(),
299 public_signature_type_references: Vec::new(),
300 namespace_object_aliases: Vec::new(),
301 iconify_prefixes: Vec::new(),
302 }
303}
304
305fn merge_script_into_module(
306 kind: SfcKind,
307 script: &SfcScript,
308 combined: &mut ModuleInfo,
309 template_visible_imports: &mut FxHashSet<String>,
310 template_visible_bound_targets: &mut FxHashMap<String, String>,
311 need_complexity: bool,
312) {
313 if let Some(src) = &script.src {
314 add_script_src_import(combined, src);
315 }
316
317 let allocator = Allocator::default();
318 let parser_return =
319 Parser::new(&allocator, &script.body, source_type_for_script(script)).parse();
320 let mut extractor = ModuleInfoExtractor::new();
321 extractor.visit_program(&parser_return.program);
322
323 let augmented_body = build_generic_attr_probe_source(script);
329 let empty_template_used = rustc_hash::FxHashSet::default();
335 let binding_usage = if let Some(augmented) = augmented_body.as_deref() {
336 let augmented_return =
337 Parser::new(&allocator, augmented, source_type_for_script(script)).parse();
338 compute_import_binding_usage(
339 &augmented_return.program,
340 &extractor.imports,
341 &empty_template_used,
342 )
343 } else {
344 compute_import_binding_usage(
345 &parser_return.program,
346 &extractor.imports,
347 &empty_template_used,
348 )
349 };
350 combined
351 .unused_import_bindings
352 .extend(binding_usage.unused.iter().cloned());
353 combined
354 .type_referenced_import_bindings
355 .extend(binding_usage.type_referenced.iter().cloned());
356 combined
357 .value_referenced_import_bindings
358 .extend(binding_usage.value_referenced.iter().cloned());
359 if need_complexity {
360 combined.complexity.extend(translate_script_complexity(
361 script,
362 &parser_return.program,
363 &combined.line_offsets,
364 ));
365 }
366
367 if is_template_visible_script(kind, script) {
368 template_visible_imports.extend(
369 extractor
370 .imports
371 .iter()
372 .filter(|import| !import.local_name.is_empty())
373 .map(|import| import.local_name.clone()),
374 );
375 template_visible_bound_targets.extend(
376 extractor
377 .binding_target_names()
378 .iter()
379 .filter(|(local, _)| !local.starts_with("this."))
380 .map(|(local, target)| (local.clone(), target.clone())),
381 );
382 }
383
384 extractor.merge_into(combined);
385}
386
387fn translate_script_complexity(
388 script: &SfcScript,
389 program: &oxc_ast::ast::Program<'_>,
390 sfc_line_offsets: &[u32],
391) -> Vec<FunctionComplexity> {
392 let script_line_offsets = compute_line_offsets(&script.body);
393 let mut complexity = crate::complexity::compute_complexity(program, &script_line_offsets);
394 let (body_start_line, body_start_col) =
395 byte_offset_to_line_col(sfc_line_offsets, script.byte_offset as u32);
396
397 for function in &mut complexity {
398 function.line = body_start_line + function.line.saturating_sub(1);
399 if function.line == body_start_line {
400 function.col += body_start_col;
401 }
402 }
403
404 complexity
405}
406
407fn add_script_src_import(module: &mut ModuleInfo, source: &str) {
408 module.imports.push(ImportInfo {
411 source: normalize_asset_url(source),
412 imported_name: ImportedName::SideEffect,
413 local_name: String::new(),
414 is_type_only: false,
415 from_style: false,
416 span: Span::default(),
417 source_span: Span::default(),
418 });
419}
420
421fn style_lang_is_scss(lang: Option<&str>) -> bool {
427 matches!(lang, Some("scss" | "sass"))
428}
429
430fn style_lang_is_css_like(lang: Option<&str>) -> bool {
431 lang.is_none() || matches!(lang, Some("css"))
432}
433
434fn merge_style_into_module(style: &SfcStyle, combined: &mut ModuleInfo) {
435 if let Some(src) = &style.src {
440 combined.imports.push(ImportInfo {
441 source: normalize_asset_url(src),
442 imported_name: ImportedName::SideEffect,
443 local_name: String::new(),
444 is_type_only: false,
445 from_style: true,
446 span: Span::default(),
447 source_span: Span::default(),
448 });
449 }
450
451 let lang = style.lang.as_deref();
452 let is_scss = style_lang_is_scss(lang);
453 let is_css_like = style_lang_is_css_like(lang);
454 if !is_scss && !is_css_like {
455 return;
456 }
457
458 for source in crate::css::extract_css_import_sources(&style.body, is_scss) {
459 combined.imports.push(ImportInfo {
460 source: source.normalized,
461 imported_name: if source.is_plugin {
462 ImportedName::Default
463 } else {
464 ImportedName::SideEffect
465 },
466 local_name: String::new(),
467 is_type_only: false,
468 from_style: true,
469 span: Span::default(),
470 source_span: Span::default(),
471 });
472 }
473}
474
475fn source_type_for_script(script: &SfcScript) -> SourceType {
476 match (script.is_typescript, script.is_jsx) {
477 (true, true) => SourceType::tsx(),
478 (true, false) => SourceType::ts(),
479 (false, true) => SourceType::jsx(),
480 (false, false) => SourceType::mjs(),
481 }
482}
483
484fn build_generic_attr_probe_source(script: &SfcScript) -> Option<String> {
490 let constraint = script.generic_attr.as_deref()?.trim();
491 if constraint.is_empty() {
492 return None;
493 }
494 Some(format!(
495 "{}\n;type __FALLOW_GENERIC_ATTR_PROBE<{}> = unknown;\n",
496 script.body, constraint,
497 ))
498}
499
500fn apply_template_usage(
501 kind: SfcKind,
502 source: &str,
503 template_visible_imports: &FxHashSet<String>,
504 template_visible_bound_targets: &FxHashMap<String, String>,
505 combined: &mut ModuleInfo,
506) {
507 if template_visible_imports.is_empty() && template_visible_bound_targets.is_empty() {
508 return;
509 }
510
511 let template_usage = collect_template_usage_with_bound_targets(
512 kind,
513 source,
514 template_visible_imports,
515 template_visible_bound_targets,
516 );
517 combined
518 .unused_import_bindings
519 .retain(|binding| !template_usage.used_bindings.contains(binding));
520 combined
521 .member_accesses
522 .extend(template_usage.member_accesses);
523 combined
524 .whole_object_uses
525 .extend(template_usage.whole_object_uses);
526}
527
528fn is_template_visible_script(kind: SfcKind, script: &SfcScript) -> bool {
529 match kind {
530 SfcKind::Vue => script.is_setup,
531 SfcKind::Svelte => !script.is_context_module,
532 }
533}
534
535#[cfg(all(test, not(miri)))]
538mod tests {
539 use super::*;
540
541 #[test]
544 fn is_sfc_file_vue() {
545 assert!(is_sfc_file(Path::new("App.vue")));
546 }
547
548 #[test]
549 fn is_sfc_file_svelte() {
550 assert!(is_sfc_file(Path::new("Counter.svelte")));
551 }
552
553 #[test]
554 fn is_sfc_file_rejects_ts() {
555 assert!(!is_sfc_file(Path::new("utils.ts")));
556 }
557
558 #[test]
559 fn is_sfc_file_rejects_jsx() {
560 assert!(!is_sfc_file(Path::new("App.jsx")));
561 }
562
563 #[test]
564 fn is_sfc_file_rejects_astro() {
565 assert!(!is_sfc_file(Path::new("Layout.astro")));
566 }
567
568 #[test]
571 fn single_plain_script() {
572 let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
573 assert_eq!(scripts.len(), 1);
574 assert_eq!(scripts[0].body, "const x = 1;");
575 assert!(!scripts[0].is_typescript);
576 assert!(!scripts[0].is_jsx);
577 assert!(scripts[0].src.is_none());
578 }
579
580 #[test]
581 fn single_ts_script() {
582 let scripts = extract_sfc_scripts(r#"<script lang="ts">const x: number = 1;</script>"#);
583 assert_eq!(scripts.len(), 1);
584 assert!(scripts[0].is_typescript);
585 assert!(!scripts[0].is_jsx);
586 }
587
588 #[test]
589 fn single_tsx_script() {
590 let scripts = extract_sfc_scripts(r#"<script lang="tsx">const el = <div />;</script>"#);
591 assert_eq!(scripts.len(), 1);
592 assert!(scripts[0].is_typescript);
593 assert!(scripts[0].is_jsx);
594 }
595
596 #[test]
597 fn single_jsx_script() {
598 let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
599 assert_eq!(scripts.len(), 1);
600 assert!(!scripts[0].is_typescript);
601 assert!(scripts[0].is_jsx);
602 }
603
604 #[test]
607 fn two_script_blocks() {
608 let source = r#"
609<script lang="ts">
610export default {};
611</script>
612<script setup lang="ts">
613const count = 0;
614</script>
615"#;
616 let scripts = extract_sfc_scripts(source);
617 assert_eq!(scripts.len(), 2);
618 assert!(scripts[0].body.contains("export default"));
619 assert!(scripts[1].body.contains("count"));
620 }
621
622 #[test]
625 fn script_setup_extracted() {
626 let scripts =
627 extract_sfc_scripts(r#"<script setup lang="ts">import { ref } from 'vue';</script>"#);
628 assert_eq!(scripts.len(), 1);
629 assert!(scripts[0].body.contains("import"));
630 assert!(scripts[0].is_typescript);
631 }
632
633 #[test]
636 fn script_src_detected() {
637 let scripts = extract_sfc_scripts(r#"<script src="./component.ts" lang="ts"></script>"#);
638 assert_eq!(scripts.len(), 1);
639 assert_eq!(scripts[0].src.as_deref(), Some("./component.ts"));
640 }
641
642 #[test]
643 fn data_src_not_treated_as_src() {
644 let scripts =
645 extract_sfc_scripts(r#"<script lang="ts" data-src="./nope.ts">const x = 1;</script>"#);
646 assert_eq!(scripts.len(), 1);
647 assert!(scripts[0].src.is_none());
648 }
649
650 #[test]
653 fn script_inside_html_comment_filtered() {
654 let source = r#"
655<!-- <script lang="ts">import { bad } from 'bad';</script> -->
656<script lang="ts">import { good } from 'good';</script>
657"#;
658 let scripts = extract_sfc_scripts(source);
659 assert_eq!(scripts.len(), 1);
660 assert!(scripts[0].body.contains("good"));
661 }
662
663 #[test]
664 fn spanning_comment_filters_script() {
665 let source = r#"
666<!-- disabled:
667<script lang="ts">import { bad } from 'bad';</script>
668-->
669<script lang="ts">const ok = true;</script>
670"#;
671 let scripts = extract_sfc_scripts(source);
672 assert_eq!(scripts.len(), 1);
673 assert!(scripts[0].body.contains("ok"));
674 }
675
676 #[test]
677 fn string_containing_comment_markers_not_corrupted() {
678 let source = r#"
680<script setup lang="ts">
681const marker = "<!-- not a comment -->";
682import { ref } from 'vue';
683</script>
684"#;
685 let scripts = extract_sfc_scripts(source);
686 assert_eq!(scripts.len(), 1);
687 assert!(scripts[0].body.contains("import"));
688 }
689
690 #[test]
693 fn generic_attr_with_angle_bracket() {
694 let source =
695 r#"<script setup lang="ts" generic="T extends Foo<Bar>">const x = 1;</script>"#;
696 let scripts = extract_sfc_scripts(source);
697 assert_eq!(scripts.len(), 1);
698 assert_eq!(scripts[0].body, "const x = 1;");
699 }
700
701 #[test]
702 fn nested_generic_attr() {
703 let source = r#"<script setup lang="ts" generic="T extends Map<string, Set<number>>">const x = 1;</script>"#;
704 let scripts = extract_sfc_scripts(source);
705 assert_eq!(scripts.len(), 1);
706 assert_eq!(scripts[0].body, "const x = 1;");
707 }
708
709 #[test]
712 fn lang_single_quoted() {
713 let scripts = extract_sfc_scripts("<script lang='ts'>const x = 1;</script>");
714 assert_eq!(scripts.len(), 1);
715 assert!(scripts[0].is_typescript);
716 }
717
718 #[test]
721 fn uppercase_script_tag() {
722 let scripts = extract_sfc_scripts(r#"<SCRIPT lang="ts">const x = 1;</SCRIPT>"#);
723 assert_eq!(scripts.len(), 1);
724 assert!(scripts[0].is_typescript);
725 }
726
727 #[test]
730 fn no_script_block() {
731 let scripts = extract_sfc_scripts("<template><div>Hello</div></template>");
732 assert!(scripts.is_empty());
733 }
734
735 #[test]
736 fn empty_script_body() {
737 let scripts = extract_sfc_scripts(r#"<script lang="ts"></script>"#);
738 assert_eq!(scripts.len(), 1);
739 assert!(scripts[0].body.is_empty());
740 }
741
742 #[test]
743 fn whitespace_only_script() {
744 let scripts = extract_sfc_scripts("<script lang=\"ts\">\n \n</script>");
745 assert_eq!(scripts.len(), 1);
746 assert!(scripts[0].body.trim().is_empty());
747 }
748
749 #[test]
750 fn byte_offset_is_set() {
751 let source = r#"<template><div/></template><script lang="ts">code</script>"#;
752 let scripts = extract_sfc_scripts(source);
753 assert_eq!(scripts.len(), 1);
754 let offset = scripts[0].byte_offset;
756 assert_eq!(&source[offset..offset + 4], "code");
757 }
758
759 #[test]
760 fn script_with_extra_attributes() {
761 let scripts = extract_sfc_scripts(
762 r#"<script lang="ts" id="app" type="module" data-custom="val">const x = 1;</script>"#,
763 );
764 assert_eq!(scripts.len(), 1);
765 assert!(scripts[0].is_typescript);
766 assert!(scripts[0].src.is_none());
767 }
768
769 #[test]
772 fn multiple_script_blocks_exports_combined() {
773 let source = r#"
774<script lang="ts">
775export const version = '1.0';
776</script>
777<script setup lang="ts">
778import { ref } from 'vue';
779const count = ref(0);
780</script>
781"#;
782 let info = parse_sfc_to_module(FileId(0), Path::new("Dual.vue"), source, 0, false);
783 assert!(
785 info.exports
786 .iter()
787 .any(|e| matches!(&e.name, crate::ExportName::Named(n) if n == "version")),
788 "export from <script> block should be extracted"
789 );
790 assert!(
792 info.imports.iter().any(|i| i.source == "vue"),
793 "import from <script setup> block should be extracted"
794 );
795 }
796
797 #[test]
800 fn lang_tsx_detected_as_typescript_jsx() {
801 let scripts =
802 extract_sfc_scripts(r#"<script lang="tsx">const el = <div>{x}</div>;</script>"#);
803 assert_eq!(scripts.len(), 1);
804 assert!(scripts[0].is_typescript, "lang=tsx should be typescript");
805 assert!(scripts[0].is_jsx, "lang=tsx should be jsx");
806 }
807
808 #[test]
811 fn multiline_html_comment_filters_all_script_blocks_inside() {
812 let source = r#"
813<!--
814 This whole section is disabled:
815 <script lang="ts">import { bad1 } from 'bad1';</script>
816 <script lang="ts">import { bad2 } from 'bad2';</script>
817-->
818<script lang="ts">import { good } from 'good';</script>
819"#;
820 let scripts = extract_sfc_scripts(source);
821 assert_eq!(scripts.len(), 1);
822 assert!(scripts[0].body.contains("good"));
823 }
824
825 #[test]
828 fn script_src_generates_side_effect_import() {
829 let info = parse_sfc_to_module(
830 FileId(0),
831 Path::new("External.vue"),
832 r#"<script src="./external-logic.ts" lang="ts"></script>"#,
833 0,
834 false,
835 );
836 assert!(
837 info.imports
838 .iter()
839 .any(|i| i.source == "./external-logic.ts"
840 && matches!(i.imported_name, ImportedName::SideEffect)),
841 "script src should generate a side-effect import"
842 );
843 }
844
845 #[test]
848 fn parse_sfc_no_script_returns_empty_module() {
849 let info = parse_sfc_to_module(
850 FileId(0),
851 Path::new("Empty.vue"),
852 "<template><div>Hello</div></template>",
853 42,
854 false,
855 );
856 assert!(info.imports.is_empty());
857 assert!(info.exports.is_empty());
858 assert_eq!(info.content_hash, 42);
859 assert_eq!(info.file_id, FileId(0));
860 }
861
862 #[test]
863 fn parse_sfc_has_line_offsets() {
864 let info = parse_sfc_to_module(
865 FileId(0),
866 Path::new("LineOffsets.vue"),
867 r#"<script lang="ts">const x = 1;</script>"#,
868 0,
869 false,
870 );
871 assert!(!info.line_offsets.is_empty());
872 }
873
874 #[test]
875 fn parse_sfc_has_suppressions() {
876 let info = parse_sfc_to_module(
877 FileId(0),
878 Path::new("Suppressions.vue"),
879 r#"<script lang="ts">
880// fallow-ignore-file
881export const foo = 1;
882</script>"#,
883 0,
884 false,
885 );
886 assert!(!info.suppressions.is_empty());
887 }
888
889 #[test]
890 fn source_type_jsx_detection() {
891 let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
892 assert_eq!(scripts.len(), 1);
893 assert!(!scripts[0].is_typescript);
894 assert!(scripts[0].is_jsx);
895 }
896
897 #[test]
898 fn source_type_plain_js_detection() {
899 let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
900 assert_eq!(scripts.len(), 1);
901 assert!(!scripts[0].is_typescript);
902 assert!(!scripts[0].is_jsx);
903 }
904
905 #[test]
906 fn is_sfc_file_rejects_no_extension() {
907 assert!(!is_sfc_file(Path::new("Makefile")));
908 }
909
910 #[test]
911 fn is_sfc_file_rejects_mdx() {
912 assert!(!is_sfc_file(Path::new("post.mdx")));
913 }
914
915 #[test]
916 fn is_sfc_file_rejects_css() {
917 assert!(!is_sfc_file(Path::new("styles.css")));
918 }
919
920 #[test]
921 fn multiple_script_blocks_both_have_offsets() {
922 let source = r#"<script lang="ts">const a = 1;</script>
923<script setup lang="ts">const b = 2;</script>"#;
924 let scripts = extract_sfc_scripts(source);
925 assert_eq!(scripts.len(), 2);
926 let offset0 = scripts[0].byte_offset;
928 let offset1 = scripts[1].byte_offset;
929 assert_eq!(
930 &source[offset0..offset0 + "const a = 1;".len()],
931 "const a = 1;"
932 );
933 assert_eq!(
934 &source[offset1..offset1 + "const b = 2;".len()],
935 "const b = 2;"
936 );
937 }
938
939 #[test]
940 fn script_with_src_and_lang() {
941 let scripts = extract_sfc_scripts(r#"<script src="./logic.ts" lang="tsx"></script>"#);
943 assert_eq!(scripts.len(), 1);
944 assert_eq!(scripts[0].src.as_deref(), Some("./logic.ts"));
945 assert!(scripts[0].is_typescript);
946 assert!(scripts[0].is_jsx);
947 }
948
949 #[test]
952 fn extract_style_block_lang_scss() {
953 let source = r#"<template/><style lang="scss">@import 'Foo';</style>"#;
954 let styles = extract_sfc_styles(source);
955 assert_eq!(styles.len(), 1);
956 assert_eq!(styles[0].lang.as_deref(), Some("scss"));
957 assert!(styles[0].body.contains("@import"));
958 assert!(styles[0].src.is_none());
959 }
960
961 #[test]
962 fn extract_style_block_with_src() {
963 let source = r#"<style src="./theme.scss" lang="scss"></style>"#;
964 let styles = extract_sfc_styles(source);
965 assert_eq!(styles.len(), 1);
966 assert_eq!(styles[0].src.as_deref(), Some("./theme.scss"));
967 assert_eq!(styles[0].lang.as_deref(), Some("scss"));
968 }
969
970 #[test]
971 fn extract_style_block_plain_no_lang() {
972 let source = r"<style>.foo { color: red; }</style>";
973 let styles = extract_sfc_styles(source);
974 assert_eq!(styles.len(), 1);
975 assert!(styles[0].lang.is_none());
976 }
977
978 #[test]
979 fn extract_multiple_style_blocks() {
980 let source = r#"<style lang="scss">@import 'a';</style>
981<style scoped lang="scss">@import 'b';</style>"#;
982 let styles = extract_sfc_styles(source);
983 assert_eq!(styles.len(), 2);
984 }
985
986 #[test]
987 fn style_block_inside_html_comment_filtered() {
988 let source = r#"<!-- <style lang="scss">@import 'bad';</style> -->
989<style lang="scss">@import 'good';</style>"#;
990 let styles = extract_sfc_styles(source);
991 assert_eq!(styles.len(), 1);
992 assert!(styles[0].body.contains("good"));
993 }
994
995 #[test]
996 fn parse_sfc_extracts_style_imports_with_from_style_flag() {
997 let info = parse_sfc_to_module(
998 FileId(0),
999 Path::new("Foo.vue"),
1000 r#"<template/><style lang="scss">@import 'Foo';</style>"#,
1001 0,
1002 false,
1003 );
1004 let style_import = info
1005 .imports
1006 .iter()
1007 .find(|i| i.source == "./Foo")
1008 .expect("scss @import 'Foo' should be normalized to ./Foo");
1009 assert!(
1010 style_import.from_style,
1011 "imports from <style> blocks must carry from_style=true so the resolver \
1012 enables SCSS partial fallback for the SFC importer"
1013 );
1014 assert!(matches!(
1015 style_import.imported_name,
1016 ImportedName::SideEffect
1017 ));
1018 }
1019
1020 #[test]
1021 fn parse_sfc_extracts_style_plugin_as_default_import() {
1022 let info = parse_sfc_to_module(
1023 FileId(0),
1024 Path::new("Foo.vue"),
1025 r#"<template/><style>@plugin "./tailwind-plugin.js";</style>"#,
1026 0,
1027 false,
1028 );
1029 let plugin_import = info
1030 .imports
1031 .iter()
1032 .find(|i| i.source == "./tailwind-plugin.js")
1033 .expect("style @plugin should create an import");
1034 assert!(plugin_import.from_style);
1035 assert!(matches!(plugin_import.imported_name, ImportedName::Default));
1036 }
1037
1038 #[test]
1039 fn parse_sfc_extracts_style_src_with_from_style_flag() {
1040 let info = parse_sfc_to_module(
1041 FileId(0),
1042 Path::new("Bar.vue"),
1043 r#"<style src="./Bar.scss" lang="scss"></style>"#,
1044 0,
1045 false,
1046 );
1047 let style_src = info
1048 .imports
1049 .iter()
1050 .find(|i| i.source == "./Bar.scss")
1051 .expect("<style src=\"./Bar.scss\"> should produce a side-effect import");
1052 assert!(style_src.from_style);
1053 }
1054
1055 #[test]
1056 fn parse_sfc_skips_unsupported_style_lang_body_but_keeps_src() {
1057 let info = parse_sfc_to_module(
1059 FileId(0),
1060 Path::new("Baz.vue"),
1061 r#"<style lang="postcss" src="./Baz.pcss">@custom-rule "skipped";</style>"#,
1062 0,
1063 false,
1064 );
1065 assert!(
1066 info.imports.iter().any(|i| i.source == "./Baz.pcss"),
1067 "src reference should still be seeded for unsupported lang"
1068 );
1069 assert!(
1070 !info.imports.iter().any(|i| i.source.contains("skipped")),
1071 "postcss body should not be scanned for @import directives"
1072 );
1073 }
1074}