Skip to main content

fallow_extract/
css.rs

1//! CSS/SCSS file parsing and CSS Module class name extraction.
2//!
3//! Handles `@import`, `@use`, `@forward`, `@plugin`, `@apply`, `@tailwind` directives,
4//! and extracts class names as named exports from `.module.css`/`.module.scss` files.
5//!
6//! Extraction is a deliberate hybrid, not a half-finished migration. lightningcss
7//! owns the membership decision for standard CSS (which `.token` occurrences are
8//! genuine class selectors, via `lightningcss_class_set`); the regex scanners own
9//! span location and the entire SCSS path. lightningcss parses standard CSS only,
10//! not SCSS syntax (`@use`, `@forward`, `//` line comments, `$variables`), so SCSS
11//! files are gated away from the parser and the regex chain stays as permanent
12//! infrastructure rather than a transitional step toward an all-parser tokenizer.
13
14use std::path::Path;
15use std::sync::LazyLock;
16
17use lightningcss::rules::CssRule;
18use lightningcss::selector::{Component, PseudoClass, Selector, SelectorList};
19use lightningcss::stylesheet::{ParserOptions, StyleSheet};
20use oxc_span::Span;
21use rustc_hash::FxHashSet;
22
23use crate::{ExportInfo, ExportName, ImportInfo, ImportedName, ModuleInfo, VisibilityTag};
24use fallow_types::discover::FileId;
25
26/// Regex to extract CSS @import sources.
27/// Matches: @import "path"; @import 'path'; @import url("path"); @import url('path'); @import url(path);
28static CSS_IMPORT_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
29    crate::static_regex(
30        r#"@import\s+(?:url\(\s*(?:["']([^"']+)["']|([^)]+))\s*\)|["']([^"']+)["'])"#,
31    )
32});
33
34/// Regex to extract SCSS @use and @forward sources.
35/// Matches: @use "path"; @use 'path'; @forward "path"; @forward 'path';
36static SCSS_USE_RE: LazyLock<regex::Regex> =
37    LazyLock::new(|| crate::static_regex(r#"@(?:use|forward)\s+["']([^"']+)["']"#));
38
39/// Regex to extract Tailwind CSS @plugin sources.
40/// Matches: @plugin "package"; @plugin 'package'; @plugin "./local-plugin.js";
41static CSS_PLUGIN_RE: LazyLock<regex::Regex> =
42    LazyLock::new(|| crate::static_regex(r#"@plugin\s+["']([^"']+)["']"#));
43
44/// Regex to extract @apply class references.
45/// Matches: @apply class1 class2 class3;
46static CSS_APPLY_RE: LazyLock<regex::Regex> =
47    LazyLock::new(|| crate::static_regex(r"@apply\s+[^;}\n]+"));
48
49/// Regex to extract @tailwind directives.
50/// Matches: @tailwind base; @tailwind components; @tailwind utilities;
51static CSS_TAILWIND_RE: LazyLock<regex::Regex> =
52    LazyLock::new(|| crate::static_regex(r"@tailwind\s+\w+"));
53
54/// Regex to match CSS block comments (`/* ... */`) for stripping before extraction.
55static CSS_COMMENT_RE: LazyLock<regex::Regex> =
56    LazyLock::new(|| crate::static_regex(r"(?s)/\*.*?\*/"));
57
58/// Regex to match SCSS single-line comments (`// ...`) for stripping before extraction.
59static SCSS_LINE_COMMENT_RE: LazyLock<regex::Regex> =
60    LazyLock::new(|| crate::static_regex(r"//[^\n]*"));
61
62/// Regex to extract CSS class names from selectors.
63/// Matches `.className` in selectors. Applied after stripping comments, strings, and URLs.
64static CSS_CLASS_RE: LazyLock<regex::Regex> =
65    LazyLock::new(|| crate::static_regex(r"\.([a-zA-Z_][a-zA-Z0-9_-]*)"));
66
67/// Regex to strip quoted strings and `url(...)` content from CSS before class extraction.
68/// Prevents false positives from `content: ".foo"` and `url(./path/file.ext)`.
69static CSS_NON_SELECTOR_RE: LazyLock<regex::Regex> =
70    LazyLock::new(|| crate::static_regex(r#"(?s)"[^"]*"|'[^']*'|url\([^)]*\)"#));
71
72/// Regex to strip the prelude of `@layer` and `@import` at-rules before
73/// CSS-Modules class extraction. Matches the `@keyword` plus everything up to
74/// (but not including) the next `;` or `{`, so block bodies are preserved.
75///
76/// Narrow allowlist by design (issue #540): only at-rules whose preludes
77/// legitimately carry dot-separated identifiers without selector semantics are
78/// stripped. `@layer foo.bar` (CSS Cascading & Inheritance L5) lists layer
79/// names; `@import url("x.css") layer(theme.button)` carries a parenthesised
80/// layer reference. `@scope (.foo) to (.bar)` keeps its existing behavior
81/// because the prelude IS a selector list and `.foo` / `.bar` are real class
82/// references that the user may want to surface as exports.
83static CSS_AT_RULE_PRELUDE_RE: LazyLock<regex::Regex> =
84    LazyLock::new(|| crate::static_regex(r"@(?:layer|import)\b[^;{]*"));
85
86pub(crate) fn is_css_file(path: &Path) -> bool {
87    path.extension()
88        .and_then(|e| e.to_str())
89        .is_some_and(|ext| matches!(ext, "css" | "scss" | "sass" | "less"))
90}
91
92/// A CSS import source with both the literal source and fallow's resolver-normalized form.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct CssImportSource {
95    /// The import source exactly as it appeared in `@import` / `@use` / `@forward` / `@plugin`.
96    pub raw: String,
97    /// The source normalized for fallow's resolver (`variables` -> `./variables` in SCSS).
98    pub normalized: String,
99    /// Whether this source came from Tailwind CSS `@plugin`.
100    pub is_plugin: bool,
101    /// Span of the source specifier in the original CSS/SCSS input.
102    pub span: Span,
103}
104
105fn is_css_module_file(path: &Path) -> bool {
106    is_css_file(path)
107        && path
108            .file_stem()
109            .and_then(|s| s.to_str())
110            .is_some_and(|stem| stem.ends_with(".module"))
111}
112
113/// Returns true if a CSS import source is a remote URL or data URI that should be skipped.
114fn is_css_url_import(source: &str) -> bool {
115    source.starts_with("http://") || source.starts_with("https://") || source.starts_with("data:")
116}
117
118/// Normalize a CSS/SCSS import path to use `./` prefix for relative paths.
119/// Bare file names such as `reset.css` stay relative for CSS ergonomics, while
120/// package subpaths such as `tailwindcss/theme.css` stay bare so bundler-style
121/// package CSS imports resolve through `node_modules`.
122///
123/// When `is_scss` is true, extensionless specifiers that are not SCSS built-in
124/// modules (`sass:*`) are treated as relative imports (SCSS partial convention).
125/// This handles `@use 'variables'` resolving to `./_variables.scss`.
126///
127/// Scoped npm packages (`@scope/pkg`) are always kept bare, even when they have
128/// CSS extensions (e.g., `@fontsource/monaspace-neon/400.css`). Bundlers like
129/// Vite resolve these from node_modules, not as relative paths.
130fn normalize_css_import_path(path: String, is_scss: bool) -> String {
131    if path.starts_with('.') || path.starts_with('/') || path.contains("://") {
132        return path;
133    }
134    if path.starts_with('@') && path.contains('/') {
135        return path;
136    }
137    let path_ref = std::path::Path::new(&path);
138    if !is_scss
139        && path.contains('/')
140        && path_ref
141            .extension()
142            .and_then(|e| e.to_str())
143            .is_some_and(is_style_extension)
144    {
145        return path;
146    }
147    let ext = std::path::Path::new(&path)
148        .extension()
149        .and_then(|e| e.to_str());
150    match ext {
151        Some(e) if is_style_extension(e) => format!("./{path}"),
152        _ => {
153            if is_scss && !path.contains(':') {
154                format!("./{path}")
155            } else {
156                path
157            }
158        }
159    }
160}
161
162fn is_style_extension(ext: &str) -> bool {
163    ext.eq_ignore_ascii_case("css")
164        || ext.eq_ignore_ascii_case("scss")
165        || ext.eq_ignore_ascii_case("sass")
166        || ext.eq_ignore_ascii_case("less")
167}
168
169/// Strip comments from CSS/SCSS source to avoid matching directives inside comments.
170#[cfg(test)]
171fn strip_css_comments(source: &str, is_scss: bool) -> String {
172    let stripped = CSS_COMMENT_RE.replace_all(source, "");
173    if is_scss {
174        SCSS_LINE_COMMENT_RE.replace_all(&stripped, "").into_owned()
175    } else {
176        stripped.into_owned()
177    }
178}
179
180fn mask_css_comments(source: &str, is_scss: bool) -> String {
181    let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
182    if is_scss {
183        masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
184    }
185    masked
186}
187
188/// Normalize a Tailwind CSS `@plugin` target.
189///
190/// Unlike SCSS `@use`, extensionless targets such as `daisyui` are package
191/// specifiers, not local partials. Keep bare specifiers bare and only preserve
192/// explicit relative/root-relative paths.
193fn normalize_css_plugin_path(path: String) -> String {
194    path
195}
196
197/// Extract `@import` / `@use` / `@forward` / `@plugin` source paths from a CSS/SCSS string.
198///
199/// Returns both the raw source and the normalized source. URL imports
200/// (`http://`, `https://`, `data:`) are skipped. Use [`extract_css_imports`]
201/// when only the normalized form is needed.
202///
203/// Regex-based by design: this path also handles the SCSS `@use` / `@forward`
204/// forms, which lightningcss does not parse, so unlike class extraction there is
205/// no parser-backed set to defer the membership decision to.
206#[must_use]
207pub fn extract_css_import_sources(source: &str, is_scss: bool) -> Vec<CssImportSource> {
208    let stripped = mask_css_comments(source, is_scss);
209    let mut out = Vec::new();
210
211    for cap in CSS_IMPORT_RE.captures_iter(&stripped) {
212        let raw = cap.get(1).or_else(|| cap.get(2)).or_else(|| cap.get(3));
213        if let Some(m) = raw {
214            let (src, span) = trimmed_match_with_span(m);
215            if !src.is_empty() && !is_css_url_import(&src) {
216                out.push(CssImportSource {
217                    normalized: normalize_css_import_path(src.clone(), is_scss),
218                    raw: src,
219                    is_plugin: false,
220                    span,
221                });
222            }
223        }
224    }
225
226    if is_scss {
227        for cap in SCSS_USE_RE.captures_iter(&stripped) {
228            if let Some(m) = cap.get(1) {
229                let (raw, span) = trimmed_match_with_span(m);
230                out.push(CssImportSource {
231                    normalized: normalize_css_import_path(raw.clone(), true),
232                    raw,
233                    is_plugin: false,
234                    span,
235                });
236            }
237        }
238    }
239
240    for cap in CSS_PLUGIN_RE.captures_iter(&stripped) {
241        if let Some(m) = cap.get(1) {
242            let (raw, span) = trimmed_match_with_span(m);
243            if !raw.is_empty() && !is_css_url_import(&raw) {
244                out.push(CssImportSource {
245                    normalized: normalize_css_plugin_path(raw.clone()),
246                    raw,
247                    is_plugin: true,
248                    span,
249                });
250            }
251        }
252    }
253
254    out
255}
256
257fn trimmed_match_with_span(m: regex::Match<'_>) -> (String, Span) {
258    let raw = m.as_str();
259    let trimmed_start = raw.len() - raw.trim_start().len();
260    let trimmed_end = raw.trim_end().len();
261    let start = m.start() + trimmed_start;
262    let end = m.start() + trimmed_end;
263    (raw.trim().to_string(), Span::new(start as u32, end as u32))
264}
265
266/// Extract normalized `@import` / `@use` / `@forward` / `@plugin` source paths from a CSS/SCSS string.
267///
268/// Returns specifiers normalized via `normalize_css_import_path`. URL imports
269/// (`http://`, `https://`, `data:`) are skipped. Used by callers that only need
270/// entry/dependency source paths; callers that need import kind information
271/// should use [`extract_css_import_sources`].
272#[must_use]
273pub fn extract_css_imports(source: &str, is_scss: bool) -> Vec<String> {
274    extract_css_import_sources(source, is_scss)
275        .into_iter()
276        .map(|source| source.normalized)
277        .collect()
278}
279
280/// Opening of a Tailwind v4 `@theme` block: `@theme`, optional modifier keywords
281/// (`inline` / `static` / `reference` / `default`), then the `{`. Matches up to
282/// and including the brace so the caller can brace-match the body from `end()`.
283static CSS_THEME_OPEN_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
284    crate::static_regex(r"@theme(?:\s+(?:inline|static|reference|default))*\s*\{")
285});
286
287/// A `var(--custom-property)` reference, capturing the dashed-ident name without
288/// the leading `--`. Used only to credit a theme token read by another theme
289/// token inside a `@theme` interior (lightningcss skips the unknown at-rule).
290static CSS_VAR_REF_RE: LazyLock<regex::Regex> =
291    LazyLock::new(|| crate::static_regex(r"var\(\s*--([A-Za-z0-9_-]+)"));
292
293/// A Tailwind v4 `@theme` token definition: the custom-property name WITHOUT the
294/// leading `--` (e.g. `color-brand`) and its 1-based line in the source.
295#[derive(Debug, Clone, PartialEq, Eq)]
296pub struct ThemeTokenDef {
297    /// The custom-property name with the `--` prefix stripped (`color-brand`).
298    pub name: String,
299    /// 1-based line of the declaration in the original source.
300    pub line: u32,
301}
302
303/// Result of scanning a CSS source for Tailwind v4 `@theme` blocks.
304#[derive(Debug, Clone, Default, PartialEq, Eq)]
305pub struct ThemeScan {
306    /// Custom-property tokens DEFINED at the top level of a `@theme` block, with
307    /// the `*`-reset form (`--color-*: initial`) and bare-namespace declarations
308    /// excluded. Deduped by name (first definition wins for the line).
309    pub tokens: Vec<ThemeTokenDef>,
310    /// Custom-property names (without `--`) READ via `var()` anywhere inside a
311    /// `@theme` block interior. lightningcss does not descend into the unknown
312    /// `@theme` at-rule, so these reads are invisible to `CssAnalytics`; a token
313    /// backing another token (`--color-button: var(--color-brand)`) keeps the
314    /// backing token live.
315    pub theme_var_reads: Vec<String>,
316}
317
318/// Scan a CSS source for Tailwind v4 `@theme` blocks, returning the defined
319/// design tokens plus the custom properties read via `var()` inside those blocks.
320///
321/// Tailwind v4 is CSS-first, so `@theme { --color-brand: #f00; }` is the unit of
322/// a user-authored design token. lightningcss treats `@theme` as an unknown
323/// at-rule and skips it, so this is a separate brace-matching pass (comments and
324/// strings masked first so braces / semicolons inside them never break the block
325/// boundary). Only top-level `--ident: value` declarations are tokens; declarations
326/// inside a nested block (e.g. `@keyframes` for `--animate-*`) are not.
327#[must_use]
328pub fn scan_theme_blocks(source: &str) -> ThemeScan {
329    // Fast path: skip the masking allocation for the common no-`@theme` file.
330    if !source.contains("@theme") {
331        return ThemeScan::default();
332    }
333    // Mask comments AND strings/url() so a brace or semicolon inside either does
334    // not break the block boundary. Both masks preserve byte length, so offsets in the
335    // masked buffer line up 1:1 with the original (line numbers are counted in
336    // the original below).
337    let masked = mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE);
338    let bytes = masked.as_bytes();
339    let mut out = ThemeScan::default();
340    let mut seen: FxHashSet<String> = FxHashSet::default();
341    for open in CSS_THEME_OPEN_RE.find_iter(&masked) {
342        let body_start = open.end();
343        // Brace-match from just after the opening `{` to its partner.
344        let mut depth = 1usize;
345        let mut i = body_start;
346        while i < bytes.len() {
347            match bytes[i] {
348                b'{' => depth += 1,
349                b'}' => {
350                    depth -= 1;
351                    if depth == 0 {
352                        break;
353                    }
354                }
355                _ => {}
356            }
357            i += 1;
358        }
359        let body_end = i.min(bytes.len());
360        collect_theme_declarations(
361            source,
362            &masked,
363            body_start,
364            body_end,
365            &mut out.tokens,
366            &mut seen,
367        );
368        if let Some(body) = masked.get(body_start..body_end) {
369            for cap in CSS_VAR_REF_RE.captures_iter(body) {
370                if let Some(name) = cap.get(1) {
371                    out.theme_var_reads.push(name.as_str().to_owned());
372                }
373            }
374        }
375    }
376    out
377}
378
379/// Walk a masked `@theme` body collecting top-level `--ident: value` declarations
380/// as tokens. Tracks brace depth so declarations inside a nested block (e.g. an
381/// `@keyframes` for `--animate-*`) are skipped, and statement position so only a
382/// `--ident` at a declaration start counts. The `*`-reset form (`--color-*`) is
383/// excluded because the `*` breaks the ident scan before the `:`.
384fn collect_theme_declarations(
385    source: &str,
386    masked: &str,
387    start: usize,
388    end: usize,
389    out: &mut Vec<ThemeTokenDef>,
390    seen: &mut FxHashSet<String>,
391) {
392    let bytes = masked.as_bytes();
393    let mut depth = 0usize;
394    let mut expect_decl = true;
395    let mut i = start;
396    while i < end {
397        let b = bytes[i];
398        match b {
399            b'{' => {
400                depth += 1;
401                expect_decl = false;
402                i += 1;
403            }
404            b'}' => {
405                depth = depth.saturating_sub(1);
406                if depth == 0 {
407                    expect_decl = true;
408                }
409                i += 1;
410            }
411            b';' => {
412                if depth == 0 {
413                    expect_decl = true;
414                }
415                i += 1;
416            }
417            _ if b.is_ascii_whitespace() => i += 1,
418            _ => {
419                if depth == 0 && expect_decl {
420                    expect_decl = false;
421                    if b == b'-' && bytes.get(i + 1) == Some(&b'-') {
422                        let id_start = i;
423                        let mut j = i;
424                        while j < end {
425                            let c = bytes[j];
426                            if c == b'-' || c == b'_' || c.is_ascii_alphanumeric() {
427                                j += 1;
428                            } else {
429                                break;
430                            }
431                        }
432                        let mut k = j;
433                        while k < end && bytes[k].is_ascii_whitespace() {
434                            k += 1;
435                        }
436                        // Only a `--ident:` (no `*` before the colon) is a token.
437                        if k < end && bytes[k] == b':' {
438                            let name = &masked[id_start + 2..j];
439                            if !name.is_empty() && seen.insert(name.to_owned()) {
440                                let line = 1 + source
441                                    .get(..id_start)
442                                    .map_or(0, |s| s.bytes().filter(|&x| x == b'\n').count());
443                                out.push(ThemeTokenDef {
444                                    name: name.to_owned(),
445                                    line: u32::try_from(line).unwrap_or(u32::MAX),
446                                });
447                            }
448                        }
449                        i = j;
450                    } else {
451                        i += 1;
452                    }
453                } else {
454                    i += 1;
455                }
456            }
457        }
458    }
459}
460
461/// Extract the utility tokens referenced in `@apply` directive bodies across a
462/// CSS source (comment / string masked). `@apply rounded-card font-bold;` yields
463/// `["rounded-card", "font-bold"]`. The leading-`!` and trailing-`!` important
464/// modifiers and a bare `!important` token are stripped, so a theme token whose
465/// utility is applied only via `@apply` is credited as used.
466#[must_use]
467pub fn extract_apply_tokens(source: &str) -> Vec<String> {
468    // Fast path: skip the masking allocation for the common no-`@apply` file.
469    if !source.contains("@apply") {
470        return Vec::new();
471    }
472    let masked = mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE);
473    let mut out = Vec::new();
474    for m in CSS_APPLY_RE.find_iter(&masked) {
475        let body = m.as_str().trim_start_matches("@apply");
476        for token in body.split_whitespace() {
477            let token = token.trim_matches('!');
478            if token.is_empty() || token == "important" {
479                continue;
480            }
481            out.push(token.to_owned());
482        }
483    }
484    out
485}
486
487/// Mask every regex match in `src` with ASCII spaces (`0x20`) of equal byte
488/// length, so byte offsets in the returned string correspond 1:1 to byte
489/// offsets in the original.
490///
491/// Used to neutralise CSS comments, quoted strings, `url(...)`, and at-rule
492/// preludes before scanning for `.class` selectors, while preserving the
493/// original-source positions that callers need to populate `ExportInfo.span`
494/// (issue #549). The `regex` crate guarantees match boundaries respect UTF-8
495/// char boundaries, so the masked buffer is always valid UTF-8.
496fn mask_with_whitespace(src: &str, re: &regex::Regex) -> String {
497    let mut out = String::with_capacity(src.len());
498    let mut cursor = 0;
499    for m in re.find_iter(src) {
500        out.push_str(&src[cursor..m.start()]);
501        for _ in m.start()..m.end() {
502            out.push(' ');
503        }
504        cursor = m.end();
505    }
506    out.push_str(&src[cursor..]);
507    out
508}
509
510/// Collect the authoritative set of class-selector names from a CSS source by
511/// parsing it into a real AST (lightningcss). Returns `None` only on a
512/// catastrophic parse failure (Sass syntax that is not standard CSS), in which
513/// case the caller falls back to the regex scanner. With `error_recovery` on,
514/// individual malformed rules are recovered silently and contribute a partial
515/// set rather than triggering the fallback, so a broken rule drops only its own
516/// classes (a conservative miss) instead of returning `None`.
517///
518/// This is the source of truth for which `.token` occurrences are genuine class
519/// selectors. It natively excludes `@layer foo.bar` layer names, `@import ...
520/// layer(theme.button)` layer references, `@keyframes` step selectors, id and
521/// element selectors, and the contents of comments / strings / `url()`, which
522/// the older regex-only scanner had to approximate with a stack of masking
523/// passes. Classes nested inside `:is()` / `:where()` / `:not()` / `:has()` /
524/// `:any()` / `::slotted()` / `:host()` / `:nth-child(... of ...)` are
525/// collected too, matching the regex scanner's "every `.class` token" behavior.
526fn lightningcss_class_set(source: &str) -> Option<FxHashSet<String>> {
527    let options = ParserOptions {
528        // Recover from individual malformed rules so a single bad rule does not
529        // discard class names from the rest of the file.
530        error_recovery: true,
531        // These files are `.module.css` / `.module.scss`, so parse in CSS Modules
532        // mode. That makes the `:local()` / `:global()` pseudo-classes parse as
533        // real selectors rather than erroring, so classes wrapped in them are
534        // collected (matching the regex scanner). Renaming is a print-time
535        // concern, so the AST class names stay the original author-written names.
536        css_modules: Some(lightningcss::css_modules::Config::default()),
537        ..ParserOptions::default()
538    };
539    let stylesheet = StyleSheet::parse(source, options).ok()?;
540    let mut classes = FxHashSet::default();
541    collect_classes_from_rules(&stylesheet.rules.0, &mut classes);
542    Some(classes)
543}
544
545/// Recursively collect class-selector names from a list of CSS rules, descending
546/// into every grouping rule (`@media`, `@supports`, `@container`, `@layer {}`,
547/// `@document`, `@starting-style`, `@scope`, nested style rules) so a class
548/// declared anywhere contributes to the set.
549fn collect_classes_from_rules(rules: &[CssRule<'_>], classes: &mut FxHashSet<String>) {
550    for rule in rules {
551        match rule {
552            CssRule::Style(style) => {
553                collect_classes_from_selector_list(&style.selectors, classes);
554                collect_classes_from_rules(&style.rules.0, classes);
555            }
556            CssRule::Media(rule) => collect_classes_from_rules(&rule.rules.0, classes),
557            CssRule::Supports(rule) => collect_classes_from_rules(&rule.rules.0, classes),
558            CssRule::Container(rule) => collect_classes_from_rules(&rule.rules.0, classes),
559            CssRule::LayerBlock(rule) => collect_classes_from_rules(&rule.rules.0, classes),
560            CssRule::MozDocument(rule) => collect_classes_from_rules(&rule.rules.0, classes),
561            CssRule::StartingStyle(rule) => collect_classes_from_rules(&rule.rules.0, classes),
562            CssRule::Nesting(rule) => {
563                collect_classes_from_selector_list(&rule.style.selectors, classes);
564                collect_classes_from_rules(&rule.style.rules.0, classes);
565            }
566            CssRule::Scope(rule) => {
567                if let Some(scope_start) = &rule.scope_start {
568                    collect_classes_from_selector_list(scope_start, classes);
569                }
570                if let Some(scope_end) = &rule.scope_end {
571                    collect_classes_from_selector_list(scope_end, classes);
572                }
573                collect_classes_from_rules(&rule.rules.0, classes);
574            }
575            _ => {}
576        }
577    }
578}
579
580fn collect_classes_from_selector_list(list: &SelectorList<'_>, classes: &mut FxHashSet<String>) {
581    for selector in &list.0 {
582        collect_classes_from_selector(selector, classes);
583    }
584}
585
586fn collect_classes_from_selector(selector: &Selector<'_>, classes: &mut FxHashSet<String>) {
587    for component in selector.iter_raw_match_order() {
588        match component {
589            Component::Class(name) => {
590                classes.insert(name.0.to_string());
591            }
592            Component::Is(list)
593            | Component::Where(list)
594            | Component::Has(list)
595            | Component::Negation(list)
596            | Component::Any(_, list) => {
597                for nested in list.as_ref() {
598                    collect_classes_from_selector(nested, classes);
599                }
600            }
601            Component::Slotted(nested) | Component::Host(Some(nested)) => {
602                collect_classes_from_selector(nested, classes);
603            }
604            Component::NthOf(data) => {
605                for nested in data.selectors() {
606                    collect_classes_from_selector(nested, classes);
607                }
608            }
609            // CSS Modules `:local(.foo)` / `:global(.foo)` wrap a real selector.
610            Component::NonTSPseudoClass(
611                PseudoClass::Local { selector } | PseudoClass::Global { selector },
612            ) => collect_classes_from_selector(selector, classes),
613            _ => {}
614        }
615    }
616}
617
618/// Extract class names from a CSS module file as named exports.
619///
620/// For standard CSS, lightningcss parses the source into an AST and supplies the
621/// authoritative set of class-selector names; the byte-offset scanner then
622/// locates each name's [`Span`] in the ORIGINAL `source` (pointing at the bare
623/// class name, no leading dot) so downstream `compute_line_offsets` resolves the
624/// real declaration line and column instead of falling back to line:1 col:0
625/// (issue #549). For SCSS (Sass syntax lightningcss does not parse) and for any
626/// CSS that fails to parse outright, the regex-only scanner is used unchanged.
627pub fn extract_css_module_exports(source: &str, is_scss: bool) -> Vec<ExportInfo> {
628    if !is_scss && let Some(class_set) = lightningcss_class_set(source) {
629        return scan_css_module_exports(source, is_scss, Some(&class_set));
630    }
631    scan_css_module_exports(source, is_scss, None)
632}
633
634/// Scan `source` for `.class` tokens and emit one [`ExportInfo`] per distinct
635/// class (first occurrence wins), with a [`Span`] pointing at the post-dot
636/// identifier in the original source.
637///
638/// When `class_filter` is `Some`, only tokens present in the AST-derived set are
639/// emitted, so the parser owns the membership decision and the scanner owns only
640/// span location. When `class_filter` is `None` (SCSS / parse-failure fallback),
641/// the at-rule prelude is masked to keep `@layer foo.bar` / `@import ...
642/// layer(...)` segments from being mistaken for classes.
643fn scan_css_module_exports(
644    source: &str,
645    is_scss: bool,
646    class_filter: Option<&FxHashSet<String>>,
647) -> Vec<ExportInfo> {
648    let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
649    if is_scss {
650        masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
651    }
652    masked = mask_with_whitespace(&masked, &CSS_NON_SELECTOR_RE);
653    if class_filter.is_none() {
654        masked = mask_with_whitespace(&masked, &CSS_AT_RULE_PRELUDE_RE);
655    }
656
657    let mut seen = FxHashSet::default();
658    let mut exports = Vec::new();
659    for cap in CSS_CLASS_RE.captures_iter(&masked) {
660        if let Some(m) = cap.get(1) {
661            let class_name = m.as_str().to_string();
662            if class_filter.is_some_and(|filter| !filter.contains(&class_name)) {
663                continue;
664            }
665            if seen.insert(class_name.clone()) {
666                #[expect(
667                    clippy::cast_possible_truncation,
668                    reason = "CSS files exceeding u32::MAX bytes are not a realistic input"
669                )]
670                let span = Span::new(m.start() as u32, m.end() as u32);
671                exports.push(ExportInfo {
672                    name: ExportName::Named(class_name),
673                    local_name: None,
674                    is_type_only: false,
675                    visibility: VisibilityTag::None,
676                    span,
677                    members: Vec::new(),
678                    is_side_effect_used: false,
679                    super_class: None,
680                });
681            }
682        }
683    }
684    exports
685}
686
687/// Parse a CSS/SCSS file, extracting @import, @use, @forward, @plugin, @apply, and @tailwind directives.
688pub(crate) fn parse_css_to_module(
689    file_id: FileId,
690    path: &Path,
691    source: &str,
692    content_hash: u64,
693) -> ModuleInfo {
694    let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
695    let is_scss = path
696        .extension()
697        .and_then(|e| e.to_str())
698        .is_some_and(|ext| matches!(ext, "scss" | "sass" | "less"));
699
700    let stripped = mask_css_comments(source, is_scss);
701
702    let mut imports = Vec::new();
703
704    for source in extract_css_import_sources(source, is_scss) {
705        imports.push(ImportInfo {
706            source: source.normalized,
707            imported_name: if source.is_plugin {
708                ImportedName::Default
709            } else {
710                ImportedName::SideEffect
711            },
712            local_name: String::new(),
713            is_type_only: false,
714            from_style: false,
715            span: source.span,
716            source_span: source.span,
717        });
718    }
719
720    let has_apply = CSS_APPLY_RE.is_match(&stripped);
721    let has_tailwind = CSS_TAILWIND_RE.is_match(&stripped);
722    if has_apply || has_tailwind {
723        imports.push(ImportInfo {
724            source: "tailwindcss".to_string(),
725            imported_name: ImportedName::SideEffect,
726            local_name: String::new(),
727            is_type_only: false,
728            from_style: false,
729            span: Span::default(),
730            source_span: Span::default(),
731        });
732    }
733
734    let exports = if is_css_module_file(path) {
735        extract_css_module_exports(source, is_scss)
736    } else {
737        Vec::new()
738    };
739
740    ModuleInfo {
741        file_id,
742        exports,
743        imports,
744        re_exports: Vec::new(),
745        dynamic_imports: Vec::new(),
746        dynamic_import_patterns: Vec::new(),
747        require_calls: Vec::new(),
748        package_path_references: Vec::new(),
749        member_accesses: Vec::new(),
750        whole_object_uses: Vec::new(),
751        has_cjs_exports: false,
752        has_angular_component_template_url: false,
753        content_hash,
754        suppressions: parsed_suppressions.suppressions,
755        unknown_suppression_kinds: parsed_suppressions.unknown_kinds,
756        unused_import_bindings: Vec::new(),
757        type_referenced_import_bindings: Vec::new(),
758        value_referenced_import_bindings: Vec::new(),
759        line_offsets: fallow_types::extract::compute_line_offsets(source),
760        complexity: Vec::new(),
761        flag_uses: Vec::new(),
762        class_heritage: vec![],
763        injection_tokens: vec![],
764        local_type_declarations: Vec::new(),
765        public_signature_type_references: Vec::new(),
766        namespace_object_aliases: Vec::new(),
767        iconify_prefixes: Vec::new(),
768        iconify_icon_names: Vec::new(),
769        auto_import_candidates: Vec::new(),
770        directives: Vec::new(),
771        client_only_dynamic_import_spans: Vec::new(),
772        security_sinks: Vec::new(),
773        security_sinks_skipped: 0,
774        security_unresolved_callee_sites: Vec::new(),
775        tainted_bindings: Vec::new(),
776        sanitized_sink_args: Vec::new(),
777        security_control_sites: Vec::new(),
778        callee_uses: Vec::new(),
779        misplaced_directives: Vec::new(),
780        inline_server_action_exports: Vec::new(),
781        di_key_sites: Vec::new(),
782        has_dynamic_provide: false,
783        referenced_import_bindings: Vec::new(),
784        component_props: Vec::new(),
785        has_props_attrs_fallthrough: false,
786        has_define_expose: false,
787        has_define_model: false,
788        has_unharvestable_props: false,
789        component_emits: Vec::new(),
790        angular_inputs: Vec::new(),
791        angular_outputs: Vec::new(),
792        angular_component_selectors: Vec::new(),
793        angular_used_selectors: Vec::new(),
794        angular_entry_component_refs: Vec::new(),
795        has_dynamic_component_render: false,
796        has_unharvestable_emits: false,
797        has_dynamic_emit: false,
798        has_emit_whole_object_use: false,
799        load_return_keys: Vec::new(),
800        has_unharvestable_load: false,
801        has_load_data_whole_use: false,
802        has_page_data_store_whole_use: false,
803        component_functions: Vec::new(),
804        react_props: Vec::new(),
805        hook_uses: Vec::new(),
806        render_edges: Vec::new(),
807        svelte_dispatched_events: Vec::new(),
808        svelte_listened_events: Vec::new(),
809        has_dynamic_dispatch: false,
810    }
811}
812
813#[cfg(test)]
814mod tests {
815    use super::*;
816
817    /// Helper to collect export names as strings from `extract_css_module_exports`.
818    fn export_names(source: &str) -> Vec<String> {
819        extract_css_module_exports(source, false)
820            .into_iter()
821            .filter_map(|e| match e.name {
822                ExportName::Named(n) => Some(n),
823                ExportName::Default => None,
824            })
825            .collect()
826    }
827
828    #[test]
829    fn is_css_file_css() {
830        assert!(is_css_file(Path::new("styles.css")));
831    }
832
833    #[test]
834    fn is_css_file_scss() {
835        assert!(is_css_file(Path::new("styles.scss")));
836    }
837
838    #[test]
839    fn is_css_file_sass() {
840        assert!(is_css_file(Path::new("styles.sass")));
841    }
842
843    #[test]
844    fn is_css_file_less() {
845        assert!(is_css_file(Path::new("styles.less")));
846    }
847
848    #[test]
849    fn is_css_file_rejects_js() {
850        assert!(!is_css_file(Path::new("app.js")));
851    }
852
853    #[test]
854    fn is_css_file_rejects_ts() {
855        assert!(!is_css_file(Path::new("app.ts")));
856    }
857
858    #[test]
859    fn is_css_file_rejects_no_extension() {
860        assert!(!is_css_file(Path::new("Makefile")));
861    }
862
863    #[test]
864    fn is_css_module_file_module_css() {
865        assert!(is_css_module_file(Path::new("Component.module.css")));
866    }
867
868    #[test]
869    fn is_css_module_file_module_scss() {
870        assert!(is_css_module_file(Path::new("Component.module.scss")));
871    }
872
873    #[test]
874    fn is_css_module_file_rejects_plain_css() {
875        assert!(!is_css_module_file(Path::new("styles.css")));
876    }
877
878    #[test]
879    fn is_css_module_file_rejects_plain_scss() {
880        assert!(!is_css_module_file(Path::new("styles.scss")));
881    }
882
883    #[test]
884    fn is_css_module_file_rejects_module_js() {
885        assert!(!is_css_module_file(Path::new("utils.module.js")));
886    }
887
888    #[test]
889    fn extracts_single_class() {
890        let names = export_names(".foo { color: red; }");
891        assert_eq!(names, vec!["foo"]);
892    }
893
894    #[test]
895    fn extracts_multiple_classes() {
896        let names = export_names(".foo { } .bar { }");
897        assert_eq!(names, vec!["foo", "bar"]);
898    }
899
900    #[test]
901    fn extracts_nested_classes() {
902        let names = export_names(".foo .bar { color: red; }");
903        assert!(names.contains(&"foo".to_string()));
904        assert!(names.contains(&"bar".to_string()));
905    }
906
907    #[test]
908    fn extracts_hyphenated_class() {
909        let names = export_names(".my-class { }");
910        assert_eq!(names, vec!["my-class"]);
911    }
912
913    #[test]
914    fn extracts_camel_case_class() {
915        let names = export_names(".myClass { }");
916        assert_eq!(names, vec!["myClass"]);
917    }
918
919    #[test]
920    fn extracts_class_inside_global_pseudo() {
921        // CSS Modules `:global(.foo)` must surface `foo`: the parser understands
922        // the wrapped selector, which the regex scanner could not on its own.
923        let names = export_names(":global(.globalClass) { color: red; }");
924        assert_eq!(names, vec!["globalClass"]);
925    }
926
927    #[test]
928    fn extracts_class_inside_local_pseudo() {
929        let names = export_names(":local(.localClass) { color: red; }");
930        assert_eq!(names, vec!["localClass"]);
931    }
932
933    #[test]
934    fn extracts_classes_inside_negation() {
935        let names = export_names(".btn:not(.disabled) { }");
936        assert!(names.contains(&"btn".to_string()), "got {names:?}");
937        assert!(names.contains(&"disabled".to_string()), "got {names:?}");
938    }
939
940    #[test]
941    fn extracts_classes_inside_is_and_where() {
942        let names = export_names(":is(.a, .b) :where(.c) { }");
943        for expected in ["a", "b", "c"] {
944            assert!(
945                names.contains(&expected.to_string()),
946                "missing {expected} in {names:?}"
947            );
948        }
949    }
950
951    #[test]
952    fn extracts_underscore_class() {
953        let names = export_names("._hidden { } .__wrapper { }");
954        assert!(names.contains(&"_hidden".to_string()));
955        assert!(names.contains(&"__wrapper".to_string()));
956    }
957
958    #[test]
959    fn pseudo_selector_hover() {
960        let names = export_names(".foo:hover { color: blue; }");
961        assert_eq!(names, vec!["foo"]);
962    }
963
964    #[test]
965    fn pseudo_selector_focus() {
966        let names = export_names(".input:focus { outline: none; }");
967        assert_eq!(names, vec!["input"]);
968    }
969
970    #[test]
971    fn pseudo_element_before() {
972        let names = export_names(".icon::before { content: ''; }");
973        assert_eq!(names, vec!["icon"]);
974    }
975
976    #[test]
977    fn combined_pseudo_selectors() {
978        let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
979        assert_eq!(names, vec!["btn"]);
980    }
981
982    #[test]
983    fn classes_inside_media_query() {
984        let names = export_names(
985            "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
986        );
987        assert!(names.contains(&"mobile-nav".to_string()));
988        assert!(names.contains(&"desktop-nav".to_string()));
989    }
990
991    #[test]
992    fn classes_inside_multi_line_media_query() {
993        let names =
994            export_names("@media\n  screen and (min-width: 600px)\n{\n  .real { color: red; }\n}");
995        assert_eq!(names, vec!["real"]);
996    }
997
998    #[test]
999    fn at_layer_statement_does_not_export() {
1000        let names = export_names("@layer foo.bar;");
1001        assert!(names.is_empty(), "got {names:?}");
1002        let names = export_names("@layer foo.bar, foo.baz;");
1003        assert!(names.is_empty(), "got {names:?}");
1004    }
1005
1006    #[test]
1007    fn at_layer_block_keeps_body_classes() {
1008        let names = export_names("@layer foo.bar { .root { color: red; } }");
1009        assert_eq!(names, vec!["root"]);
1010    }
1011
1012    #[test]
1013    fn at_layer_multiline_prelude_keeps_body_classes() {
1014        let names = export_names("@layer\n  foo.bar\n{ .root { color: red; } }");
1015        assert_eq!(names, vec!["root"]);
1016    }
1017
1018    #[test]
1019    fn at_layer_with_nested_media_keeps_body() {
1020        let names =
1021            export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
1022        assert_eq!(names, vec!["real"]);
1023    }
1024
1025    #[test]
1026    fn at_import_with_layer_attribute_does_not_export() {
1027        let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
1028        assert!(names.is_empty(), "got {names:?}");
1029    }
1030
1031    #[test]
1032    fn class_then_at_layer_does_not_leak_prelude() {
1033        let names =
1034            export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
1035        assert_eq!(names, vec!["outer", "inner"]);
1036    }
1037
1038    #[test]
1039    fn at_scope_keeps_selector_list_classes() {
1040        let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
1041        assert!(names.contains(&"parent".to_string()), "got {names:?}");
1042        assert!(names.contains(&"child".to_string()), "got {names:?}");
1043        assert!(names.contains(&"title".to_string()), "got {names:?}");
1044    }
1045
1046    #[test]
1047    fn at_keyframes_numeric_step_is_not_class() {
1048        let names = export_names(
1049            "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
1050        );
1051        assert!(names.is_empty(), "got {names:?}");
1052    }
1053
1054    #[test]
1055    fn at_webkit_keyframes_keeps_body_classes() {
1056        let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
1057        assert_eq!(names, vec!["real"]);
1058    }
1059
1060    #[test]
1061    fn deduplicates_repeated_class() {
1062        let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
1063        assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
1064    }
1065
1066    #[test]
1067    fn empty_source() {
1068        let names = export_names("");
1069        assert!(names.is_empty());
1070    }
1071
1072    #[test]
1073    fn no_classes() {
1074        let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
1075        assert!(names.is_empty());
1076    }
1077
1078    #[test]
1079    fn ignores_classes_in_block_comments() {
1080        let names = export_names("/* .fake { } */ .real { }");
1081        assert!(!names.contains(&"fake".to_string()));
1082        assert!(names.contains(&"real".to_string()));
1083    }
1084
1085    #[test]
1086    fn ignores_classes_in_scss_line_comments() {
1087        let exports = extract_css_module_exports("// .fake\n.real { }", true);
1088        let names: Vec<_> = exports
1089            .iter()
1090            .filter_map(|e| match &e.name {
1091                ExportName::Named(n) => Some(n.as_str()),
1092                ExportName::Default => None,
1093            })
1094            .collect();
1095        assert_eq!(names, vec!["real"]);
1096    }
1097
1098    #[test]
1099    fn ignores_classes_in_strings() {
1100        let names = export_names(r#".real { content: ".fake"; }"#);
1101        assert!(names.contains(&"real".to_string()));
1102        assert!(!names.contains(&"fake".to_string()));
1103    }
1104
1105    #[test]
1106    fn ignores_classes_in_url() {
1107        let names = export_names(".real { background: url(./images/hero.png); }");
1108        assert!(names.contains(&"real".to_string()));
1109        assert!(!names.contains(&"png".to_string()));
1110    }
1111
1112    #[test]
1113    fn strip_css_block_comment() {
1114        let result = strip_css_comments("/* removed */ .kept { }", false);
1115        assert!(!result.contains("removed"));
1116        assert!(result.contains(".kept"));
1117    }
1118
1119    #[test]
1120    fn strip_scss_line_comment() {
1121        let result = strip_css_comments("// removed\n.kept { }", true);
1122        assert!(!result.contains("removed"));
1123        assert!(result.contains(".kept"));
1124    }
1125
1126    #[test]
1127    fn strip_scss_preserves_css_outside_comments() {
1128        let source = "// line comment\n/* block comment */\n.visible { color: red; }";
1129        let result = strip_css_comments(source, true);
1130        assert!(result.contains(".visible"));
1131    }
1132
1133    #[test]
1134    fn url_import_http() {
1135        assert!(is_css_url_import("http://example.com/style.css"));
1136    }
1137
1138    #[test]
1139    fn url_import_https() {
1140        assert!(is_css_url_import("https://fonts.googleapis.com/css"));
1141    }
1142
1143    #[test]
1144    fn url_import_data() {
1145        assert!(is_css_url_import("data:text/css;base64,abc"));
1146    }
1147
1148    #[test]
1149    fn url_import_local_not_skipped() {
1150        assert!(!is_css_url_import("./local.css"));
1151    }
1152
1153    #[test]
1154    fn url_import_bare_specifier_not_skipped() {
1155        assert!(!is_css_url_import("tailwindcss"));
1156    }
1157
1158    #[test]
1159    fn normalize_relative_dot_path_unchanged() {
1160        assert_eq!(
1161            normalize_css_import_path("./reset.css".to_string(), false),
1162            "./reset.css"
1163        );
1164    }
1165
1166    #[test]
1167    fn normalize_parent_relative_path_unchanged() {
1168        assert_eq!(
1169            normalize_css_import_path("../shared.scss".to_string(), false),
1170            "../shared.scss"
1171        );
1172    }
1173
1174    #[test]
1175    fn normalize_absolute_path_unchanged() {
1176        assert_eq!(
1177            normalize_css_import_path("/styles/main.css".to_string(), false),
1178            "/styles/main.css"
1179        );
1180    }
1181
1182    #[test]
1183    fn normalize_url_unchanged() {
1184        assert_eq!(
1185            normalize_css_import_path("https://example.com/style.css".to_string(), false),
1186            "https://example.com/style.css"
1187        );
1188    }
1189
1190    #[test]
1191    fn normalize_bare_css_gets_dot_slash() {
1192        assert_eq!(
1193            normalize_css_import_path("app.css".to_string(), false),
1194            "./app.css"
1195        );
1196    }
1197
1198    #[test]
1199    fn normalize_css_package_subpath_stays_bare() {
1200        assert_eq!(
1201            normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
1202            "tailwindcss/theme.css"
1203        );
1204    }
1205
1206    #[test]
1207    fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
1208        assert_eq!(
1209            normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
1210            "highlight.js/styles/github.css"
1211        );
1212    }
1213
1214    #[test]
1215    fn normalize_bare_scss_gets_dot_slash() {
1216        assert_eq!(
1217            normalize_css_import_path("vars.scss".to_string(), false),
1218            "./vars.scss"
1219        );
1220    }
1221
1222    #[test]
1223    fn normalize_bare_sass_gets_dot_slash() {
1224        assert_eq!(
1225            normalize_css_import_path("main.sass".to_string(), false),
1226            "./main.sass"
1227        );
1228    }
1229
1230    #[test]
1231    fn normalize_bare_less_gets_dot_slash() {
1232        assert_eq!(
1233            normalize_css_import_path("theme.less".to_string(), false),
1234            "./theme.less"
1235        );
1236    }
1237
1238    #[test]
1239    fn normalize_bare_js_extension_stays_bare() {
1240        assert_eq!(
1241            normalize_css_import_path("module.js".to_string(), false),
1242            "module.js"
1243        );
1244    }
1245
1246    #[test]
1247    fn normalize_scss_bare_partial_gets_dot_slash() {
1248        assert_eq!(
1249            normalize_css_import_path("variables".to_string(), true),
1250            "./variables"
1251        );
1252    }
1253
1254    #[test]
1255    fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
1256        assert_eq!(
1257            normalize_css_import_path("base/reset".to_string(), true),
1258            "./base/reset"
1259        );
1260    }
1261
1262    #[test]
1263    fn normalize_scss_builtin_stays_bare() {
1264        assert_eq!(
1265            normalize_css_import_path("sass:math".to_string(), true),
1266            "sass:math"
1267        );
1268    }
1269
1270    #[test]
1271    fn normalize_scss_relative_path_unchanged() {
1272        assert_eq!(
1273            normalize_css_import_path("../styles/variables".to_string(), true),
1274            "../styles/variables"
1275        );
1276    }
1277
1278    #[test]
1279    fn normalize_css_bare_extensionless_stays_bare() {
1280        assert_eq!(
1281            normalize_css_import_path("tailwindcss".to_string(), false),
1282            "tailwindcss"
1283        );
1284    }
1285
1286    #[test]
1287    fn normalize_scoped_package_with_css_extension_stays_bare() {
1288        assert_eq!(
1289            normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
1290            "@fontsource/monaspace-neon/400.css"
1291        );
1292    }
1293
1294    #[test]
1295    fn normalize_scoped_package_with_scss_extension_stays_bare() {
1296        assert_eq!(
1297            normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
1298            "@company/design-system/tokens.scss"
1299        );
1300    }
1301
1302    #[test]
1303    fn normalize_scoped_package_without_extension_stays_bare() {
1304        assert_eq!(
1305            normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
1306            "@fallow/design-system/styles"
1307        );
1308    }
1309
1310    #[test]
1311    fn normalize_scoped_package_extensionless_scss_stays_bare() {
1312        assert_eq!(
1313            normalize_css_import_path("@company/tokens".to_string(), true),
1314            "@company/tokens"
1315        );
1316    }
1317
1318    #[test]
1319    fn normalize_path_alias_with_css_extension_stays_bare() {
1320        assert_eq!(
1321            normalize_css_import_path("@/components/Button.css".to_string(), false),
1322            "@/components/Button.css"
1323        );
1324    }
1325
1326    #[test]
1327    fn normalize_path_alias_extensionless_stays_bare() {
1328        assert_eq!(
1329            normalize_css_import_path("@/styles/variables".to_string(), false),
1330            "@/styles/variables"
1331        );
1332    }
1333
1334    #[test]
1335    fn strip_css_no_comments() {
1336        let source = ".foo { color: red; }";
1337        assert_eq!(strip_css_comments(source, false), source);
1338    }
1339
1340    #[test]
1341    fn strip_css_multiple_block_comments() {
1342        let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
1343        let result = strip_css_comments(source, false);
1344        assert!(!result.contains("comment-one"));
1345        assert!(!result.contains("comment-two"));
1346        assert!(result.contains(".foo"));
1347        assert!(result.contains(".bar"));
1348    }
1349
1350    #[test]
1351    fn strip_scss_does_not_affect_non_scss() {
1352        let source = "// this stays\n.foo { }";
1353        let result = strip_css_comments(source, false);
1354        assert!(result.contains("// this stays"));
1355    }
1356
1357    #[test]
1358    fn css_module_parses_suppressions() {
1359        let info = parse_css_to_module(
1360            fallow_types::discover::FileId(0),
1361            Path::new("Component.module.css"),
1362            "/* fallow-ignore-file */\n.btn { color: red; }",
1363            0,
1364        );
1365        assert!(!info.suppressions.is_empty());
1366        assert_eq!(info.suppressions[0].line, 0);
1367    }
1368
1369    #[test]
1370    fn extracts_class_starting_with_underscore() {
1371        let names = export_names("._private { } .__dunder { }");
1372        assert!(names.contains(&"_private".to_string()));
1373        assert!(names.contains(&"__dunder".to_string()));
1374    }
1375
1376    #[test]
1377    fn ignores_id_selectors() {
1378        let names = export_names("#myId { color: red; }");
1379        assert!(!names.contains(&"myId".to_string()));
1380    }
1381
1382    #[test]
1383    fn ignores_element_selectors() {
1384        let names = export_names("div { color: red; } span { }");
1385        assert!(names.is_empty());
1386    }
1387
1388    #[test]
1389    fn extract_css_imports_at_import_quoted() {
1390        let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
1391        assert_eq!(imports, vec!["./reset.css"]);
1392    }
1393
1394    #[test]
1395    fn extract_css_imports_package_subpath_stays_bare() {
1396        let imports =
1397            extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
1398        assert_eq!(imports, vec!["tailwindcss/theme.css"]);
1399    }
1400
1401    #[test]
1402    fn extract_css_imports_at_import_url() {
1403        let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
1404        assert_eq!(imports, vec!["./reset.css"]);
1405    }
1406
1407    #[test]
1408    fn extract_css_imports_skips_remote_urls() {
1409        let imports =
1410            extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
1411        assert!(imports.is_empty());
1412    }
1413
1414    #[test]
1415    fn extract_css_imports_scss_use_normalizes_partial() {
1416        let imports = extract_css_imports(r#"@use "variables";"#, true);
1417        assert_eq!(imports, vec!["./variables"]);
1418    }
1419
1420    #[test]
1421    fn extract_css_imports_scss_forward_normalizes_partial() {
1422        let imports = extract_css_imports(r#"@forward "tokens";"#, true);
1423        assert_eq!(imports, vec!["./tokens"]);
1424    }
1425
1426    #[test]
1427    fn extract_css_imports_skips_comments() {
1428        let imports = extract_css_imports(
1429            r#"/* @import "./hidden.scss"; */
1430@use "real";"#,
1431            true,
1432        );
1433        assert_eq!(imports, vec!["./real"]);
1434    }
1435
1436    #[test]
1437    fn extract_css_imports_at_plugin_keeps_package_bare() {
1438        let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1439        assert_eq!(imports, vec!["daisyui"]);
1440    }
1441
1442    #[test]
1443    fn extract_css_imports_at_plugin_tracks_relative_file() {
1444        let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1445        assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1446    }
1447
1448    #[test]
1449    fn extract_css_imports_scss_at_import_kept_relative() {
1450        let imports = extract_css_imports(r"@import 'Foo';", true);
1451        assert_eq!(imports, vec!["./Foo"]);
1452    }
1453
1454    #[test]
1455    fn extract_css_imports_additional_data_string_body() {
1456        let body = r#"@use "./src/styles/global.scss";"#;
1457        let imports = extract_css_imports(body, true);
1458        assert_eq!(imports, vec!["./src/styles/global.scss"]);
1459    }
1460
1461    #[test]
1462    fn mask_with_whitespace_preserves_byte_length() {
1463        let src = "/* hello */ .foo { }";
1464        let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1465        assert_eq!(masked.len(), src.len());
1466        assert!(masked.is_char_boundary(src.len()));
1467    }
1468
1469    #[test]
1470    fn mask_with_whitespace_preserves_offsets_around_multibyte() {
1471        let src = "/* \u{2713} */ .foo { }";
1472        let foo_offset = src.find(".foo").expect("`.foo` present");
1473        let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1474        assert_eq!(masked.len(), src.len());
1475        assert_eq!(masked.find(".foo"), Some(foo_offset));
1476    }
1477
1478    /// Resolve a span's start to (line, col) using the same primitives the
1479    /// downstream pipeline uses in `crates/core/src/analyze/unused_exports.rs`.
1480    fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1481        let offsets = fallow_types::extract::compute_line_offsets(source);
1482        fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1483    }
1484
1485    #[test]
1486    fn span_points_at_real_class_declaration_line() {
1487        let source = "\n\n\n\n.foo { color: red; }\n";
1488        let exports = extract_css_module_exports(source, false);
1489        assert_eq!(exports.len(), 1);
1490        let span = exports[0].span;
1491        let (line, col) = span_line_col(source, span.start);
1492        assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1493        assert_eq!(
1494            col, 1,
1495            "column points at `f` in `.foo` (post-dot identifier)"
1496        );
1497        assert_eq!(
1498            &source[span.start as usize..span.end as usize],
1499            "foo",
1500            "span range must slice to the class identifier in the original source"
1501        );
1502    }
1503
1504    #[test]
1505    fn span_survives_multibyte_comment_prefix() {
1506        let source = "/* \u{2713} */\n.foo { }";
1507        let exports = extract_css_module_exports(source, false);
1508        assert_eq!(exports.len(), 1);
1509        let span = exports[0].span;
1510        assert!(
1511            source.is_char_boundary(span.start as usize),
1512            "span.start must lie on a UTF-8 char boundary"
1513        );
1514        assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1515    }
1516
1517    #[test]
1518    fn span_skips_at_layer_prelude_dot_segments() {
1519        let source = "@layer foo.bar { }\n.root { }\n";
1520        let exports = extract_css_module_exports(source, false);
1521        let names: Vec<_> = exports
1522            .iter()
1523            .filter_map(|e| match &e.name {
1524                ExportName::Named(n) => Some(n.as_str()),
1525                ExportName::Default => None,
1526            })
1527            .collect();
1528        assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1529        let span = exports[0].span;
1530        let (line, _col) = span_line_col(source, span.start);
1531        assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1532        assert_eq!(&source[span.start as usize..span.end as usize], "root");
1533    }
1534
1535    #[test]
1536    fn span_skips_classes_in_strings() {
1537        let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1538        let exports = extract_css_module_exports(source, false);
1539        let names: Vec<_> = exports
1540            .iter()
1541            .filter_map(|e| match &e.name {
1542                ExportName::Named(n) => Some(n.as_str()),
1543                ExportName::Default => None,
1544            })
1545            .collect();
1546        assert_eq!(names, vec!["real", "also-real"]);
1547        for export in &exports {
1548            let span = export.span;
1549            let slice = &source[span.start as usize..span.end as usize];
1550            match &export.name {
1551                ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1552                ExportName::Default => unreachable!("CSS modules emit only named exports"),
1553            }
1554        }
1555    }
1556
1557    #[test]
1558    fn span_deduplicates_to_first_occurrence() {
1559        let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1560        let exports = extract_css_module_exports(source, false);
1561        assert_eq!(exports.len(), 1);
1562        let (line, _col) = span_line_col(source, exports[0].span.start);
1563        assert_eq!(
1564            line, 1,
1565            "first occurrence wins for deduplicated class names"
1566        );
1567    }
1568
1569    #[test]
1570    fn span_inside_media_query() {
1571        let source =
1572            "@media (max-width: 768px) {\n  .mobile { display: block; }\n  .desktop { }\n}\n";
1573        let exports = extract_css_module_exports(source, false);
1574        let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
1575            .iter()
1576            .filter_map(|e| match &e.name {
1577                ExportName::Named(n) => Some((n.as_str(), e.span)),
1578                ExportName::Default => None,
1579            })
1580            .collect();
1581        let mobile_line = span_line_col(source, by_name["mobile"].start).0;
1582        let desktop_line = span_line_col(source, by_name["desktop"].start).0;
1583        assert_eq!(mobile_line, 2);
1584        assert_eq!(desktop_line, 3);
1585    }
1586
1587    #[test]
1588    fn at_layer_only_module_emits_no_exports() {
1589        let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
1590        assert!(exports.is_empty());
1591    }
1592
1593    #[test]
1594    fn parse_css_to_module_resolves_real_line_offsets() {
1595        let source = "\n\n\n\n.foo { color: red; }\n";
1596        let info = parse_css_to_module(
1597            fallow_types::discover::FileId(0),
1598            Path::new("Component.module.css"),
1599            source,
1600            0,
1601        );
1602        assert_eq!(info.exports.len(), 1);
1603        let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
1604            &info.line_offsets,
1605            info.exports[0].span.start,
1606        );
1607        assert_eq!(line, 5, "downstream line must equal the source line");
1608    }
1609
1610    fn theme_token_names(source: &str) -> Vec<String> {
1611        scan_theme_blocks(source)
1612            .tokens
1613            .into_iter()
1614            .map(|t| t.name)
1615            .collect()
1616    }
1617
1618    #[test]
1619    fn theme_single_block_collects_tokens() {
1620        let names = theme_token_names("@theme { --color-brand: #f00; --radius-card: 8px; }");
1621        assert_eq!(names, vec!["color-brand", "radius-card"]);
1622    }
1623
1624    #[test]
1625    fn theme_dashed_multi_segment_names() {
1626        let names = theme_token_names(
1627            "@theme {\n  --font-weight-heavy: 900;\n  --inset-shadow-glow: 0 0 4px red;\n}",
1628        );
1629        assert_eq!(names, vec!["font-weight-heavy", "inset-shadow-glow"]);
1630    }
1631
1632    #[test]
1633    fn theme_inline_and_static_modifiers() {
1634        assert_eq!(
1635            theme_token_names("@theme inline { --color-a: red; }"),
1636            vec!["color-a"]
1637        );
1638        assert_eq!(
1639            theme_token_names("@theme static { --color-b: red; }"),
1640            vec!["color-b"]
1641        );
1642    }
1643
1644    #[test]
1645    fn theme_multiple_blocks_union() {
1646        let names = theme_token_names(
1647            "@theme { --color-a: red; }\n.x { color: blue; }\n@theme { --spacing-gutter: 1rem; }",
1648        );
1649        assert_eq!(names, vec!["color-a", "spacing-gutter"]);
1650    }
1651
1652    #[test]
1653    fn theme_reset_form_excluded() {
1654        // `--color-*: initial` is a namespace reset directive, not a token.
1655        let names = theme_token_names("@theme { --color-*: initial; --color-brand: red; }");
1656        assert_eq!(names, vec!["color-brand"]);
1657    }
1658
1659    #[test]
1660    fn theme_no_block_yields_nothing() {
1661        assert!(theme_token_names(".x { --color-brand: red; }").is_empty());
1662    }
1663
1664    #[test]
1665    fn theme_line_numbers() {
1666        let scan = scan_theme_blocks("@theme {\n  --color-a: red;\n  --radius-b: 4px;\n}");
1667        assert_eq!(scan.tokens[0].line, 2);
1668        assert_eq!(scan.tokens[1].line, 3);
1669    }
1670
1671    #[test]
1672    fn theme_token_backs_token_via_var() {
1673        let scan = scan_theme_blocks(
1674            "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
1675        );
1676        assert!(scan.theme_var_reads.contains(&"color-brand".to_string()));
1677    }
1678
1679    #[test]
1680    fn theme_nested_keyframes_body_not_collected() {
1681        // `@keyframes` inside `@theme` (for `--animate-*`) must not surface its
1682        // step selectors or interior as theme tokens.
1683        let names = theme_token_names(
1684            "@theme {\n  --animate-spin: spin 1s linear infinite;\n  @keyframes spin { from { --x: 0; } to { --y: 1; } }\n}",
1685        );
1686        assert_eq!(names, vec!["animate-spin"]);
1687    }
1688
1689    #[test]
1690    fn theme_comment_block_ignored() {
1691        let names = theme_token_names("/* @theme { --color-fake: red; } */ .x { color: blue; }");
1692        assert!(names.is_empty(), "got {names:?}");
1693    }
1694
1695    #[test]
1696    fn theme_deduplicates_repeated_token() {
1697        let names = theme_token_names("@theme { --color-a: red; --color-a: blue; }");
1698        assert_eq!(names, vec!["color-a"]);
1699    }
1700
1701    #[test]
1702    fn apply_tokens_basic() {
1703        let tokens = extract_apply_tokens(".panel { @apply rounded-card font-bold; }");
1704        assert_eq!(tokens, vec!["rounded-card", "font-bold"]);
1705    }
1706
1707    #[test]
1708    fn apply_tokens_strips_important() {
1709        let tokens = extract_apply_tokens(".x { @apply text-brand! font-bold !important; }");
1710        assert_eq!(tokens, vec!["text-brand", "font-bold"]);
1711    }
1712
1713    #[test]
1714    fn apply_tokens_ignored_in_comments() {
1715        let tokens = extract_apply_tokens("/* @apply hidden-token; */ .x { color: red; }");
1716        assert!(tokens.is_empty(), "got {tokens:?}");
1717    }
1718}