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        content_hash,
378        suppressions,
379        unused_import_bindings: Vec::new(),
380        type_referenced_import_bindings: Vec::new(),
381        value_referenced_import_bindings: Vec::new(),
382        line_offsets: fallow_types::extract::compute_line_offsets(source),
383        complexity: Vec::new(),
384        flag_uses: Vec::new(),
385        class_heritage: vec![],
386        local_type_declarations: Vec::new(),
387        public_signature_type_references: Vec::new(),
388        namespace_object_aliases: Vec::new(),
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395
396    /// Helper to collect export names as strings from `extract_css_module_exports`.
397    fn export_names(source: &str) -> Vec<String> {
398        extract_css_module_exports(source)
399            .into_iter()
400            .filter_map(|e| match e.name {
401                ExportName::Named(n) => Some(n),
402                ExportName::Default => None,
403            })
404            .collect()
405    }
406
407    // ── is_css_file ──────────────────────────────────────────────
408
409    #[test]
410    fn is_css_file_css() {
411        assert!(is_css_file(Path::new("styles.css")));
412    }
413
414    #[test]
415    fn is_css_file_scss() {
416        assert!(is_css_file(Path::new("styles.scss")));
417    }
418
419    #[test]
420    fn is_css_file_rejects_js() {
421        assert!(!is_css_file(Path::new("app.js")));
422    }
423
424    #[test]
425    fn is_css_file_rejects_ts() {
426        assert!(!is_css_file(Path::new("app.ts")));
427    }
428
429    #[test]
430    fn is_css_file_rejects_less() {
431        assert!(!is_css_file(Path::new("styles.less")));
432    }
433
434    #[test]
435    fn is_css_file_rejects_no_extension() {
436        assert!(!is_css_file(Path::new("Makefile")));
437    }
438
439    // ── is_css_module_file ───────────────────────────────────────
440
441    #[test]
442    fn is_css_module_file_module_css() {
443        assert!(is_css_module_file(Path::new("Component.module.css")));
444    }
445
446    #[test]
447    fn is_css_module_file_module_scss() {
448        assert!(is_css_module_file(Path::new("Component.module.scss")));
449    }
450
451    #[test]
452    fn is_css_module_file_rejects_plain_css() {
453        assert!(!is_css_module_file(Path::new("styles.css")));
454    }
455
456    #[test]
457    fn is_css_module_file_rejects_plain_scss() {
458        assert!(!is_css_module_file(Path::new("styles.scss")));
459    }
460
461    #[test]
462    fn is_css_module_file_rejects_module_js() {
463        assert!(!is_css_module_file(Path::new("utils.module.js")));
464    }
465
466    // ── extract_css_module_exports: basic class extraction ───────
467
468    #[test]
469    fn extracts_single_class() {
470        let names = export_names(".foo { color: red; }");
471        assert_eq!(names, vec!["foo"]);
472    }
473
474    #[test]
475    fn extracts_multiple_classes() {
476        let names = export_names(".foo { } .bar { }");
477        assert_eq!(names, vec!["foo", "bar"]);
478    }
479
480    #[test]
481    fn extracts_nested_classes() {
482        let names = export_names(".foo .bar { color: red; }");
483        assert!(names.contains(&"foo".to_string()));
484        assert!(names.contains(&"bar".to_string()));
485    }
486
487    #[test]
488    fn extracts_hyphenated_class() {
489        let names = export_names(".my-class { }");
490        assert_eq!(names, vec!["my-class"]);
491    }
492
493    #[test]
494    fn extracts_camel_case_class() {
495        let names = export_names(".myClass { }");
496        assert_eq!(names, vec!["myClass"]);
497    }
498
499    #[test]
500    fn extracts_underscore_class() {
501        let names = export_names("._hidden { } .__wrapper { }");
502        assert!(names.contains(&"_hidden".to_string()));
503        assert!(names.contains(&"__wrapper".to_string()));
504    }
505
506    // ── Pseudo-selectors ─────────────────────────────────────────
507
508    #[test]
509    fn pseudo_selector_hover() {
510        let names = export_names(".foo:hover { color: blue; }");
511        assert_eq!(names, vec!["foo"]);
512    }
513
514    #[test]
515    fn pseudo_selector_focus() {
516        let names = export_names(".input:focus { outline: none; }");
517        assert_eq!(names, vec!["input"]);
518    }
519
520    #[test]
521    fn pseudo_element_before() {
522        let names = export_names(".icon::before { content: ''; }");
523        assert_eq!(names, vec!["icon"]);
524    }
525
526    #[test]
527    fn combined_pseudo_selectors() {
528        let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
529        // "btn" should be deduplicated
530        assert_eq!(names, vec!["btn"]);
531    }
532
533    // ── Media queries ────────────────────────────────────────────
534
535    #[test]
536    fn classes_inside_media_query() {
537        let names = export_names(
538            "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
539        );
540        assert!(names.contains(&"mobile-nav".to_string()));
541        assert!(names.contains(&"desktop-nav".to_string()));
542    }
543
544    // ── Deduplication ────────────────────────────────────────────
545
546    #[test]
547    fn deduplicates_repeated_class() {
548        let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
549        assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
550    }
551
552    // ── Edge cases ───────────────────────────────────────────────
553
554    #[test]
555    fn empty_source() {
556        let names = export_names("");
557        assert!(names.is_empty());
558    }
559
560    #[test]
561    fn no_classes() {
562        let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
563        assert!(names.is_empty());
564    }
565
566    #[test]
567    fn ignores_classes_in_block_comments() {
568        // Note: extract_css_module_exports itself does NOT strip comments;
569        // comments are stripped in parse_css_to_module before calling it.
570        // But CSS_NON_SELECTOR_RE strips quoted strings. Testing the
571        // strip_css_comments + extract pipeline via the stripped source:
572        let stripped = strip_css_comments("/* .fake { } */ .real { }", false);
573        let names = export_names(&stripped);
574        assert!(!names.contains(&"fake".to_string()));
575        assert!(names.contains(&"real".to_string()));
576    }
577
578    #[test]
579    fn ignores_classes_in_strings() {
580        let names = export_names(r#".real { content: ".fake"; }"#);
581        assert!(names.contains(&"real".to_string()));
582        assert!(!names.contains(&"fake".to_string()));
583    }
584
585    #[test]
586    fn ignores_classes_in_url() {
587        let names = export_names(".real { background: url(./images/hero.png); }");
588        assert!(names.contains(&"real".to_string()));
589        // "png" from "hero.png" should not be extracted
590        assert!(!names.contains(&"png".to_string()));
591    }
592
593    // ── strip_css_comments ───────────────────────────────────────
594
595    #[test]
596    fn strip_css_block_comment() {
597        let result = strip_css_comments("/* removed */ .kept { }", false);
598        assert!(!result.contains("removed"));
599        assert!(result.contains(".kept"));
600    }
601
602    #[test]
603    fn strip_scss_line_comment() {
604        let result = strip_css_comments("// removed\n.kept { }", true);
605        assert!(!result.contains("removed"));
606        assert!(result.contains(".kept"));
607    }
608
609    #[test]
610    fn strip_scss_preserves_css_outside_comments() {
611        let source = "// line comment\n/* block comment */\n.visible { color: red; }";
612        let result = strip_css_comments(source, true);
613        assert!(result.contains(".visible"));
614    }
615
616    // ── is_css_url_import ────────────────────────────────────────
617
618    #[test]
619    fn url_import_http() {
620        assert!(is_css_url_import("http://example.com/style.css"));
621    }
622
623    #[test]
624    fn url_import_https() {
625        assert!(is_css_url_import("https://fonts.googleapis.com/css"));
626    }
627
628    #[test]
629    fn url_import_data() {
630        assert!(is_css_url_import("data:text/css;base64,abc"));
631    }
632
633    #[test]
634    fn url_import_local_not_skipped() {
635        assert!(!is_css_url_import("./local.css"));
636    }
637
638    #[test]
639    fn url_import_bare_specifier_not_skipped() {
640        assert!(!is_css_url_import("tailwindcss"));
641    }
642
643    // ── normalize_css_import_path ─────────────────────────────────
644
645    #[test]
646    fn normalize_relative_dot_path_unchanged() {
647        assert_eq!(
648            normalize_css_import_path("./reset.css".to_string(), false),
649            "./reset.css"
650        );
651    }
652
653    #[test]
654    fn normalize_parent_relative_path_unchanged() {
655        assert_eq!(
656            normalize_css_import_path("../shared.scss".to_string(), false),
657            "../shared.scss"
658        );
659    }
660
661    #[test]
662    fn normalize_absolute_path_unchanged() {
663        assert_eq!(
664            normalize_css_import_path("/styles/main.css".to_string(), false),
665            "/styles/main.css"
666        );
667    }
668
669    #[test]
670    fn normalize_url_unchanged() {
671        assert_eq!(
672            normalize_css_import_path("https://example.com/style.css".to_string(), false),
673            "https://example.com/style.css"
674        );
675    }
676
677    #[test]
678    fn normalize_bare_css_gets_dot_slash() {
679        assert_eq!(
680            normalize_css_import_path("app.css".to_string(), false),
681            "./app.css"
682        );
683    }
684
685    #[test]
686    fn normalize_css_package_subpath_stays_bare() {
687        assert_eq!(
688            normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
689            "tailwindcss/theme.css"
690        );
691    }
692
693    #[test]
694    fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
695        assert_eq!(
696            normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
697            "highlight.js/styles/github.css"
698        );
699    }
700
701    #[test]
702    fn normalize_bare_scss_gets_dot_slash() {
703        assert_eq!(
704            normalize_css_import_path("vars.scss".to_string(), false),
705            "./vars.scss"
706        );
707    }
708
709    #[test]
710    fn normalize_bare_sass_gets_dot_slash() {
711        assert_eq!(
712            normalize_css_import_path("main.sass".to_string(), false),
713            "./main.sass"
714        );
715    }
716
717    #[test]
718    fn normalize_bare_less_gets_dot_slash() {
719        assert_eq!(
720            normalize_css_import_path("theme.less".to_string(), false),
721            "./theme.less"
722        );
723    }
724
725    #[test]
726    fn normalize_bare_js_extension_stays_bare() {
727        assert_eq!(
728            normalize_css_import_path("module.js".to_string(), false),
729            "module.js"
730        );
731    }
732
733    // ── SCSS partial normalization ───────────────────────────────
734
735    #[test]
736    fn normalize_scss_bare_partial_gets_dot_slash() {
737        assert_eq!(
738            normalize_css_import_path("variables".to_string(), true),
739            "./variables"
740        );
741    }
742
743    #[test]
744    fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
745        assert_eq!(
746            normalize_css_import_path("base/reset".to_string(), true),
747            "./base/reset"
748        );
749    }
750
751    #[test]
752    fn normalize_scss_builtin_stays_bare() {
753        assert_eq!(
754            normalize_css_import_path("sass:math".to_string(), true),
755            "sass:math"
756        );
757    }
758
759    #[test]
760    fn normalize_scss_relative_path_unchanged() {
761        assert_eq!(
762            normalize_css_import_path("../styles/variables".to_string(), true),
763            "../styles/variables"
764        );
765    }
766
767    #[test]
768    fn normalize_css_bare_extensionless_stays_bare() {
769        // In CSS context (not SCSS), extensionless imports are npm packages
770        assert_eq!(
771            normalize_css_import_path("tailwindcss".to_string(), false),
772            "tailwindcss"
773        );
774    }
775
776    // ── Scoped npm packages stay bare ───────────────────────────
777
778    #[test]
779    fn normalize_scoped_package_with_css_extension_stays_bare() {
780        assert_eq!(
781            normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
782            "@fontsource/monaspace-neon/400.css"
783        );
784    }
785
786    #[test]
787    fn normalize_scoped_package_with_scss_extension_stays_bare() {
788        assert_eq!(
789            normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
790            "@company/design-system/tokens.scss"
791        );
792    }
793
794    #[test]
795    fn normalize_scoped_package_without_extension_stays_bare() {
796        assert_eq!(
797            normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
798            "@fallow/design-system/styles"
799        );
800    }
801
802    #[test]
803    fn normalize_scoped_package_extensionless_scss_stays_bare() {
804        assert_eq!(
805            normalize_css_import_path("@company/tokens".to_string(), true),
806            "@company/tokens"
807        );
808    }
809
810    #[test]
811    fn normalize_path_alias_with_css_extension_stays_bare() {
812        // Path aliases like `@/components/Button.css` (configured via tsconfig paths
813        // or Vite alias) share the `@` prefix with scoped packages. They must stay
814        // bare so the resolver's path-alias path can handle them; prepending `./`
815        // would break resolution.
816        assert_eq!(
817            normalize_css_import_path("@/components/Button.css".to_string(), false),
818            "@/components/Button.css"
819        );
820    }
821
822    #[test]
823    fn normalize_path_alias_extensionless_stays_bare() {
824        assert_eq!(
825            normalize_css_import_path("@/styles/variables".to_string(), false),
826            "@/styles/variables"
827        );
828    }
829
830    // ── strip_css_comments edge cases ─────────────────────────────
831
832    #[test]
833    fn strip_css_no_comments() {
834        let source = ".foo { color: red; }";
835        assert_eq!(strip_css_comments(source, false), source);
836    }
837
838    #[test]
839    fn strip_css_multiple_block_comments() {
840        let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
841        let result = strip_css_comments(source, false);
842        assert!(!result.contains("comment-one"));
843        assert!(!result.contains("comment-two"));
844        assert!(result.contains(".foo"));
845        assert!(result.contains(".bar"));
846    }
847
848    #[test]
849    fn strip_scss_does_not_affect_non_scss() {
850        // When is_scss=false, line comments should NOT be stripped
851        let source = "// this stays\n.foo { }";
852        let result = strip_css_comments(source, false);
853        assert!(result.contains("// this stays"));
854    }
855
856    // ── parse_css_to_module: suppression integration ──────────────
857
858    #[test]
859    fn css_module_parses_suppressions() {
860        let info = parse_css_to_module(
861            fallow_types::discover::FileId(0),
862            Path::new("Component.module.css"),
863            "/* fallow-ignore-file */\n.btn { color: red; }",
864            0,
865        );
866        assert!(!info.suppressions.is_empty());
867        assert_eq!(info.suppressions[0].line, 0);
868    }
869
870    // ── CSS class name edge cases ─────────────────────────────────
871
872    #[test]
873    fn extracts_class_starting_with_underscore() {
874        let names = export_names("._private { } .__dunder { }");
875        assert!(names.contains(&"_private".to_string()));
876        assert!(names.contains(&"__dunder".to_string()));
877    }
878
879    #[test]
880    fn ignores_id_selectors() {
881        let names = export_names("#myId { color: red; }");
882        assert!(!names.contains(&"myId".to_string()));
883    }
884
885    #[test]
886    fn ignores_element_selectors() {
887        let names = export_names("div { color: red; } span { }");
888        assert!(names.is_empty());
889    }
890
891    // ── extract_css_imports (issue #195: vite additionalData / SFC styles) ──
892
893    #[test]
894    fn extract_css_imports_at_import_quoted() {
895        let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
896        assert_eq!(imports, vec!["./reset.css"]);
897    }
898
899    #[test]
900    fn extract_css_imports_package_subpath_stays_bare() {
901        let imports =
902            extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
903        assert_eq!(imports, vec!["tailwindcss/theme.css"]);
904    }
905
906    #[test]
907    fn extract_css_imports_at_import_url() {
908        let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
909        assert_eq!(imports, vec!["./reset.css"]);
910    }
911
912    #[test]
913    fn extract_css_imports_skips_remote_urls() {
914        let imports =
915            extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
916        assert!(imports.is_empty());
917    }
918
919    #[test]
920    fn extract_css_imports_scss_use_normalizes_partial() {
921        let imports = extract_css_imports(r#"@use "variables";"#, true);
922        assert_eq!(imports, vec!["./variables"]);
923    }
924
925    #[test]
926    fn extract_css_imports_scss_forward_normalizes_partial() {
927        let imports = extract_css_imports(r#"@forward "tokens";"#, true);
928        assert_eq!(imports, vec!["./tokens"]);
929    }
930
931    #[test]
932    fn extract_css_imports_skips_comments() {
933        let imports = extract_css_imports(
934            r#"/* @import "./hidden.scss"; */
935@use "real";"#,
936            true,
937        );
938        assert_eq!(imports, vec!["./real"]);
939    }
940
941    #[test]
942    fn extract_css_imports_at_plugin_keeps_package_bare() {
943        let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
944        assert_eq!(imports, vec!["daisyui"]);
945    }
946
947    #[test]
948    fn extract_css_imports_at_plugin_tracks_relative_file() {
949        let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
950        assert_eq!(imports, vec!["./tailwind-plugin.js"]);
951    }
952
953    #[test]
954    fn extract_css_imports_scss_at_import_kept_relative() {
955        let imports = extract_css_imports(r"@import 'Foo';", true);
956        // Bare specifier in SCSS context is normalized to ./
957        assert_eq!(imports, vec!["./Foo"]);
958    }
959
960    #[test]
961    fn extract_css_imports_additional_data_string_body() {
962        // Mimics what Vite's css.preprocessorOptions.scss.additionalData ships
963        let body = r#"@use "./src/styles/global.scss";"#;
964        let imports = extract_css_imports(body, true);
965        assert_eq!(imports, vec!["./src/styles/global.scss"]);
966    }
967}