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