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