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::compute_import_binding_usage;
23use crate::sfc_template::{SfcKind, collect_template_usage_with_bound_targets};
24use crate::source_map::ExtractionResult;
25use crate::visitor::ModuleInfoExtractor;
26use crate::{ImportInfo, ImportedName, ModuleInfo};
27use fallow_types::discover::FileId;
28use fallow_types::extract::{FunctionComplexity, byte_offset_to_line_col, compute_line_offsets};
29use oxc_span::Span;
30
31static SCRIPT_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
34 crate::static_regex(
35 r#"(?is)<script\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>(?P<body>[\s\S]*?)</script>"#,
36 )
37});
38
39static LANG_ATTR_RE: LazyLock<regex::Regex> =
41 LazyLock::new(|| crate::static_regex(r#"lang\s*=\s*["'](\w+)["']"#));
42
43static SRC_ATTR_RE: LazyLock<regex::Regex> =
46 LazyLock::new(|| crate::static_regex(r#"(?:^|\s)src\s*=\s*["']([^"']+)["']"#));
47
48static SETUP_ATTR_RE: LazyLock<regex::Regex> =
50 LazyLock::new(|| crate::static_regex(r"(?:^|\s)setup(?:\s|$)"));
51
52static CONTEXT_MODULE_ATTR_RE: LazyLock<regex::Regex> =
54 LazyLock::new(|| crate::static_regex(r#"context\s*=\s*["']module["']"#));
55
56static SVELTE_MODULE_ATTR_RE: LazyLock<regex::Regex> =
61 LazyLock::new(|| crate::static_regex(r"(?:^|\s)module(?:\s|$|=)"));
62
63static VUE_GENERIC_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
67 crate::static_regex(r#"(?:^|\s)generic\s*=\s*"([^"]*)"|(?:^|\s)generic\s*=\s*'([^']*)'"#)
68});
69
70static SVELTE_GENERICS_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
73 crate::static_regex(r#"(?:^|\s)generics\s*=\s*"([^"]*)"|(?:^|\s)generics\s*=\s*'([^']*)'"#)
74});
75
76static HTML_COMMENT_RE: LazyLock<regex::Regex> =
78 LazyLock::new(|| crate::static_regex(r"(?s)<!--.*?-->"));
79
80static PROPS_ATTRS_SPREAD_RE: LazyLock<regex::Regex> =
85 LazyLock::new(|| crate::static_regex(r#"v-bind\s*=\s*["'](?:\$attrs|\$props|props)["']"#));
86
87static SVELTE_TEMPLATE_DATA_WHOLE_USE_RE: LazyLock<regex::Regex> =
95 LazyLock::new(|| crate::static_regex(r"(?:=\s*\{\s*data\s*\}|\{\s*\.\.\.\s*data\s*\})"));
96
97static TEMPLATE_EMIT_CALL_RE: LazyLock<regex::Regex> =
107 LazyLock::new(|| crate::static_regex(r#"([\w$]+)\s*\(\s*(?:'([\w:-]*)'|"([\w:-]*)"|(\S))"#));
108
109static STYLE_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
113 crate::static_regex(
114 r#"(?is)<style\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>(?P<body>[\s\S]*?)</style>"#,
115 )
116});
117
118static TEMPLATE_ASSET_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
133 crate::static_regex(
134 r#"(?si)<(?:img|source|video|audio|track|embed)\b(?:[^>"']|"[^"]*"|'[^']*')*?\s(?:src|poster)\s*=\s*(?:"((?:\./|\.\./)[^"<>{}?#\s]*)"|'((?:\./|\.\./)[^'<>{}?#\s]*)')"#,
135 )
136});
137
138fn mask_non_markup_regions(source: &str) -> String {
142 let mut masked = source.to_string();
143 for re in [&*SCRIPT_BLOCK_RE, &*STYLE_BLOCK_RE, &*HTML_COMMENT_RE] {
144 masked = re
145 .replace_all(&masked, |caps: ®ex::Captures<'_>| {
146 " ".repeat(caps[0].len())
147 })
148 .into_owned();
149 }
150 masked
151}
152
153fn collect_template_asset_refs(source: &str) -> Vec<(String, Span)> {
156 let masked = mask_non_markup_regions(source);
157 let mut refs = Vec::new();
158 for caps in TEMPLATE_ASSET_RE.captures_iter(&masked) {
159 let Some(value) = caps.get(1).or_else(|| caps.get(2)) else {
160 continue;
161 };
162 let raw = value.as_str();
163 if raw.is_empty() {
164 continue;
165 }
166 refs.push((
167 normalize_asset_url(raw),
168 Span::new(value.start() as u32, value.end() as u32),
169 ));
170 }
171 refs
172}
173
174pub struct SfcScript {
176 pub body: String,
178 pub is_typescript: bool,
180 pub is_jsx: bool,
182 pub byte_offset: usize,
184 pub src: Option<String>,
186 pub src_span: Option<Span>,
188 pub is_setup: bool,
190 pub is_context_module: bool,
192 pub generic_attr: Option<String>,
196}
197
198pub fn extract_sfc_scripts(source: &str) -> Vec<SfcScript> {
200 let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
201 .find_iter(source)
202 .map(|m| (m.start(), m.end()))
203 .collect();
204
205 SCRIPT_BLOCK_RE
206 .captures_iter(source)
207 .filter(|cap| {
208 let start = cap.get(0).map_or(0, |m| m.start());
209 !comment_ranges
210 .iter()
211 .any(|&(cs, ce)| start >= cs && start < ce)
212 })
213 .map(|cap| {
214 let attrs = cap.name("attrs").map_or("", |m| m.as_str());
215 let body_match = cap.name("body");
216 let byte_offset = body_match.map_or(0, |m| m.start());
217 let body = body_match.map_or("", |m| m.as_str()).to_string();
218 let lang = LANG_ATTR_RE
219 .captures(attrs)
220 .and_then(|c| c.get(1))
221 .map(|m| m.as_str());
222 let is_typescript = matches!(lang, Some("ts" | "tsx"));
223 let is_jsx = matches!(lang, Some("tsx" | "jsx"));
224 let src = SRC_ATTR_RE
225 .captures(attrs)
226 .and_then(|c| c.get(1))
227 .map(|m| m.as_str().to_string());
228 let attrs_start = cap.name("attrs").map_or(0, |m| m.start());
229 let src_span = SRC_ATTR_RE.captures(attrs).and_then(|c| c.get(1)).map(|m| {
230 Span::new(
231 (attrs_start + m.start()) as u32,
232 (attrs_start + m.end()) as u32,
233 )
234 });
235 let is_setup = SETUP_ATTR_RE.is_match(attrs);
236 let is_context_module =
241 CONTEXT_MODULE_ATTR_RE.is_match(attrs) || SVELTE_MODULE_ATTR_RE.is_match(attrs);
242 let generic_attr = VUE_GENERIC_ATTR_RE
243 .captures(attrs)
244 .or_else(|| SVELTE_GENERICS_ATTR_RE.captures(attrs))
245 .and_then(|cap| cap.get(1).or_else(|| cap.get(2)))
246 .map(|m| m.as_str().to_string())
247 .filter(|value| !value.trim().is_empty());
248 SfcScript {
249 body,
250 is_typescript,
251 is_jsx,
252 byte_offset,
253 src,
254 src_span,
255 is_setup,
256 is_context_module,
257 generic_attr,
258 }
259 })
260 .collect()
261}
262
263pub struct SfcStyle {
265 pub body: String,
267 pub lang: Option<String>,
270 pub src: Option<String>,
272 pub src_span: Option<Span>,
274 pub byte_offset: usize,
276}
277
278pub struct SourceRegion {
281 pub body: String,
283 pub byte_offset: usize,
285}
286
287#[must_use]
293pub fn extract_sfc_template_regions(source: &str) -> Vec<SourceRegion> {
294 let mut ranges: Vec<(usize, usize)> = SCRIPT_BLOCK_RE
295 .find_iter(source)
296 .chain(STYLE_BLOCK_RE.find_iter(source))
297 .chain(HTML_COMMENT_RE.find_iter(source))
298 .map(|m| (m.start(), m.end()))
299 .collect();
300 ranges.sort_unstable_by_key(|(start, _)| *start);
301 ranges_to_gaps(source, &ranges)
302}
303
304pub fn extract_sfc_styles(source: &str) -> Vec<SfcStyle> {
311 let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
312 .find_iter(source)
313 .map(|m| (m.start(), m.end()))
314 .collect();
315
316 STYLE_BLOCK_RE
317 .captures_iter(source)
318 .filter(|cap| {
319 let start = cap.get(0).map_or(0, |m| m.start());
320 !comment_ranges
321 .iter()
322 .any(|&(cs, ce)| start >= cs && start < ce)
323 })
324 .map(|cap| {
325 let attrs = cap.name("attrs").map_or("", |m| m.as_str());
326 let body = cap.name("body").map_or("", |m| m.as_str()).to_string();
327 let byte_offset = cap.name("body").map_or(0, |m| m.start());
328 let lang = LANG_ATTR_RE
329 .captures(attrs)
330 .and_then(|c| c.get(1))
331 .map(|m| m.as_str().to_string());
332 let src = SRC_ATTR_RE
333 .captures(attrs)
334 .and_then(|c| c.get(1))
335 .map(|m| m.as_str().to_string());
336 let attrs_start = cap.name("attrs").map_or(0, |m| m.start());
337 let src_span = SRC_ATTR_RE.captures(attrs).and_then(|c| c.get(1)).map(|m| {
338 Span::new(
339 (attrs_start + m.start()) as u32,
340 (attrs_start + m.end()) as u32,
341 )
342 });
343 SfcStyle {
344 body,
345 lang,
346 src,
347 src_span,
348 byte_offset,
349 }
350 })
351 .collect()
352}
353
354pub(crate) fn ranges_to_gaps(source: &str, ranges: &[(usize, usize)]) -> Vec<SourceRegion> {
358 let mut regions = Vec::new();
359 let mut cursor = 0;
360 for &(start, end) in ranges {
361 if start > cursor {
362 push_region(source, cursor, start, &mut regions);
363 }
364 cursor = cursor.max(end);
365 }
366 if cursor < source.len() {
367 push_region(source, cursor, source.len(), &mut regions);
368 }
369 regions
370}
371
372fn push_region(source: &str, start: usize, end: usize, regions: &mut Vec<SourceRegion>) {
373 let Some(body) = source.get(start..end) else {
374 return;
375 };
376 if body.trim().is_empty() {
377 return;
378 }
379 regions.push(SourceRegion {
380 body: body.to_string(),
381 byte_offset: start,
382 });
383}
384
385#[must_use]
387pub fn is_sfc_file(path: &Path) -> bool {
388 path.extension()
389 .and_then(|e| e.to_str())
390 .is_some_and(|ext| ext == "vue" || ext == "svelte")
391}
392
393#[cfg(test)]
395fn parse_sfc_to_module(
396 file_id: FileId,
397 path: &Path,
398 source: &str,
399 content_hash: u64,
400 need_complexity: bool,
401) -> ModuleInfo {
402 parse_sfc_to_module_with_mode(
403 file_id,
404 path,
405 source,
406 content_hash,
407 need_complexity,
408 fallow_types::shared_state::ExtractionMode::Standard,
409 )
410}
411
412pub(crate) fn parse_sfc_to_module_with_mode(
413 file_id: FileId,
414 path: &Path,
415 source: &str,
416 content_hash: u64,
417 need_complexity: bool,
418 mode: fallow_types::shared_state::ExtractionMode,
419) -> ModuleInfo {
420 let scripts = extract_sfc_scripts(source);
421 let styles = extract_sfc_styles(source);
422 let kind = sfc_kind(path);
423 let mut combined = empty_sfc_module(file_id, source, content_hash);
424 let mut template_visible_imports: FxHashSet<String> = FxHashSet::default();
425 let mut template_visible_bound_targets: FxHashMap<String, String> = FxHashMap::default();
426 let mut template_visible_iterable_types: FxHashMap<String, String> = FxHashMap::default();
427 let mut props_return_binding: Option<String> = None;
428 let mut emit_return_binding: Option<String> = None;
429
430 for script in &scripts {
431 merge_script_into_module(&mut SfcScriptMergeInput {
432 kind,
433 script,
434 combined: &mut combined,
435 template_visible_imports: &mut template_visible_imports,
436 template_visible_bound_targets: &mut template_visible_bound_targets,
437 template_visible_iterable_types: &mut template_visible_iterable_types,
438 props_return_binding: &mut props_return_binding,
439 emit_return_binding: &mut emit_return_binding,
440 need_complexity,
441 mode,
442 });
443 }
444
445 for style in &styles {
446 merge_style_into_module(style, &mut combined);
447 }
448
449 if kind == SfcKind::Vue
453 && !combined.component_props.is_empty()
454 && PROPS_ATTRS_SPREAD_RE.is_match(source)
455 {
456 combined.has_props_attrs_fallthrough = true;
457 }
458
459 apply_template_usage(TemplateUsageInput {
460 kind,
461 source,
462 template_visible_imports,
463 template_visible_bound_targets,
464 template_visible_iterable_types: &template_visible_iterable_types,
465 props_return_binding: props_return_binding.as_deref(),
466 credit_load_data: kind == SfcKind::Svelte && is_sveltekit_route_data_component(path),
467 combined: &mut combined,
468 });
469
470 if need_complexity {
471 append_template_complexity(kind, source, &mut combined);
472 }
473
474 if kind == SfcKind::Vue && !combined.component_emits.is_empty() {
478 apply_template_emit_usage(source, emit_return_binding.as_deref(), &mut combined);
479 }
480
481 if kind == SfcKind::Svelte {
485 combined.svelte_listened_events =
486 crate::sfc_template::collect_svelte_listened_events(source);
487 }
488
489 append_template_asset_imports(source, &mut combined);
490 dedup_import_binding_lists(&mut combined);
491 apply_component_contracts(kind, source, &mut combined);
492
493 combined
494}
495
496fn append_template_complexity(kind: SfcKind, source: &str, combined: &mut ModuleInfo) {
504 match kind {
505 SfcKind::Vue => {
506 combined.complexity.extend(
507 crate::template_complexity::compute_vue_template_complexity(source),
508 );
509 }
510 SfcKind::Svelte => combined
513 .complexity
514 .extend(crate::template_complexity::compute_svelte_template_complexity(source)),
515 }
516}
517
518fn append_template_asset_imports(source: &str, combined: &mut ModuleInfo) {
522 for (specifier, span) in collect_template_asset_refs(source) {
523 combined.imports.push(ImportInfo {
524 source: specifier,
525 imported_name: ImportedName::SideEffect,
526 local_name: String::new(),
527 is_type_only: false,
528 is_type_only_star: false,
529 from_style: false,
530 span,
531 source_span: span,
532 });
533 }
534}
535
536fn dedup_import_binding_lists(combined: &mut ModuleInfo) {
539 combined.unused_import_bindings.sort_unstable();
540 combined.unused_import_bindings.dedup();
541 combined.type_referenced_import_bindings.sort_unstable();
542 combined.type_referenced_import_bindings.dedup();
543 combined.value_referenced_import_bindings.sort_unstable();
544 combined.value_referenced_import_bindings.dedup();
545 combined.auto_import_candidates.sort_unstable();
546 combined.auto_import_candidates.dedup();
547}
548
549fn sfc_kind(path: &Path) -> SfcKind {
550 if path.extension().and_then(|ext| ext.to_str()) == Some("vue") {
551 SfcKind::Vue
552 } else {
553 SfcKind::Svelte
554 }
555}
556
557fn is_sveltekit_route_data_component(path: &Path) -> bool {
568 let Some(stem) = path
569 .file_name()
570 .and_then(|name| name.to_str())
571 .and_then(|name| name.strip_suffix(".svelte"))
572 else {
573 return false;
574 };
575 ["+page", "+layout"].iter().any(|prefix| {
576 stem.strip_prefix(prefix)
577 .is_some_and(|rest| rest.is_empty() || rest.starts_with('@'))
578 })
579}
580
581fn empty_sfc_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
582 let parsed = crate::suppress::parse_suppressions_from_source(source);
583
584 crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
585 file_id,
586 content_hash,
587 source,
588 parsed_suppressions: parsed,
589 imports: Vec::new(),
590 exports: Vec::new(),
591 })
592}
593
594#[path = "sfc_script_merge.rs"]
595mod script_merge;
596use script_merge::merge_script_into_module;
597struct SfcScriptMergeInput<'a> {
598 kind: SfcKind,
599 script: &'a SfcScript,
600 combined: &'a mut ModuleInfo,
601 template_visible_imports: &'a mut FxHashSet<String>,
602 template_visible_bound_targets: &'a mut FxHashMap<String, String>,
603 template_visible_iterable_types: &'a mut FxHashMap<String, String>,
604 props_return_binding: &'a mut Option<String>,
605 emit_return_binding: &'a mut Option<String>,
606 need_complexity: bool,
607 mode: fallow_types::shared_state::ExtractionMode,
608}
609
610fn merge_script_binding_usage(
621 input: &mut SfcScriptMergeInput<'_>,
622 allocator: &Allocator,
623 imports: &[ImportInfo],
624 import_equals_bindings: &[String],
625 semantic_usage: crate::parse::SemanticUsage,
626) {
627 let augmented_body = build_generic_attr_probe_source(input.script);
628 let empty_template_used = FxHashSet::default();
629 let (binding_usage, auto_import_candidates) = if let Some(augmented) = augmented_body.as_deref()
630 {
631 let augmented_return =
632 Parser::new(allocator, augmented, source_type_for_script(input.script)).parse();
633 (
634 compute_import_binding_usage(
635 &augmented_return.program,
636 imports,
637 import_equals_bindings,
638 &empty_template_used,
639 ),
640 semantic_usage.auto_import_candidates,
641 )
642 } else {
643 (
644 semantic_usage.import_binding_usage,
645 semantic_usage.auto_import_candidates,
646 )
647 };
648 crate::parse::append_declaration_merge_facts(
649 &mut input.combined.semantic_facts,
650 semantic_usage.declaration_merges,
651 input.script.byte_offset as u32,
652 );
653 input
654 .combined
655 .unused_import_bindings
656 .extend(binding_usage.unused.iter().cloned());
657 input
658 .combined
659 .type_referenced_import_bindings
660 .extend(binding_usage.type_referenced.iter().cloned());
661 input
662 .combined
663 .value_referenced_import_bindings
664 .extend(binding_usage.value_referenced.iter().cloned());
665 input
666 .combined
667 .auto_import_candidates
668 .extend(auto_import_candidates);
669}
670
671fn harvest_template_visible_bindings(
675 input: &mut SfcScriptMergeInput<'_>,
676 extractor: &ModuleInfoExtractor,
677) {
678 input.template_visible_imports.extend(
679 extractor
680 .imports
681 .iter()
682 .filter(|import| !import.local_name.is_empty())
683 .map(|import| import.local_name.clone()),
684 );
685 input.template_visible_bound_targets.extend(
686 extractor
687 .binding_target_names()
688 .iter()
689 .filter(|(local, _)| !local.starts_with("this."))
690 .filter_map(|(local, target)| {
691 target
692 .class_name()
693 .map(|class_name| (local.clone(), class_name.to_string()))
694 }),
695 );
696 input.template_visible_iterable_types.extend(
700 extractor
701 .array_binding_element_types()
702 .iter()
703 .filter(|(local, _)| !local.starts_with("this."))
704 .map(|(local, element)| (local.clone(), element.clone())),
705 );
706}
707
708fn merge_svelte_props_into(
712 combined: &mut ModuleInfo,
713 program: &oxc_ast::ast::Program<'_>,
714 byte_offset: usize,
715) {
716 let harvest = crate::sfc_props::harvest_svelte_props(program);
717 if harvest.has_unharvestable_props {
718 combined.has_unharvestable_props = true;
719 }
720 if harvest.has_props_attrs_fallthrough {
721 combined.has_props_attrs_fallthrough = true;
722 }
723 for mut prop in harvest.props {
724 prop.span_start += byte_offset as u32;
725 combined.component_props.push(prop);
726 }
727}
728
729fn merge_vue_props_emits_into(
736 input: &mut SfcScriptMergeInput<'_>,
737 program: &oxc_ast::ast::Program<'_>,
738 extractor: &mut ModuleInfoExtractor,
739) {
740 let byte_offset = input.script.byte_offset as u32;
741 if input.script.is_setup {
742 apply_props_harvest(
743 input,
744 crate::sfc_props::harvest_define_props(program),
745 byte_offset,
746 extractor,
747 );
748 apply_emits_harvest(
749 input,
750 crate::sfc_props::harvest_define_emits(program),
751 byte_offset,
752 );
753 } else {
754 apply_props_harvest(
755 input,
756 crate::sfc_props::harvest_options_api_props(program),
757 byte_offset,
758 extractor,
759 );
760 apply_emits_harvest(
761 input,
762 crate::sfc_props::harvest_options_api_emits(program),
763 byte_offset,
764 );
765 }
766}
767
768fn apply_props_harvest(
774 input: &mut SfcScriptMergeInput<'_>,
775 harvest: crate::sfc_props::DefinePropsHarvest,
776 byte_offset: u32,
777 extractor: &mut ModuleInfoExtractor,
778) {
779 if harvest.has_unharvestable_props {
780 input.combined.has_unharvestable_props = true;
781 }
782 if harvest.has_props_attrs_fallthrough {
783 input.combined.has_props_attrs_fallthrough = true;
784 }
785 if harvest.has_define_expose {
786 input.combined.has_define_expose = true;
787 }
788 if harvest.has_define_model {
789 input.combined.has_define_model = true;
790 }
791 if let Some(binding) = harvest.props_return_binding {
792 *input.props_return_binding = Some(binding);
793 }
794 for (field_name, element_type) in harvest.props_array_element_types {
802 extractor
803 .array_binding_element_types_mut()
804 .insert(format!("props.{field_name}"), element_type);
805 }
806 for mut prop in harvest.props {
807 prop.span_start += byte_offset;
808 input.combined.component_props.push(prop);
809 }
810}
811
812fn apply_emits_harvest(
818 input: &mut SfcScriptMergeInput<'_>,
819 harvest: crate::sfc_props::DefineEmitsHarvest,
820 byte_offset: u32,
821) {
822 if harvest.has_unharvestable_emits {
823 input.combined.has_unharvestable_emits = true;
824 }
825 if harvest.has_dynamic_emit {
826 input.combined.has_dynamic_emit = true;
827 }
828 if harvest.has_emit_whole_object_use {
829 input.combined.has_emit_whole_object_use = true;
830 }
831 if let Some(binding) = harvest.emit_binding {
832 *input.emit_return_binding = Some(binding);
833 }
834 for mut emit in harvest.emits {
835 emit.span_start += byte_offset;
836 input.combined.component_emits.push(emit);
837 }
838}
839
840pub(crate) fn translate_script_complexity(
844 script: &SfcScript,
845 program: &oxc_ast::ast::Program<'_>,
846 sfc_line_offsets: &[u32],
847) -> Vec<FunctionComplexity> {
848 let script_line_offsets = compute_line_offsets(&script.body);
849 let mut complexity =
850 crate::complexity::compute_complexity(program, &script.body, &script_line_offsets);
851 let (body_start_line, body_start_col) = byte_offset_to_line_col(
852 sfc_line_offsets,
853 u32::try_from(script.byte_offset).unwrap_or(u32::MAX),
854 );
855
856 for function in &mut complexity {
857 function.line = body_start_line + function.line.saturating_sub(1);
858 if function.line == body_start_line {
859 function.col += body_start_col;
860 }
861 }
862
863 complexity
864}
865
866fn add_script_src_import(module: &mut ModuleInfo, source: &str, source_span: Option<Span>) {
867 let span = source_span.unwrap_or_default();
868 module.imports.push(ImportInfo {
869 source: normalize_asset_url(source),
870 imported_name: ImportedName::SideEffect,
871 local_name: String::new(),
872 is_type_only: false,
873 is_type_only_star: false,
874 from_style: false,
875 span,
876 source_span: span,
877 });
878}
879
880fn style_lang_is_scss(lang: Option<&str>) -> bool {
886 matches!(lang, Some("scss" | "sass"))
887}
888
889fn style_lang_is_css_like(lang: Option<&str>) -> bool {
890 lang.is_none() || matches!(lang, Some("css"))
891}
892
893fn merge_style_into_module(style: &SfcStyle, combined: &mut ModuleInfo) {
894 if let Some(src) = &style.src {
895 let span = style.src_span.unwrap_or_default();
896 combined.imports.push(ImportInfo {
897 source: normalize_asset_url(src),
898 imported_name: ImportedName::SideEffect,
899 local_name: String::new(),
900 is_type_only: false,
901 is_type_only_star: false,
902 from_style: true,
903 span,
904 source_span: span,
905 });
906 }
907
908 let lang = style.lang.as_deref();
909 let is_scss = style_lang_is_scss(lang);
910 if !is_scss && !style_lang_is_css_like(lang) {
911 return;
912 }
913
914 let masked = crate::css_url::mask_style_block(&style.body, is_scss, combined);
915 for source in crate::css::import_sources_from_masked(&masked, is_scss) {
916 let source_span = Span::new(
917 style.byte_offset as u32 + source.span.start,
918 style.byte_offset as u32 + source.span.end,
919 );
920 combined.imports.push(ImportInfo {
921 source: source.normalized,
922 imported_name: if source.is_plugin {
923 ImportedName::Default
924 } else {
925 ImportedName::SideEffect
926 },
927 local_name: String::new(),
928 is_type_only: false,
929 is_type_only_star: false,
930 from_style: true,
931 span: source_span,
932 source_span,
933 });
934 }
935}
936
937pub(crate) fn source_type_for_script(script: &SfcScript) -> SourceType {
938 source_type_for(script.is_typescript, script.is_jsx)
939}
940
941fn source_type_for(is_typescript: bool, is_jsx: bool) -> SourceType {
942 match (is_typescript, is_jsx) {
943 (true, true) => SourceType::tsx(),
944 (true, false) => SourceType::ts(),
945 (false, true) => SourceType::jsx(),
946 (false, false) => SourceType::mjs(),
947 }
948}
949
950#[must_use]
960pub fn sfc_merged_script_source(source: &str) -> Option<(String, SourceType)> {
961 let scripts: Vec<SfcScript> = extract_sfc_scripts(source)
962 .into_iter()
963 .filter(|script| script.src.is_none())
964 .collect();
965 if scripts.is_empty() {
966 return None;
967 }
968 let is_typescript = scripts.iter().any(|script| script.is_typescript);
969 let is_jsx = scripts.iter().any(|script| script.is_jsx);
970 let mut merged = String::new();
971 for script in &scripts {
972 let body = build_generic_attr_probe_source(script);
973 merged.push_str(body.as_deref().unwrap_or(&script.body));
974 merged.push_str("\n;\n");
975 }
976 Some((merged, source_type_for(is_typescript, is_jsx)))
977}
978
979fn build_generic_attr_probe_source(script: &SfcScript) -> Option<String> {
985 let constraint = script.generic_attr.as_deref()?.trim();
986 if constraint.is_empty() {
987 return None;
988 }
989 Some(format!(
990 "{}\n;type __FALLOW_GENERIC_ATTR_PROBE<{}> = unknown;\n",
991 script.body, constraint,
992 ))
993}
994
995struct TemplateUsageInput<'a> {
996 kind: SfcKind,
997 source: &'a str,
998 template_visible_imports: FxHashSet<String>,
999 template_visible_bound_targets: FxHashMap<String, String>,
1000 template_visible_iterable_types: &'a FxHashMap<String, String>,
1001 props_return_binding: Option<&'a str>,
1002 credit_load_data: bool,
1003 combined: &'a mut ModuleInfo,
1004}
1005
1006fn apply_template_usage(input: TemplateUsageInput<'_>) {
1007 let TemplateUsageInput {
1008 kind,
1009 source,
1010 template_visible_imports,
1011 template_visible_bound_targets,
1012 template_visible_iterable_types,
1013 props_return_binding,
1014 credit_load_data,
1015 combined,
1016 } = input;
1017 let credited = build_template_credited_set(
1018 template_visible_imports,
1019 props_return_binding,
1020 credit_load_data,
1021 source,
1022 combined,
1023 );
1024 let template_usage = compute_template_usage(
1025 kind,
1026 source,
1027 &credited,
1028 template_visible_bound_targets,
1029 template_visible_iterable_types,
1030 credit_load_data,
1031 );
1032 apply_prop_template_credit(&template_usage, props_return_binding, combined);
1033 merge_template_usage_into_combined(template_usage, combined);
1034}
1035
1036fn build_template_credited_set(
1042 template_visible_imports: FxHashSet<String>,
1043 props_return_binding: Option<&str>,
1044 credit_load_data: bool,
1045 source: &str,
1046 combined: &mut ModuleInfo,
1047) -> FxHashSet<String> {
1048 let mut credited = template_visible_imports;
1049 if credit_load_data {
1054 credited.insert("data".to_string());
1055 if SVELTE_TEMPLATE_DATA_WHOLE_USE_RE.is_match(source) {
1058 combined.has_load_data_whole_use = true;
1059 }
1060 }
1061 if !combined.component_props.is_empty() {
1062 for prop in &combined.component_props {
1063 credited.insert(prop.name.clone());
1066 credited.insert(prop.local.clone());
1067 }
1068 credited.insert("$props".to_string());
1071 if let Some(binding) = props_return_binding {
1072 credited.insert(binding.to_string());
1073 }
1074 }
1075 credited
1076}
1077
1078fn compute_template_usage(
1083 kind: SfcKind,
1084 source: &str,
1085 credited: &FxHashSet<String>,
1086 mut template_visible_bound_targets: FxHashMap<String, String>,
1087 template_visible_iterable_types: &FxHashMap<String, String>,
1088 credit_load_data: bool,
1089) -> crate::template_usage::TemplateUsage {
1090 if credit_load_data {
1091 template_visible_bound_targets.remove("data");
1092 }
1093 collect_template_usage_with_bound_targets(
1094 kind,
1095 source,
1096 credited,
1097 &template_visible_bound_targets,
1098 template_visible_iterable_types,
1099 )
1100}
1101
1102fn apply_prop_template_credit(
1107 template_usage: &crate::template_usage::TemplateUsage,
1108 props_return_binding: Option<&str>,
1109 combined: &mut ModuleInfo,
1110) {
1111 if !combined.component_props.is_empty() {
1112 let member_used: FxHashSet<&str> = template_usage
1113 .member_accesses
1114 .iter()
1115 .filter(|access| {
1116 access.object == "$props"
1117 || props_return_binding.is_some_and(|binding| access.object == binding)
1118 })
1119 .map(|access| access.member.as_str())
1120 .collect();
1121 for prop in &mut combined.component_props {
1122 if template_usage.used_bindings.contains(&prop.name)
1123 || template_usage.used_bindings.contains(&prop.local)
1124 || member_used.contains(prop.name.as_str())
1125 {
1126 prop.used_in_template = true;
1127 }
1128 }
1129 }
1130
1131 if let Some(binding) = props_return_binding
1132 && (template_usage.used_bindings.contains(binding)
1133 || template_usage
1134 .whole_object_uses
1135 .iter()
1136 .any(|used| used == binding))
1137 {
1138 combined.has_props_attrs_fallthrough = true;
1139 }
1140}
1141
1142fn merge_template_usage_into_combined(
1147 template_usage: crate::template_usage::TemplateUsage,
1148 combined: &mut ModuleInfo,
1149) {
1150 combined
1151 .unused_import_bindings
1152 .retain(|binding| !template_usage.used_bindings.contains(binding));
1153 let mut member_accesses = std::mem::take(&mut combined.member_accesses).to_vec();
1154 member_accesses.extend(template_usage.member_accesses);
1155 combined.member_accesses = member_accesses.into();
1156 let mut whole_object_uses = std::mem::take(&mut combined.whole_object_uses).to_vec();
1157 whole_object_uses.extend(template_usage.whole_object_uses);
1158 combined.whole_object_uses = whole_object_uses.into();
1159 combined
1160 .security_sinks
1161 .extend(template_usage.security_sinks);
1162 if !template_usage.unresolved_tag_names.is_empty() {
1163 let mut names: Vec<String> = template_usage.unresolved_tag_names.into_iter().collect();
1164 names.sort_unstable();
1165 combined.auto_import_candidates.extend(names);
1166 combined.auto_import_candidates.dedup();
1167 }
1168}
1169
1170fn apply_template_emit_usage(
1188 source: &str,
1189 emit_return_binding: Option<&str>,
1190 combined: &mut ModuleInfo,
1191) {
1192 let masked = mask_non_markup_regions(source);
1193 let mut used: FxHashSet<String> = FxHashSet::default();
1194 let mut dynamic = false;
1195
1196 for caps in TEMPLATE_EMIT_CALL_RE.captures_iter(&masked) {
1197 let Some(callee) = caps.get(1) else {
1198 continue;
1199 };
1200 let callee = callee.as_str();
1201 let is_emit_call =
1202 callee == "$emit" || emit_return_binding.is_some_and(|binding| callee == binding);
1203 if !is_emit_call {
1204 continue;
1205 }
1206 if let Some(event) = caps.get(2).or_else(|| caps.get(3)) {
1207 used.insert(event.as_str().to_string());
1210 } else if caps.get(4).is_some() {
1211 dynamic = true;
1214 }
1215 }
1216
1217 if dynamic {
1218 combined.has_dynamic_emit = true;
1219 }
1220 if !used.is_empty() {
1221 for emit in &mut combined.component_emits {
1222 if used.contains(&emit.name) {
1223 emit.used = true;
1224 }
1225 }
1226 }
1227}
1228
1229fn is_template_visible_script(kind: SfcKind, script: &SfcScript) -> bool {
1230 match kind {
1231 SfcKind::Vue => script.is_setup,
1232 SfcKind::Svelte => !script.is_context_module,
1233 }
1234}
1235
1236#[cfg(all(test, not(miri)))]
1237mod tests {
1238 use super::*;
1239 use fallow_types::extract::{
1240 ClassThisMemberAccessFact, ClassThisWholeObjectUseFact, SemanticFactView,
1241 };
1242
1243 #[test]
1244 fn merged_script_source_joins_inline_blocks_as_typescript() {
1245 let source = r#"<script>export const a = 1;</script>
1246<script setup lang="ts" generic="T extends Item">defineProps<{ a: T }>();</script>
1247<script src="./external.ts"></script>"#;
1248 let (merged, source_type) =
1249 sfc_merged_script_source(source).expect("inline scripts give a source");
1250 assert!(source_type.is_typescript());
1251 assert!(merged.contains("export const a = 1;"));
1252 assert!(merged.contains("defineProps<{ a: T }>();"));
1253 assert!(merged.contains("<T extends Item>"));
1254 assert!(!merged.contains("external"));
1255 }
1256
1257 #[test]
1258 fn merged_script_source_is_none_without_inline_script() {
1259 assert!(sfc_merged_script_source("<template><div /></template>").is_none());
1260 assert!(sfc_merged_script_source(r#"<script src="./a.ts"></script>"#).is_none());
1261 }
1262
1263 #[test]
1264 fn is_sfc_file_vue() {
1265 assert!(is_sfc_file(Path::new("App.vue")));
1266 }
1267
1268 #[test]
1269 fn is_sfc_file_svelte() {
1270 assert!(is_sfc_file(Path::new("Counter.svelte")));
1271 }
1272
1273 #[test]
1274 fn is_sfc_file_rejects_ts() {
1275 assert!(!is_sfc_file(Path::new("utils.ts")));
1276 }
1277
1278 #[test]
1279 fn is_sfc_file_rejects_jsx() {
1280 assert!(!is_sfc_file(Path::new("App.jsx")));
1281 }
1282
1283 #[test]
1284 fn is_sfc_file_rejects_astro() {
1285 assert!(!is_sfc_file(Path::new("Layout.astro")));
1286 }
1287
1288 #[test]
1289 fn single_plain_script() {
1290 let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1291 assert_eq!(scripts.len(), 1);
1292 assert_eq!(scripts[0].body, "const x = 1;");
1293 assert!(!scripts[0].is_typescript);
1294 assert!(!scripts[0].is_jsx);
1295 assert!(scripts[0].src.is_none());
1296 }
1297
1298 #[test]
1299 fn single_ts_script() {
1300 let scripts = extract_sfc_scripts(r#"<script lang="ts">const x: number = 1;</script>"#);
1301 assert_eq!(scripts.len(), 1);
1302 assert!(scripts[0].is_typescript);
1303 assert!(!scripts[0].is_jsx);
1304 }
1305
1306 #[test]
1307 fn single_tsx_script() {
1308 let scripts = extract_sfc_scripts(r#"<script lang="tsx">const el = <div />;</script>"#);
1309 assert_eq!(scripts.len(), 1);
1310 assert!(scripts[0].is_typescript);
1311 assert!(scripts[0].is_jsx);
1312 }
1313
1314 #[test]
1315 fn single_jsx_script() {
1316 let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
1317 assert_eq!(scripts.len(), 1);
1318 assert!(!scripts[0].is_typescript);
1319 assert!(scripts[0].is_jsx);
1320 }
1321
1322 #[test]
1323 fn two_script_blocks() {
1324 let source = r#"
1325<script lang="ts">
1326export default {};
1327</script>
1328<script setup lang="ts">
1329const count = 0;
1330</script>
1331"#;
1332 let scripts = extract_sfc_scripts(source);
1333 assert_eq!(scripts.len(), 2);
1334 assert!(scripts[0].body.contains("export default"));
1335 assert!(scripts[1].body.contains("count"));
1336 }
1337
1338 #[test]
1339 fn script_setup_extracted() {
1340 let scripts =
1341 extract_sfc_scripts(r#"<script setup lang="ts">import { ref } from 'vue';</script>"#);
1342 assert_eq!(scripts.len(), 1);
1343 assert!(scripts[0].body.contains("import"));
1344 assert!(scripts[0].is_typescript);
1345 }
1346
1347 #[test]
1348 fn script_src_detected() {
1349 let scripts = extract_sfc_scripts(r#"<script src="./component.ts" lang="ts"></script>"#);
1350 assert_eq!(scripts.len(), 1);
1351 assert_eq!(scripts[0].src.as_deref(), Some("./component.ts"));
1352 }
1353
1354 #[test]
1357 fn svelte4_context_module_is_module_context() {
1358 let scripts =
1359 extract_sfc_scripts(r#"<script context="module">export const x = 1;</script>"#);
1360 assert_eq!(scripts.len(), 1);
1361 assert!(scripts[0].is_context_module);
1362 }
1363
1364 #[test]
1365 fn svelte5_bare_module_attr_is_module_context() {
1366 let scripts = extract_sfc_scripts(r"<script module>export const x = 1;</script>");
1367 assert_eq!(scripts.len(), 1);
1368 assert!(scripts[0].is_context_module);
1369 }
1370
1371 #[test]
1372 fn svelte5_module_with_lang_is_module_context() {
1373 let scripts =
1374 extract_sfc_scripts(r#"<script module lang="ts">export const x = 1;</script>"#);
1375 assert_eq!(scripts.len(), 1);
1376 assert!(scripts[0].is_context_module);
1377 assert!(scripts[0].is_typescript);
1378 }
1379
1380 #[test]
1381 fn plain_script_is_not_module_context() {
1382 let scripts = extract_sfc_scripts(r"<script>const x = 1;</script>");
1383 assert_eq!(scripts.len(), 1);
1384 assert!(!scripts[0].is_context_module);
1385 }
1386
1387 #[test]
1388 fn lang_ts_script_is_not_module_context() {
1389 let scripts = extract_sfc_scripts(r#"<script lang="ts">const x = 1;</script>"#);
1390 assert_eq!(scripts.len(), 1);
1391 assert!(!scripts[0].is_context_module);
1392 }
1393
1394 #[test]
1395 fn data_module_attr_is_not_module_context() {
1396 let scripts =
1398 extract_sfc_scripts(r#"<script data-module="x" lang="ts">const x = 1;</script>"#);
1399 assert_eq!(scripts.len(), 1);
1400 assert!(!scripts[0].is_context_module);
1401 }
1402
1403 #[test]
1404 fn bare_module_script_is_not_template_visible() {
1405 let module_script = SfcScript {
1408 body: String::new(),
1409 is_typescript: false,
1410 is_jsx: false,
1411 byte_offset: 0,
1412 src: None,
1413 src_span: None,
1414 is_setup: false,
1415 is_context_module: true,
1416 generic_attr: None,
1417 };
1418 assert!(!is_template_visible_script(SfcKind::Svelte, &module_script));
1419 let instance_script = SfcScript {
1420 is_context_module: false,
1421 ..module_script
1422 };
1423 assert!(is_template_visible_script(
1424 SfcKind::Svelte,
1425 &instance_script
1426 ));
1427 }
1428
1429 #[test]
1430 fn data_src_not_treated_as_src() {
1431 let scripts =
1432 extract_sfc_scripts(r#"<script lang="ts" data-src="./nope.ts">const x = 1;</script>"#);
1433 assert_eq!(scripts.len(), 1);
1434 assert!(scripts[0].src.is_none());
1435 }
1436
1437 #[test]
1438 fn script_inside_html_comment_filtered() {
1439 let source = r#"
1440<!-- <script lang="ts">import { bad } from 'bad';</script> -->
1441<script lang="ts">import { good } from 'good';</script>
1442"#;
1443 let scripts = extract_sfc_scripts(source);
1444 assert_eq!(scripts.len(), 1);
1445 assert!(scripts[0].body.contains("good"));
1446 }
1447
1448 #[test]
1449 fn spanning_comment_filters_script() {
1450 let source = r#"
1451<!-- disabled:
1452<script lang="ts">import { bad } from 'bad';</script>
1453-->
1454<script lang="ts">const ok = true;</script>
1455"#;
1456 let scripts = extract_sfc_scripts(source);
1457 assert_eq!(scripts.len(), 1);
1458 assert!(scripts[0].body.contains("ok"));
1459 }
1460
1461 #[test]
1462 fn string_containing_comment_markers_not_corrupted() {
1463 let source = r#"
1464<script setup lang="ts">
1465const marker = "<!-- not a comment -->";
1466import { ref } from 'vue';
1467</script>
1468"#;
1469 let scripts = extract_sfc_scripts(source);
1470 assert_eq!(scripts.len(), 1);
1471 assert!(scripts[0].body.contains("import"));
1472 }
1473
1474 #[test]
1475 fn generic_attr_with_angle_bracket() {
1476 let source =
1477 r#"<script setup lang="ts" generic="T extends Foo<Bar>">const x = 1;</script>"#;
1478 let scripts = extract_sfc_scripts(source);
1479 assert_eq!(scripts.len(), 1);
1480 assert_eq!(scripts[0].body, "const x = 1;");
1481 }
1482
1483 #[test]
1484 fn nested_generic_attr() {
1485 let source = r#"<script setup lang="ts" generic="T extends Map<string, Set<number>>">const x = 1;</script>"#;
1486 let scripts = extract_sfc_scripts(source);
1487 assert_eq!(scripts.len(), 1);
1488 assert_eq!(scripts[0].body, "const x = 1;");
1489 }
1490
1491 #[test]
1492 fn lang_single_quoted() {
1493 let scripts = extract_sfc_scripts("<script lang='ts'>const x = 1;</script>");
1494 assert_eq!(scripts.len(), 1);
1495 assert!(scripts[0].is_typescript);
1496 }
1497
1498 #[test]
1499 fn uppercase_script_tag() {
1500 let scripts = extract_sfc_scripts(r#"<SCRIPT lang="ts">const x = 1;</SCRIPT>"#);
1501 assert_eq!(scripts.len(), 1);
1502 assert!(scripts[0].is_typescript);
1503 }
1504
1505 #[test]
1506 fn no_script_block() {
1507 let scripts = extract_sfc_scripts("<template><div>Hello</div></template>");
1508 assert!(scripts.is_empty());
1509 }
1510
1511 #[test]
1512 fn empty_script_body() {
1513 let scripts = extract_sfc_scripts(r#"<script lang="ts"></script>"#);
1514 assert_eq!(scripts.len(), 1);
1515 assert!(scripts[0].body.is_empty());
1516 }
1517
1518 #[test]
1519 fn whitespace_only_script() {
1520 let scripts = extract_sfc_scripts("<script lang=\"ts\">\n \n</script>");
1521 assert_eq!(scripts.len(), 1);
1522 assert!(scripts[0].body.trim().is_empty());
1523 }
1524
1525 #[test]
1526 fn byte_offset_is_set() {
1527 let source = r#"<template><div/></template><script lang="ts">code</script>"#;
1528 let scripts = extract_sfc_scripts(source);
1529 assert_eq!(scripts.len(), 1);
1530 let offset = scripts[0].byte_offset;
1531 assert_eq!(&source[offset..offset + 4], "code");
1532 }
1533
1534 #[test]
1535 fn script_with_extra_attributes() {
1536 let scripts = extract_sfc_scripts(
1537 r#"<script lang="ts" id="app" type="module" data-custom="val">const x = 1;</script>"#,
1538 );
1539 assert_eq!(scripts.len(), 1);
1540 assert!(scripts[0].is_typescript);
1541 assert!(scripts[0].src.is_none());
1542 }
1543
1544 #[test]
1545 fn multiple_script_blocks_exports_combined() {
1546 let source = r#"
1547<script lang="ts">
1548export const version = '1.0';
1549</script>
1550<script setup lang="ts">
1551import { ref } from 'vue';
1552const count = ref(0);
1553</script>
1554"#;
1555 let info = parse_sfc_to_module(FileId(0), Path::new("Dual.vue"), source, 0, false);
1556 assert!(
1557 info.exports
1558 .iter()
1559 .any(|e| matches!(&e.name, crate::ExportName::Named(n) if n == "version")),
1560 "export from <script> block should be extracted"
1561 );
1562 assert!(
1563 info.imports.iter().any(|i| i.source == "vue"),
1564 "import from <script setup> block should be extracted"
1565 );
1566 }
1567
1568 #[test]
1569 fn class_this_facts_survive_sfc_script_merge() {
1570 let source = r#"
1571<script lang="ts">
1572export class Service {
1573 client!: Client;
1574
1575 run() {
1576 this.client.execute();
1577 Object.keys(this.client);
1578 }
1579}
1580</script>
1581"#;
1582 let info = parse_sfc_to_module(FileId(0), Path::new("Service.vue"), source, 0, false);
1583 let facts = SemanticFactView::new(&info.semantic_facts, &info.member_accesses);
1584
1585 assert_eq!(
1586 facts.class_this_member_accesses(),
1587 vec![ClassThisMemberAccessFact {
1588 class_local_name: "Service".to_string(),
1589 object: "this.client".to_string(),
1590 member: "execute".to_string(),
1591 }]
1592 );
1593 assert_eq!(
1594 facts.class_this_whole_object_uses(),
1595 vec![ClassThisWholeObjectUseFact {
1596 class_local_name: "Service".to_string(),
1597 object: "this.client".to_string(),
1598 }]
1599 );
1600 }
1601
1602 #[test]
1603 fn lang_tsx_detected_as_typescript_jsx() {
1604 let scripts =
1605 extract_sfc_scripts(r#"<script lang="tsx">const el = <div>{x}</div>;</script>"#);
1606 assert_eq!(scripts.len(), 1);
1607 assert!(scripts[0].is_typescript, "lang=tsx should be typescript");
1608 assert!(scripts[0].is_jsx, "lang=tsx should be jsx");
1609 }
1610
1611 #[test]
1612 fn multiline_html_comment_filters_all_script_blocks_inside() {
1613 let source = r#"
1614<!--
1615 This whole section is disabled:
1616 <script lang="ts">import { bad1 } from 'bad1';</script>
1617 <script lang="ts">import { bad2 } from 'bad2';</script>
1618-->
1619<script lang="ts">import { good } from 'good';</script>
1620"#;
1621 let scripts = extract_sfc_scripts(source);
1622 assert_eq!(scripts.len(), 1);
1623 assert!(scripts[0].body.contains("good"));
1624 }
1625
1626 #[test]
1627 fn script_src_generates_side_effect_import() {
1628 let info = parse_sfc_to_module(
1629 FileId(0),
1630 Path::new("External.vue"),
1631 r#"<script src="./external-logic.ts" lang="ts"></script>"#,
1632 0,
1633 false,
1634 );
1635 assert!(
1636 info.imports
1637 .iter()
1638 .any(|i| i.source == "./external-logic.ts"
1639 && matches!(i.imported_name, ImportedName::SideEffect)),
1640 "script src should generate a side-effect import"
1641 );
1642 }
1643
1644 #[test]
1645 fn parse_sfc_no_script_returns_empty_module() {
1646 let info = parse_sfc_to_module(
1647 FileId(0),
1648 Path::new("Empty.vue"),
1649 "<template><div>Hello</div></template>",
1650 42,
1651 false,
1652 );
1653 assert!(info.imports.is_empty());
1654 assert!(info.exports.is_empty());
1655 assert_eq!(info.content_hash, 42);
1656 assert_eq!(info.file_id, FileId(0));
1657 }
1658
1659 #[test]
1660 fn parse_sfc_has_line_offsets() {
1661 let info = parse_sfc_to_module(
1662 FileId(0),
1663 Path::new("LineOffsets.vue"),
1664 r#"<script lang="ts">const x = 1;</script>"#,
1665 0,
1666 false,
1667 );
1668 assert!(!info.line_offsets.is_empty());
1669 }
1670
1671 #[test]
1672 fn parse_sfc_has_suppressions() {
1673 let info = parse_sfc_to_module(
1674 FileId(0),
1675 Path::new("Suppressions.vue"),
1676 r#"<script lang="ts">
1677// fallow-ignore-file
1678export const foo = 1;
1679</script>"#,
1680 0,
1681 false,
1682 );
1683 assert!(!info.suppressions.is_empty());
1684 }
1685
1686 #[test]
1687 fn source_type_plain_js_detection() {
1688 let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1689 assert_eq!(scripts.len(), 1);
1690 assert!(!scripts[0].is_typescript);
1691 assert!(!scripts[0].is_jsx);
1692 }
1693
1694 #[test]
1695 fn is_sfc_file_rejects_no_extension() {
1696 assert!(!is_sfc_file(Path::new("Makefile")));
1697 }
1698
1699 #[test]
1700 fn is_sfc_file_rejects_mdx() {
1701 assert!(!is_sfc_file(Path::new("post.mdx")));
1702 }
1703
1704 #[test]
1705 fn is_sfc_file_rejects_css() {
1706 assert!(!is_sfc_file(Path::new("styles.css")));
1707 }
1708
1709 #[test]
1710 fn multiple_script_blocks_both_have_offsets() {
1711 let source = r#"<script lang="ts">const a = 1;</script>
1712<script setup lang="ts">const b = 2;</script>"#;
1713 let scripts = extract_sfc_scripts(source);
1714 assert_eq!(scripts.len(), 2);
1715 let offset0 = scripts[0].byte_offset;
1716 let offset1 = scripts[1].byte_offset;
1717 assert_eq!(
1718 &source[offset0..offset0 + "const a = 1;".len()],
1719 "const a = 1;"
1720 );
1721 assert_eq!(
1722 &source[offset1..offset1 + "const b = 2;".len()],
1723 "const b = 2;"
1724 );
1725 }
1726
1727 #[test]
1728 fn script_with_src_and_lang() {
1729 let scripts = extract_sfc_scripts(r#"<script src="./logic.ts" lang="tsx"></script>"#);
1730 assert_eq!(scripts.len(), 1);
1731 assert_eq!(scripts[0].src.as_deref(), Some("./logic.ts"));
1732 assert!(scripts[0].is_typescript);
1733 assert!(scripts[0].is_jsx);
1734 }
1735
1736 #[test]
1737 fn extract_style_block_lang_scss() {
1738 let source = r#"<template/><style lang="scss">@import 'Foo';</style>"#;
1739 let styles = extract_sfc_styles(source);
1740 assert_eq!(styles.len(), 1);
1741 assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1742 assert!(styles[0].body.contains("@import"));
1743 assert!(styles[0].src.is_none());
1744 }
1745
1746 #[test]
1747 fn extract_style_block_with_src() {
1748 let source = r#"<style src="./theme.scss" lang="scss"></style>"#;
1749 let styles = extract_sfc_styles(source);
1750 assert_eq!(styles.len(), 1);
1751 assert_eq!(styles[0].src.as_deref(), Some("./theme.scss"));
1752 assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1753 }
1754
1755 #[test]
1756 fn extract_style_block_plain_no_lang() {
1757 let source = r"<style>.foo { color: red; }</style>";
1758 let styles = extract_sfc_styles(source);
1759 assert_eq!(styles.len(), 1);
1760 assert!(styles[0].lang.is_none());
1761 }
1762
1763 #[test]
1764 fn extract_multiple_style_blocks() {
1765 let source = r#"<style lang="scss">@import 'a';</style>
1766<style scoped lang="scss">@import 'b';</style>"#;
1767 let styles = extract_sfc_styles(source);
1768 assert_eq!(styles.len(), 2);
1769 }
1770
1771 #[test]
1772 fn style_block_inside_html_comment_filtered() {
1773 let source = r#"<!-- <style lang="scss">@import 'bad';</style> -->
1774<style lang="scss">@import 'good';</style>"#;
1775 let styles = extract_sfc_styles(source);
1776 assert_eq!(styles.len(), 1);
1777 assert!(styles[0].body.contains("good"));
1778 }
1779
1780 #[test]
1781 fn parse_sfc_extracts_style_imports_with_from_style_flag() {
1782 let info = parse_sfc_to_module(
1783 FileId(0),
1784 Path::new("Foo.vue"),
1785 r#"<template/><style lang="scss">@import 'Foo';</style>"#,
1786 0,
1787 false,
1788 );
1789 let style_import = info
1790 .imports
1791 .iter()
1792 .find(|i| i.source == "./Foo")
1793 .expect("scss @import 'Foo' should be normalized to ./Foo");
1794 assert!(
1795 style_import.from_style,
1796 "imports from <style> blocks must carry from_style=true so the resolver \
1797 enables SCSS partial fallback for the SFC importer"
1798 );
1799 assert!(matches!(
1800 style_import.imported_name,
1801 ImportedName::SideEffect
1802 ));
1803 }
1804
1805 #[test]
1806 fn parse_sfc_extracts_style_plugin_as_default_import() {
1807 let info = parse_sfc_to_module(
1808 FileId(0),
1809 Path::new("Foo.vue"),
1810 r#"<template/><style>@plugin "./tailwind-plugin.js";</style>"#,
1811 0,
1812 false,
1813 );
1814 let plugin_import = info
1815 .imports
1816 .iter()
1817 .find(|i| i.source == "./tailwind-plugin.js")
1818 .expect("style @plugin should create an import");
1819 assert!(plugin_import.from_style);
1820 assert!(matches!(plugin_import.imported_name, ImportedName::Default));
1821 }
1822
1823 #[test]
1824 fn parse_sfc_extracts_style_src_with_from_style_flag() {
1825 let info = parse_sfc_to_module(
1826 FileId(0),
1827 Path::new("Bar.vue"),
1828 r#"<style src="./Bar.scss" lang="scss"></style>"#,
1829 0,
1830 false,
1831 );
1832 let style_src = info
1833 .imports
1834 .iter()
1835 .find(|i| i.source == "./Bar.scss")
1836 .expect("<style src=\"./Bar.scss\"> should produce a side-effect import");
1837 assert!(style_src.from_style);
1838 }
1839
1840 #[test]
1841 fn parse_sfc_skips_unsupported_style_lang_body_but_keeps_src() {
1842 let info = parse_sfc_to_module(
1843 FileId(0),
1844 Path::new("Baz.vue"),
1845 r#"<style lang="postcss" src="./Baz.pcss">@custom-rule "skipped";</style>"#,
1846 0,
1847 false,
1848 );
1849 assert!(
1850 info.imports.iter().any(|i| i.source == "./Baz.pcss"),
1851 "src reference should still be seeded for unsupported lang"
1852 );
1853 assert!(
1854 !info.imports.iter().any(|i| i.source.contains("skipped")),
1855 "postcss body should not be scanned for @import directives"
1856 );
1857 }
1858
1859 fn asset_refs(source: &str) -> Vec<String> {
1860 super::collect_template_asset_refs(source)
1861 .into_iter()
1862 .map(|(s, _)| s)
1863 .collect()
1864 }
1865
1866 #[test]
1867 fn captures_static_relative_template_asset_refs() {
1868 assert_eq!(
1869 asset_refs(r#"<template><img src="./logo.png" /></template>"#),
1870 vec!["./logo.png".to_string()]
1871 );
1872 assert_eq!(
1873 asset_refs(r#"<source src="../media/clip.mp4">"#),
1874 vec!["../media/clip.mp4".to_string()]
1875 );
1876 assert_eq!(
1877 asset_refs(r#"<video poster="./thumb.jpg"></video>"#),
1878 vec!["./thumb.jpg".to_string()]
1879 );
1880 }
1881
1882 #[test]
1883 fn skips_dynamic_alias_root_remote_and_query_asset_refs() {
1884 assert!(asset_refs(r#"<img :src="logo" />"#).is_empty());
1886 assert!(asset_refs(r#"<img v-bind:src="logo" />"#).is_empty());
1887 assert!(asset_refs(r#"<img bind:src="logo" />"#).is_empty());
1888 assert!(asset_refs(r"<img src={logo} />").is_empty());
1889 assert!(asset_refs(r#"<img data-src="./x.png" />"#).is_empty());
1890 assert!(asset_refs(r#"<img src="@/assets/x.png" />"#).is_empty());
1892 assert!(asset_refs(r#"<img src="/logo.png" />"#).is_empty());
1893 assert!(asset_refs(r#"<img src="https://cdn/x.png" />"#).is_empty());
1894 assert!(asset_refs(r#"<img src="./x.png?inline" />"#).is_empty());
1896 assert!(asset_refs(r#"<img src="{{ logo }}" />"#).is_empty());
1898 }
1899
1900 #[test]
1901 fn skips_custom_component_src_prop() {
1902 assert!(asset_refs(r#"<MyImage src="./x.png" />"#).is_empty());
1904 assert!(asset_refs(r#"<AppIcon src="../icons/y.svg" />"#).is_empty());
1905 }
1906
1907 #[test]
1908 fn skips_asset_refs_inside_script_style_and_comments() {
1909 assert!(asset_refs(r#"<script>const x = "<img src='./a.png'>"</script>"#).is_empty());
1911 assert!(asset_refs(r#"<style>/* <img src="./b.png"> */ .x{}</style>"#).is_empty());
1912 assert!(asset_refs(r#"<!-- <img src="./c.png" /> -->"#).is_empty());
1913 }
1914
1915 #[test]
1916 fn parse_sfc_emits_template_asset_as_side_effect_import() {
1917 let info = parse_sfc_to_module(
1918 FileId(0),
1919 Path::new("Hero.vue"),
1920 r#"<template><img src="./hero.png" /></template><script>let x=1</script>"#,
1921 0,
1922 false,
1923 );
1924 assert!(
1925 info.imports.iter().any(|i| i.source == "./hero.png"
1926 && matches!(i.imported_name, ImportedName::SideEffect)
1927 && !i.from_style),
1928 "template <img src> should seed a SideEffect import: {:?}",
1929 info.imports
1930 );
1931 }
1932
1933 fn svelte_props(source: &str) -> Vec<crate::ModuleInfo> {
1936 vec![parse_sfc_to_module(
1937 FileId(0),
1938 Path::new("Component.svelte"),
1939 source,
1940 0,
1941 false,
1942 )]
1943 }
1944
1945 fn prop_names(info: &crate::ModuleInfo) -> Vec<String> {
1946 let mut names: Vec<String> = info
1947 .component_props
1948 .iter()
1949 .map(|p| p.name.clone())
1950 .collect();
1951 names.sort();
1952 names
1953 }
1954
1955 #[test]
1956 fn svelte_shorthand_props_harvested() {
1957 let info = &svelte_props(r"<script>let { a, b } = $props();</script>")[0];
1959 assert_eq!(prop_names(info), vec!["a", "b"]);
1960 for prop in &info.component_props {
1961 assert_eq!(prop.local, prop.name);
1962 }
1963 }
1964
1965 #[test]
1966 fn svelte_renamed_prop_tracks_local_and_script_use() {
1967 let info =
1970 &svelte_props(r"<script>let { a: alias } = $props(); console.log(alias);</script>")[0];
1971 assert_eq!(prop_names(info), vec!["a"]);
1972 let prop = &info.component_props[0];
1973 assert_eq!(prop.local, "alias");
1974 assert!(
1975 prop.used_in_script,
1976 "alias is referenced, so a is used in script"
1977 );
1978 }
1979
1980 #[test]
1981 fn svelte_unreferenced_prop_is_unused_in_script() {
1982 let info = &svelte_props(r"<script>let { a } = $props();</script>")[0];
1983 assert_eq!(prop_names(info), vec!["a"]);
1984 assert!(!info.component_props[0].used_in_script);
1985 }
1986
1987 #[test]
1988 fn svelte_default_prop_peeled() {
1989 let info = &svelte_props(r"<script>let { a = 1 } = $props();</script>")[0];
1991 assert_eq!(prop_names(info), vec!["a"]);
1992 }
1993
1994 #[test]
1995 fn svelte_bindable_default_peeled() {
1996 let info = &svelte_props(r"<script>let { a = $bindable() } = $props();</script>")[0];
1999 assert_eq!(prop_names(info), vec!["a"]);
2000 }
2001
2002 #[test]
2003 fn svelte_rest_element_sets_fallthrough_abstain() {
2004 let info = &svelte_props(r"<script>let { a, ...rest } = $props();</script>")[0];
2006 assert!(info.has_props_attrs_fallthrough);
2007 }
2008
2009 #[test]
2010 fn svelte_bare_identifier_binding_sets_unharvestable_abstain() {
2011 let info = &svelte_props(r"<script>let p = $props(); console.log(p.x);</script>")[0];
2013 assert!(info.has_unharvestable_props);
2014 assert!(info.component_props.is_empty());
2015 }
2016
2017 #[test]
2018 fn svelte_nested_destructure_sets_unharvestable_abstain() {
2019 let info = &svelte_props(r"<script>let { a: { x } } = $props();</script>")[0];
2021 assert!(info.has_unharvestable_props);
2022 }
2023
2024 #[test]
2025 fn svelte_prop_used_only_in_markup_credited_as_template_root() {
2026 let info = &svelte_props(r"<script>let { a } = $props();</script><p>{a}</p>")[0];
2029 assert_eq!(prop_names(info), vec!["a"]);
2030 assert!(
2031 info.component_props[0].used_in_template,
2032 "a is used in markup, so used_in_template should be true"
2033 );
2034 }
2035
2036 #[test]
2037 fn svelte_module_script_props_not_harvested() {
2038 let info = &svelte_props(
2040 r"<script module>let { a } = $props();</script><script>let { b } = $props();</script>",
2041 )[0];
2042 assert_eq!(prop_names(info), vec!["b"]);
2044 }
2045
2046 fn dispatched_names(info: &crate::ModuleInfo) -> Vec<String> {
2049 let mut names: Vec<String> = info
2050 .svelte_dispatched_events
2051 .iter()
2052 .map(|e| e.name.clone())
2053 .collect();
2054 names.sort();
2055 names
2056 }
2057
2058 #[test]
2059 fn svelte_dispatch_literal_event_is_harvested() {
2060 let info = &svelte_props(
2061 r"<script>import { createEventDispatcher } from 'svelte';
2062 const dispatch = createEventDispatcher();
2063 function save() { dispatch('save'); }</script>",
2064 )[0];
2065 assert_eq!(dispatched_names(info), vec!["save"]);
2066 assert!(!info.has_dynamic_dispatch);
2067 }
2068
2069 #[test]
2070 fn svelte_dispatch_without_svelte_import_is_ignored() {
2071 let info = &svelte_props(
2074 r"<script>function createEventDispatcher() { return () => {}; }
2075 const dispatch = createEventDispatcher();
2076 dispatch('save');</script>",
2077 )[0];
2078 assert!(info.svelte_dispatched_events.is_empty());
2079 }
2080
2081 #[test]
2082 fn svelte_dynamic_dispatch_sets_abstain() {
2083 let info = &svelte_props(
2084 r"<script>import { createEventDispatcher } from 'svelte';
2085 const dispatch = createEventDispatcher();
2086 function fire(name) { dispatch(name); }</script>",
2087 )[0];
2088 assert!(
2089 info.has_dynamic_dispatch,
2090 "a non-literal dispatch arg must set the abstain flag"
2091 );
2092 }
2093
2094 #[test]
2095 fn svelte_dispatch_whole_value_use_sets_abstain() {
2096 let info = &svelte_props(
2097 r"<script>import { createEventDispatcher } from 'svelte';
2098 const dispatch = createEventDispatcher();
2099 forward(dispatch);</script>",
2100 )[0];
2101 assert!(
2102 info.has_dynamic_dispatch,
2103 "passing the dispatch binding as a whole value must set the abstain flag"
2104 );
2105 }
2106
2107 #[test]
2108 fn svelte_listened_event_on_component_is_harvested() {
2109 let info =
2110 &svelte_props(r"<script>import Child from './Child.svelte';</script><Child on:save />")
2111 [0];
2112 assert!(info.svelte_listened_events.contains(&"save".to_string()));
2113 }
2114}
2115
2116fn apply_component_contracts(kind: SfcKind, source: &str, combined: &mut ModuleInfo) {
2117 let framework = match kind {
2118 SfcKind::Vue => fallow_types::extract::ComponentFramework::Vue,
2119 SfcKind::Svelte => fallow_types::extract::ComponentFramework::Svelte,
2120 };
2121 let callers = crate::sfc_template::component_contracts::collect(
2122 &mask_non_markup_regions(source),
2123 &combined.imports,
2124 framework,
2125 0,
2126 combined
2127 .component_contracts
2128 .as_deref()
2129 .map_or(&[], |facts| facts.spread_bindings.as_slice()),
2130 combined
2131 .component_contracts
2132 .as_deref()
2133 .map_or(&[], |facts| facts.aliases.as_slice()),
2134 );
2135 crate::component_contracts::merge(&mut combined.component_contracts, callers, 0, None);
2136 if let Some(facts) = &mut combined.component_contracts {
2137 let credited: FxHashSet<String> = facts
2138 .declarations
2139 .iter()
2140 .flat_map(|prop| [prop.local.clone(), prop.name.clone()])
2141 .collect();
2142 let usage = collect_template_usage_with_bound_targets(
2143 kind,
2144 source,
2145 &credited,
2146 &FxHashMap::default(),
2147 &FxHashMap::default(),
2148 );
2149 for declaration in &mut facts.declarations {
2150 declaration.is_used |= usage.used_bindings.contains(&declaration.local)
2151 || usage.member_accesses.iter().any(|access| {
2152 access.object == declaration.local && access.member == declaration.name
2153 });
2154 }
2155 }
2156 if let Some(facts) = &mut combined.component_contracts {
2157 for declaration in &mut facts.declarations {
2158 if let Some(prop) = combined
2159 .component_props
2160 .iter()
2161 .find(|prop| prop.name == declaration.name)
2162 {
2163 declaration.is_used |= prop.used_in_template;
2164 }
2165 declaration.incomplete |= combined.has_props_attrs_fallthrough
2166 || combined.has_define_expose
2167 || combined.has_define_model;
2168 }
2169 }
2170
2171 crate::component_contracts::attach_sfc_default_export(combined);
2172}