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