Skip to main content

fallow_extract/
sfc.rs

1//! Vue/Svelte Single File Component (SFC) script and style extraction.
2//!
3//! Extracts `<script>` block content from `.vue` and `.svelte` files with the
4//! linear block scan of `sfc_blocks`,
5//! handling `lang`, `src` metadata, and `generic` attributes, and filtering
6//! HTML comments. Vue external script references are emitted as graph edges;
7//! Svelte markup-level script `src` references are treated as runtime HTML.
8//! Also extracts `<style>` block sources (`@import` / `@use` / `@forward` /
9//! `@plugin` and `<style src="...">`) so referenced CSS / SCSS files become
10//! reachable from the component, preventing false `unused-files` reports on
11//! co-located styles.
12
13use std::path::Path;
14use std::sync::LazyLock;
15
16use oxc_allocator::Allocator;
17use oxc_ast_visit::Visit;
18use oxc_parser::Parser;
19use oxc_span::SourceType;
20use rustc_hash::{FxHashMap, FxHashSet};
21
22use crate::asset_url::normalize_asset_url;
23use crate::parse::compute_import_binding_usage;
24use crate::sfc_blocks::{script_blocks, style_blocks};
25use crate::sfc_template::{SfcKind, collect_template_usage_with_bound_targets};
26use crate::source_map::ExtractionResult;
27use crate::visitor::ModuleInfoExtractor;
28use crate::{ImportInfo, ImportedName, ModuleInfo};
29use fallow_types::discover::FileId;
30use fallow_types::extract::{FunctionComplexity, byte_offset_to_line_col, compute_line_offsets};
31use oxc_span::Span;
32
33/// Regex to extract the `lang` attribute value from a script tag.
34static LANG_ATTR_RE: LazyLock<regex::Regex> =
35    LazyLock::new(|| crate::static_regex(r#"lang\s*=\s*["'](\w+)["']"#));
36
37/// Regex to extract the `src` attribute value from a script tag.
38/// Requires whitespace (or start of string) before `src` to avoid matching `data-src` etc.
39static SRC_ATTR_RE: LazyLock<regex::Regex> =
40    LazyLock::new(|| crate::static_regex(r#"(?:^|\s)src\s*=\s*["']([^"']+)["']"#));
41
42/// Regex to detect Vue's bare `setup` attribute.
43static SETUP_ATTR_RE: LazyLock<regex::Regex> =
44    LazyLock::new(|| crate::static_regex(r"(?:^|\s)setup(?:\s|$)"));
45
46/// Regex to detect Svelte's `context="module"` attribute (Svelte 4).
47static CONTEXT_MODULE_ATTR_RE: LazyLock<regex::Regex> =
48    LazyLock::new(|| crate::static_regex(r#"context\s*=\s*["']module["']"#));
49
50/// Regex to detect Svelte 5's bare `module` script attribute (`<script module>`,
51/// `<script module lang="ts">`). Anchored like [`SETUP_ATTR_RE`] so `module` must
52/// be a standalone attribute, not a substring of another attr name (e.g.
53/// `data-module`) or value.
54static SVELTE_MODULE_ATTR_RE: LazyLock<regex::Regex> =
55    LazyLock::new(|| crate::static_regex(r"(?:^|\s)module(?:\s|$|=)"));
56
57/// Regex to extract Vue's `generic="..."` attribute value (script-setup
58/// generics). Matches the contents between the quotes and stops at the
59/// closing quote, mirroring `LANG_ATTR_RE`.
60static VUE_GENERIC_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
61    crate::static_regex(r#"(?:^|\s)generic\s*=\s*"([^"]*)"|(?:^|\s)generic\s*=\s*'([^']*)'"#)
62});
63
64/// Regex to extract Svelte's `generics="..."` attribute value (Svelte 4
65/// generic script attribute, repurposed by some Svelte 5 code).
66static SVELTE_GENERICS_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
67    crate::static_regex(r#"(?:^|\s)generics\s*=\s*"([^"]*)"|(?:^|\s)generics\s*=\s*'([^']*)'"#)
68});
69
70/// Regex to match HTML comments for filtering script blocks inside comments.
71static HTML_COMMENT_RE: LazyLock<regex::Regex> =
72    LazyLock::new(|| crate::static_regex(r"(?s)<!--.*?-->"));
73
74/// Regex to detect a whole-object prop/attr spread in a Vue template:
75/// `v-bind="$attrs"`, `v-bind="$props"`, or `v-bind="props"` (with single or
76/// double quotes). A bound prop may be consumed indirectly, so the
77/// `unused-component-prop` detector abstains on the whole file when this matches.
78static PROPS_ATTRS_SPREAD_RE: LazyLock<regex::Regex> =
79    LazyLock::new(|| crate::static_regex(r#"v-bind\s*=\s*["'](?:\$attrs|\$props|props)["']"#));
80
81/// Static asset references in SFC markup: `<img src="./logo.png">`,
82/// `<source src="...">`, `<video poster="...">`, etc.
83///
84/// Scoped to genuine asset elements (`img` / `source` / `video` / `audio` /
85/// `track` / `embed`) so a custom component's `src` PROP (`<MyImage src="./x">`)
86/// is never misread as an asset edge. ONLY plain relative literals (`./` or
87/// `../`) are captured: dynamic bindings (`:src`, `v-bind:src`, `bind:src`,
88/// `src={...}`, `data-src`), alias-prefixed (`@/`), root-relative (`/foo`),
89/// remote, interpolated (`{{ }}` / `{ }`), and query/hash-suffixed values are
90/// all skipped (the value class excludes `{`, `?`, `#`, whitespace, and angle
91/// brackets, and the alternation anchors on a leading `./` or `../`). A
92/// captured ref becomes a `SideEffect` import; an existing asset resolves to
93/// `ExternalFile` (no finding) and a genuinely-missing one surfaces as
94/// `unresolved-import` on the trusted resolver path.
95static TEMPLATE_ASSET_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
96    crate::static_regex(
97        r#"(?si)<(?:img|source|video|audio|track|embed)\b(?:[^>"']|"[^"]*"|'[^']*')*?\s(?:src|poster)\s*=\s*(?:"((?:\./|\.\./)[^"<>{}?#\s]*)"|'((?:\./|\.\./)[^'<>{}?#\s]*)')"#,
98    )
99});
100
101/// Mask `<script>` / `<style>` blocks and HTML comments to equal-length spaces
102/// so a markup-region scan (asset refs) sees only the template, while byte
103/// offsets still map 1:1 into the original source for line/col reporting.
104fn mask_non_markup_regions(source: &str) -> String {
105    let mut masked = source.to_string();
106    let spans: Vec<_> = script_blocks(&masked).into_iter().map(|b| b.span).collect();
107    mask_spans(&mut masked, spans);
108    let spans: Vec<_> = style_blocks(&masked).into_iter().map(|b| b.span).collect();
109    mask_spans(&mut masked, spans);
110    let spans: Vec<_> = HTML_COMMENT_RE
111        .find_iter(&masked)
112        .map(|m| m.range())
113        .collect();
114    mask_spans(&mut masked, spans);
115    masked
116}
117
118/// Replace each of `spans` with spaces of the same byte length.
119fn mask_spans(text: &mut String, spans: Vec<std::ops::Range<usize>>) {
120    for span in spans {
121        let len = span.len();
122        text.replace_range(span, &" ".repeat(len));
123    }
124}
125
126/// Whether `pos` is inside one of the sorted, disjoint `ranges`.
127fn in_ranges(ranges: &[(usize, usize)], pos: usize) -> bool {
128    let index = ranges.partition_point(|&(_, end)| end <= pos);
129    ranges.get(index).is_some_and(|&(start, _)| start <= pos)
130}
131
132/// Collect static relative asset references from SFC markup as
133/// `(normalized_specifier, value_span)` pairs. See [`TEMPLATE_ASSET_RE`].
134fn collect_template_asset_refs(source: &str) -> Vec<(String, Span)> {
135    let masked = mask_non_markup_regions(source);
136    let mut refs = Vec::new();
137    for caps in TEMPLATE_ASSET_RE.captures_iter(&masked) {
138        let Some(value) = caps.get(1).or_else(|| caps.get(2)) else {
139            continue;
140        };
141        let raw = value.as_str();
142        if raw.is_empty() {
143            continue;
144        }
145        refs.push((
146            normalize_asset_url(raw),
147            Span::new(value.start() as u32, value.end() as u32),
148        ));
149    }
150    refs
151}
152
153/// An extracted `<script>` block from a Vue or Svelte SFC.
154pub struct SfcScript {
155    /// The script body text.
156    pub body: String,
157    /// Whether the script uses TypeScript (`lang="ts"` or `lang="tsx"`).
158    pub is_typescript: bool,
159    /// Whether the script uses JSX syntax (`lang="tsx"` or `lang="jsx"`).
160    pub is_jsx: bool,
161    /// Byte offset of the script body within the full SFC source.
162    pub byte_offset: usize,
163    /// External script source path from `src` attribute.
164    pub src: Option<String>,
165    /// Span of the `src` attribute value in the full SFC source.
166    pub src_span: Option<Span>,
167    /// Whether this script is a Vue `<script setup>` block.
168    pub is_setup: bool,
169    /// Whether this script is a Svelte module-context block.
170    pub is_context_module: bool,
171    /// Type-parameter list from a `generic="..."` (Vue) or `generics="..."`
172    /// (Svelte) attribute on the script tag. Holds the bare constraint, no
173    /// surrounding angle brackets, e.g. `T extends Test<boolean>`.
174    pub generic_attr: Option<String>,
175}
176
177/// Extract all `<script>` blocks from a Vue/Svelte SFC source string.
178pub fn extract_sfc_scripts(source: &str) -> Vec<SfcScript> {
179    let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
180        .find_iter(source)
181        .map(|m| (m.start(), m.end()))
182        .collect();
183
184    script_blocks(source)
185        .into_iter()
186        .filter(|block| !in_ranges(&comment_ranges, block.span.start))
187        .map(|block| {
188            let attrs = &source[block.attrs.clone()];
189            let byte_offset = block.body.start;
190            let body = source[block.body].to_string();
191            let lang = LANG_ATTR_RE
192                .captures(attrs)
193                .and_then(|c| c.get(1))
194                .map(|m| m.as_str());
195            let is_typescript = matches!(lang, Some("ts" | "tsx"));
196            let is_jsx = matches!(lang, Some("tsx" | "jsx"));
197            let src = SRC_ATTR_RE
198                .captures(attrs)
199                .and_then(|c| c.get(1))
200                .map(|m| m.as_str().to_string());
201            let attrs_start = block.attrs.start;
202            let src_span = SRC_ATTR_RE.captures(attrs).and_then(|c| c.get(1)).map(|m| {
203                Span::new(
204                    (attrs_start + m.start()) as u32,
205                    (attrs_start + m.end()) as u32,
206                )
207            });
208            let is_setup = SETUP_ATTR_RE.is_match(attrs);
209            // Svelte module context: Svelte 4 `context="module"` OR Svelte 5's
210            // bare `module` attribute. Both scope declarations to the module
211            // script (not the instance), so `is_template_visible_script` returns
212            // false and the instance/module split for runes harvest is correct.
213            let is_context_module =
214                CONTEXT_MODULE_ATTR_RE.is_match(attrs) || SVELTE_MODULE_ATTR_RE.is_match(attrs);
215            let generic_attr = VUE_GENERIC_ATTR_RE
216                .captures(attrs)
217                .or_else(|| SVELTE_GENERICS_ATTR_RE.captures(attrs))
218                .and_then(|cap| cap.get(1).or_else(|| cap.get(2)))
219                .map(|m| m.as_str().to_string())
220                .filter(|value| !value.trim().is_empty());
221            SfcScript {
222                body,
223                is_typescript,
224                is_jsx,
225                byte_offset,
226                src,
227                src_span,
228                is_setup,
229                is_context_module,
230                generic_attr,
231            }
232        })
233        .collect()
234}
235
236/// An extracted `<style>` block from a Vue or Svelte SFC.
237pub struct SfcStyle {
238    /// The style body text (CSS / SCSS / Sass / Less / Stylus / PostCSS source).
239    pub body: String,
240    /// The `lang` attribute value (`scss`, `sass`, `less`, `stylus`, `postcss`, ...).
241    /// `None` for plain `<style>` (CSS).
242    pub lang: Option<String>,
243    /// External style source path from the `src` attribute (`<style src="./theme.scss">`).
244    pub src: Option<String>,
245    /// Span of the `src` attribute value in the full SFC source.
246    pub src_span: Option<Span>,
247    /// Byte offset of the style body within the full SFC source.
248    pub byte_offset: usize,
249}
250
251/// A source region extracted from a larger file while preserving the byte
252/// offset of the region body in the original source.
253pub struct SourceRegion {
254    /// Region body text.
255    pub body: String,
256    /// Byte offset of `body` within the original source.
257    pub byte_offset: usize,
258}
259
260/// Extract template markup regions from a Vue/Svelte SFC.
261///
262/// The returned regions exclude `<script>` blocks, `<style>` blocks, and HTML
263/// comments, so callers can tokenize authored markup without reading code or
264/// comments as template text. Offsets always point into the original SFC source.
265#[must_use]
266pub fn extract_sfc_template_regions(source: &str) -> Vec<SourceRegion> {
267    let mut ranges: Vec<(usize, usize)> = script_blocks(source)
268        .into_iter()
269        .chain(style_blocks(source))
270        .map(|block| block.span)
271        .chain(HTML_COMMENT_RE.find_iter(source).map(|m| m.range()))
272        .map(|span| (span.start, span.end))
273        .collect();
274    ranges.sort_unstable_by_key(|(start, _)| *start);
275    ranges_to_gaps(source, &ranges)
276}
277
278/// Extract all `<style>` blocks from a Vue/Svelte SFC source string.
279///
280/// Mirrors [`extract_sfc_scripts`]: filters blocks inside HTML comments and
281/// captures the `lang` and `src` attributes so the caller can route the body to
282/// the right preprocessor's import scanner (currently only CSS / SCSS / Sass) or
283/// seed the `src` reference as a side-effect import.
284pub fn extract_sfc_styles(source: &str) -> Vec<SfcStyle> {
285    let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
286        .find_iter(source)
287        .map(|m| (m.start(), m.end()))
288        .collect();
289
290    style_blocks(source)
291        .into_iter()
292        .filter(|block| !in_ranges(&comment_ranges, block.span.start))
293        .map(|block| {
294            let attrs = &source[block.attrs.clone()];
295            let byte_offset = block.body.start;
296            let body = source[block.body].to_string();
297            let lang = LANG_ATTR_RE
298                .captures(attrs)
299                .and_then(|c| c.get(1))
300                .map(|m| m.as_str().to_string());
301            let src = SRC_ATTR_RE
302                .captures(attrs)
303                .and_then(|c| c.get(1))
304                .map(|m| m.as_str().to_string());
305            let attrs_start = block.attrs.start;
306            let src_span = SRC_ATTR_RE.captures(attrs).and_then(|c| c.get(1)).map(|m| {
307                Span::new(
308                    (attrs_start + m.start()) as u32,
309                    (attrs_start + m.end()) as u32,
310                )
311            });
312            SfcStyle {
313                body,
314                lang,
315                src,
316                src_span,
317                byte_offset,
318            }
319        })
320        .collect()
321}
322
323/// Turn masked `ranges` into the gap regions between them, preserving byte
324/// offsets. `ranges` must be sorted by start offset; unsorted input silently
325/// drops the gaps that precede an out-of-order range.
326pub(crate) fn ranges_to_gaps(source: &str, ranges: &[(usize, usize)]) -> Vec<SourceRegion> {
327    let mut regions = Vec::new();
328    let mut cursor = 0;
329    for &(start, end) in ranges {
330        if start > cursor {
331            push_region(source, cursor, start, &mut regions);
332        }
333        cursor = cursor.max(end);
334    }
335    if cursor < source.len() {
336        push_region(source, cursor, source.len(), &mut regions);
337    }
338    regions
339}
340
341fn push_region(source: &str, start: usize, end: usize, regions: &mut Vec<SourceRegion>) {
342    let Some(body) = source.get(start..end) else {
343        return;
344    };
345    if body.trim().is_empty() {
346        return;
347    }
348    regions.push(SourceRegion {
349        body: body.to_string(),
350        byte_offset: start,
351    });
352}
353
354/// Check if a file path is a Vue or Svelte SFC (`.vue` or `.svelte`).
355#[must_use]
356pub fn is_sfc_file(path: &Path) -> bool {
357    path.extension()
358        .and_then(|e| e.to_str())
359        .is_some_and(|ext| ext == "vue" || ext == "svelte")
360}
361
362/// Parse an SFC file by extracting and combining all `<script>` and `<style>` blocks.
363#[cfg(test)]
364fn parse_sfc_to_module(
365    file_id: FileId,
366    path: &Path,
367    source: &str,
368    content_hash: u64,
369    need_complexity: bool,
370) -> ModuleInfo {
371    parse_sfc_to_module_with_mode(
372        file_id,
373        path,
374        source,
375        content_hash,
376        need_complexity,
377        fallow_types::shared_state::ExtractionMode::Standard,
378    )
379}
380
381pub(crate) fn parse_sfc_to_module_with_mode(
382    file_id: FileId,
383    path: &Path,
384    source: &str,
385    content_hash: u64,
386    need_complexity: bool,
387    mode: fallow_types::shared_state::ExtractionMode,
388) -> ModuleInfo {
389    let scripts = extract_sfc_scripts(source);
390    let styles = extract_sfc_styles(source);
391    let kind = sfc_kind(path);
392    let mut combined = empty_sfc_module(file_id, source, content_hash);
393    let mut template_visible_imports: FxHashSet<String> = FxHashSet::default();
394    let mut template_visible_bound_targets: FxHashMap<String, String> = FxHashMap::default();
395    let mut template_visible_iterable_types: FxHashMap<String, String> = FxHashMap::default();
396    let mut props_return_binding: Option<String> = None;
397    let mut emit_return_binding: Option<String> = None;
398    let mut shared_scope_references = SharedScopeReferences::default();
399    let mut script_binding_context = crate::template_usage::ScriptBindingContext::default();
400    let has_setup_script = scripts.iter().any(|script| script.is_setup);
401
402    for script in &scripts {
403        merge_script_into_module(&mut SfcScriptMergeInput {
404            kind,
405            script,
406            has_setup_script,
407            combined: &mut combined,
408            shared_scope_references: &mut shared_scope_references,
409            template_visible_imports: &mut template_visible_imports,
410            template_visible_bound_targets: &mut template_visible_bound_targets,
411            template_visible_iterable_types: &mut template_visible_iterable_types,
412            props_return_binding: &mut props_return_binding,
413            emit_return_binding: &mut emit_return_binding,
414            script_binding_context: &mut script_binding_context,
415            need_complexity,
416            mode,
417        });
418    }
419    if scripts.len() > 1 {
420        credit_shared_scope_references(&shared_scope_references, &mut combined);
421    }
422
423    for style in &styles {
424        merge_style_into_module(style, &mut combined);
425    }
426
427    // Whole-object prop/attr spread in the template (`v-bind="$attrs"`,
428    // `v-bind="$props"`, `v-bind="props"`) can consume a prop indirectly, so the
429    // `unused-component-prop` detector must abstain on the whole file.
430    if kind == SfcKind::Vue
431        && !combined.component_props.is_empty()
432        && PROPS_ATTRS_SPREAD_RE.is_match(source)
433    {
434        combined.has_props_attrs_fallthrough = true;
435    }
436
437    // The template can call `$emit` and the `defineEmits()` binding. A template in
438    // another language (`lang="pug"`) is not scanned, so the component abstains.
439    if kind == SfcKind::Vue && !combined.component_emits.is_empty() {
440        combined.has_dynamic_emit |= crate::sfc_template::vue_template_is_not_html(source);
441        script_binding_context
442            .emit_bindings
443            .insert("$emit".to_string());
444        script_binding_context
445            .emit_bindings
446            .extend(emit_return_binding.iter().cloned());
447    }
448
449    apply_template_usage(TemplateUsageInput {
450        kind,
451        source,
452        script_binding_context,
453        template_visible_imports,
454        template_visible_bound_targets,
455        template_visible_iterable_types: &template_visible_iterable_types,
456        props_return_binding: props_return_binding.as_deref(),
457        credit_load_data: kind == SfcKind::Svelte && is_sveltekit_route_data_component(path),
458        combined: &mut combined,
459    });
460
461    if need_complexity {
462        append_template_complexity(kind, source, &mut combined);
463    }
464
465    // Harvest Svelte template `on:<name>` listener bindings on component tags
466    // into the per-file listened set; the `unused-svelte-event` detector unions
467    // these project-wide to decide which dispatched events are dead. The name
468    // is an attribute name, which the snippet visitor cannot see.
469    if kind == SfcKind::Svelte {
470        combined.svelte_listened_events =
471            crate::sfc_template::collect_svelte_listened_events(source);
472    }
473
474    append_template_asset_imports(source, &mut combined);
475    dedup_import_binding_lists(&mut combined);
476    apply_component_contracts(kind, source, &mut combined);
477
478    combined
479}
480
481/// Append the synthetic `<template>` complexity entry for the SFC. Counts
482/// template control flow (`v-if`/`v-for`, `{#if}`/`{#each}`) and
483/// bound-expression/interpolation complexity so a template-heavy SFC is not
484/// scored as artificially simple. The scanners mask `<script>`/`<style>`/comments,
485/// so script control flow is NOT double-counted (it is scored by
486/// `translate_script_complexity`). Mirrors Angular's synthetic entry; no new rule
487/// or threshold, the entry folds into the existing complexity aggregate.
488fn append_template_complexity(kind: SfcKind, source: &str, combined: &mut ModuleInfo) {
489    match kind {
490        SfcKind::Vue => {
491            combined.complexity.extend(
492                crate::template_complexity::compute_vue_template_complexity(source),
493            );
494        }
495        // Svelte yields the `<template>` unit plus one `<snippet:NAME>` unit
496        // per top-level `{#snippet}` block.
497        SfcKind::Svelte => combined
498            .complexity
499            .extend(crate::template_complexity::compute_svelte_template_complexity(source)),
500    }
501}
502
503/// Turn static relative asset references in markup (`<img src="./logo.png">`)
504/// into `SideEffect` imports so a genuinely-missing asset surfaces as
505/// `unresolved-import` (existing assets resolve to `ExternalFile`, no finding).
506fn append_template_asset_imports(source: &str, combined: &mut ModuleInfo) {
507    for (specifier, span) in collect_template_asset_refs(source) {
508        combined.imports.push(ImportInfo {
509            source: specifier,
510            imported_name: ImportedName::SideEffect,
511            local_name: String::new(),
512            is_type_only: false,
513            is_type_only_star: false,
514            from_style: false,
515            span,
516            source_span: span,
517        });
518    }
519}
520
521/// Sort and dedup the per-script import-binding accumulator lists so the merged
522/// SFC module reports each binding once in a stable order.
523fn dedup_import_binding_lists(combined: &mut ModuleInfo) {
524    combined.unused_import_bindings.sort_unstable();
525    combined.unused_import_bindings.dedup();
526    combined.type_referenced_import_bindings.sort_unstable();
527    combined.type_referenced_import_bindings.dedup();
528    combined.value_referenced_import_bindings.sort_unstable();
529    combined.value_referenced_import_bindings.dedup();
530    combined.auto_import_candidates.sort_unstable();
531    combined.auto_import_candidates.dedup();
532}
533
534fn sfc_kind(path: &Path) -> SfcKind {
535    if path.extension().and_then(|ext| ext.to_str()) == Some("vue") {
536        SfcKind::Vue
537    } else {
538        SfcKind::Svelte
539    }
540}
541
542/// SvelteKit route components receive a `data` prop populated by the route's
543/// `load()` return object. This predicate gates the `data`-as-template-root
544/// credit (unused-load-data-key Primitive B) to exactly those files. It matches
545/// `+page.svelte` / `+layout.svelte` AND their layout-reset variants
546/// (`+page@.svelte`, `+page@named.svelte`, `+page@(group).svelte`, and the
547/// `+layout@...` forms), all of which still receive the `data` prop. `+error.svelte`
548/// is excluded (it receives `$page.error`, not the `load()` `data` prop), and a
549/// non-route file like `+pageHelper.svelte` is excluded by the grammar (the part
550/// after `+page` must be empty or start with `@`). The leading `+` is a
551/// SvelteKit-only filename convention, so no ordinary `.svelte` component matches.
552fn is_sveltekit_route_data_component(path: &Path) -> bool {
553    let Some(stem) = path
554        .file_name()
555        .and_then(|name| name.to_str())
556        .and_then(|name| name.strip_suffix(".svelte"))
557    else {
558        return false;
559    };
560    ["+page", "+layout"].iter().any(|prefix| {
561        stem.strip_prefix(prefix)
562            .is_some_and(|rest| rest.is_empty() || rest.starts_with('@'))
563    })
564}
565
566fn empty_sfc_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
567    let parsed = crate::suppress_literals::parse_sfc_suppressions(source);
568
569    crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
570        file_id,
571        content_hash,
572        source,
573        parsed_suppressions: parsed,
574        imports: Vec::new(),
575        exports: Vec::new(),
576    })
577}
578
579#[path = "sfc_script_merge.rs"]
580mod script_merge;
581pub(crate) use script_merge::translate_script_complexity;
582use script_merge::{
583    SfcScriptMergeInput, SharedScopeReferences, credit_shared_scope_references,
584    merge_script_into_module,
585};
586
587/// Compute and merge this script's import-binding usage (unused / type- and
588/// value-referenced) plus auto-import candidates into `combined`. A
589/// `generic="..."` attribute re-parses an augmented body so a type-only import
590/// consumed solely inside the constraint stays classified as type-referenced.
591///
592/// The re-parse recomputes the whole verdict, so it is handed the
593/// `import X = require('./x')` locals as well: those live outside `imports`,
594/// and without them such a binding would keep crediting its target on a
595/// `generic="..."` script while the plain `<script setup>` next to it reports
596/// (issue #2365).
597fn merge_script_binding_usage(
598    input: &mut SfcScriptMergeInput<'_>,
599    allocator: &Allocator,
600    imports: &[ImportInfo],
601    import_equals_bindings: &[String],
602    semantic_usage: crate::parse::SemanticUsage,
603) {
604    let augmented_body = build_generic_attr_probe_source(input.script);
605    let binding_usage = if let Some(augmented) = augmented_body.as_deref() {
606        let augmented_return =
607            Parser::new(allocator, augmented, source_type_for_script(input.script)).parse();
608        let mut probe = compute_import_binding_usage(
609            &augmented_return.program,
610            imports,
611            import_equals_bindings,
612            &FxHashSet::default(),
613        );
614        input
615            .shared_scope_references
616            .record_references(input.kind, &mut probe);
617        probe.import_binding_usage
618    } else {
619        semantic_usage.import_binding_usage
620    };
621    let auto_import_candidates = semantic_usage.auto_import_candidates;
622    crate::parse::append_declaration_merge_facts(
623        &mut input.combined.semantic_facts,
624        semantic_usage.declaration_merges,
625        input.script.byte_offset as u32,
626    );
627    input
628        .combined
629        .unused_import_bindings
630        .extend(binding_usage.unused.iter().cloned());
631    input
632        .combined
633        .type_referenced_import_bindings
634        .extend(binding_usage.type_referenced.iter().cloned());
635    input
636        .combined
637        .value_referenced_import_bindings
638        .extend(binding_usage.value_referenced.iter().cloned());
639    input
640        .combined
641        .auto_import_candidates
642        .extend(auto_import_candidates);
643}
644
645/// Carry an instance script's import locals and binding-target names into the
646/// template-visible sets (dropping empty locals and `this.`-prefixed targets) so
647/// the template scanner can credit them.
648fn harvest_template_visible_bindings(
649    input: &mut SfcScriptMergeInput<'_>,
650    extractor: &ModuleInfoExtractor,
651) {
652    input.template_visible_imports.extend(
653        extractor
654            .imports
655            .iter()
656            .filter(|import| !import.local_name.is_empty())
657            .map(|import| import.local_name.clone()),
658    );
659    input.template_visible_bound_targets.extend(
660        extractor
661            .binding_target_names()
662            .iter()
663            .filter(|(local, _)| !local.starts_with("this."))
664            .filter_map(|(local, target)| {
665                target
666                    .class_name()
667                    .map(|class_name| (local.clone(), class_name.to_string()))
668            }),
669    );
670    // Array / reactive-array binding element classes, so the Vue template
671    // scanner can type a `v-for` loop variable to its source's element class
672    // (issue #1707). `this.`-filtered for parity with bound targets.
673    input.template_visible_iterable_types.extend(
674        extractor
675            .array_binding_element_types()
676            .iter()
677            .filter(|(local, _)| !local.starts_with("this."))
678            .map(|(local, element)| (local.clone(), element.clone())),
679    );
680}
681
682/// Harvest Svelte 5 `$props()` declared props from an instance `<script>`
683/// program into `combined.component_props` (reusing the Vue IR + abstain flags),
684/// remapping each prop's body-relative span onto the SFC source via `byte_offset`.
685fn merge_svelte_props_into(
686    combined: &mut ModuleInfo,
687    program: &oxc_ast::ast::Program<'_>,
688    byte_offset: usize,
689) {
690    let harvest = crate::sfc_props::harvest_svelte_props(program);
691    if harvest.has_unharvestable_props {
692        combined.has_unharvestable_props = true;
693    }
694    if harvest.has_props_attrs_fallthrough {
695        combined.has_props_attrs_fallthrough = true;
696    }
697    for mut prop in harvest.props {
698        prop.span_start += byte_offset as u32;
699        combined.component_props.push(prop);
700    }
701}
702
703/// Harvest Vue prop/emit declarations into `combined`, remapping body-relative
704/// spans onto the SFC source via the script byte offset. The `<script setup>`
705/// path harvests `defineProps` / `defineEmits` (and the `defineExpose` /
706/// `defineModel` abstain flags + return bindings); the non-setup path harvests
707/// the Options API `props:` / `emits:` (same IR, same abstain flags, same remap,
708/// only the harvest source differs).
709fn merge_vue_props_emits_into(
710    input: &mut SfcScriptMergeInput<'_>,
711    program: &oxc_ast::ast::Program<'_>,
712    extractor: &mut ModuleInfoExtractor,
713) {
714    let byte_offset = input.script.byte_offset as u32;
715    if input.script.is_setup {
716        apply_props_harvest(
717            input,
718            crate::sfc_props::harvest_define_props(program),
719            byte_offset,
720            extractor,
721        );
722        apply_emits_harvest(
723            input,
724            crate::sfc_props::harvest_define_emits(program),
725            byte_offset,
726        );
727    } else {
728        apply_props_harvest(
729            input,
730            crate::sfc_props::harvest_options_api_props(program),
731            byte_offset,
732            extractor,
733        );
734        apply_emits_harvest(
735            input,
736            crate::sfc_props::harvest_options_api_emits(program),
737            byte_offset,
738        );
739    }
740}
741
742/// Fold a prop harvest (setup `defineProps` or Options-API `props:`) into
743/// `combined`: copy the abstain flags and `defineProps` return binding, then push
744/// each prop with its span remapped onto the SFC source. The setup-only fields
745/// (`has_define_expose` / `has_define_model` / `props_return_binding`) default to
746/// `false`/`None` in the Options-API harvest, so the shared copy is inert there.
747fn apply_props_harvest(
748    input: &mut SfcScriptMergeInput<'_>,
749    harvest: crate::sfc_props::DefinePropsHarvest,
750    byte_offset: u32,
751    extractor: &mut ModuleInfoExtractor,
752) {
753    if harvest.has_unharvestable_props {
754        input.combined.has_unharvestable_props = true;
755    }
756    if harvest.has_props_attrs_fallthrough {
757        input.combined.has_props_attrs_fallthrough = true;
758    }
759    if harvest.has_define_expose {
760        input.combined.has_define_expose = true;
761    }
762    if harvest.has_define_model {
763        input.combined.has_define_model = true;
764    }
765    if let Some(binding) = harvest.props_return_binding {
766        *input.props_return_binding = Some(binding);
767    }
768    // Record each props array field's element class keyed `props.<field>` into the
769    // visitor's array-binding element-types map (issue #1711). This runs before
770    // `harvest_template_visible_bindings` reads that map into
771    // `template_visible_iterable_types`, so a `v-for="(util) of props.items"`
772    // matches the `"props.items"` key and types `util` to the element class.
773    // Over-credit only: the harvest records a field only when its type resolved
774    // to a non-builtin array element class, so this can never add a finding.
775    for (field_name, element_type) in harvest.props_array_element_types {
776        extractor
777            .array_binding_element_types_mut()
778            .insert(format!("props.{field_name}"), element_type);
779    }
780    for mut prop in harvest.props {
781        prop.span_start += byte_offset;
782        input.combined.component_props.push(prop);
783    }
784}
785
786/// Fold an emit harvest (setup `defineEmits` or Options-API `emits:`) into
787/// `combined`: copy the abstain flags and emit return binding, then push each
788/// emit with its span remapped onto the SFC source. The setup-only fields
789/// (`has_emit_whole_object_use` / `emit_binding`) default to `false`/`None` in
790/// the Options-API harvest, so the shared copy is inert there.
791fn apply_emits_harvest(
792    input: &mut SfcScriptMergeInput<'_>,
793    harvest: crate::sfc_props::DefineEmitsHarvest,
794    byte_offset: u32,
795) {
796    if harvest.has_unharvestable_emits {
797        input.combined.has_unharvestable_emits = true;
798    }
799    if harvest.has_dynamic_emit {
800        input.combined.has_dynamic_emit = true;
801    }
802    if harvest.has_emit_whole_object_use {
803        input.combined.has_emit_whole_object_use = true;
804    }
805    if let Some(binding) = harvest.emit_binding {
806        *input.emit_return_binding = Some(binding);
807    }
808    for mut emit in harvest.emits {
809        emit.span_start += byte_offset;
810        input.combined.component_emits.push(emit);
811    }
812}
813
814fn add_script_src_import(module: &mut ModuleInfo, source: &str, source_span: Option<Span>) {
815    let span = source_span.unwrap_or_default();
816    module.imports.push(ImportInfo {
817        source: normalize_asset_url(source),
818        imported_name: ImportedName::SideEffect,
819        local_name: String::new(),
820        is_type_only: false,
821        is_type_only_star: false,
822        from_style: false,
823        span,
824        source_span: span,
825    });
826}
827
828/// `lang` attribute values whose body we know how to scan for `@import` /
829/// `@use` / `@forward` / `@plugin` directives. Plain `<style>` (no `lang`) is treated as
830/// CSS. `less`, `stylus`, and `postcss` bodies are NOT scanned because their
831/// import syntax differs (`@import (reference)` modifiers, etc.); their
832/// `<style src="...">` references are still seeded.
833fn style_lang_is_scss(lang: Option<&str>) -> bool {
834    matches!(lang, Some("scss" | "sass"))
835}
836
837fn style_lang_is_css_like(lang: Option<&str>) -> bool {
838    lang.is_none() || matches!(lang, Some("css"))
839}
840
841fn merge_style_into_module(style: &SfcStyle, combined: &mut ModuleInfo) {
842    if let Some(src) = &style.src {
843        let span = style.src_span.unwrap_or_default();
844        combined.imports.push(ImportInfo {
845            source: normalize_asset_url(src),
846            imported_name: ImportedName::SideEffect,
847            local_name: String::new(),
848            is_type_only: false,
849            is_type_only_star: false,
850            from_style: true,
851            span,
852            source_span: span,
853        });
854    }
855
856    let lang = style.lang.as_deref();
857    let is_scss = style_lang_is_scss(lang);
858    if !is_scss && !style_lang_is_css_like(lang) {
859        return;
860    }
861
862    let masked = crate::css_url::mask_style_block(&style.body, is_scss, combined);
863    for source in crate::css::import_sources_from_masked(&masked, is_scss) {
864        let source_span = Span::new(
865            style.byte_offset as u32 + source.span.start,
866            style.byte_offset as u32 + source.span.end,
867        );
868        combined.imports.push(ImportInfo {
869            source: source.normalized,
870            imported_name: if source.is_plugin {
871                ImportedName::Default
872            } else {
873                ImportedName::SideEffect
874            },
875            local_name: String::new(),
876            is_type_only: false,
877            is_type_only_star: false,
878            from_style: true,
879            span: source_span,
880            source_span,
881        });
882    }
883}
884
885pub(crate) fn source_type_for_script(script: &SfcScript) -> SourceType {
886    source_type_for(script.is_typescript, script.is_jsx)
887}
888
889fn source_type_for(is_typescript: bool, is_jsx: bool) -> SourceType {
890    match (is_typescript, is_jsx) {
891        (true, true) => SourceType::tsx(),
892        (true, false) => SourceType::ts(),
893        (false, true) => SourceType::jsx(),
894        (false, false) => SourceType::mjs(),
895    }
896}
897
898/// Join the inline `<script>` blocks of a Vue or Svelte SFC into one program
899/// source for whole-file binding analysis.
900///
901/// The SFC compilers merge `<script>` and `<script setup>` (Vue) or the module
902/// and instance scripts (Svelte) into one module, so a binding in one block is
903/// visible in the other. Each `generic="..."` constraint is kept as an
904/// unexported type alias, so a type that only the constraint uses still has a
905/// reference. The result uses TypeScript when any block uses TypeScript.
906/// Returns `None` when the SFC has no inline script.
907#[must_use]
908pub fn sfc_merged_script_source(source: &str) -> Option<(String, SourceType)> {
909    let scripts: Vec<SfcScript> = extract_sfc_scripts(source)
910        .into_iter()
911        .filter(|script| script.src.is_none())
912        .collect();
913    if scripts.is_empty() {
914        return None;
915    }
916    let is_typescript = scripts.iter().any(|script| script.is_typescript);
917    let is_jsx = scripts.iter().any(|script| script.is_jsx);
918    let mut merged = String::new();
919    for script in &scripts {
920        let body = build_generic_attr_probe_source(script);
921        merged.push_str(body.as_deref().unwrap_or(&script.body));
922        merged.push_str("\n;\n");
923    }
924    Some((merged, source_type_for(is_typescript, is_jsx)))
925}
926
927/// Build an augmented script body that pins the `generic="..."` constraint as
928/// a synthetic local type alias. The alias is unexported and uses a sentinel
929/// name so it can't collide with user code. Returns `None` when there is no
930/// generic attribute to pin (the common case), so callers fall back to the
931/// raw body without paying for a second parse.
932fn build_generic_attr_probe_source(script: &SfcScript) -> Option<String> {
933    let constraint = script.generic_attr.as_deref()?.trim();
934    if constraint.is_empty() {
935        return None;
936    }
937    Some(format!(
938        "{}\n;type __FALLOW_GENERIC_ATTR_PROBE<{}> = unknown;\n",
939        script.body, constraint,
940    ))
941}
942
943struct TemplateUsageInput<'a> {
944    kind: SfcKind,
945    source: &'a str,
946    script_binding_context: crate::template_usage::ScriptBindingContext,
947    template_visible_imports: FxHashSet<String>,
948    template_visible_bound_targets: FxHashMap<String, String>,
949    template_visible_iterable_types: &'a FxHashMap<String, String>,
950    props_return_binding: Option<&'a str>,
951    credit_load_data: bool,
952    combined: &'a mut ModuleInfo,
953}
954
955fn apply_template_usage(input: TemplateUsageInput<'_>) {
956    let TemplateUsageInput {
957        kind,
958        source,
959        script_binding_context,
960        template_visible_imports,
961        template_visible_bound_targets,
962        template_visible_iterable_types,
963        props_return_binding,
964        credit_load_data,
965        combined,
966    } = input;
967    let credited = build_template_credited_set(
968        template_visible_imports,
969        props_return_binding,
970        credit_load_data,
971        combined,
972    );
973    let file_id = combined.file_id;
974    let seed = crate::template_usage::TemplateUsage::with_markup_sink(
975        script_binding_context,
976        std::mem::replace(combined, ModuleInfo::empty(file_id)),
977    );
978    let mut template_visible_bound_targets = template_visible_bound_targets;
979    if credit_load_data {
980        template_visible_bound_targets.remove("data");
981    }
982    let mut template_usage = compute_template_usage(
983        kind,
984        source,
985        &credited,
986        &template_visible_bound_targets,
987        template_visible_iterable_types,
988        seed,
989    );
990    let module = template_usage.take_markup_module();
991    debug_assert!(
992        module.is_some(),
993        "the template scan gives back the component module of its markup sink"
994    );
995    if let Some(module) = module {
996        *combined = module;
997    }
998    // A route component that passes the whole `data` prop in markup
999    // (`{data}`, `data={data}`, `{...data}`, `fn(data)`) lets a child read any
1000    // load key, so the unused-load-data-key detector must abstain.
1001    combined.has_load_data_whole_use |= credit_load_data && template_usage.uses_whole("data");
1002    apply_prop_template_credit(&template_usage, props_return_binding, combined);
1003    merge_template_usage_into_combined(template_usage, combined);
1004}
1005
1006/// Build the set of template-credited names: the template-visible imports plus
1007/// each harvested prop name / destructure local, Vue's implicit `$props`, the
1008/// `defineProps` return binding, and (for SvelteKit route components) the `data`
1009/// load prop. Crediting a prop name against an import is inert.
1010fn build_template_credited_set(
1011    template_visible_imports: FxHashSet<String>,
1012    props_return_binding: Option<&str>,
1013    credit_load_data: bool,
1014    combined: &ModuleInfo,
1015) -> FxHashSet<String> {
1016    let mut credited = template_visible_imports;
1017    // unused-load-data-key Primitive B: a SvelteKit route component receives a
1018    // `data` prop populated by the route's `load()` return object. Credit `data`
1019    // as a recognized root so its template member accesses (`data.<key>`) are
1020    // emitted for the cross-file load-data-key join, gated to route components.
1021    if credit_load_data {
1022        credited.insert("data".to_string());
1023    }
1024    if !combined.component_props.is_empty() {
1025        for prop in &combined.component_props {
1026            // Credit both the declared name (Vue exposes props by name in the
1027            // template) and the destructure local (a renamed prop is used via it).
1028            credited.insert(prop.name.clone());
1029            credited.insert(prop.local.clone());
1030        }
1031        // Vue's implicit `$props` whole-props object is always available in a
1032        // template; credit `$props.<name>` member accesses too.
1033        credited.insert("$props".to_string());
1034        if let Some(binding) = props_return_binding {
1035            credited.insert(binding.to_string());
1036        }
1037    }
1038    credited
1039}
1040
1041/// Scan the template for usage of the credited names and bound targets into
1042/// `seed`. For a SvelteKit route, the caller drops `data` from the bound
1043/// targets so its template member accesses stay keyed on `data` (not remapped
1044/// onto the generated `PageData` / `LayoutData` type) for the cross-file
1045/// load-data join.
1046fn compute_template_usage(
1047    kind: SfcKind,
1048    source: &str,
1049    credited: &FxHashSet<String>,
1050    template_visible_bound_targets: &FxHashMap<String, String>,
1051    template_visible_iterable_types: &FxHashMap<String, String>,
1052    seed: crate::template_usage::TemplateUsage,
1053) -> crate::template_usage::TemplateUsage {
1054    crate::sfc_template::collect_template_usage_seeded(
1055        kind,
1056        source,
1057        credited,
1058        template_visible_bound_targets,
1059        template_visible_iterable_types,
1060        seed,
1061    )
1062}
1063
1064/// Mark each harvested prop `used_in_template` when the template references it by
1065/// bare name (destructure form) or via a `<props>.<name>` / `$props.<name>`
1066/// member access. A bare reference to a custom `defineProps` return binding as a
1067/// whole object means abstain on the whole file (`has_props_attrs_fallthrough`).
1068fn apply_prop_template_credit(
1069    template_usage: &crate::template_usage::TemplateUsage,
1070    props_return_binding: Option<&str>,
1071    combined: &mut ModuleInfo,
1072) {
1073    if !combined.component_props.is_empty() {
1074        let member_used: FxHashSet<&str> = template_usage
1075            .member_accesses
1076            .iter()
1077            .filter(|access| {
1078                access.object == "$props"
1079                    || props_return_binding.is_some_and(|binding| access.object == binding)
1080            })
1081            .map(|access| access.member.as_str())
1082            .collect();
1083        for prop in &mut combined.component_props {
1084            if template_usage.used_bindings.contains(&prop.name)
1085                || template_usage.used_bindings.contains(&prop.local)
1086                || member_used.contains(prop.name.as_str())
1087            {
1088                prop.used_in_template = true;
1089            }
1090        }
1091    }
1092
1093    if let Some(binding) = props_return_binding
1094        && (template_usage.used_bindings.contains(binding)
1095            || template_usage
1096                .whole_object_uses
1097                .iter()
1098                .any(|used| used == binding))
1099    {
1100        combined.has_props_attrs_fallthrough = true;
1101    }
1102}
1103
1104/// Drain the scanned template usage into `combined`: retain unused-import
1105/// bindings the template did not consume, extend member accesses / whole-object
1106/// uses / security sinks, and fold unresolved tag names into auto-import
1107/// candidates (sorted + deduped).
1108fn merge_template_usage_into_combined(
1109    template_usage: crate::template_usage::TemplateUsage,
1110    combined: &mut ModuleInfo,
1111) {
1112    combined
1113        .unused_import_bindings
1114        .retain(|binding| !template_usage.used_bindings.contains(binding));
1115    let mut member_accesses = std::mem::take(&mut combined.member_accesses).to_vec();
1116    member_accesses.extend(template_usage.member_accesses);
1117    combined.member_accesses = member_accesses.into();
1118    let mut whole_object_uses = std::mem::take(&mut combined.whole_object_uses).to_vec();
1119    whole_object_uses.extend(template_usage.whole_object_uses);
1120    combined.whole_object_uses = whole_object_uses.into();
1121    combined
1122        .security_sinks
1123        .extend(template_usage.security_sinks);
1124    if !template_usage.unresolved_tag_names.is_empty() {
1125        let mut names: Vec<String> = template_usage.unresolved_tag_names.into_iter().collect();
1126        names.sort_unstable();
1127        combined.auto_import_candidates.extend(names);
1128        combined.auto_import_candidates.dedup();
1129    }
1130}
1131
1132fn is_template_visible_script(kind: SfcKind, script: &SfcScript) -> bool {
1133    match kind {
1134        SfcKind::Vue => script.is_setup,
1135        SfcKind::Svelte => !script.is_context_module,
1136    }
1137}
1138
1139#[cfg(all(test, not(miri)))]
1140mod tests {
1141    use super::*;
1142    use fallow_types::extract::{
1143        ClassThisMemberAccessFact, ClassThisWholeObjectUseFact, SemanticFactView,
1144    };
1145
1146    #[test]
1147    fn merged_script_source_joins_inline_blocks_as_typescript() {
1148        let source = r#"<script>export const a = 1;</script>
1149<script setup lang="ts" generic="T extends Item">defineProps<{ a: T }>();</script>
1150<script src="./external.ts"></script>"#;
1151        let (merged, source_type) =
1152            sfc_merged_script_source(source).expect("inline scripts give a source");
1153        assert!(source_type.is_typescript());
1154        assert!(merged.contains("export const a = 1;"));
1155        assert!(merged.contains("defineProps<{ a: T }>();"));
1156        assert!(merged.contains("<T extends Item>"));
1157        assert!(!merged.contains("external"));
1158    }
1159
1160    #[test]
1161    fn merged_script_source_is_none_without_inline_script() {
1162        assert!(sfc_merged_script_source("<template><div /></template>").is_none());
1163        assert!(sfc_merged_script_source(r#"<script src="./a.ts"></script>"#).is_none());
1164    }
1165
1166    #[test]
1167    fn is_sfc_file_vue() {
1168        assert!(is_sfc_file(Path::new("App.vue")));
1169    }
1170
1171    #[test]
1172    fn is_sfc_file_svelte() {
1173        assert!(is_sfc_file(Path::new("Counter.svelte")));
1174    }
1175
1176    #[test]
1177    fn is_sfc_file_rejects_ts() {
1178        assert!(!is_sfc_file(Path::new("utils.ts")));
1179    }
1180
1181    #[test]
1182    fn is_sfc_file_rejects_jsx() {
1183        assert!(!is_sfc_file(Path::new("App.jsx")));
1184    }
1185
1186    #[test]
1187    fn is_sfc_file_rejects_astro() {
1188        assert!(!is_sfc_file(Path::new("Layout.astro")));
1189    }
1190
1191    #[test]
1192    fn single_plain_script() {
1193        let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1194        assert_eq!(scripts.len(), 1);
1195        assert_eq!(scripts[0].body, "const x = 1;");
1196        assert!(!scripts[0].is_typescript);
1197        assert!(!scripts[0].is_jsx);
1198        assert!(scripts[0].src.is_none());
1199    }
1200
1201    #[test]
1202    fn single_ts_script() {
1203        let scripts = extract_sfc_scripts(r#"<script lang="ts">const x: number = 1;</script>"#);
1204        assert_eq!(scripts.len(), 1);
1205        assert!(scripts[0].is_typescript);
1206        assert!(!scripts[0].is_jsx);
1207    }
1208
1209    #[test]
1210    fn single_tsx_script() {
1211        let scripts = extract_sfc_scripts(r#"<script lang="tsx">const el = <div />;</script>"#);
1212        assert_eq!(scripts.len(), 1);
1213        assert!(scripts[0].is_typescript);
1214        assert!(scripts[0].is_jsx);
1215    }
1216
1217    #[test]
1218    fn single_jsx_script() {
1219        let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
1220        assert_eq!(scripts.len(), 1);
1221        assert!(!scripts[0].is_typescript);
1222        assert!(scripts[0].is_jsx);
1223    }
1224
1225    #[test]
1226    fn two_script_blocks() {
1227        let source = r#"
1228<script lang="ts">
1229export default {};
1230</script>
1231<script setup lang="ts">
1232const count = 0;
1233</script>
1234"#;
1235        let scripts = extract_sfc_scripts(source);
1236        assert_eq!(scripts.len(), 2);
1237        assert!(scripts[0].body.contains("export default"));
1238        assert!(scripts[1].body.contains("count"));
1239    }
1240
1241    #[test]
1242    fn script_setup_extracted() {
1243        let scripts =
1244            extract_sfc_scripts(r#"<script setup lang="ts">import { ref } from 'vue';</script>"#);
1245        assert_eq!(scripts.len(), 1);
1246        assert!(scripts[0].body.contains("import"));
1247        assert!(scripts[0].is_typescript);
1248    }
1249
1250    #[test]
1251    fn script_src_detected() {
1252        let scripts = extract_sfc_scripts(r#"<script src="./component.ts" lang="ts"></script>"#);
1253        assert_eq!(scripts.len(), 1);
1254        assert_eq!(scripts[0].src.as_deref(), Some("./component.ts"));
1255    }
1256
1257    // -- Svelte module-context recognition (W1.1 piece 1) ----------------------
1258
1259    #[test]
1260    fn svelte4_context_module_is_module_context() {
1261        let scripts =
1262            extract_sfc_scripts(r#"<script context="module">export const x = 1;</script>"#);
1263        assert_eq!(scripts.len(), 1);
1264        assert!(scripts[0].is_context_module);
1265    }
1266
1267    #[test]
1268    fn svelte5_bare_module_attr_is_module_context() {
1269        let scripts = extract_sfc_scripts(r"<script module>export const x = 1;</script>");
1270        assert_eq!(scripts.len(), 1);
1271        assert!(scripts[0].is_context_module);
1272    }
1273
1274    #[test]
1275    fn svelte5_module_with_lang_is_module_context() {
1276        let scripts =
1277            extract_sfc_scripts(r#"<script module lang="ts">export const x = 1;</script>"#);
1278        assert_eq!(scripts.len(), 1);
1279        assert!(scripts[0].is_context_module);
1280        assert!(scripts[0].is_typescript);
1281    }
1282
1283    #[test]
1284    fn plain_script_is_not_module_context() {
1285        let scripts = extract_sfc_scripts(r"<script>const x = 1;</script>");
1286        assert_eq!(scripts.len(), 1);
1287        assert!(!scripts[0].is_context_module);
1288    }
1289
1290    #[test]
1291    fn lang_ts_script_is_not_module_context() {
1292        let scripts = extract_sfc_scripts(r#"<script lang="ts">const x = 1;</script>"#);
1293        assert_eq!(scripts.len(), 1);
1294        assert!(!scripts[0].is_context_module);
1295    }
1296
1297    #[test]
1298    fn data_module_attr_is_not_module_context() {
1299        // The `(?:^|\s)module(?:\s|$|=)` anchor must not match `data-module`.
1300        let scripts =
1301            extract_sfc_scripts(r#"<script data-module="x" lang="ts">const x = 1;</script>"#);
1302        assert_eq!(scripts.len(), 1);
1303        assert!(!scripts[0].is_context_module);
1304    }
1305
1306    #[test]
1307    fn bare_module_script_is_not_template_visible() {
1308        // AC-2: a bare `<script module>` is scoped as module context, so its
1309        // imports are NOT credited as template-visible (matching `context="module"`).
1310        let module_script = SfcScript {
1311            body: String::new(),
1312            is_typescript: false,
1313            is_jsx: false,
1314            byte_offset: 0,
1315            src: None,
1316            src_span: None,
1317            is_setup: false,
1318            is_context_module: true,
1319            generic_attr: None,
1320        };
1321        assert!(!is_template_visible_script(SfcKind::Svelte, &module_script));
1322        let instance_script = SfcScript {
1323            is_context_module: false,
1324            ..module_script
1325        };
1326        assert!(is_template_visible_script(
1327            SfcKind::Svelte,
1328            &instance_script
1329        ));
1330    }
1331
1332    #[test]
1333    fn data_src_not_treated_as_src() {
1334        let scripts =
1335            extract_sfc_scripts(r#"<script lang="ts" data-src="./nope.ts">const x = 1;</script>"#);
1336        assert_eq!(scripts.len(), 1);
1337        assert!(scripts[0].src.is_none());
1338    }
1339
1340    #[test]
1341    fn script_inside_html_comment_filtered() {
1342        let source = r#"
1343<!-- <script lang="ts">import { bad } from 'bad';</script> -->
1344<script lang="ts">import { good } from 'good';</script>
1345"#;
1346        let scripts = extract_sfc_scripts(source);
1347        assert_eq!(scripts.len(), 1);
1348        assert!(scripts[0].body.contains("good"));
1349    }
1350
1351    #[test]
1352    fn spanning_comment_filters_script() {
1353        let source = r#"
1354<!-- disabled:
1355<script lang="ts">import { bad } from 'bad';</script>
1356-->
1357<script lang="ts">const ok = true;</script>
1358"#;
1359        let scripts = extract_sfc_scripts(source);
1360        assert_eq!(scripts.len(), 1);
1361        assert!(scripts[0].body.contains("ok"));
1362    }
1363
1364    #[test]
1365    fn string_containing_comment_markers_not_corrupted() {
1366        let source = r#"
1367<script setup lang="ts">
1368const marker = "<!-- not a comment -->";
1369import { ref } from 'vue';
1370</script>
1371"#;
1372        let scripts = extract_sfc_scripts(source);
1373        assert_eq!(scripts.len(), 1);
1374        assert!(scripts[0].body.contains("import"));
1375    }
1376
1377    #[test]
1378    fn generic_attr_with_angle_bracket() {
1379        let source =
1380            r#"<script setup lang="ts" generic="T extends Foo<Bar>">const x = 1;</script>"#;
1381        let scripts = extract_sfc_scripts(source);
1382        assert_eq!(scripts.len(), 1);
1383        assert_eq!(scripts[0].body, "const x = 1;");
1384    }
1385
1386    #[test]
1387    fn nested_generic_attr() {
1388        let source = r#"<script setup lang="ts" generic="T extends Map<string, Set<number>>">const x = 1;</script>"#;
1389        let scripts = extract_sfc_scripts(source);
1390        assert_eq!(scripts.len(), 1);
1391        assert_eq!(scripts[0].body, "const x = 1;");
1392    }
1393
1394    #[test]
1395    fn lang_single_quoted() {
1396        let scripts = extract_sfc_scripts("<script lang='ts'>const x = 1;</script>");
1397        assert_eq!(scripts.len(), 1);
1398        assert!(scripts[0].is_typescript);
1399    }
1400
1401    #[test]
1402    fn uppercase_script_tag() {
1403        let scripts = extract_sfc_scripts(r#"<SCRIPT lang="ts">const x = 1;</SCRIPT>"#);
1404        assert_eq!(scripts.len(), 1);
1405        assert!(scripts[0].is_typescript);
1406    }
1407
1408    #[test]
1409    fn no_script_block() {
1410        let scripts = extract_sfc_scripts("<template><div>Hello</div></template>");
1411        assert!(scripts.is_empty());
1412    }
1413
1414    #[test]
1415    fn empty_script_body() {
1416        let scripts = extract_sfc_scripts(r#"<script lang="ts"></script>"#);
1417        assert_eq!(scripts.len(), 1);
1418        assert!(scripts[0].body.is_empty());
1419    }
1420
1421    #[test]
1422    fn whitespace_only_script() {
1423        let scripts = extract_sfc_scripts("<script lang=\"ts\">\n  \n</script>");
1424        assert_eq!(scripts.len(), 1);
1425        assert!(scripts[0].body.trim().is_empty());
1426    }
1427
1428    #[test]
1429    fn byte_offset_is_set() {
1430        let source = r#"<template><div/></template><script lang="ts">code</script>"#;
1431        let scripts = extract_sfc_scripts(source);
1432        assert_eq!(scripts.len(), 1);
1433        let offset = scripts[0].byte_offset;
1434        assert_eq!(&source[offset..offset + 4], "code");
1435    }
1436
1437    #[test]
1438    fn script_with_extra_attributes() {
1439        let scripts = extract_sfc_scripts(
1440            r#"<script lang="ts" id="app" type="module" data-custom="val">const x = 1;</script>"#,
1441        );
1442        assert_eq!(scripts.len(), 1);
1443        assert!(scripts[0].is_typescript);
1444        assert!(scripts[0].src.is_none());
1445    }
1446
1447    #[test]
1448    fn multiple_script_blocks_exports_combined() {
1449        let source = r#"
1450<script lang="ts">
1451export const version = '1.0';
1452</script>
1453<script setup lang="ts">
1454import { ref } from 'vue';
1455const count = ref(0);
1456</script>
1457"#;
1458        let info = parse_sfc_to_module(FileId(0), Path::new("Dual.vue"), source, 0, false);
1459        assert!(
1460            info.exports
1461                .iter()
1462                .any(|e| matches!(&e.name, crate::ExportName::Named(n) if n == "version")),
1463            "export from <script> block should be extracted"
1464        );
1465        assert!(
1466            info.imports.iter().any(|i| i.source == "vue"),
1467            "import from <script setup> block should be extracted"
1468        );
1469    }
1470
1471    #[test]
1472    fn class_this_facts_survive_sfc_script_merge() {
1473        let source = r#"
1474<script lang="ts">
1475export class Service {
1476    client!: Client;
1477
1478    run() {
1479        this.client.execute();
1480        Object.keys(this.client);
1481    }
1482}
1483</script>
1484"#;
1485        let info = parse_sfc_to_module(FileId(0), Path::new("Service.vue"), source, 0, false);
1486        let facts = SemanticFactView::new(&info.semantic_facts, &info.member_accesses);
1487
1488        assert_eq!(
1489            facts.class_this_member_accesses(),
1490            vec![ClassThisMemberAccessFact {
1491                class_local_name: "Service".to_string(),
1492                object: "this.client".to_string(),
1493                member: "execute".to_string(),
1494            }]
1495        );
1496        assert_eq!(
1497            facts.class_this_whole_object_uses(),
1498            vec![ClassThisWholeObjectUseFact {
1499                class_local_name: "Service".to_string(),
1500                object: "this.client".to_string(),
1501            }]
1502        );
1503    }
1504
1505    #[test]
1506    fn lang_tsx_detected_as_typescript_jsx() {
1507        let scripts =
1508            extract_sfc_scripts(r#"<script lang="tsx">const el = <div>{x}</div>;</script>"#);
1509        assert_eq!(scripts.len(), 1);
1510        assert!(scripts[0].is_typescript, "lang=tsx should be typescript");
1511        assert!(scripts[0].is_jsx, "lang=tsx should be jsx");
1512    }
1513
1514    #[test]
1515    fn multiline_html_comment_filters_all_script_blocks_inside() {
1516        let source = r#"
1517<!--
1518  This whole section is disabled:
1519  <script lang="ts">import { bad1 } from 'bad1';</script>
1520  <script lang="ts">import { bad2 } from 'bad2';</script>
1521-->
1522<script lang="ts">import { good } from 'good';</script>
1523"#;
1524        let scripts = extract_sfc_scripts(source);
1525        assert_eq!(scripts.len(), 1);
1526        assert!(scripts[0].body.contains("good"));
1527    }
1528
1529    #[test]
1530    fn script_src_generates_side_effect_import() {
1531        let info = parse_sfc_to_module(
1532            FileId(0),
1533            Path::new("External.vue"),
1534            r#"<script src="./external-logic.ts" lang="ts"></script>"#,
1535            0,
1536            false,
1537        );
1538        assert!(
1539            info.imports
1540                .iter()
1541                .any(|i| i.source == "./external-logic.ts"
1542                    && matches!(i.imported_name, ImportedName::SideEffect)),
1543            "script src should generate a side-effect import"
1544        );
1545    }
1546
1547    #[test]
1548    fn parse_sfc_no_script_returns_empty_module() {
1549        let info = parse_sfc_to_module(
1550            FileId(0),
1551            Path::new("Empty.vue"),
1552            "<template><div>Hello</div></template>",
1553            42,
1554            false,
1555        );
1556        assert!(info.imports.is_empty());
1557        assert!(info.exports.is_empty());
1558        assert_eq!(info.content_hash, 42);
1559        assert_eq!(info.file_id, FileId(0));
1560    }
1561
1562    #[test]
1563    fn parse_sfc_has_line_offsets() {
1564        let info = parse_sfc_to_module(
1565            FileId(0),
1566            Path::new("LineOffsets.vue"),
1567            r#"<script lang="ts">const x = 1;</script>"#,
1568            0,
1569            false,
1570        );
1571        assert!(!info.line_offsets.is_empty());
1572    }
1573
1574    #[test]
1575    fn parse_sfc_has_suppressions() {
1576        let info = parse_sfc_to_module(
1577            FileId(0),
1578            Path::new("Suppressions.vue"),
1579            r#"<script lang="ts">
1580// fallow-ignore-file
1581export const foo = 1;
1582</script>"#,
1583            0,
1584            false,
1585        );
1586        assert!(!info.suppressions.is_empty());
1587    }
1588
1589    #[test]
1590    fn source_type_plain_js_detection() {
1591        let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1592        assert_eq!(scripts.len(), 1);
1593        assert!(!scripts[0].is_typescript);
1594        assert!(!scripts[0].is_jsx);
1595    }
1596
1597    #[test]
1598    fn is_sfc_file_rejects_no_extension() {
1599        assert!(!is_sfc_file(Path::new("Makefile")));
1600    }
1601
1602    #[test]
1603    fn is_sfc_file_rejects_mdx() {
1604        assert!(!is_sfc_file(Path::new("post.mdx")));
1605    }
1606
1607    #[test]
1608    fn is_sfc_file_rejects_css() {
1609        assert!(!is_sfc_file(Path::new("styles.css")));
1610    }
1611
1612    #[test]
1613    fn multiple_script_blocks_both_have_offsets() {
1614        let source = r#"<script lang="ts">const a = 1;</script>
1615<script setup lang="ts">const b = 2;</script>"#;
1616        let scripts = extract_sfc_scripts(source);
1617        assert_eq!(scripts.len(), 2);
1618        let offset0 = scripts[0].byte_offset;
1619        let offset1 = scripts[1].byte_offset;
1620        assert_eq!(
1621            &source[offset0..offset0 + "const a = 1;".len()],
1622            "const a = 1;"
1623        );
1624        assert_eq!(
1625            &source[offset1..offset1 + "const b = 2;".len()],
1626            "const b = 2;"
1627        );
1628    }
1629
1630    #[test]
1631    fn script_with_src_and_lang() {
1632        let scripts = extract_sfc_scripts(r#"<script src="./logic.ts" lang="tsx"></script>"#);
1633        assert_eq!(scripts.len(), 1);
1634        assert_eq!(scripts[0].src.as_deref(), Some("./logic.ts"));
1635        assert!(scripts[0].is_typescript);
1636        assert!(scripts[0].is_jsx);
1637    }
1638
1639    #[test]
1640    fn extract_style_block_lang_scss() {
1641        let source = r#"<template/><style lang="scss">@import 'Foo';</style>"#;
1642        let styles = extract_sfc_styles(source);
1643        assert_eq!(styles.len(), 1);
1644        assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1645        assert!(styles[0].body.contains("@import"));
1646        assert!(styles[0].src.is_none());
1647    }
1648
1649    #[test]
1650    fn extract_style_block_with_src() {
1651        let source = r#"<style src="./theme.scss" lang="scss"></style>"#;
1652        let styles = extract_sfc_styles(source);
1653        assert_eq!(styles.len(), 1);
1654        assert_eq!(styles[0].src.as_deref(), Some("./theme.scss"));
1655        assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1656    }
1657
1658    #[test]
1659    fn extract_style_block_plain_no_lang() {
1660        let source = r"<style>.foo { color: red; }</style>";
1661        let styles = extract_sfc_styles(source);
1662        assert_eq!(styles.len(), 1);
1663        assert!(styles[0].lang.is_none());
1664    }
1665
1666    #[test]
1667    fn extract_multiple_style_blocks() {
1668        let source = r#"<style lang="scss">@import 'a';</style>
1669<style scoped lang="scss">@import 'b';</style>"#;
1670        let styles = extract_sfc_styles(source);
1671        assert_eq!(styles.len(), 2);
1672    }
1673
1674    #[test]
1675    fn style_block_inside_html_comment_filtered() {
1676        let source = r#"<!-- <style lang="scss">@import 'bad';</style> -->
1677<style lang="scss">@import 'good';</style>"#;
1678        let styles = extract_sfc_styles(source);
1679        assert_eq!(styles.len(), 1);
1680        assert!(styles[0].body.contains("good"));
1681    }
1682
1683    #[test]
1684    fn parse_sfc_extracts_style_imports_with_from_style_flag() {
1685        let info = parse_sfc_to_module(
1686            FileId(0),
1687            Path::new("Foo.vue"),
1688            r#"<template/><style lang="scss">@import 'Foo';</style>"#,
1689            0,
1690            false,
1691        );
1692        let style_import = info
1693            .imports
1694            .iter()
1695            .find(|i| i.source == "./Foo")
1696            .expect("scss @import 'Foo' should be normalized to ./Foo");
1697        assert!(
1698            style_import.from_style,
1699            "imports from <style> blocks must carry from_style=true so the resolver \
1700             enables SCSS partial fallback for the SFC importer"
1701        );
1702        assert!(matches!(
1703            style_import.imported_name,
1704            ImportedName::SideEffect
1705        ));
1706    }
1707
1708    #[test]
1709    fn parse_sfc_extracts_style_plugin_as_default_import() {
1710        let info = parse_sfc_to_module(
1711            FileId(0),
1712            Path::new("Foo.vue"),
1713            r#"<template/><style>@plugin "./tailwind-plugin.js";</style>"#,
1714            0,
1715            false,
1716        );
1717        let plugin_import = info
1718            .imports
1719            .iter()
1720            .find(|i| i.source == "./tailwind-plugin.js")
1721            .expect("style @plugin should create an import");
1722        assert!(plugin_import.from_style);
1723        assert!(matches!(plugin_import.imported_name, ImportedName::Default));
1724    }
1725
1726    #[test]
1727    fn parse_sfc_extracts_style_src_with_from_style_flag() {
1728        let info = parse_sfc_to_module(
1729            FileId(0),
1730            Path::new("Bar.vue"),
1731            r#"<style src="./Bar.scss" lang="scss"></style>"#,
1732            0,
1733            false,
1734        );
1735        let style_src = info
1736            .imports
1737            .iter()
1738            .find(|i| i.source == "./Bar.scss")
1739            .expect("<style src=\"./Bar.scss\"> should produce a side-effect import");
1740        assert!(style_src.from_style);
1741    }
1742
1743    #[test]
1744    fn parse_sfc_skips_unsupported_style_lang_body_but_keeps_src() {
1745        let info = parse_sfc_to_module(
1746            FileId(0),
1747            Path::new("Baz.vue"),
1748            r#"<style lang="postcss" src="./Baz.pcss">@custom-rule "skipped";</style>"#,
1749            0,
1750            false,
1751        );
1752        assert!(
1753            info.imports.iter().any(|i| i.source == "./Baz.pcss"),
1754            "src reference should still be seeded for unsupported lang"
1755        );
1756        assert!(
1757            !info.imports.iter().any(|i| i.source.contains("skipped")),
1758            "postcss body should not be scanned for @import directives"
1759        );
1760    }
1761
1762    fn asset_refs(source: &str) -> Vec<String> {
1763        super::collect_template_asset_refs(source)
1764            .into_iter()
1765            .map(|(s, _)| s)
1766            .collect()
1767    }
1768
1769    #[test]
1770    fn captures_static_relative_template_asset_refs() {
1771        assert_eq!(
1772            asset_refs(r#"<template><img src="./logo.png" /></template>"#),
1773            vec!["./logo.png".to_string()]
1774        );
1775        assert_eq!(
1776            asset_refs(r#"<source src="../media/clip.mp4">"#),
1777            vec!["../media/clip.mp4".to_string()]
1778        );
1779        assert_eq!(
1780            asset_refs(r#"<video poster="./thumb.jpg"></video>"#),
1781            vec!["./thumb.jpg".to_string()]
1782        );
1783    }
1784
1785    #[test]
1786    fn skips_dynamic_alias_root_remote_and_query_asset_refs() {
1787        // Dynamic bindings (Vue `:src`, `v-bind:src`, Svelte `bind:src` / `src={}`).
1788        assert!(asset_refs(r#"<img :src="logo" />"#).is_empty());
1789        assert!(asset_refs(r#"<img v-bind:src="logo" />"#).is_empty());
1790        assert!(asset_refs(r#"<img bind:src="logo" />"#).is_empty());
1791        assert!(asset_refs(r"<img src={logo} />").is_empty());
1792        assert!(asset_refs(r#"<img data-src="./x.png" />"#).is_empty());
1793        // Alias-prefixed, root-relative, remote, bare: not plain relative literals.
1794        assert!(asset_refs(r#"<img src="@/assets/x.png" />"#).is_empty());
1795        assert!(asset_refs(r#"<img src="/logo.png" />"#).is_empty());
1796        assert!(asset_refs(r#"<img src="https://cdn/x.png" />"#).is_empty());
1797        // Query / hash suffix abstains (the resolver cannot verify them).
1798        assert!(asset_refs(r#"<img src="./x.png?inline" />"#).is_empty());
1799        // Interpolated value abstains.
1800        assert!(asset_refs(r#"<img src="{{ logo }}" />"#).is_empty());
1801    }
1802
1803    #[test]
1804    fn skips_custom_component_src_prop() {
1805        // A custom component's `src` PROP must never be read as an asset edge.
1806        assert!(asset_refs(r#"<MyImage src="./x.png" />"#).is_empty());
1807        assert!(asset_refs(r#"<AppIcon src="../icons/y.svg" />"#).is_empty());
1808    }
1809
1810    #[test]
1811    fn skips_asset_refs_inside_script_style_and_comments() {
1812        // Masked regions must not contribute asset refs.
1813        assert!(asset_refs(r#"<script>const x = "<img src='./a.png'>"</script>"#).is_empty());
1814        assert!(asset_refs(r#"<style>/* <img src="./b.png"> */ .x{}</style>"#).is_empty());
1815        assert!(asset_refs(r#"<!-- <img src="./c.png" /> -->"#).is_empty());
1816    }
1817
1818    #[test]
1819    fn parse_sfc_emits_template_asset_as_side_effect_import() {
1820        let info = parse_sfc_to_module(
1821            FileId(0),
1822            Path::new("Hero.vue"),
1823            r#"<template><img src="./hero.png" /></template><script>let x=1</script>"#,
1824            0,
1825            false,
1826        );
1827        assert!(
1828            info.imports.iter().any(|i| i.source == "./hero.png"
1829                && matches!(i.imported_name, ImportedName::SideEffect)
1830                && !i.from_style),
1831            "template <img src> should seed a SideEffect import: {:?}",
1832            info.imports
1833        );
1834    }
1835
1836    // -- Svelte 5 `$props()` rune harvest (W1.1 piece 2) -----------------------
1837
1838    fn svelte_props(source: &str) -> Vec<crate::ModuleInfo> {
1839        vec![parse_sfc_to_module(
1840            FileId(0),
1841            Path::new("Component.svelte"),
1842            source,
1843            0,
1844            false,
1845        )]
1846    }
1847
1848    fn prop_names(info: &crate::ModuleInfo) -> Vec<String> {
1849        let mut names: Vec<String> = info
1850            .component_props
1851            .iter()
1852            .map(|p| p.name.clone())
1853            .collect();
1854        names.sort();
1855        names
1856    }
1857
1858    #[test]
1859    fn svelte_shorthand_props_harvested() {
1860        // AC-3: `let { a, b } = $props()` harvests `a`, `b` with `local == name`.
1861        let info = &svelte_props(r"<script>let { a, b } = $props();</script>")[0];
1862        assert_eq!(prop_names(info), vec!["a", "b"]);
1863        for prop in &info.component_props {
1864            assert_eq!(prop.local, prop.name);
1865        }
1866    }
1867
1868    #[test]
1869    fn svelte_renamed_prop_tracks_local_and_script_use() {
1870        // AC-4: `let { a: alias } = $props()` harvests `a` with `local == "alias"`,
1871        // and a reference to `alias` sets `used_in_script` for prop `a`.
1872        let info =
1873            &svelte_props(r"<script>let { a: alias } = $props(); console.log(alias);</script>")[0];
1874        assert_eq!(prop_names(info), vec!["a"]);
1875        let prop = &info.component_props[0];
1876        assert_eq!(prop.local, "alias");
1877        assert!(
1878            prop.used_in_script,
1879            "alias is referenced, so a is used in script"
1880        );
1881    }
1882
1883    #[test]
1884    fn svelte_unreferenced_prop_is_unused_in_script() {
1885        let info = &svelte_props(r"<script>let { a } = $props();</script>")[0];
1886        assert_eq!(prop_names(info), vec!["a"]);
1887        assert!(!info.component_props[0].used_in_script);
1888    }
1889
1890    #[test]
1891    fn svelte_default_prop_peeled() {
1892        // AC-5: `let { a = 1 } = $props()` harvests `a` (default peeled).
1893        let info = &svelte_props(r"<script>let { a = 1 } = $props();</script>")[0];
1894        assert_eq!(prop_names(info), vec!["a"]);
1895    }
1896
1897    #[test]
1898    fn svelte_bindable_default_peeled() {
1899        // The bindable form `let { a = $bindable() } = $props()`: `a` is still a
1900        // declared prop (the default value is irrelevant to the local name).
1901        let info = &svelte_props(r"<script>let { a = $bindable() } = $props();</script>")[0];
1902        assert_eq!(prop_names(info), vec!["a"]);
1903    }
1904
1905    #[test]
1906    fn svelte_rest_element_sets_fallthrough_abstain() {
1907        // AC-6: `let { a, ...rest } = $props()` sets has_props_attrs_fallthrough.
1908        let info = &svelte_props(r"<script>let { a, ...rest } = $props();</script>")[0];
1909        assert!(info.has_props_attrs_fallthrough);
1910    }
1911
1912    #[test]
1913    fn svelte_bare_identifier_binding_sets_unharvestable_abstain() {
1914        // AC-7: `let p = $props()` (no destructure) sets has_unharvestable_props.
1915        let info = &svelte_props(r"<script>let p = $props(); console.log(p.x);</script>")[0];
1916        assert!(info.has_unharvestable_props);
1917        assert!(info.component_props.is_empty());
1918    }
1919
1920    #[test]
1921    fn svelte_nested_destructure_sets_unharvestable_abstain() {
1922        // A nested destructure (`{ a: { x } }`) cannot be flattened. Abstain.
1923        let info = &svelte_props(r"<script>let { a: { x } } = $props();</script>")[0];
1924        assert!(info.has_unharvestable_props);
1925    }
1926
1927    #[test]
1928    fn svelte_prop_used_only_in_markup_credited_as_template_root() {
1929        // AC-8: a prop used only in markup (`{a}`) is credited via
1930        // `apply_template_usage`, so `used_in_template` is set (parity with Vue).
1931        let info = &svelte_props(r"<script>let { a } = $props();</script><p>{a}</p>")[0];
1932        assert_eq!(prop_names(info), vec!["a"]);
1933        assert!(
1934            info.component_props[0].used_in_template,
1935            "a is used in markup, so used_in_template should be true"
1936        );
1937    }
1938
1939    #[test]
1940    fn svelte_module_script_props_not_harvested() {
1941        // `$props()` is instance-only; a module-context script must not harvest.
1942        let info = &svelte_props(
1943            r"<script module>let { a } = $props();</script><script>let { b } = $props();</script>",
1944        )[0];
1945        // Only the instance script's `b` is harvested.
1946        assert_eq!(prop_names(info), vec!["b"]);
1947    }
1948
1949    // -- Svelte custom-event dispatch harvest (unused-svelte-event) ------------
1950
1951    fn dispatched_names(info: &crate::ModuleInfo) -> Vec<String> {
1952        let mut names: Vec<String> = info
1953            .svelte_dispatched_events
1954            .iter()
1955            .map(|e| e.name.clone())
1956            .collect();
1957        names.sort();
1958        names
1959    }
1960
1961    #[test]
1962    fn svelte_dispatch_literal_event_is_harvested() {
1963        let info = &svelte_props(
1964            r"<script>import { createEventDispatcher } from 'svelte';
1965              const dispatch = createEventDispatcher();
1966              function save() { dispatch('save'); }</script>",
1967        )[0];
1968        assert_eq!(dispatched_names(info), vec!["save"]);
1969        assert!(!info.has_dynamic_dispatch);
1970    }
1971
1972    #[test]
1973    fn svelte_dispatch_without_svelte_import_is_ignored() {
1974        // A local `createEventDispatcher` not imported from `svelte` is not a
1975        // dispatcher; the `dispatch('save')` call records nothing.
1976        let info = &svelte_props(
1977            r"<script>function createEventDispatcher() { return () => {}; }
1978              const dispatch = createEventDispatcher();
1979              dispatch('save');</script>",
1980        )[0];
1981        assert!(info.svelte_dispatched_events.is_empty());
1982    }
1983
1984    #[test]
1985    fn svelte_dynamic_dispatch_sets_abstain() {
1986        let info = &svelte_props(
1987            r"<script>import { createEventDispatcher } from 'svelte';
1988              const dispatch = createEventDispatcher();
1989              function fire(name) { dispatch(name); }</script>",
1990        )[0];
1991        assert!(
1992            info.has_dynamic_dispatch,
1993            "a non-literal dispatch arg must set the abstain flag"
1994        );
1995    }
1996
1997    #[test]
1998    fn svelte_dispatch_whole_value_use_sets_abstain() {
1999        let info = &svelte_props(
2000            r"<script>import { createEventDispatcher } from 'svelte';
2001              const dispatch = createEventDispatcher();
2002              forward(dispatch);</script>",
2003        )[0];
2004        assert!(
2005            info.has_dynamic_dispatch,
2006            "passing the dispatch binding as a whole value must set the abstain flag"
2007        );
2008    }
2009
2010    #[test]
2011    fn svelte_listened_event_on_component_is_harvested() {
2012        let info =
2013            &svelte_props(r"<script>import Child from './Child.svelte';</script><Child on:save />")
2014                [0];
2015        assert!(info.svelte_listened_events.contains(&"save".to_string()));
2016    }
2017}
2018
2019fn apply_component_contracts(kind: SfcKind, source: &str, combined: &mut ModuleInfo) {
2020    let framework = match kind {
2021        SfcKind::Vue => fallow_types::extract::ComponentFramework::Vue,
2022        SfcKind::Svelte => fallow_types::extract::ComponentFramework::Svelte,
2023    };
2024    let callers = crate::sfc_template::component_contracts::collect(
2025        &mask_non_markup_regions(source),
2026        &combined.imports,
2027        framework,
2028        0,
2029        combined
2030            .component_contracts
2031            .as_deref()
2032            .map_or(&[], |facts| facts.spread_bindings.as_slice()),
2033        combined
2034            .component_contracts
2035            .as_deref()
2036            .map_or(&[], |facts| facts.aliases.as_slice()),
2037    );
2038    crate::component_contracts::merge(&mut combined.component_contracts, callers, 0, None);
2039    if let Some(facts) = &mut combined.component_contracts {
2040        let credited: FxHashSet<String> = facts
2041            .declarations
2042            .iter()
2043            .flat_map(|prop| [prop.local.clone(), prop.name.clone()])
2044            .collect();
2045        let usage = collect_template_usage_with_bound_targets(
2046            kind,
2047            source,
2048            &credited,
2049            &FxHashMap::default(),
2050            &FxHashMap::default(),
2051        );
2052        for declaration in &mut facts.declarations {
2053            declaration.is_used |= usage.used_bindings.contains(&declaration.local)
2054                || usage.member_accesses.iter().any(|access| {
2055                    access.object == declaration.local && access.member == declaration.name
2056                });
2057        }
2058    }
2059    if let Some(facts) = &mut combined.component_contracts {
2060        for declaration in &mut facts.declarations {
2061            if let Some(prop) = combined
2062                .component_props
2063                .iter()
2064                .find(|prop| prop.name == declaration.name)
2065            {
2066                declaration.is_used |= prop.used_in_template;
2067            }
2068            declaration.incomplete |= combined.has_props_attrs_fallthrough
2069                || combined.has_define_expose
2070                || combined.has_define_model;
2071        }
2072    }
2073
2074    crate::component_contracts::attach_sfc_default_export(combined);
2075}