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