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
6use std::path::Path;
7use std::sync::LazyLock;
8
9use oxc_span::Span;
10
11use crate::{ExportInfo, ExportName, ImportInfo, ImportedName, ModuleInfo, VisibilityTag};
12use fallow_types::discover::FileId;
13
14/// Regex to extract CSS @import sources.
15/// Matches: @import "path"; @import 'path'; @import url("path"); @import url('path'); @import url(path);
16static CSS_IMPORT_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
17    regex::Regex::new(r#"@import\s+(?:url\(\s*(?:["']([^"']+)["']|([^)]+))\s*\)|["']([^"']+)["'])"#)
18        .expect("valid regex")
19});
20
21/// Regex to extract SCSS @use and @forward sources.
22/// Matches: @use "path"; @use 'path'; @forward "path"; @forward 'path';
23static SCSS_USE_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
24    regex::Regex::new(r#"@(?:use|forward)\s+["']([^"']+)["']"#).expect("valid regex")
25});
26
27/// Regex to extract Tailwind CSS @plugin sources.
28/// Matches: @plugin "package"; @plugin 'package'; @plugin "./local-plugin.js";
29static CSS_PLUGIN_RE: LazyLock<regex::Regex> =
30    LazyLock::new(|| regex::Regex::new(r#"@plugin\s+["']([^"']+)["']"#).expect("valid regex"));
31
32/// Regex to extract @apply class references.
33/// Matches: @apply class1 class2 class3;
34static CSS_APPLY_RE: LazyLock<regex::Regex> =
35    LazyLock::new(|| regex::Regex::new(r"@apply\s+[^;}\n]+").expect("valid regex"));
36
37/// Regex to extract @tailwind directives.
38/// Matches: @tailwind base; @tailwind components; @tailwind utilities;
39static CSS_TAILWIND_RE: LazyLock<regex::Regex> =
40    LazyLock::new(|| regex::Regex::new(r"@tailwind\s+\w+").expect("valid regex"));
41
42/// Regex to match CSS block comments (`/* ... */`) for stripping before extraction.
43static CSS_COMMENT_RE: LazyLock<regex::Regex> =
44    LazyLock::new(|| regex::Regex::new(r"(?s)/\*.*?\*/").expect("valid regex"));
45
46/// Regex to match SCSS single-line comments (`// ...`) for stripping before extraction.
47static SCSS_LINE_COMMENT_RE: LazyLock<regex::Regex> =
48    LazyLock::new(|| regex::Regex::new(r"//[^\n]*").expect("valid regex"));
49
50/// Regex to extract CSS class names from selectors.
51/// Matches `.className` in selectors. Applied after stripping comments, strings, and URLs.
52static CSS_CLASS_RE: LazyLock<regex::Regex> =
53    LazyLock::new(|| regex::Regex::new(r"\.([a-zA-Z_][a-zA-Z0-9_-]*)").expect("valid regex"));
54
55/// Regex to strip quoted strings and `url(...)` content from CSS before class extraction.
56/// Prevents false positives from `content: ".foo"` and `url(./path/file.ext)`.
57static CSS_NON_SELECTOR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
58    regex::Regex::new(r#"(?s)"[^"]*"|'[^']*'|url\([^)]*\)"#).expect("valid regex")
59});
60
61pub(crate) fn is_css_file(path: &Path) -> bool {
62    path.extension()
63        .and_then(|e| e.to_str())
64        .is_some_and(|ext| ext == "css" || ext == "scss")
65}
66
67/// A CSS import source with both the literal source and fallow's resolver-normalized form.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct CssImportSource {
70    /// The import source exactly as it appeared in `@import` / `@use` / `@forward` / `@plugin`.
71    pub raw: String,
72    /// The source normalized for fallow's resolver (`variables` -> `./variables` in SCSS).
73    pub normalized: String,
74    /// Whether this source came from Tailwind CSS `@plugin`.
75    pub is_plugin: bool,
76}
77
78fn is_css_module_file(path: &Path) -> bool {
79    is_css_file(path)
80        && path
81            .file_stem()
82            .and_then(|s| s.to_str())
83            .is_some_and(|stem| stem.ends_with(".module"))
84}
85
86/// Returns true if a CSS import source is a remote URL or data URI that should be skipped.
87fn is_css_url_import(source: &str) -> bool {
88    source.starts_with("http://") || source.starts_with("https://") || source.starts_with("data:")
89}
90
91/// Normalize a CSS/SCSS import path to use `./` prefix for relative paths.
92/// Bare file names such as `reset.css` stay relative for CSS ergonomics, while
93/// package subpaths such as `tailwindcss/theme.css` stay bare so bundler-style
94/// package CSS imports resolve through `node_modules`.
95///
96/// When `is_scss` is true, extensionless specifiers that are not SCSS built-in
97/// modules (`sass:*`) are treated as relative imports (SCSS partial convention).
98/// This handles `@use 'variables'` resolving to `./_variables.scss`.
99///
100/// Scoped npm packages (`@scope/pkg`) are always kept bare, even when they have
101/// CSS extensions (e.g., `@fontsource/monaspace-neon/400.css`). Bundlers like
102/// Vite resolve these from node_modules, not as relative paths.
103fn normalize_css_import_path(path: String, is_scss: bool) -> String {
104    if path.starts_with('.') || path.starts_with('/') || path.contains("://") {
105        return path;
106    }
107    // Scoped npm packages (`@scope/...`) are always bare specifiers resolved
108    // from node_modules, regardless of file extension.
109    if path.starts_with('@') && path.contains('/') {
110        return path;
111    }
112    let path_ref = std::path::Path::new(&path);
113    if !is_scss
114        && path.contains('/')
115        && path_ref
116            .extension()
117            .and_then(|e| e.to_str())
118            .is_some_and(is_style_extension)
119    {
120        return path;
121    }
122    // Bare filenames with CSS/SCSS extensions are relative file imports.
123    let ext = std::path::Path::new(&path)
124        .extension()
125        .and_then(|e| e.to_str());
126    match ext {
127        Some(e) if is_style_extension(e) => format!("./{path}"),
128        _ => {
129            // In SCSS, extensionless bare specifiers like `@use 'variables'` are
130            // local partials, not npm packages. SCSS built-in modules (`sass:math`,
131            // `sass:color`) use a colon prefix and should stay bare.
132            if is_scss && !path.contains(':') {
133                format!("./{path}")
134            } else {
135                path
136            }
137        }
138    }
139}
140
141fn is_style_extension(ext: &str) -> bool {
142    ext.eq_ignore_ascii_case("css")
143        || ext.eq_ignore_ascii_case("scss")
144        || ext.eq_ignore_ascii_case("sass")
145        || ext.eq_ignore_ascii_case("less")
146}
147
148/// Strip comments from CSS/SCSS source to avoid matching directives inside comments.
149fn strip_css_comments(source: &str, is_scss: bool) -> String {
150    let stripped = CSS_COMMENT_RE.replace_all(source, "");
151    if is_scss {
152        SCSS_LINE_COMMENT_RE.replace_all(&stripped, "").into_owned()
153    } else {
154        stripped.into_owned()
155    }
156}
157
158/// Normalize a Tailwind CSS `@plugin` target.
159///
160/// Unlike SCSS `@use`, extensionless targets such as `daisyui` are package
161/// specifiers, not local partials. Keep bare specifiers bare and only preserve
162/// explicit relative/root-relative paths.
163fn normalize_css_plugin_path(path: String) -> String {
164    path
165}
166
167/// Extract `@import` / `@use` / `@forward` / `@plugin` source paths from a CSS/SCSS string.
168///
169/// Returns both the raw source and the normalized source. URL imports
170/// (`http://`, `https://`, `data:`) are skipped. Use [`extract_css_imports`]
171/// when only the normalized form is needed.
172#[must_use]
173pub fn extract_css_import_sources(source: &str, is_scss: bool) -> Vec<CssImportSource> {
174    let stripped = strip_css_comments(source, is_scss);
175    let mut out = Vec::new();
176
177    for cap in CSS_IMPORT_RE.captures_iter(&stripped) {
178        let raw = cap
179            .get(1)
180            .or_else(|| cap.get(2))
181            .or_else(|| cap.get(3))
182            .map(|m| m.as_str().trim().to_string());
183        if let Some(src) = raw
184            && !src.is_empty()
185            && !is_css_url_import(&src)
186        {
187            out.push(CssImportSource {
188                normalized: normalize_css_import_path(src.clone(), is_scss),
189                raw: src,
190                is_plugin: false,
191            });
192        }
193    }
194
195    if is_scss {
196        for cap in SCSS_USE_RE.captures_iter(&stripped) {
197            if let Some(m) = cap.get(1) {
198                let raw = m.as_str().to_string();
199                out.push(CssImportSource {
200                    normalized: normalize_css_import_path(raw.clone(), true),
201                    raw,
202                    is_plugin: false,
203                });
204            }
205        }
206    }
207
208    for cap in CSS_PLUGIN_RE.captures_iter(&stripped) {
209        if let Some(m) = cap.get(1) {
210            let raw = m.as_str().trim().to_string();
211            if !raw.is_empty() && !is_css_url_import(&raw) {
212                out.push(CssImportSource {
213                    normalized: normalize_css_plugin_path(raw.clone()),
214                    raw,
215                    is_plugin: true,
216                });
217            }
218        }
219    }
220
221    out
222}
223
224/// Extract normalized `@import` / `@use` / `@forward` / `@plugin` source paths from a CSS/SCSS string.
225///
226/// Returns specifiers normalized via `normalize_css_import_path`. URL imports
227/// (`http://`, `https://`, `data:`) are skipped. Used by callers that only need
228/// entry/dependency source paths; callers that need import kind information
229/// should use [`extract_css_import_sources`].
230#[must_use]
231pub fn extract_css_imports(source: &str, is_scss: bool) -> Vec<String> {
232    extract_css_import_sources(source, is_scss)
233        .into_iter()
234        .map(|source| source.normalized)
235        .collect()
236}
237
238/// Extract class names from a CSS module file as named exports.
239pub fn extract_css_module_exports(source: &str) -> Vec<ExportInfo> {
240    let cleaned = CSS_NON_SELECTOR_RE.replace_all(source, "");
241    let mut seen = rustc_hash::FxHashSet::default();
242    let mut exports = Vec::new();
243    for cap in CSS_CLASS_RE.captures_iter(&cleaned) {
244        if let Some(m) = cap.get(1) {
245            let class_name = m.as_str().to_string();
246            if seen.insert(class_name.clone()) {
247                exports.push(ExportInfo {
248                    name: ExportName::Named(class_name),
249                    local_name: None,
250                    is_type_only: false,
251                    visibility: VisibilityTag::None,
252                    span: Span::default(),
253                    members: Vec::new(),
254                    is_side_effect_used: false,
255                    super_class: None,
256                });
257            }
258        }
259    }
260    exports
261}
262
263/// Parse a CSS/SCSS file, extracting @import, @use, @forward, @plugin, @apply, and @tailwind directives.
264pub(crate) fn parse_css_to_module(
265    file_id: FileId,
266    path: &Path,
267    source: &str,
268    content_hash: u64,
269) -> ModuleInfo {
270    let suppressions = crate::suppress::parse_suppressions_from_source(source);
271    let is_scss = path
272        .extension()
273        .and_then(|e| e.to_str())
274        .is_some_and(|ext| ext == "scss");
275
276    // Strip comments before matching to avoid false positives from commented-out code.
277    let stripped = strip_css_comments(source, is_scss);
278
279    let mut imports = Vec::new();
280
281    // Extract @import statements
282    for cap in CSS_IMPORT_RE.captures_iter(&stripped) {
283        let source_path = cap
284            .get(1)
285            .or_else(|| cap.get(2))
286            .or_else(|| cap.get(3))
287            .map(|m| m.as_str().trim().to_string());
288        if let Some(src) = source_path
289            && !src.is_empty()
290            && !is_css_url_import(&src)
291        {
292            // CSS/SCSS @import resolves relative paths without ./ prefix,
293            // so normalize to ./ to avoid bare-specifier misclassification
294            let src = normalize_css_import_path(src, is_scss);
295            imports.push(ImportInfo {
296                source: src,
297                imported_name: ImportedName::SideEffect,
298                local_name: String::new(),
299                is_type_only: false,
300                from_style: false,
301                span: Span::default(),
302                source_span: Span::default(),
303            });
304        }
305    }
306
307    // Extract SCSS @use/@forward statements
308    if is_scss {
309        for cap in SCSS_USE_RE.captures_iter(&stripped) {
310            if let Some(m) = cap.get(1) {
311                imports.push(ImportInfo {
312                    source: normalize_css_import_path(m.as_str().to_string(), true),
313                    imported_name: ImportedName::SideEffect,
314                    local_name: String::new(),
315                    is_type_only: false,
316                    from_style: false,
317                    span: Span::default(),
318                    source_span: Span::default(),
319                });
320            }
321        }
322    }
323
324    // Extract Tailwind CSS @plugin directives. These can reference npm packages
325    // (e.g. `@plugin "daisyui"`) or explicit local plugin files.
326    for cap in CSS_PLUGIN_RE.captures_iter(&stripped) {
327        if let Some(m) = cap.get(1) {
328            let source = m.as_str().trim().to_string();
329            if !source.is_empty() && !is_css_url_import(&source) {
330                imports.push(ImportInfo {
331                    source: normalize_css_plugin_path(source),
332                    imported_name: ImportedName::Default,
333                    local_name: String::new(),
334                    is_type_only: false,
335                    from_style: false,
336                    span: Span::default(),
337                    source_span: Span::default(),
338                });
339            }
340        }
341    }
342
343    // If @apply or @tailwind directives exist, create a synthetic import to tailwindcss
344    // to mark the dependency as used
345    let has_apply = CSS_APPLY_RE.is_match(&stripped);
346    let has_tailwind = CSS_TAILWIND_RE.is_match(&stripped);
347    if has_apply || has_tailwind {
348        imports.push(ImportInfo {
349            source: "tailwindcss".to_string(),
350            imported_name: ImportedName::SideEffect,
351            local_name: String::new(),
352            is_type_only: false,
353            from_style: false,
354            span: Span::default(),
355            source_span: Span::default(),
356        });
357    }
358
359    // For CSS module files, extract class names as named exports
360    let exports = if is_css_module_file(path) {
361        extract_css_module_exports(&stripped)
362    } else {
363        Vec::new()
364    };
365
366    ModuleInfo {
367        file_id,
368        exports,
369        imports,
370        re_exports: Vec::new(),
371        dynamic_imports: Vec::new(),
372        dynamic_import_patterns: Vec::new(),
373        require_calls: Vec::new(),
374        member_accesses: Vec::new(),
375        whole_object_uses: Vec::new(),
376        has_cjs_exports: false,
377        has_angular_component_template_url: false,
378        content_hash,
379        suppressions,
380        unused_import_bindings: Vec::new(),
381        type_referenced_import_bindings: Vec::new(),
382        value_referenced_import_bindings: Vec::new(),
383        line_offsets: fallow_types::extract::compute_line_offsets(source),
384        complexity: Vec::new(),
385        flag_uses: Vec::new(),
386        class_heritage: vec![],
387        local_type_declarations: Vec::new(),
388        public_signature_type_references: Vec::new(),
389        namespace_object_aliases: Vec::new(),
390    }
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396
397    /// Helper to collect export names as strings from `extract_css_module_exports`.
398    fn export_names(source: &str) -> Vec<String> {
399        extract_css_module_exports(source)
400            .into_iter()
401            .filter_map(|e| match e.name {
402                ExportName::Named(n) => Some(n),
403                ExportName::Default => None,
404            })
405            .collect()
406    }
407
408    // ── is_css_file ──────────────────────────────────────────────
409
410    #[test]
411    fn is_css_file_css() {
412        assert!(is_css_file(Path::new("styles.css")));
413    }
414
415    #[test]
416    fn is_css_file_scss() {
417        assert!(is_css_file(Path::new("styles.scss")));
418    }
419
420    #[test]
421    fn is_css_file_rejects_js() {
422        assert!(!is_css_file(Path::new("app.js")));
423    }
424
425    #[test]
426    fn is_css_file_rejects_ts() {
427        assert!(!is_css_file(Path::new("app.ts")));
428    }
429
430    #[test]
431    fn is_css_file_rejects_less() {
432        assert!(!is_css_file(Path::new("styles.less")));
433    }
434
435    #[test]
436    fn is_css_file_rejects_no_extension() {
437        assert!(!is_css_file(Path::new("Makefile")));
438    }
439
440    // ── is_css_module_file ───────────────────────────────────────
441
442    #[test]
443    fn is_css_module_file_module_css() {
444        assert!(is_css_module_file(Path::new("Component.module.css")));
445    }
446
447    #[test]
448    fn is_css_module_file_module_scss() {
449        assert!(is_css_module_file(Path::new("Component.module.scss")));
450    }
451
452    #[test]
453    fn is_css_module_file_rejects_plain_css() {
454        assert!(!is_css_module_file(Path::new("styles.css")));
455    }
456
457    #[test]
458    fn is_css_module_file_rejects_plain_scss() {
459        assert!(!is_css_module_file(Path::new("styles.scss")));
460    }
461
462    #[test]
463    fn is_css_module_file_rejects_module_js() {
464        assert!(!is_css_module_file(Path::new("utils.module.js")));
465    }
466
467    // ── extract_css_module_exports: basic class extraction ───────
468
469    #[test]
470    fn extracts_single_class() {
471        let names = export_names(".foo { color: red; }");
472        assert_eq!(names, vec!["foo"]);
473    }
474
475    #[test]
476    fn extracts_multiple_classes() {
477        let names = export_names(".foo { } .bar { }");
478        assert_eq!(names, vec!["foo", "bar"]);
479    }
480
481    #[test]
482    fn extracts_nested_classes() {
483        let names = export_names(".foo .bar { color: red; }");
484        assert!(names.contains(&"foo".to_string()));
485        assert!(names.contains(&"bar".to_string()));
486    }
487
488    #[test]
489    fn extracts_hyphenated_class() {
490        let names = export_names(".my-class { }");
491        assert_eq!(names, vec!["my-class"]);
492    }
493
494    #[test]
495    fn extracts_camel_case_class() {
496        let names = export_names(".myClass { }");
497        assert_eq!(names, vec!["myClass"]);
498    }
499
500    #[test]
501    fn extracts_underscore_class() {
502        let names = export_names("._hidden { } .__wrapper { }");
503        assert!(names.contains(&"_hidden".to_string()));
504        assert!(names.contains(&"__wrapper".to_string()));
505    }
506
507    // ── Pseudo-selectors ─────────────────────────────────────────
508
509    #[test]
510    fn pseudo_selector_hover() {
511        let names = export_names(".foo:hover { color: blue; }");
512        assert_eq!(names, vec!["foo"]);
513    }
514
515    #[test]
516    fn pseudo_selector_focus() {
517        let names = export_names(".input:focus { outline: none; }");
518        assert_eq!(names, vec!["input"]);
519    }
520
521    #[test]
522    fn pseudo_element_before() {
523        let names = export_names(".icon::before { content: ''; }");
524        assert_eq!(names, vec!["icon"]);
525    }
526
527    #[test]
528    fn combined_pseudo_selectors() {
529        let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
530        // "btn" should be deduplicated
531        assert_eq!(names, vec!["btn"]);
532    }
533
534    // ── Media queries ────────────────────────────────────────────
535
536    #[test]
537    fn classes_inside_media_query() {
538        let names = export_names(
539            "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
540        );
541        assert!(names.contains(&"mobile-nav".to_string()));
542        assert!(names.contains(&"desktop-nav".to_string()));
543    }
544
545    // ── Deduplication ────────────────────────────────────────────
546
547    #[test]
548    fn deduplicates_repeated_class() {
549        let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
550        assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
551    }
552
553    // ── Edge cases ───────────────────────────────────────────────
554
555    #[test]
556    fn empty_source() {
557        let names = export_names("");
558        assert!(names.is_empty());
559    }
560
561    #[test]
562    fn no_classes() {
563        let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
564        assert!(names.is_empty());
565    }
566
567    #[test]
568    fn ignores_classes_in_block_comments() {
569        // Note: extract_css_module_exports itself does NOT strip comments;
570        // comments are stripped in parse_css_to_module before calling it.
571        // But CSS_NON_SELECTOR_RE strips quoted strings. Testing the
572        // strip_css_comments + extract pipeline via the stripped source:
573        let stripped = strip_css_comments("/* .fake { } */ .real { }", false);
574        let names = export_names(&stripped);
575        assert!(!names.contains(&"fake".to_string()));
576        assert!(names.contains(&"real".to_string()));
577    }
578
579    #[test]
580    fn ignores_classes_in_strings() {
581        let names = export_names(r#".real { content: ".fake"; }"#);
582        assert!(names.contains(&"real".to_string()));
583        assert!(!names.contains(&"fake".to_string()));
584    }
585
586    #[test]
587    fn ignores_classes_in_url() {
588        let names = export_names(".real { background: url(./images/hero.png); }");
589        assert!(names.contains(&"real".to_string()));
590        // "png" from "hero.png" should not be extracted
591        assert!(!names.contains(&"png".to_string()));
592    }
593
594    // ── strip_css_comments ───────────────────────────────────────
595
596    #[test]
597    fn strip_css_block_comment() {
598        let result = strip_css_comments("/* removed */ .kept { }", false);
599        assert!(!result.contains("removed"));
600        assert!(result.contains(".kept"));
601    }
602
603    #[test]
604    fn strip_scss_line_comment() {
605        let result = strip_css_comments("// removed\n.kept { }", true);
606        assert!(!result.contains("removed"));
607        assert!(result.contains(".kept"));
608    }
609
610    #[test]
611    fn strip_scss_preserves_css_outside_comments() {
612        let source = "// line comment\n/* block comment */\n.visible { color: red; }";
613        let result = strip_css_comments(source, true);
614        assert!(result.contains(".visible"));
615    }
616
617    // ── is_css_url_import ────────────────────────────────────────
618
619    #[test]
620    fn url_import_http() {
621        assert!(is_css_url_import("http://example.com/style.css"));
622    }
623
624    #[test]
625    fn url_import_https() {
626        assert!(is_css_url_import("https://fonts.googleapis.com/css"));
627    }
628
629    #[test]
630    fn url_import_data() {
631        assert!(is_css_url_import("data:text/css;base64,abc"));
632    }
633
634    #[test]
635    fn url_import_local_not_skipped() {
636        assert!(!is_css_url_import("./local.css"));
637    }
638
639    #[test]
640    fn url_import_bare_specifier_not_skipped() {
641        assert!(!is_css_url_import("tailwindcss"));
642    }
643
644    // ── normalize_css_import_path ─────────────────────────────────
645
646    #[test]
647    fn normalize_relative_dot_path_unchanged() {
648        assert_eq!(
649            normalize_css_import_path("./reset.css".to_string(), false),
650            "./reset.css"
651        );
652    }
653
654    #[test]
655    fn normalize_parent_relative_path_unchanged() {
656        assert_eq!(
657            normalize_css_import_path("../shared.scss".to_string(), false),
658            "../shared.scss"
659        );
660    }
661
662    #[test]
663    fn normalize_absolute_path_unchanged() {
664        assert_eq!(
665            normalize_css_import_path("/styles/main.css".to_string(), false),
666            "/styles/main.css"
667        );
668    }
669
670    #[test]
671    fn normalize_url_unchanged() {
672        assert_eq!(
673            normalize_css_import_path("https://example.com/style.css".to_string(), false),
674            "https://example.com/style.css"
675        );
676    }
677
678    #[test]
679    fn normalize_bare_css_gets_dot_slash() {
680        assert_eq!(
681            normalize_css_import_path("app.css".to_string(), false),
682            "./app.css"
683        );
684    }
685
686    #[test]
687    fn normalize_css_package_subpath_stays_bare() {
688        assert_eq!(
689            normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
690            "tailwindcss/theme.css"
691        );
692    }
693
694    #[test]
695    fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
696        assert_eq!(
697            normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
698            "highlight.js/styles/github.css"
699        );
700    }
701
702    #[test]
703    fn normalize_bare_scss_gets_dot_slash() {
704        assert_eq!(
705            normalize_css_import_path("vars.scss".to_string(), false),
706            "./vars.scss"
707        );
708    }
709
710    #[test]
711    fn normalize_bare_sass_gets_dot_slash() {
712        assert_eq!(
713            normalize_css_import_path("main.sass".to_string(), false),
714            "./main.sass"
715        );
716    }
717
718    #[test]
719    fn normalize_bare_less_gets_dot_slash() {
720        assert_eq!(
721            normalize_css_import_path("theme.less".to_string(), false),
722            "./theme.less"
723        );
724    }
725
726    #[test]
727    fn normalize_bare_js_extension_stays_bare() {
728        assert_eq!(
729            normalize_css_import_path("module.js".to_string(), false),
730            "module.js"
731        );
732    }
733
734    // ── SCSS partial normalization ───────────────────────────────
735
736    #[test]
737    fn normalize_scss_bare_partial_gets_dot_slash() {
738        assert_eq!(
739            normalize_css_import_path("variables".to_string(), true),
740            "./variables"
741        );
742    }
743
744    #[test]
745    fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
746        assert_eq!(
747            normalize_css_import_path("base/reset".to_string(), true),
748            "./base/reset"
749        );
750    }
751
752    #[test]
753    fn normalize_scss_builtin_stays_bare() {
754        assert_eq!(
755            normalize_css_import_path("sass:math".to_string(), true),
756            "sass:math"
757        );
758    }
759
760    #[test]
761    fn normalize_scss_relative_path_unchanged() {
762        assert_eq!(
763            normalize_css_import_path("../styles/variables".to_string(), true),
764            "../styles/variables"
765        );
766    }
767
768    #[test]
769    fn normalize_css_bare_extensionless_stays_bare() {
770        // In CSS context (not SCSS), extensionless imports are npm packages
771        assert_eq!(
772            normalize_css_import_path("tailwindcss".to_string(), false),
773            "tailwindcss"
774        );
775    }
776
777    // ── Scoped npm packages stay bare ───────────────────────────
778
779    #[test]
780    fn normalize_scoped_package_with_css_extension_stays_bare() {
781        assert_eq!(
782            normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
783            "@fontsource/monaspace-neon/400.css"
784        );
785    }
786
787    #[test]
788    fn normalize_scoped_package_with_scss_extension_stays_bare() {
789        assert_eq!(
790            normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
791            "@company/design-system/tokens.scss"
792        );
793    }
794
795    #[test]
796    fn normalize_scoped_package_without_extension_stays_bare() {
797        assert_eq!(
798            normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
799            "@fallow/design-system/styles"
800        );
801    }
802
803    #[test]
804    fn normalize_scoped_package_extensionless_scss_stays_bare() {
805        assert_eq!(
806            normalize_css_import_path("@company/tokens".to_string(), true),
807            "@company/tokens"
808        );
809    }
810
811    #[test]
812    fn normalize_path_alias_with_css_extension_stays_bare() {
813        // Path aliases like `@/components/Button.css` (configured via tsconfig paths
814        // or Vite alias) share the `@` prefix with scoped packages. They must stay
815        // bare so the resolver's path-alias path can handle them; prepending `./`
816        // would break resolution.
817        assert_eq!(
818            normalize_css_import_path("@/components/Button.css".to_string(), false),
819            "@/components/Button.css"
820        );
821    }
822
823    #[test]
824    fn normalize_path_alias_extensionless_stays_bare() {
825        assert_eq!(
826            normalize_css_import_path("@/styles/variables".to_string(), false),
827            "@/styles/variables"
828        );
829    }
830
831    // ── strip_css_comments edge cases ─────────────────────────────
832
833    #[test]
834    fn strip_css_no_comments() {
835        let source = ".foo { color: red; }";
836        assert_eq!(strip_css_comments(source, false), source);
837    }
838
839    #[test]
840    fn strip_css_multiple_block_comments() {
841        let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
842        let result = strip_css_comments(source, false);
843        assert!(!result.contains("comment-one"));
844        assert!(!result.contains("comment-two"));
845        assert!(result.contains(".foo"));
846        assert!(result.contains(".bar"));
847    }
848
849    #[test]
850    fn strip_scss_does_not_affect_non_scss() {
851        // When is_scss=false, line comments should NOT be stripped
852        let source = "// this stays\n.foo { }";
853        let result = strip_css_comments(source, false);
854        assert!(result.contains("// this stays"));
855    }
856
857    // ── parse_css_to_module: suppression integration ──────────────
858
859    #[test]
860    fn css_module_parses_suppressions() {
861        let info = parse_css_to_module(
862            fallow_types::discover::FileId(0),
863            Path::new("Component.module.css"),
864            "/* fallow-ignore-file */\n.btn { color: red; }",
865            0,
866        );
867        assert!(!info.suppressions.is_empty());
868        assert_eq!(info.suppressions[0].line, 0);
869    }
870
871    // ── CSS class name edge cases ─────────────────────────────────
872
873    #[test]
874    fn extracts_class_starting_with_underscore() {
875        let names = export_names("._private { } .__dunder { }");
876        assert!(names.contains(&"_private".to_string()));
877        assert!(names.contains(&"__dunder".to_string()));
878    }
879
880    #[test]
881    fn ignores_id_selectors() {
882        let names = export_names("#myId { color: red; }");
883        assert!(!names.contains(&"myId".to_string()));
884    }
885
886    #[test]
887    fn ignores_element_selectors() {
888        let names = export_names("div { color: red; } span { }");
889        assert!(names.is_empty());
890    }
891
892    // ── extract_css_imports (issue #195: vite additionalData / SFC styles) ──
893
894    #[test]
895    fn extract_css_imports_at_import_quoted() {
896        let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
897        assert_eq!(imports, vec!["./reset.css"]);
898    }
899
900    #[test]
901    fn extract_css_imports_package_subpath_stays_bare() {
902        let imports =
903            extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
904        assert_eq!(imports, vec!["tailwindcss/theme.css"]);
905    }
906
907    #[test]
908    fn extract_css_imports_at_import_url() {
909        let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
910        assert_eq!(imports, vec!["./reset.css"]);
911    }
912
913    #[test]
914    fn extract_css_imports_skips_remote_urls() {
915        let imports =
916            extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
917        assert!(imports.is_empty());
918    }
919
920    #[test]
921    fn extract_css_imports_scss_use_normalizes_partial() {
922        let imports = extract_css_imports(r#"@use "variables";"#, true);
923        assert_eq!(imports, vec!["./variables"]);
924    }
925
926    #[test]
927    fn extract_css_imports_scss_forward_normalizes_partial() {
928        let imports = extract_css_imports(r#"@forward "tokens";"#, true);
929        assert_eq!(imports, vec!["./tokens"]);
930    }
931
932    #[test]
933    fn extract_css_imports_skips_comments() {
934        let imports = extract_css_imports(
935            r#"/* @import "./hidden.scss"; */
936@use "real";"#,
937            true,
938        );
939        assert_eq!(imports, vec!["./real"]);
940    }
941
942    #[test]
943    fn extract_css_imports_at_plugin_keeps_package_bare() {
944        let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
945        assert_eq!(imports, vec!["daisyui"]);
946    }
947
948    #[test]
949    fn extract_css_imports_at_plugin_tracks_relative_file() {
950        let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
951        assert_eq!(imports, vec!["./tailwind-plugin.js"]);
952    }
953
954    #[test]
955    fn extract_css_imports_scss_at_import_kept_relative() {
956        let imports = extract_css_imports(r"@import 'Foo';", true);
957        // Bare specifier in SCSS context is normalized to ./
958        assert_eq!(imports, vec!["./Foo"]);
959    }
960
961    #[test]
962    fn extract_css_imports_additional_data_string_body() {
963        // Mimics what Vite's css.preprocessorOptions.scss.additionalData ships
964        let body = r#"@use "./src/styles/global.scss";"#;
965        let imports = extract_css_imports(body, true);
966        assert_eq!(imports, vec!["./src/styles/global.scss"]);
967    }
968}