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
393pub(crate) fn parse_sfc_to_module(
395 file_id: FileId,
396 path: &Path,
397 source: &str,
398 content_hash: u64,
399 need_complexity: bool,
400) -> ModuleInfo {
401 let scripts = extract_sfc_scripts(source);
402 let styles = extract_sfc_styles(source);
403 let kind = sfc_kind(path);
404 let mut combined = empty_sfc_module(file_id, source, content_hash);
405 let mut template_visible_imports: FxHashSet<String> = FxHashSet::default();
406 let mut template_visible_bound_targets: FxHashMap<String, String> = FxHashMap::default();
407 let mut template_visible_iterable_types: FxHashMap<String, String> = FxHashMap::default();
408 let mut props_return_binding: Option<String> = None;
409 let mut emit_return_binding: Option<String> = None;
410
411 for script in &scripts {
412 merge_script_into_module(&mut SfcScriptMergeInput {
413 kind,
414 script,
415 combined: &mut combined,
416 template_visible_imports: &mut template_visible_imports,
417 template_visible_bound_targets: &mut template_visible_bound_targets,
418 template_visible_iterable_types: &mut template_visible_iterable_types,
419 props_return_binding: &mut props_return_binding,
420 emit_return_binding: &mut emit_return_binding,
421 need_complexity,
422 });
423 }
424
425 for style in &styles {
426 merge_style_into_module(style, &mut combined);
427 }
428
429 if kind == SfcKind::Vue
433 && !combined.component_props.is_empty()
434 && PROPS_ATTRS_SPREAD_RE.is_match(source)
435 {
436 combined.has_props_attrs_fallthrough = true;
437 }
438
439 apply_template_usage(TemplateUsageInput {
440 kind,
441 source,
442 template_visible_imports,
443 template_visible_bound_targets,
444 template_visible_iterable_types: &template_visible_iterable_types,
445 props_return_binding: props_return_binding.as_deref(),
446 credit_load_data: kind == SfcKind::Svelte && is_sveltekit_route_data_component(path),
447 combined: &mut combined,
448 });
449
450 if need_complexity {
451 append_template_complexity(kind, source, &mut combined);
452 }
453
454 if kind == SfcKind::Vue && !combined.component_emits.is_empty() {
458 apply_template_emit_usage(source, emit_return_binding.as_deref(), &mut combined);
459 }
460
461 if kind == SfcKind::Svelte {
465 combined.svelte_listened_events =
466 crate::sfc_template::collect_svelte_listened_events(source);
467 }
468
469 append_template_asset_imports(source, &mut combined);
470 dedup_import_binding_lists(&mut combined);
471 apply_component_contracts(kind, source, &mut combined);
472
473 combined
474}
475
476fn append_template_complexity(kind: SfcKind, source: &str, combined: &mut ModuleInfo) {
484 match kind {
485 SfcKind::Vue => {
486 combined.complexity.extend(
487 crate::template_complexity::compute_vue_template_complexity(source),
488 );
489 }
490 SfcKind::Svelte => combined
493 .complexity
494 .extend(crate::template_complexity::compute_svelte_template_complexity(source)),
495 }
496}
497
498fn append_template_asset_imports(source: &str, combined: &mut ModuleInfo) {
502 for (specifier, span) in collect_template_asset_refs(source) {
503 combined.imports.push(ImportInfo {
504 source: specifier,
505 imported_name: ImportedName::SideEffect,
506 local_name: String::new(),
507 is_type_only: false,
508 is_type_only_star: false,
509 from_style: false,
510 span,
511 source_span: span,
512 });
513 }
514}
515
516fn dedup_import_binding_lists(combined: &mut ModuleInfo) {
519 combined.unused_import_bindings.sort_unstable();
520 combined.unused_import_bindings.dedup();
521 combined.type_referenced_import_bindings.sort_unstable();
522 combined.type_referenced_import_bindings.dedup();
523 combined.value_referenced_import_bindings.sort_unstable();
524 combined.value_referenced_import_bindings.dedup();
525 combined.auto_import_candidates.sort_unstable();
526 combined.auto_import_candidates.dedup();
527}
528
529fn sfc_kind(path: &Path) -> SfcKind {
530 if path.extension().and_then(|ext| ext.to_str()) == Some("vue") {
531 SfcKind::Vue
532 } else {
533 SfcKind::Svelte
534 }
535}
536
537fn is_sveltekit_route_data_component(path: &Path) -> bool {
548 let Some(stem) = path
549 .file_name()
550 .and_then(|name| name.to_str())
551 .and_then(|name| name.strip_suffix(".svelte"))
552 else {
553 return false;
554 };
555 ["+page", "+layout"].iter().any(|prefix| {
556 stem.strip_prefix(prefix)
557 .is_some_and(|rest| rest.is_empty() || rest.starts_with('@'))
558 })
559}
560
561fn empty_sfc_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
562 let parsed = crate::suppress::parse_suppressions_from_source(source);
563
564 crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
565 file_id,
566 content_hash,
567 source,
568 parsed_suppressions: parsed,
569 imports: Vec::new(),
570 exports: Vec::new(),
571 })
572}
573
574struct SfcScriptMergeInput<'a> {
575 kind: SfcKind,
576 script: &'a SfcScript,
577 combined: &'a mut ModuleInfo,
578 template_visible_imports: &'a mut FxHashSet<String>,
579 template_visible_bound_targets: &'a mut FxHashMap<String, String>,
580 template_visible_iterable_types: &'a mut FxHashMap<String, String>,
581 props_return_binding: &'a mut Option<String>,
582 emit_return_binding: &'a mut Option<String>,
583 need_complexity: bool,
584}
585
586fn merge_script_into_module(input: &mut SfcScriptMergeInput<'_>) {
587 if input.kind == SfcKind::Vue
588 && let Some(src) = &input.script.src
589 {
590 add_script_src_import(input.combined, src, input.script.src_span);
591 }
592
593 let allocator = Allocator::default();
594 let parser_return = Parser::new(
595 &allocator,
596 &input.script.body,
597 source_type_for_script(input.script),
598 )
599 .parse();
600 let mut extractor = ModuleInfoExtractor::new();
601 extractor.set_top_level_is_component_body(is_template_visible_script(input.kind, input.script));
602 extractor.visit_program(&parser_return.program);
603 let empty_template_used = FxHashSet::default();
604 let mut semantic_usage = crate::parse::compute_semantic_usage_for_extractor(
605 &parser_return.program,
606 &mut extractor,
607 &empty_template_used,
608 );
609 if input.kind == SfcKind::Vue || is_template_visible_script(input.kind, input.script) {
610 crate::component_contracts::merge(
611 &mut input.combined.component_contracts,
612 std::mem::take(&mut semantic_usage.component_contracts),
613 input.script.byte_offset as u32,
614 Some(match input.kind {
615 SfcKind::Vue => fallow_types::extract::ComponentFramework::Vue,
616 SfcKind::Svelte => fallow_types::extract::ComponentFramework::Svelte,
617 }),
618 );
619 }
620 let extraction = ExtractionResult::contiguous(&input.script.body, input.script.byte_offset);
621 extractor.remap_spans_with(|span| extraction.remap_span(span));
622 extractor.resolve_typed_destructure_bindings();
623
624 merge_script_binding_usage(
625 input,
626 &allocator,
627 &extractor.imports,
628 &extractor.import_equals_bindings,
629 semantic_usage,
630 );
631 if input.need_complexity {
632 input
633 .combined
634 .complexity
635 .extend(translate_script_complexity(
636 input.script,
637 &parser_return.program,
638 &input.combined.line_offsets,
639 ));
640 }
641
642 if input.kind == SfcKind::Vue {
646 merge_vue_props_emits_into(input, &parser_return.program, &mut extractor);
647 }
648
649 if input.kind == SfcKind::Svelte && is_template_visible_script(input.kind, input.script) {
654 merge_svelte_props_into(
655 input.combined,
656 &parser_return.program,
657 input.script.byte_offset,
658 );
659 }
660
661 if is_template_visible_script(input.kind, input.script) {
662 harvest_template_visible_bindings(input, &extractor);
663 }
664
665 let dispatch_base = input.combined.svelte_dispatched_events.len();
670 extractor.merge_into(input.combined);
671 for event in &mut input.combined.svelte_dispatched_events[dispatch_base..] {
672 event.span_start += input.script.byte_offset as u32;
673 }
674}
675
676fn merge_script_binding_usage(
687 input: &mut SfcScriptMergeInput<'_>,
688 allocator: &Allocator,
689 imports: &[ImportInfo],
690 import_equals_bindings: &[String],
691 semantic_usage: crate::parse::SemanticUsage,
692) {
693 let augmented_body = build_generic_attr_probe_source(input.script);
694 let empty_template_used = FxHashSet::default();
695 let (binding_usage, auto_import_candidates) = if let Some(augmented) = augmented_body.as_deref()
696 {
697 let augmented_return =
698 Parser::new(allocator, augmented, source_type_for_script(input.script)).parse();
699 (
700 compute_import_binding_usage(
701 &augmented_return.program,
702 imports,
703 import_equals_bindings,
704 &empty_template_used,
705 ),
706 semantic_usage.auto_import_candidates,
707 )
708 } else {
709 (
710 semantic_usage.import_binding_usage,
711 semantic_usage.auto_import_candidates,
712 )
713 };
714 crate::parse::append_declaration_merge_facts(
715 &mut input.combined.semantic_facts,
716 semantic_usage.declaration_merges,
717 input.script.byte_offset as u32,
718 );
719 input
720 .combined
721 .unused_import_bindings
722 .extend(binding_usage.unused.iter().cloned());
723 input
724 .combined
725 .type_referenced_import_bindings
726 .extend(binding_usage.type_referenced.iter().cloned());
727 input
728 .combined
729 .value_referenced_import_bindings
730 .extend(binding_usage.value_referenced.iter().cloned());
731 input
732 .combined
733 .auto_import_candidates
734 .extend(auto_import_candidates);
735}
736
737fn harvest_template_visible_bindings(
741 input: &mut SfcScriptMergeInput<'_>,
742 extractor: &ModuleInfoExtractor,
743) {
744 input.template_visible_imports.extend(
745 extractor
746 .imports
747 .iter()
748 .filter(|import| !import.local_name.is_empty())
749 .map(|import| import.local_name.clone()),
750 );
751 input.template_visible_bound_targets.extend(
752 extractor
753 .binding_target_names()
754 .iter()
755 .filter(|(local, _)| !local.starts_with("this."))
756 .filter_map(|(local, target)| {
757 target
758 .class_name()
759 .map(|class_name| (local.clone(), class_name.to_string()))
760 }),
761 );
762 input.template_visible_iterable_types.extend(
766 extractor
767 .array_binding_element_types()
768 .iter()
769 .filter(|(local, _)| !local.starts_with("this."))
770 .map(|(local, element)| (local.clone(), element.clone())),
771 );
772}
773
774fn merge_svelte_props_into(
778 combined: &mut ModuleInfo,
779 program: &oxc_ast::ast::Program<'_>,
780 byte_offset: usize,
781) {
782 let harvest = crate::sfc_props::harvest_svelte_props(program);
783 if harvest.has_unharvestable_props {
784 combined.has_unharvestable_props = true;
785 }
786 if harvest.has_props_attrs_fallthrough {
787 combined.has_props_attrs_fallthrough = true;
788 }
789 for mut prop in harvest.props {
790 prop.span_start += byte_offset as u32;
791 combined.component_props.push(prop);
792 }
793}
794
795fn merge_vue_props_emits_into(
802 input: &mut SfcScriptMergeInput<'_>,
803 program: &oxc_ast::ast::Program<'_>,
804 extractor: &mut ModuleInfoExtractor,
805) {
806 let byte_offset = input.script.byte_offset as u32;
807 if input.script.is_setup {
808 apply_props_harvest(
809 input,
810 crate::sfc_props::harvest_define_props(program),
811 byte_offset,
812 extractor,
813 );
814 apply_emits_harvest(
815 input,
816 crate::sfc_props::harvest_define_emits(program),
817 byte_offset,
818 );
819 } else {
820 apply_props_harvest(
821 input,
822 crate::sfc_props::harvest_options_api_props(program),
823 byte_offset,
824 extractor,
825 );
826 apply_emits_harvest(
827 input,
828 crate::sfc_props::harvest_options_api_emits(program),
829 byte_offset,
830 );
831 }
832}
833
834fn apply_props_harvest(
840 input: &mut SfcScriptMergeInput<'_>,
841 harvest: crate::sfc_props::DefinePropsHarvest,
842 byte_offset: u32,
843 extractor: &mut ModuleInfoExtractor,
844) {
845 if harvest.has_unharvestable_props {
846 input.combined.has_unharvestable_props = true;
847 }
848 if harvest.has_props_attrs_fallthrough {
849 input.combined.has_props_attrs_fallthrough = true;
850 }
851 if harvest.has_define_expose {
852 input.combined.has_define_expose = true;
853 }
854 if harvest.has_define_model {
855 input.combined.has_define_model = true;
856 }
857 if let Some(binding) = harvest.props_return_binding {
858 *input.props_return_binding = Some(binding);
859 }
860 for (field_name, element_type) in harvest.props_array_element_types {
868 extractor
869 .array_binding_element_types_mut()
870 .insert(format!("props.{field_name}"), element_type);
871 }
872 for mut prop in harvest.props {
873 prop.span_start += byte_offset;
874 input.combined.component_props.push(prop);
875 }
876}
877
878fn apply_emits_harvest(
884 input: &mut SfcScriptMergeInput<'_>,
885 harvest: crate::sfc_props::DefineEmitsHarvest,
886 byte_offset: u32,
887) {
888 if harvest.has_unharvestable_emits {
889 input.combined.has_unharvestable_emits = true;
890 }
891 if harvest.has_dynamic_emit {
892 input.combined.has_dynamic_emit = true;
893 }
894 if harvest.has_emit_whole_object_use {
895 input.combined.has_emit_whole_object_use = true;
896 }
897 if let Some(binding) = harvest.emit_binding {
898 *input.emit_return_binding = Some(binding);
899 }
900 for mut emit in harvest.emits {
901 emit.span_start += byte_offset;
902 input.combined.component_emits.push(emit);
903 }
904}
905
906pub(crate) fn translate_script_complexity(
910 script: &SfcScript,
911 program: &oxc_ast::ast::Program<'_>,
912 sfc_line_offsets: &[u32],
913) -> Vec<FunctionComplexity> {
914 let script_line_offsets = compute_line_offsets(&script.body);
915 let mut complexity =
916 crate::complexity::compute_complexity(program, &script.body, &script_line_offsets);
917 let (body_start_line, body_start_col) = byte_offset_to_line_col(
918 sfc_line_offsets,
919 u32::try_from(script.byte_offset).unwrap_or(u32::MAX),
920 );
921
922 for function in &mut complexity {
923 function.line = body_start_line + function.line.saturating_sub(1);
924 if function.line == body_start_line {
925 function.col += body_start_col;
926 }
927 }
928
929 complexity
930}
931
932fn add_script_src_import(module: &mut ModuleInfo, source: &str, source_span: Option<Span>) {
933 let span = source_span.unwrap_or_default();
934 module.imports.push(ImportInfo {
935 source: normalize_asset_url(source),
936 imported_name: ImportedName::SideEffect,
937 local_name: String::new(),
938 is_type_only: false,
939 is_type_only_star: false,
940 from_style: false,
941 span,
942 source_span: span,
943 });
944}
945
946fn style_lang_is_scss(lang: Option<&str>) -> bool {
952 matches!(lang, Some("scss" | "sass"))
953}
954
955fn style_lang_is_css_like(lang: Option<&str>) -> bool {
956 lang.is_none() || matches!(lang, Some("css"))
957}
958
959fn merge_style_into_module(style: &SfcStyle, combined: &mut ModuleInfo) {
960 if let Some(src) = &style.src {
961 let span = style.src_span.unwrap_or_default();
962 combined.imports.push(ImportInfo {
963 source: normalize_asset_url(src),
964 imported_name: ImportedName::SideEffect,
965 local_name: String::new(),
966 is_type_only: false,
967 is_type_only_star: false,
968 from_style: true,
969 span,
970 source_span: span,
971 });
972 }
973
974 let lang = style.lang.as_deref();
975 let is_scss = style_lang_is_scss(lang);
976 let is_css_like = style_lang_is_css_like(lang);
977 if !is_scss && !is_css_like {
978 return;
979 }
980
981 for source in crate::css::extract_css_import_sources(&style.body, is_scss) {
982 let source_span = Span::new(
983 style.byte_offset as u32 + source.span.start,
984 style.byte_offset as u32 + source.span.end,
985 );
986 combined.imports.push(ImportInfo {
987 source: source.normalized,
988 imported_name: if source.is_plugin {
989 ImportedName::Default
990 } else {
991 ImportedName::SideEffect
992 },
993 local_name: String::new(),
994 is_type_only: false,
995 is_type_only_star: false,
996 from_style: true,
997 span: source_span,
998 source_span,
999 });
1000 }
1001}
1002
1003pub(crate) fn source_type_for_script(script: &SfcScript) -> SourceType {
1004 match (script.is_typescript, script.is_jsx) {
1005 (true, true) => SourceType::tsx(),
1006 (true, false) => SourceType::ts(),
1007 (false, true) => SourceType::jsx(),
1008 (false, false) => SourceType::mjs(),
1009 }
1010}
1011
1012fn build_generic_attr_probe_source(script: &SfcScript) -> Option<String> {
1018 let constraint = script.generic_attr.as_deref()?.trim();
1019 if constraint.is_empty() {
1020 return None;
1021 }
1022 Some(format!(
1023 "{}\n;type __FALLOW_GENERIC_ATTR_PROBE<{}> = unknown;\n",
1024 script.body, constraint,
1025 ))
1026}
1027
1028struct TemplateUsageInput<'a> {
1029 kind: SfcKind,
1030 source: &'a str,
1031 template_visible_imports: FxHashSet<String>,
1032 template_visible_bound_targets: FxHashMap<String, String>,
1033 template_visible_iterable_types: &'a FxHashMap<String, String>,
1034 props_return_binding: Option<&'a str>,
1035 credit_load_data: bool,
1036 combined: &'a mut ModuleInfo,
1037}
1038
1039fn apply_template_usage(input: TemplateUsageInput<'_>) {
1040 let TemplateUsageInput {
1041 kind,
1042 source,
1043 template_visible_imports,
1044 template_visible_bound_targets,
1045 template_visible_iterable_types,
1046 props_return_binding,
1047 credit_load_data,
1048 combined,
1049 } = input;
1050 let credited = build_template_credited_set(
1051 template_visible_imports,
1052 props_return_binding,
1053 credit_load_data,
1054 source,
1055 combined,
1056 );
1057 let template_usage = compute_template_usage(
1058 kind,
1059 source,
1060 &credited,
1061 template_visible_bound_targets,
1062 template_visible_iterable_types,
1063 credit_load_data,
1064 );
1065 apply_prop_template_credit(&template_usage, props_return_binding, combined);
1066 merge_template_usage_into_combined(template_usage, combined);
1067}
1068
1069fn build_template_credited_set(
1075 template_visible_imports: FxHashSet<String>,
1076 props_return_binding: Option<&str>,
1077 credit_load_data: bool,
1078 source: &str,
1079 combined: &mut ModuleInfo,
1080) -> FxHashSet<String> {
1081 let mut credited = template_visible_imports;
1082 if credit_load_data {
1087 credited.insert("data".to_string());
1088 if SVELTE_TEMPLATE_DATA_WHOLE_USE_RE.is_match(source) {
1091 combined.has_load_data_whole_use = true;
1092 }
1093 }
1094 if !combined.component_props.is_empty() {
1095 for prop in &combined.component_props {
1096 credited.insert(prop.name.clone());
1099 credited.insert(prop.local.clone());
1100 }
1101 credited.insert("$props".to_string());
1104 if let Some(binding) = props_return_binding {
1105 credited.insert(binding.to_string());
1106 }
1107 }
1108 credited
1109}
1110
1111fn compute_template_usage(
1116 kind: SfcKind,
1117 source: &str,
1118 credited: &FxHashSet<String>,
1119 mut template_visible_bound_targets: FxHashMap<String, String>,
1120 template_visible_iterable_types: &FxHashMap<String, String>,
1121 credit_load_data: bool,
1122) -> crate::template_usage::TemplateUsage {
1123 if credit_load_data {
1124 template_visible_bound_targets.remove("data");
1125 }
1126 collect_template_usage_with_bound_targets(
1127 kind,
1128 source,
1129 credited,
1130 &template_visible_bound_targets,
1131 template_visible_iterable_types,
1132 )
1133}
1134
1135fn apply_prop_template_credit(
1140 template_usage: &crate::template_usage::TemplateUsage,
1141 props_return_binding: Option<&str>,
1142 combined: &mut ModuleInfo,
1143) {
1144 if !combined.component_props.is_empty() {
1145 let member_used: FxHashSet<&str> = template_usage
1146 .member_accesses
1147 .iter()
1148 .filter(|access| {
1149 access.object == "$props"
1150 || props_return_binding.is_some_and(|binding| access.object == binding)
1151 })
1152 .map(|access| access.member.as_str())
1153 .collect();
1154 for prop in &mut combined.component_props {
1155 if template_usage.used_bindings.contains(&prop.name)
1156 || template_usage.used_bindings.contains(&prop.local)
1157 || member_used.contains(prop.name.as_str())
1158 {
1159 prop.used_in_template = true;
1160 }
1161 }
1162 }
1163
1164 if let Some(binding) = props_return_binding
1165 && (template_usage.used_bindings.contains(binding)
1166 || template_usage
1167 .whole_object_uses
1168 .iter()
1169 .any(|used| used == binding))
1170 {
1171 combined.has_props_attrs_fallthrough = true;
1172 }
1173}
1174
1175fn merge_template_usage_into_combined(
1180 template_usage: crate::template_usage::TemplateUsage,
1181 combined: &mut ModuleInfo,
1182) {
1183 combined
1184 .unused_import_bindings
1185 .retain(|binding| !template_usage.used_bindings.contains(binding));
1186 let mut member_accesses = std::mem::take(&mut combined.member_accesses).to_vec();
1187 member_accesses.extend(template_usage.member_accesses);
1188 combined.member_accesses = member_accesses.into();
1189 let mut whole_object_uses = std::mem::take(&mut combined.whole_object_uses).to_vec();
1190 whole_object_uses.extend(template_usage.whole_object_uses);
1191 combined.whole_object_uses = whole_object_uses.into();
1192 combined
1193 .security_sinks
1194 .extend(template_usage.security_sinks);
1195 if !template_usage.unresolved_tag_names.is_empty() {
1196 let mut names: Vec<String> = template_usage.unresolved_tag_names.into_iter().collect();
1197 names.sort_unstable();
1198 combined.auto_import_candidates.extend(names);
1199 combined.auto_import_candidates.dedup();
1200 }
1201}
1202
1203fn apply_template_emit_usage(
1221 source: &str,
1222 emit_return_binding: Option<&str>,
1223 combined: &mut ModuleInfo,
1224) {
1225 let masked = mask_non_markup_regions(source);
1226 let mut used: FxHashSet<String> = FxHashSet::default();
1227 let mut dynamic = false;
1228
1229 for caps in TEMPLATE_EMIT_CALL_RE.captures_iter(&masked) {
1230 let Some(callee) = caps.get(1) else {
1231 continue;
1232 };
1233 let callee = callee.as_str();
1234 let is_emit_call =
1235 callee == "$emit" || emit_return_binding.is_some_and(|binding| callee == binding);
1236 if !is_emit_call {
1237 continue;
1238 }
1239 if let Some(event) = caps.get(2).or_else(|| caps.get(3)) {
1240 used.insert(event.as_str().to_string());
1243 } else if caps.get(4).is_some() {
1244 dynamic = true;
1247 }
1248 }
1249
1250 if dynamic {
1251 combined.has_dynamic_emit = true;
1252 }
1253 if !used.is_empty() {
1254 for emit in &mut combined.component_emits {
1255 if used.contains(&emit.name) {
1256 emit.used = true;
1257 }
1258 }
1259 }
1260}
1261
1262fn is_template_visible_script(kind: SfcKind, script: &SfcScript) -> bool {
1263 match kind {
1264 SfcKind::Vue => script.is_setup,
1265 SfcKind::Svelte => !script.is_context_module,
1266 }
1267}
1268
1269#[cfg(all(test, not(miri)))]
1270mod tests {
1271 use super::*;
1272 use fallow_types::extract::{
1273 ClassThisMemberAccessFact, ClassThisWholeObjectUseFact, SemanticFactView,
1274 };
1275
1276 #[test]
1277 fn is_sfc_file_vue() {
1278 assert!(is_sfc_file(Path::new("App.vue")));
1279 }
1280
1281 #[test]
1282 fn is_sfc_file_svelte() {
1283 assert!(is_sfc_file(Path::new("Counter.svelte")));
1284 }
1285
1286 #[test]
1287 fn is_sfc_file_rejects_ts() {
1288 assert!(!is_sfc_file(Path::new("utils.ts")));
1289 }
1290
1291 #[test]
1292 fn is_sfc_file_rejects_jsx() {
1293 assert!(!is_sfc_file(Path::new("App.jsx")));
1294 }
1295
1296 #[test]
1297 fn is_sfc_file_rejects_astro() {
1298 assert!(!is_sfc_file(Path::new("Layout.astro")));
1299 }
1300
1301 #[test]
1302 fn single_plain_script() {
1303 let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1304 assert_eq!(scripts.len(), 1);
1305 assert_eq!(scripts[0].body, "const x = 1;");
1306 assert!(!scripts[0].is_typescript);
1307 assert!(!scripts[0].is_jsx);
1308 assert!(scripts[0].src.is_none());
1309 }
1310
1311 #[test]
1312 fn single_ts_script() {
1313 let scripts = extract_sfc_scripts(r#"<script lang="ts">const x: number = 1;</script>"#);
1314 assert_eq!(scripts.len(), 1);
1315 assert!(scripts[0].is_typescript);
1316 assert!(!scripts[0].is_jsx);
1317 }
1318
1319 #[test]
1320 fn single_tsx_script() {
1321 let scripts = extract_sfc_scripts(r#"<script lang="tsx">const el = <div />;</script>"#);
1322 assert_eq!(scripts.len(), 1);
1323 assert!(scripts[0].is_typescript);
1324 assert!(scripts[0].is_jsx);
1325 }
1326
1327 #[test]
1328 fn single_jsx_script() {
1329 let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
1330 assert_eq!(scripts.len(), 1);
1331 assert!(!scripts[0].is_typescript);
1332 assert!(scripts[0].is_jsx);
1333 }
1334
1335 #[test]
1336 fn two_script_blocks() {
1337 let source = r#"
1338<script lang="ts">
1339export default {};
1340</script>
1341<script setup lang="ts">
1342const count = 0;
1343</script>
1344"#;
1345 let scripts = extract_sfc_scripts(source);
1346 assert_eq!(scripts.len(), 2);
1347 assert!(scripts[0].body.contains("export default"));
1348 assert!(scripts[1].body.contains("count"));
1349 }
1350
1351 #[test]
1352 fn script_setup_extracted() {
1353 let scripts =
1354 extract_sfc_scripts(r#"<script setup lang="ts">import { ref } from 'vue';</script>"#);
1355 assert_eq!(scripts.len(), 1);
1356 assert!(scripts[0].body.contains("import"));
1357 assert!(scripts[0].is_typescript);
1358 }
1359
1360 #[test]
1361 fn script_src_detected() {
1362 let scripts = extract_sfc_scripts(r#"<script src="./component.ts" lang="ts"></script>"#);
1363 assert_eq!(scripts.len(), 1);
1364 assert_eq!(scripts[0].src.as_deref(), Some("./component.ts"));
1365 }
1366
1367 #[test]
1370 fn svelte4_context_module_is_module_context() {
1371 let scripts =
1372 extract_sfc_scripts(r#"<script context="module">export const x = 1;</script>"#);
1373 assert_eq!(scripts.len(), 1);
1374 assert!(scripts[0].is_context_module);
1375 }
1376
1377 #[test]
1378 fn svelte5_bare_module_attr_is_module_context() {
1379 let scripts = extract_sfc_scripts(r"<script module>export const x = 1;</script>");
1380 assert_eq!(scripts.len(), 1);
1381 assert!(scripts[0].is_context_module);
1382 }
1383
1384 #[test]
1385 fn svelte5_module_with_lang_is_module_context() {
1386 let scripts =
1387 extract_sfc_scripts(r#"<script module lang="ts">export const x = 1;</script>"#);
1388 assert_eq!(scripts.len(), 1);
1389 assert!(scripts[0].is_context_module);
1390 assert!(scripts[0].is_typescript);
1391 }
1392
1393 #[test]
1394 fn plain_script_is_not_module_context() {
1395 let scripts = extract_sfc_scripts(r"<script>const x = 1;</script>");
1396 assert_eq!(scripts.len(), 1);
1397 assert!(!scripts[0].is_context_module);
1398 }
1399
1400 #[test]
1401 fn lang_ts_script_is_not_module_context() {
1402 let scripts = extract_sfc_scripts(r#"<script lang="ts">const x = 1;</script>"#);
1403 assert_eq!(scripts.len(), 1);
1404 assert!(!scripts[0].is_context_module);
1405 }
1406
1407 #[test]
1408 fn data_module_attr_is_not_module_context() {
1409 let scripts =
1411 extract_sfc_scripts(r#"<script data-module="x" lang="ts">const x = 1;</script>"#);
1412 assert_eq!(scripts.len(), 1);
1413 assert!(!scripts[0].is_context_module);
1414 }
1415
1416 #[test]
1417 fn bare_module_script_is_not_template_visible() {
1418 let module_script = SfcScript {
1421 body: String::new(),
1422 is_typescript: false,
1423 is_jsx: false,
1424 byte_offset: 0,
1425 src: None,
1426 src_span: None,
1427 is_setup: false,
1428 is_context_module: true,
1429 generic_attr: None,
1430 };
1431 assert!(!is_template_visible_script(SfcKind::Svelte, &module_script));
1432 let instance_script = SfcScript {
1433 is_context_module: false,
1434 ..module_script
1435 };
1436 assert!(is_template_visible_script(
1437 SfcKind::Svelte,
1438 &instance_script
1439 ));
1440 }
1441
1442 #[test]
1443 fn data_src_not_treated_as_src() {
1444 let scripts =
1445 extract_sfc_scripts(r#"<script lang="ts" data-src="./nope.ts">const x = 1;</script>"#);
1446 assert_eq!(scripts.len(), 1);
1447 assert!(scripts[0].src.is_none());
1448 }
1449
1450 #[test]
1451 fn script_inside_html_comment_filtered() {
1452 let source = r#"
1453<!-- <script lang="ts">import { bad } from 'bad';</script> -->
1454<script lang="ts">import { good } from 'good';</script>
1455"#;
1456 let scripts = extract_sfc_scripts(source);
1457 assert_eq!(scripts.len(), 1);
1458 assert!(scripts[0].body.contains("good"));
1459 }
1460
1461 #[test]
1462 fn spanning_comment_filters_script() {
1463 let source = r#"
1464<!-- disabled:
1465<script lang="ts">import { bad } from 'bad';</script>
1466-->
1467<script lang="ts">const ok = true;</script>
1468"#;
1469 let scripts = extract_sfc_scripts(source);
1470 assert_eq!(scripts.len(), 1);
1471 assert!(scripts[0].body.contains("ok"));
1472 }
1473
1474 #[test]
1475 fn string_containing_comment_markers_not_corrupted() {
1476 let source = r#"
1477<script setup lang="ts">
1478const marker = "<!-- not a comment -->";
1479import { ref } from 'vue';
1480</script>
1481"#;
1482 let scripts = extract_sfc_scripts(source);
1483 assert_eq!(scripts.len(), 1);
1484 assert!(scripts[0].body.contains("import"));
1485 }
1486
1487 #[test]
1488 fn generic_attr_with_angle_bracket() {
1489 let source =
1490 r#"<script setup lang="ts" generic="T extends Foo<Bar>">const x = 1;</script>"#;
1491 let scripts = extract_sfc_scripts(source);
1492 assert_eq!(scripts.len(), 1);
1493 assert_eq!(scripts[0].body, "const x = 1;");
1494 }
1495
1496 #[test]
1497 fn nested_generic_attr() {
1498 let source = r#"<script setup lang="ts" generic="T extends Map<string, Set<number>>">const x = 1;</script>"#;
1499 let scripts = extract_sfc_scripts(source);
1500 assert_eq!(scripts.len(), 1);
1501 assert_eq!(scripts[0].body, "const x = 1;");
1502 }
1503
1504 #[test]
1505 fn lang_single_quoted() {
1506 let scripts = extract_sfc_scripts("<script lang='ts'>const x = 1;</script>");
1507 assert_eq!(scripts.len(), 1);
1508 assert!(scripts[0].is_typescript);
1509 }
1510
1511 #[test]
1512 fn uppercase_script_tag() {
1513 let scripts = extract_sfc_scripts(r#"<SCRIPT lang="ts">const x = 1;</SCRIPT>"#);
1514 assert_eq!(scripts.len(), 1);
1515 assert!(scripts[0].is_typescript);
1516 }
1517
1518 #[test]
1519 fn no_script_block() {
1520 let scripts = extract_sfc_scripts("<template><div>Hello</div></template>");
1521 assert!(scripts.is_empty());
1522 }
1523
1524 #[test]
1525 fn empty_script_body() {
1526 let scripts = extract_sfc_scripts(r#"<script lang="ts"></script>"#);
1527 assert_eq!(scripts.len(), 1);
1528 assert!(scripts[0].body.is_empty());
1529 }
1530
1531 #[test]
1532 fn whitespace_only_script() {
1533 let scripts = extract_sfc_scripts("<script lang=\"ts\">\n \n</script>");
1534 assert_eq!(scripts.len(), 1);
1535 assert!(scripts[0].body.trim().is_empty());
1536 }
1537
1538 #[test]
1539 fn byte_offset_is_set() {
1540 let source = r#"<template><div/></template><script lang="ts">code</script>"#;
1541 let scripts = extract_sfc_scripts(source);
1542 assert_eq!(scripts.len(), 1);
1543 let offset = scripts[0].byte_offset;
1544 assert_eq!(&source[offset..offset + 4], "code");
1545 }
1546
1547 #[test]
1548 fn script_with_extra_attributes() {
1549 let scripts = extract_sfc_scripts(
1550 r#"<script lang="ts" id="app" type="module" data-custom="val">const x = 1;</script>"#,
1551 );
1552 assert_eq!(scripts.len(), 1);
1553 assert!(scripts[0].is_typescript);
1554 assert!(scripts[0].src.is_none());
1555 }
1556
1557 #[test]
1558 fn multiple_script_blocks_exports_combined() {
1559 let source = r#"
1560<script lang="ts">
1561export const version = '1.0';
1562</script>
1563<script setup lang="ts">
1564import { ref } from 'vue';
1565const count = ref(0);
1566</script>
1567"#;
1568 let info = parse_sfc_to_module(FileId(0), Path::new("Dual.vue"), source, 0, false);
1569 assert!(
1570 info.exports
1571 .iter()
1572 .any(|e| matches!(&e.name, crate::ExportName::Named(n) if n == "version")),
1573 "export from <script> block should be extracted"
1574 );
1575 assert!(
1576 info.imports.iter().any(|i| i.source == "vue"),
1577 "import from <script setup> block should be extracted"
1578 );
1579 }
1580
1581 #[test]
1582 fn class_this_facts_survive_sfc_script_merge() {
1583 let source = r#"
1584<script lang="ts">
1585export class Service {
1586 client!: Client;
1587
1588 run() {
1589 this.client.execute();
1590 Object.keys(this.client);
1591 }
1592}
1593</script>
1594"#;
1595 let info = parse_sfc_to_module(FileId(0), Path::new("Service.vue"), source, 0, false);
1596 let facts = SemanticFactView::new(&info.semantic_facts, &info.member_accesses);
1597
1598 assert_eq!(
1599 facts.class_this_member_accesses(),
1600 vec![ClassThisMemberAccessFact {
1601 class_local_name: "Service".to_string(),
1602 object: "this.client".to_string(),
1603 member: "execute".to_string(),
1604 }]
1605 );
1606 assert_eq!(
1607 facts.class_this_whole_object_uses(),
1608 vec![ClassThisWholeObjectUseFact {
1609 class_local_name: "Service".to_string(),
1610 object: "this.client".to_string(),
1611 }]
1612 );
1613 }
1614
1615 #[test]
1616 fn lang_tsx_detected_as_typescript_jsx() {
1617 let scripts =
1618 extract_sfc_scripts(r#"<script lang="tsx">const el = <div>{x}</div>;</script>"#);
1619 assert_eq!(scripts.len(), 1);
1620 assert!(scripts[0].is_typescript, "lang=tsx should be typescript");
1621 assert!(scripts[0].is_jsx, "lang=tsx should be jsx");
1622 }
1623
1624 #[test]
1625 fn multiline_html_comment_filters_all_script_blocks_inside() {
1626 let source = r#"
1627<!--
1628 This whole section is disabled:
1629 <script lang="ts">import { bad1 } from 'bad1';</script>
1630 <script lang="ts">import { bad2 } from 'bad2';</script>
1631-->
1632<script lang="ts">import { good } from 'good';</script>
1633"#;
1634 let scripts = extract_sfc_scripts(source);
1635 assert_eq!(scripts.len(), 1);
1636 assert!(scripts[0].body.contains("good"));
1637 }
1638
1639 #[test]
1640 fn script_src_generates_side_effect_import() {
1641 let info = parse_sfc_to_module(
1642 FileId(0),
1643 Path::new("External.vue"),
1644 r#"<script src="./external-logic.ts" lang="ts"></script>"#,
1645 0,
1646 false,
1647 );
1648 assert!(
1649 info.imports
1650 .iter()
1651 .any(|i| i.source == "./external-logic.ts"
1652 && matches!(i.imported_name, ImportedName::SideEffect)),
1653 "script src should generate a side-effect import"
1654 );
1655 }
1656
1657 #[test]
1658 fn parse_sfc_no_script_returns_empty_module() {
1659 let info = parse_sfc_to_module(
1660 FileId(0),
1661 Path::new("Empty.vue"),
1662 "<template><div>Hello</div></template>",
1663 42,
1664 false,
1665 );
1666 assert!(info.imports.is_empty());
1667 assert!(info.exports.is_empty());
1668 assert_eq!(info.content_hash, 42);
1669 assert_eq!(info.file_id, FileId(0));
1670 }
1671
1672 #[test]
1673 fn parse_sfc_has_line_offsets() {
1674 let info = parse_sfc_to_module(
1675 FileId(0),
1676 Path::new("LineOffsets.vue"),
1677 r#"<script lang="ts">const x = 1;</script>"#,
1678 0,
1679 false,
1680 );
1681 assert!(!info.line_offsets.is_empty());
1682 }
1683
1684 #[test]
1685 fn parse_sfc_has_suppressions() {
1686 let info = parse_sfc_to_module(
1687 FileId(0),
1688 Path::new("Suppressions.vue"),
1689 r#"<script lang="ts">
1690// fallow-ignore-file
1691export const foo = 1;
1692</script>"#,
1693 0,
1694 false,
1695 );
1696 assert!(!info.suppressions.is_empty());
1697 }
1698
1699 #[test]
1700 fn source_type_plain_js_detection() {
1701 let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1702 assert_eq!(scripts.len(), 1);
1703 assert!(!scripts[0].is_typescript);
1704 assert!(!scripts[0].is_jsx);
1705 }
1706
1707 #[test]
1708 fn is_sfc_file_rejects_no_extension() {
1709 assert!(!is_sfc_file(Path::new("Makefile")));
1710 }
1711
1712 #[test]
1713 fn is_sfc_file_rejects_mdx() {
1714 assert!(!is_sfc_file(Path::new("post.mdx")));
1715 }
1716
1717 #[test]
1718 fn is_sfc_file_rejects_css() {
1719 assert!(!is_sfc_file(Path::new("styles.css")));
1720 }
1721
1722 #[test]
1723 fn multiple_script_blocks_both_have_offsets() {
1724 let source = r#"<script lang="ts">const a = 1;</script>
1725<script setup lang="ts">const b = 2;</script>"#;
1726 let scripts = extract_sfc_scripts(source);
1727 assert_eq!(scripts.len(), 2);
1728 let offset0 = scripts[0].byte_offset;
1729 let offset1 = scripts[1].byte_offset;
1730 assert_eq!(
1731 &source[offset0..offset0 + "const a = 1;".len()],
1732 "const a = 1;"
1733 );
1734 assert_eq!(
1735 &source[offset1..offset1 + "const b = 2;".len()],
1736 "const b = 2;"
1737 );
1738 }
1739
1740 #[test]
1741 fn script_with_src_and_lang() {
1742 let scripts = extract_sfc_scripts(r#"<script src="./logic.ts" lang="tsx"></script>"#);
1743 assert_eq!(scripts.len(), 1);
1744 assert_eq!(scripts[0].src.as_deref(), Some("./logic.ts"));
1745 assert!(scripts[0].is_typescript);
1746 assert!(scripts[0].is_jsx);
1747 }
1748
1749 #[test]
1750 fn extract_style_block_lang_scss() {
1751 let source = r#"<template/><style lang="scss">@import 'Foo';</style>"#;
1752 let styles = extract_sfc_styles(source);
1753 assert_eq!(styles.len(), 1);
1754 assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1755 assert!(styles[0].body.contains("@import"));
1756 assert!(styles[0].src.is_none());
1757 }
1758
1759 #[test]
1760 fn extract_style_block_with_src() {
1761 let source = r#"<style src="./theme.scss" lang="scss"></style>"#;
1762 let styles = extract_sfc_styles(source);
1763 assert_eq!(styles.len(), 1);
1764 assert_eq!(styles[0].src.as_deref(), Some("./theme.scss"));
1765 assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1766 }
1767
1768 #[test]
1769 fn extract_style_block_plain_no_lang() {
1770 let source = r"<style>.foo { color: red; }</style>";
1771 let styles = extract_sfc_styles(source);
1772 assert_eq!(styles.len(), 1);
1773 assert!(styles[0].lang.is_none());
1774 }
1775
1776 #[test]
1777 fn extract_multiple_style_blocks() {
1778 let source = r#"<style lang="scss">@import 'a';</style>
1779<style scoped lang="scss">@import 'b';</style>"#;
1780 let styles = extract_sfc_styles(source);
1781 assert_eq!(styles.len(), 2);
1782 }
1783
1784 #[test]
1785 fn style_block_inside_html_comment_filtered() {
1786 let source = r#"<!-- <style lang="scss">@import 'bad';</style> -->
1787<style lang="scss">@import 'good';</style>"#;
1788 let styles = extract_sfc_styles(source);
1789 assert_eq!(styles.len(), 1);
1790 assert!(styles[0].body.contains("good"));
1791 }
1792
1793 #[test]
1794 fn parse_sfc_extracts_style_imports_with_from_style_flag() {
1795 let info = parse_sfc_to_module(
1796 FileId(0),
1797 Path::new("Foo.vue"),
1798 r#"<template/><style lang="scss">@import 'Foo';</style>"#,
1799 0,
1800 false,
1801 );
1802 let style_import = info
1803 .imports
1804 .iter()
1805 .find(|i| i.source == "./Foo")
1806 .expect("scss @import 'Foo' should be normalized to ./Foo");
1807 assert!(
1808 style_import.from_style,
1809 "imports from <style> blocks must carry from_style=true so the resolver \
1810 enables SCSS partial fallback for the SFC importer"
1811 );
1812 assert!(matches!(
1813 style_import.imported_name,
1814 ImportedName::SideEffect
1815 ));
1816 }
1817
1818 #[test]
1819 fn parse_sfc_extracts_style_plugin_as_default_import() {
1820 let info = parse_sfc_to_module(
1821 FileId(0),
1822 Path::new("Foo.vue"),
1823 r#"<template/><style>@plugin "./tailwind-plugin.js";</style>"#,
1824 0,
1825 false,
1826 );
1827 let plugin_import = info
1828 .imports
1829 .iter()
1830 .find(|i| i.source == "./tailwind-plugin.js")
1831 .expect("style @plugin should create an import");
1832 assert!(plugin_import.from_style);
1833 assert!(matches!(plugin_import.imported_name, ImportedName::Default));
1834 }
1835
1836 #[test]
1837 fn parse_sfc_extracts_style_src_with_from_style_flag() {
1838 let info = parse_sfc_to_module(
1839 FileId(0),
1840 Path::new("Bar.vue"),
1841 r#"<style src="./Bar.scss" lang="scss"></style>"#,
1842 0,
1843 false,
1844 );
1845 let style_src = info
1846 .imports
1847 .iter()
1848 .find(|i| i.source == "./Bar.scss")
1849 .expect("<style src=\"./Bar.scss\"> should produce a side-effect import");
1850 assert!(style_src.from_style);
1851 }
1852
1853 #[test]
1854 fn parse_sfc_skips_unsupported_style_lang_body_but_keeps_src() {
1855 let info = parse_sfc_to_module(
1856 FileId(0),
1857 Path::new("Baz.vue"),
1858 r#"<style lang="postcss" src="./Baz.pcss">@custom-rule "skipped";</style>"#,
1859 0,
1860 false,
1861 );
1862 assert!(
1863 info.imports.iter().any(|i| i.source == "./Baz.pcss"),
1864 "src reference should still be seeded for unsupported lang"
1865 );
1866 assert!(
1867 !info.imports.iter().any(|i| i.source.contains("skipped")),
1868 "postcss body should not be scanned for @import directives"
1869 );
1870 }
1871
1872 fn asset_refs(source: &str) -> Vec<String> {
1873 super::collect_template_asset_refs(source)
1874 .into_iter()
1875 .map(|(s, _)| s)
1876 .collect()
1877 }
1878
1879 #[test]
1880 fn captures_static_relative_template_asset_refs() {
1881 assert_eq!(
1882 asset_refs(r#"<template><img src="./logo.png" /></template>"#),
1883 vec!["./logo.png".to_string()]
1884 );
1885 assert_eq!(
1886 asset_refs(r#"<source src="../media/clip.mp4">"#),
1887 vec!["../media/clip.mp4".to_string()]
1888 );
1889 assert_eq!(
1890 asset_refs(r#"<video poster="./thumb.jpg"></video>"#),
1891 vec!["./thumb.jpg".to_string()]
1892 );
1893 }
1894
1895 #[test]
1896 fn skips_dynamic_alias_root_remote_and_query_asset_refs() {
1897 assert!(asset_refs(r#"<img :src="logo" />"#).is_empty());
1899 assert!(asset_refs(r#"<img v-bind:src="logo" />"#).is_empty());
1900 assert!(asset_refs(r#"<img bind:src="logo" />"#).is_empty());
1901 assert!(asset_refs(r"<img src={logo} />").is_empty());
1902 assert!(asset_refs(r#"<img data-src="./x.png" />"#).is_empty());
1903 assert!(asset_refs(r#"<img src="@/assets/x.png" />"#).is_empty());
1905 assert!(asset_refs(r#"<img src="/logo.png" />"#).is_empty());
1906 assert!(asset_refs(r#"<img src="https://cdn/x.png" />"#).is_empty());
1907 assert!(asset_refs(r#"<img src="./x.png?inline" />"#).is_empty());
1909 assert!(asset_refs(r#"<img src="{{ logo }}" />"#).is_empty());
1911 }
1912
1913 #[test]
1914 fn skips_custom_component_src_prop() {
1915 assert!(asset_refs(r#"<MyImage src="./x.png" />"#).is_empty());
1917 assert!(asset_refs(r#"<AppIcon src="../icons/y.svg" />"#).is_empty());
1918 }
1919
1920 #[test]
1921 fn skips_asset_refs_inside_script_style_and_comments() {
1922 assert!(asset_refs(r#"<script>const x = "<img src='./a.png'>"</script>"#).is_empty());
1924 assert!(asset_refs(r#"<style>/* <img src="./b.png"> */ .x{}</style>"#).is_empty());
1925 assert!(asset_refs(r#"<!-- <img src="./c.png" /> -->"#).is_empty());
1926 }
1927
1928 #[test]
1929 fn parse_sfc_emits_template_asset_as_side_effect_import() {
1930 let info = parse_sfc_to_module(
1931 FileId(0),
1932 Path::new("Hero.vue"),
1933 r#"<template><img src="./hero.png" /></template><script>let x=1</script>"#,
1934 0,
1935 false,
1936 );
1937 assert!(
1938 info.imports.iter().any(|i| i.source == "./hero.png"
1939 && matches!(i.imported_name, ImportedName::SideEffect)
1940 && !i.from_style),
1941 "template <img src> should seed a SideEffect import: {:?}",
1942 info.imports
1943 );
1944 }
1945
1946 fn svelte_props(source: &str) -> Vec<crate::ModuleInfo> {
1949 vec![parse_sfc_to_module(
1950 FileId(0),
1951 Path::new("Component.svelte"),
1952 source,
1953 0,
1954 false,
1955 )]
1956 }
1957
1958 fn prop_names(info: &crate::ModuleInfo) -> Vec<String> {
1959 let mut names: Vec<String> = info
1960 .component_props
1961 .iter()
1962 .map(|p| p.name.clone())
1963 .collect();
1964 names.sort();
1965 names
1966 }
1967
1968 #[test]
1969 fn svelte_shorthand_props_harvested() {
1970 let info = &svelte_props(r"<script>let { a, b } = $props();</script>")[0];
1972 assert_eq!(prop_names(info), vec!["a", "b"]);
1973 for prop in &info.component_props {
1974 assert_eq!(prop.local, prop.name);
1975 }
1976 }
1977
1978 #[test]
1979 fn svelte_renamed_prop_tracks_local_and_script_use() {
1980 let info =
1983 &svelte_props(r"<script>let { a: alias } = $props(); console.log(alias);</script>")[0];
1984 assert_eq!(prop_names(info), vec!["a"]);
1985 let prop = &info.component_props[0];
1986 assert_eq!(prop.local, "alias");
1987 assert!(
1988 prop.used_in_script,
1989 "alias is referenced, so a is used in script"
1990 );
1991 }
1992
1993 #[test]
1994 fn svelte_unreferenced_prop_is_unused_in_script() {
1995 let info = &svelte_props(r"<script>let { a } = $props();</script>")[0];
1996 assert_eq!(prop_names(info), vec!["a"]);
1997 assert!(!info.component_props[0].used_in_script);
1998 }
1999
2000 #[test]
2001 fn svelte_default_prop_peeled() {
2002 let info = &svelte_props(r"<script>let { a = 1 } = $props();</script>")[0];
2004 assert_eq!(prop_names(info), vec!["a"]);
2005 }
2006
2007 #[test]
2008 fn svelte_bindable_default_peeled() {
2009 let info = &svelte_props(r"<script>let { a = $bindable() } = $props();</script>")[0];
2012 assert_eq!(prop_names(info), vec!["a"]);
2013 }
2014
2015 #[test]
2016 fn svelte_rest_element_sets_fallthrough_abstain() {
2017 let info = &svelte_props(r"<script>let { a, ...rest } = $props();</script>")[0];
2019 assert!(info.has_props_attrs_fallthrough);
2020 }
2021
2022 #[test]
2023 fn svelte_bare_identifier_binding_sets_unharvestable_abstain() {
2024 let info = &svelte_props(r"<script>let p = $props(); console.log(p.x);</script>")[0];
2026 assert!(info.has_unharvestable_props);
2027 assert!(info.component_props.is_empty());
2028 }
2029
2030 #[test]
2031 fn svelte_nested_destructure_sets_unharvestable_abstain() {
2032 let info = &svelte_props(r"<script>let { a: { x } } = $props();</script>")[0];
2034 assert!(info.has_unharvestable_props);
2035 }
2036
2037 #[test]
2038 fn svelte_prop_used_only_in_markup_credited_as_template_root() {
2039 let info = &svelte_props(r"<script>let { a } = $props();</script><p>{a}</p>")[0];
2042 assert_eq!(prop_names(info), vec!["a"]);
2043 assert!(
2044 info.component_props[0].used_in_template,
2045 "a is used in markup, so used_in_template should be true"
2046 );
2047 }
2048
2049 #[test]
2050 fn svelte_module_script_props_not_harvested() {
2051 let info = &svelte_props(
2053 r"<script module>let { a } = $props();</script><script>let { b } = $props();</script>",
2054 )[0];
2055 assert_eq!(prop_names(info), vec!["b"]);
2057 }
2058
2059 fn dispatched_names(info: &crate::ModuleInfo) -> Vec<String> {
2062 let mut names: Vec<String> = info
2063 .svelte_dispatched_events
2064 .iter()
2065 .map(|e| e.name.clone())
2066 .collect();
2067 names.sort();
2068 names
2069 }
2070
2071 #[test]
2072 fn svelte_dispatch_literal_event_is_harvested() {
2073 let info = &svelte_props(
2074 r"<script>import { createEventDispatcher } from 'svelte';
2075 const dispatch = createEventDispatcher();
2076 function save() { dispatch('save'); }</script>",
2077 )[0];
2078 assert_eq!(dispatched_names(info), vec!["save"]);
2079 assert!(!info.has_dynamic_dispatch);
2080 }
2081
2082 #[test]
2083 fn svelte_dispatch_without_svelte_import_is_ignored() {
2084 let info = &svelte_props(
2087 r"<script>function createEventDispatcher() { return () => {}; }
2088 const dispatch = createEventDispatcher();
2089 dispatch('save');</script>",
2090 )[0];
2091 assert!(info.svelte_dispatched_events.is_empty());
2092 }
2093
2094 #[test]
2095 fn svelte_dynamic_dispatch_sets_abstain() {
2096 let info = &svelte_props(
2097 r"<script>import { createEventDispatcher } from 'svelte';
2098 const dispatch = createEventDispatcher();
2099 function fire(name) { dispatch(name); }</script>",
2100 )[0];
2101 assert!(
2102 info.has_dynamic_dispatch,
2103 "a non-literal dispatch arg must set the abstain flag"
2104 );
2105 }
2106
2107 #[test]
2108 fn svelte_dispatch_whole_value_use_sets_abstain() {
2109 let info = &svelte_props(
2110 r"<script>import { createEventDispatcher } from 'svelte';
2111 const dispatch = createEventDispatcher();
2112 forward(dispatch);</script>",
2113 )[0];
2114 assert!(
2115 info.has_dynamic_dispatch,
2116 "passing the dispatch binding as a whole value must set the abstain flag"
2117 );
2118 }
2119
2120 #[test]
2121 fn svelte_listened_event_on_component_is_harvested() {
2122 let info =
2123 &svelte_props(r"<script>import Child from './Child.svelte';</script><Child on:save />")
2124 [0];
2125 assert!(info.svelte_listened_events.contains(&"save".to_string()));
2126 }
2127}
2128
2129fn apply_component_contracts(kind: SfcKind, source: &str, combined: &mut ModuleInfo) {
2130 let framework = match kind {
2131 SfcKind::Vue => fallow_types::extract::ComponentFramework::Vue,
2132 SfcKind::Svelte => fallow_types::extract::ComponentFramework::Svelte,
2133 };
2134 let callers = crate::sfc_template::component_contracts::collect(
2135 &mask_non_markup_regions(source),
2136 &combined.imports,
2137 framework,
2138 0,
2139 combined
2140 .component_contracts
2141 .as_deref()
2142 .map_or(&[], |facts| facts.spread_bindings.as_slice()),
2143 combined
2144 .component_contracts
2145 .as_deref()
2146 .map_or(&[], |facts| facts.aliases.as_slice()),
2147 );
2148 crate::component_contracts::merge(&mut combined.component_contracts, callers, 0, None);
2149 if let Some(facts) = &mut combined.component_contracts {
2150 let credited: FxHashSet<String> = facts
2151 .declarations
2152 .iter()
2153 .flat_map(|prop| [prop.local.clone(), prop.name.clone()])
2154 .collect();
2155 let usage = collect_template_usage_with_bound_targets(
2156 kind,
2157 source,
2158 &credited,
2159 &FxHashMap::default(),
2160 &FxHashMap::default(),
2161 );
2162 for declaration in &mut facts.declarations {
2163 declaration.is_used |= usage.used_bindings.contains(&declaration.local)
2164 || usage.member_accesses.iter().any(|access| {
2165 access.object == declaration.local && access.member == declaration.name
2166 });
2167 }
2168 }
2169 if let Some(facts) = &mut combined.component_contracts {
2170 for declaration in &mut facts.declarations {
2171 if let Some(prop) = combined
2172 .component_props
2173 .iter()
2174 .find(|prop| prop.name == declaration.name)
2175 {
2176 declaration.is_used |= prop.used_in_template;
2177 }
2178 declaration.incomplete |= combined.has_props_attrs_fallthrough
2179 || combined.has_define_expose
2180 || combined.has_define_model;
2181 }
2182 }
2183
2184 crate::component_contracts::attach_sfc_default_export(combined);
2185}