1use std::path::Path;
16use std::sync::LazyLock;
17
18use lightningcss::rules::CssRule;
19use lightningcss::selector::{Component, PseudoClass, Selector, SelectorList};
20use lightningcss::stylesheet::{ParserOptions, StyleSheet};
21use oxc_span::Span;
22use rustc_hash::FxHashSet;
23
24use crate::{ExportInfo, ExportName, ImportInfo, ImportedName, ModuleInfo, VisibilityTag};
25use fallow_types::discover::FileId;
26
27static CSS_IMPORT_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
30 crate::static_regex(
31 r#"@import\s+(?:url\(\s*(?:["']([^"']+)["']|([^)]+))\s*\)|["']([^"']+)["'])"#,
32 )
33});
34
35static SCSS_USE_RE: LazyLock<regex::Regex> =
38 LazyLock::new(|| crate::static_regex(r#"@(?:use|forward)\s+["']([^"']+)["']"#));
39
40static CSS_PLUGIN_RE: LazyLock<regex::Regex> =
43 LazyLock::new(|| crate::static_regex(r#"@plugin\s+["']([^"']+)["']"#));
44
45static CSS_APPLY_RE: LazyLock<regex::Regex> =
48 LazyLock::new(|| crate::static_regex(r"@apply\s+[^;}\n]+"));
49
50static CSS_TAILWIND_RE: LazyLock<regex::Regex> =
53 LazyLock::new(|| crate::static_regex(r"@tailwind\s+\w+"));
54
55static CSS_COMMENT_RE: LazyLock<regex::Regex> =
57 LazyLock::new(|| crate::static_regex(r"(?s)/\*.*?\*/"));
58
59static SCSS_LINE_COMMENT_RE: LazyLock<regex::Regex> =
61 LazyLock::new(|| crate::static_regex(r"//[^\n]*"));
62
63static CSS_CLASS_RE: LazyLock<regex::Regex> =
66 LazyLock::new(|| crate::static_regex(r"\.([a-zA-Z_][a-zA-Z0-9_-]*)"));
67
68static CSS_NON_SELECTOR_RE: LazyLock<regex::Regex> =
71 LazyLock::new(|| crate::static_regex(r#"(?s)"[^"]*"|'[^']*'|url\([^)]*\)"#));
72
73static CSS_AT_RULE_PRELUDE_RE: LazyLock<regex::Regex> =
85 LazyLock::new(|| crate::static_regex(r"@(?:layer|import)\b[^;{]*"));
86
87pub(crate) fn is_css_file(path: &Path) -> bool {
88 path.extension()
89 .and_then(|e| e.to_str())
90 .is_some_and(|ext| matches!(ext, "css" | "scss" | "sass" | "less"))
91}
92
93#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct CssImportSource {
96 pub raw: String,
98 pub normalized: String,
100 pub is_plugin: bool,
102 pub span: Span,
104}
105
106fn is_css_module_file(path: &Path) -> bool {
107 is_css_file(path)
108 && path
109 .file_stem()
110 .and_then(|s| s.to_str())
111 .is_some_and(|stem| stem.ends_with(".module"))
112}
113
114fn is_css_url_import(source: &str) -> bool {
116 source.starts_with("http://") || source.starts_with("https://") || source.starts_with("data:")
117}
118
119fn normalize_css_import_path(path: String, is_scss: bool) -> String {
132 if path.starts_with('.') || path.starts_with('/') || path.contains("://") {
133 return path;
134 }
135 if path.starts_with('@') && path.contains('/') {
136 return path;
137 }
138 let path_ref = std::path::Path::new(&path);
139 if !is_scss
140 && path.contains('/')
141 && path_ref
142 .extension()
143 .and_then(|e| e.to_str())
144 .is_some_and(is_style_extension)
145 {
146 return path;
147 }
148 let ext = std::path::Path::new(&path)
149 .extension()
150 .and_then(|e| e.to_str());
151 match ext {
152 Some(e) if is_style_extension(e) => format!("./{path}"),
153 _ => {
154 if is_scss && !path.contains(':') {
155 format!("./{path}")
156 } else {
157 path
158 }
159 }
160 }
161}
162
163fn is_style_extension(ext: &str) -> bool {
164 ext.eq_ignore_ascii_case("css")
165 || ext.eq_ignore_ascii_case("scss")
166 || ext.eq_ignore_ascii_case("sass")
167 || ext.eq_ignore_ascii_case("less")
168}
169
170fn mask_css_comments(source: &str, is_scss: bool) -> String {
171 let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
172 if is_scss {
173 masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
174 }
175 masked
176}
177
178fn normalize_css_plugin_path(path: String) -> String {
184 path
185}
186
187#[must_use]
197pub fn extract_css_import_sources(source: &str, is_scss: bool) -> Vec<CssImportSource> {
198 let stripped = mask_css_comments(source, is_scss);
199 let mut out = Vec::new();
200
201 for cap in CSS_IMPORT_RE.captures_iter(&stripped) {
202 let raw = cap.get(1).or_else(|| cap.get(2)).or_else(|| cap.get(3));
203 if let Some(m) = raw {
204 let (src, span) = trimmed_match_with_span(m);
205 if !src.is_empty() && !is_css_url_import(&src) {
206 out.push(CssImportSource {
207 normalized: normalize_css_import_path(src.clone(), is_scss),
208 raw: src,
209 is_plugin: false,
210 span,
211 });
212 }
213 }
214 }
215
216 if is_scss {
217 for cap in SCSS_USE_RE.captures_iter(&stripped) {
218 if let Some(m) = cap.get(1) {
219 let (raw, span) = trimmed_match_with_span(m);
220 out.push(CssImportSource {
221 normalized: normalize_css_import_path(raw.clone(), true),
222 raw,
223 is_plugin: false,
224 span,
225 });
226 }
227 }
228 }
229
230 for cap in CSS_PLUGIN_RE.captures_iter(&stripped) {
231 if let Some(m) = cap.get(1) {
232 let (raw, span) = trimmed_match_with_span(m);
233 if !raw.is_empty() && !is_css_url_import(&raw) {
234 out.push(CssImportSource {
235 normalized: normalize_css_plugin_path(raw.clone()),
236 raw,
237 is_plugin: true,
238 span,
239 });
240 }
241 }
242 }
243
244 out
245}
246
247fn trimmed_match_with_span(m: regex::Match<'_>) -> (String, Span) {
248 let raw = m.as_str();
249 let trimmed_start = raw.len() - raw.trim_start().len();
250 let trimmed_end = raw.trim_end().len();
251 let start = m.start() + trimmed_start;
252 let end = m.start() + trimmed_end;
253 (raw.trim().to_string(), Span::new(start as u32, end as u32))
254}
255
256#[must_use]
263pub fn extract_css_imports(source: &str, is_scss: bool) -> Vec<String> {
264 extract_css_import_sources(source, is_scss)
265 .into_iter()
266 .map(|source| source.normalized)
267 .collect()
268}
269
270static CSS_THEME_OPEN_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
274 crate::static_regex(r"@theme(?:\s+(?:inline|static|reference|default))*\s*\{")
275});
276
277static CSS_VAR_REF_RE: LazyLock<regex::Regex> =
281 LazyLock::new(|| crate::static_regex(r"var\(\s*--([A-Za-z0-9_-]+)"));
282
283#[derive(Debug, Clone, PartialEq, Eq)]
286pub struct ThemeTokenDef {
287 pub name: String,
289 pub value: String,
292 pub line: u32,
294}
295
296#[derive(Debug, Clone, Default, PartialEq, Eq)]
298pub struct ThemeScan {
299 pub tokens: Vec<ThemeTokenDef>,
303 pub theme_var_reads: Vec<(String, u32)>,
310}
311
312#[must_use]
322pub fn scan_theme_blocks(source: &str) -> ThemeScan {
323 if !source.contains("@theme") {
325 return ThemeScan::default();
326 }
327 let masked = mask_theme_source(source);
328 let mut out = ThemeScan::default();
329 let mut seen: FxHashSet<String> = FxHashSet::default();
330 for open in CSS_THEME_OPEN_RE.find_iter(&masked) {
331 let body_start = open.end();
332 let body_end = find_theme_body_end(&masked, body_start);
333 collect_theme_declarations(&mut ThemeDeclarationScan {
334 source,
335 masked: &masked,
336 start: body_start,
337 end: body_end,
338 out: &mut out.tokens,
339 seen: &mut seen,
340 });
341 collect_theme_var_reads(
342 source,
343 &masked,
344 body_start,
345 body_end,
346 &mut out.theme_var_reads,
347 );
348 }
349 out
350}
351
352#[must_use]
359pub fn extract_css_var_reads_located(source: &str) -> Vec<(String, u32)> {
360 if !source.contains("var(") {
361 return Vec::new();
362 }
363 let masked = mask_theme_source(source);
364 let mut theme_bodies: Vec<(usize, usize)> = Vec::new();
367 if masked.contains("@theme") {
368 for open in CSS_THEME_OPEN_RE.find_iter(&masked) {
369 let body_start = open.end();
370 let body_end = find_theme_body_end(&masked, body_start);
371 theme_bodies.push((body_start, body_end));
372 }
373 }
374 let in_theme = |offset: usize| theme_bodies.iter().any(|&(s, e)| offset >= s && offset < e);
375 let mut out = Vec::new();
376 let mut last_pos = 0usize;
382 let mut last_line = 1u32;
383 for cap in CSS_VAR_REF_RE.captures_iter(&masked) {
384 let (Some(whole), Some(name)) = (cap.get(0), cap.get(1)) else {
385 continue;
386 };
387 if in_theme(whole.start()) {
388 continue;
389 }
390 let offset = whole.start();
391 last_line = last_line.saturating_add(newlines_between(source, last_pos, offset));
392 last_pos = offset;
393 out.push((name.as_str().to_owned(), last_line));
394 }
395 out
396}
397
398fn mask_theme_source(source: &str) -> String {
401 mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE)
402}
403
404fn find_theme_body_end(masked: &str, body_start: usize) -> usize {
406 let bytes = masked.as_bytes();
407 let mut depth = 1usize;
408 let mut i = body_start;
409 while i < bytes.len() {
410 match bytes[i] {
411 b'{' => depth += 1,
412 b'}' => {
413 depth -= 1;
414 if depth == 0 {
415 break;
416 }
417 }
418 _ => {}
419 }
420 i += 1;
421 }
422 i.min(bytes.len())
423}
424
425fn collect_theme_var_reads(
426 source: &str,
427 masked: &str,
428 body_start: usize,
429 body_end: usize,
430 out: &mut Vec<(String, u32)>,
431) {
432 let Some(body) = masked.get(body_start..body_end) else {
433 return;
434 };
435 let mut last_pos = 0usize;
440 let mut last_line = 1u32;
441 for cap in CSS_VAR_REF_RE.captures_iter(body) {
442 let (Some(whole), Some(name)) = (cap.get(0), cap.get(1)) else {
443 continue;
444 };
445 let offset = body_start + whole.start();
448 last_line = last_line.saturating_add(newlines_between(source, last_pos, offset));
449 last_pos = offset;
450 out.push((name.as_str().to_owned(), last_line));
451 }
452}
453
454fn line_at_offset(source: &str, offset: usize) -> u32 {
457 let count = source
458 .get(..offset)
459 .map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count());
460 u32::try_from(1 + count).unwrap_or(u32::MAX)
461}
462
463fn newlines_between(source: &str, from: usize, to: usize) -> u32 {
469 let count = source
470 .get(from..to)
471 .map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count());
472 u32::try_from(count).unwrap_or(u32::MAX)
473}
474
475fn collect_theme_declarations(scan: &mut ThemeDeclarationScan<'_, '_>) {
481 let bytes = scan.masked.as_bytes();
482 let mut depth = 0usize;
483 let mut expect_decl = true;
484 let mut i = scan.start;
485 while i < scan.end {
486 let b = bytes[i];
487 match b {
488 b'{' => {
489 depth += 1;
490 expect_decl = false;
491 i += 1;
492 }
493 b'}' => {
494 depth = depth.saturating_sub(1);
495 if depth == 0 {
496 expect_decl = true;
497 }
498 i += 1;
499 }
500 b';' => {
501 if depth == 0 {
502 expect_decl = true;
503 }
504 i += 1;
505 }
506 _ if b.is_ascii_whitespace() => i += 1,
507 _ => {
508 if depth == 0 && expect_decl {
509 expect_decl = false;
510 i = scan_theme_declaration(scan, b, i);
511 } else {
512 i += 1;
513 }
514 }
515 }
516 }
517}
518
519struct ThemeDeclarationScan<'a, 'b> {
520 source: &'a str,
521 masked: &'a str,
522 start: usize,
523 end: usize,
524 out: &'b mut Vec<ThemeTokenDef>,
525 seen: &'b mut FxHashSet<String>,
526}
527
528fn scan_theme_declaration(scan: &mut ThemeDeclarationScan<'_, '_>, b: u8, i: usize) -> usize {
532 let bytes = scan.masked.as_bytes();
533 if !(b == b'-' && bytes.get(i + 1) == Some(&b'-')) {
534 return i + 1;
535 }
536 let id_start = i;
537 let mut j = i;
538 while j < scan.end {
539 let c = bytes[j];
540 if c == b'-' || c == b'_' || c.is_ascii_alphanumeric() {
541 j += 1;
542 } else {
543 break;
544 }
545 }
546 let mut k = j;
547 while k < scan.end && bytes[k].is_ascii_whitespace() {
548 k += 1;
549 }
550 if k < scan.end && bytes[k] == b':' {
552 let name = &scan.masked[id_start + 2..j];
553 if !name.is_empty() && scan.seen.insert(name.to_owned()) {
554 let value = theme_declaration_value(scan.source, scan.masked, k + 1, scan.end);
555 let line = 1 + scan
556 .source
557 .get(..id_start)
558 .map_or(0, |s| s.bytes().filter(|&x| x == b'\n').count());
559 scan.out.push(ThemeTokenDef {
560 name: name.to_owned(),
561 value,
562 line: u32::try_from(line).unwrap_or(u32::MAX),
563 });
564 }
565 }
566 j
567}
568
569fn theme_declaration_value(source: &str, masked: &str, start: usize, end: usize) -> String {
570 let bytes = masked.as_bytes();
571 let mut depth = 0usize;
572 let mut i = start;
573 while i < end {
574 match bytes[i] {
575 b'{' => depth += 1,
576 b'}' => {
577 if depth == 0 {
578 break;
579 }
580 depth -= 1;
581 }
582 b';' if depth == 0 => break,
583 _ => {}
584 }
585 i += 1;
586 }
587 source
588 .get(start..i)
589 .unwrap_or_default()
590 .split_whitespace()
591 .collect::<Vec<_>>()
592 .join(" ")
593}
594
595#[must_use]
601pub fn extract_apply_tokens(source: &str) -> Vec<String> {
602 if !source.contains("@apply") {
604 return Vec::new();
605 }
606 let masked = mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE);
607 let mut out = Vec::new();
608 for m in CSS_APPLY_RE.find_iter(&masked) {
609 let body = m.as_str().trim_start_matches("@apply");
610 for token in body.split_whitespace() {
611 let token = token.trim_matches('!');
612 if token.is_empty() || token == "important" {
613 continue;
614 }
615 out.push(token.to_owned());
616 }
617 }
618 out
619}
620
621#[must_use]
626pub fn extract_apply_tokens_located(source: &str) -> Vec<(String, u32)> {
627 if !source.contains("@apply") {
628 return Vec::new();
629 }
630 let masked = mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE);
631 let mut out = Vec::new();
632 for m in CSS_APPLY_RE.find_iter(&masked) {
633 let line = line_at_offset(source, m.start());
634 let body = m.as_str().trim_start_matches("@apply");
635 for token in body.split_whitespace() {
636 let token = token.trim_matches('!');
637 if token.is_empty() || token == "important" {
638 continue;
639 }
640 out.push((token.to_owned(), line));
641 }
642 }
643 out
644}
645
646fn mask_with_whitespace(src: &str, re: ®ex::Regex) -> String {
656 let mut out = String::with_capacity(src.len());
657 let mut cursor = 0;
658 for m in re.find_iter(src) {
659 out.push_str(&src[cursor..m.start()]);
660 for _ in m.start()..m.end() {
661 out.push(' ');
662 }
663 cursor = m.end();
664 }
665 out.push_str(&src[cursor..]);
666 out
667}
668
669fn lightningcss_class_set(source: &str) -> Option<FxHashSet<String>> {
686 let options = ParserOptions {
687 error_recovery: true,
690 css_modules: Some(lightningcss::css_modules::Config::default()),
696 ..ParserOptions::default()
697 };
698 let stylesheet = StyleSheet::parse(source, options).ok()?;
699 let mut classes = FxHashSet::default();
700 collect_classes_from_rules(&stylesheet.rules.0, &mut classes);
701 Some(classes)
702}
703
704fn collect_classes_from_rules(rules: &[CssRule<'_>], classes: &mut FxHashSet<String>) {
709 for rule in rules {
710 match rule {
711 CssRule::Style(style) => {
712 collect_classes_from_selector_list(&style.selectors, classes);
713 collect_classes_from_rules(&style.rules.0, classes);
714 }
715 CssRule::Media(rule) => collect_classes_from_rules(&rule.rules.0, classes),
716 CssRule::Supports(rule) => collect_classes_from_rules(&rule.rules.0, classes),
717 CssRule::Container(rule) => collect_classes_from_rules(&rule.rules.0, classes),
718 CssRule::LayerBlock(rule) => collect_classes_from_rules(&rule.rules.0, classes),
719 CssRule::MozDocument(rule) => collect_classes_from_rules(&rule.rules.0, classes),
720 CssRule::StartingStyle(rule) => collect_classes_from_rules(&rule.rules.0, classes),
721 CssRule::Nesting(rule) => {
722 collect_classes_from_selector_list(&rule.style.selectors, classes);
723 collect_classes_from_rules(&rule.style.rules.0, classes);
724 }
725 CssRule::Scope(rule) => {
726 if let Some(scope_start) = &rule.scope_start {
727 collect_classes_from_selector_list(scope_start, classes);
728 }
729 if let Some(scope_end) = &rule.scope_end {
730 collect_classes_from_selector_list(scope_end, classes);
731 }
732 collect_classes_from_rules(&rule.rules.0, classes);
733 }
734 _ => {}
735 }
736 }
737}
738
739fn collect_classes_from_selector_list(list: &SelectorList<'_>, classes: &mut FxHashSet<String>) {
740 for selector in &list.0 {
741 collect_classes_from_selector(selector, classes);
742 }
743}
744
745fn collect_classes_from_selector(selector: &Selector<'_>, classes: &mut FxHashSet<String>) {
746 for component in selector.iter_raw_match_order() {
747 match component {
748 Component::Class(name) => {
749 classes.insert(name.0.to_string());
750 }
751 Component::Is(list)
752 | Component::Where(list)
753 | Component::Has(list)
754 | Component::Negation(list)
755 | Component::Any(_, list) => {
756 for nested in list.as_ref() {
757 collect_classes_from_selector(nested, classes);
758 }
759 }
760 Component::Slotted(nested) | Component::Host(Some(nested)) => {
761 collect_classes_from_selector(nested, classes);
762 }
763 Component::NthOf(data) => {
764 for nested in data.selectors() {
765 collect_classes_from_selector(nested, classes);
766 }
767 }
768 Component::NonTSPseudoClass(
770 PseudoClass::Local { selector } | PseudoClass::Global { selector },
771 ) => collect_classes_from_selector(selector, classes),
772 _ => {}
773 }
774 }
775}
776
777pub fn extract_css_module_exports(source: &str, is_scss: bool) -> Vec<ExportInfo> {
787 if !is_scss && let Some(class_set) = lightningcss_class_set(source) {
788 return scan_css_module_exports(source, is_scss, Some(&class_set));
789 }
790 scan_css_module_exports(source, is_scss, None)
791}
792
793fn scan_css_module_exports(
803 source: &str,
804 is_scss: bool,
805 class_filter: Option<&FxHashSet<String>>,
806) -> Vec<ExportInfo> {
807 let masked = mask_css_module_class_candidates(source, is_scss, class_filter.is_some());
808 let mut seen = FxHashSet::default();
809 let mut exports = Vec::new();
810 for cap in CSS_CLASS_RE.captures_iter(&masked) {
811 if let Some(m) = cap.get(1) {
812 push_css_class_export(m, class_filter, &mut seen, &mut exports);
813 }
814 }
815 exports
816}
817
818fn mask_css_module_class_candidates(source: &str, is_scss: bool, has_class_filter: bool) -> String {
819 let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
820 if is_scss {
821 masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
822 }
823 masked = mask_with_whitespace(&masked, &CSS_NON_SELECTOR_RE);
824 if !has_class_filter {
825 masked = mask_with_whitespace(&masked, &CSS_AT_RULE_PRELUDE_RE);
826 }
827 masked
828}
829
830fn push_css_class_export(
831 class_match: regex::Match<'_>,
832 class_filter: Option<&FxHashSet<String>>,
833 seen: &mut FxHashSet<String>,
834 exports: &mut Vec<ExportInfo>,
835) {
836 let class_name = class_match.as_str().to_string();
837 if class_filter.is_some_and(|filter| !filter.contains(&class_name)) {
838 return;
839 }
840 if seen.insert(class_name.clone()) {
841 exports.push(css_class_export(class_name, class_match));
842 }
843}
844
845fn css_class_export(class_name: String, class_match: regex::Match<'_>) -> ExportInfo {
846 #[expect(
847 clippy::cast_possible_truncation,
848 reason = "CSS files exceeding u32::MAX bytes are not a realistic input"
849 )]
850 let span = Span::new(class_match.start() as u32, class_match.end() as u32);
851 ExportInfo {
852 name: ExportName::Named(class_name),
853 local_name: None,
854 is_type_only: false,
855 visibility: VisibilityTag::None,
856 expected_unused_reason: None,
857 span,
858 members: Vec::new(),
859 is_side_effect_used: false,
860 super_class: None,
861 }
862}
863
864fn build_css_imports(source: &str, stripped: &str, is_scss: bool) -> Vec<ImportInfo> {
868 let mut imports = Vec::new();
869
870 for css_source in extract_css_import_sources(source, is_scss) {
871 imports.push(ImportInfo {
872 source: css_source.normalized,
873 imported_name: if css_source.is_plugin {
874 ImportedName::Default
875 } else {
876 ImportedName::SideEffect
877 },
878 local_name: String::new(),
879 is_type_only: false,
880 is_type_only_star: false,
881 from_style: false,
882 span: css_source.span,
883 source_span: css_source.span,
884 });
885 }
886
887 let has_apply = CSS_APPLY_RE.is_match(stripped);
888 let has_tailwind = CSS_TAILWIND_RE.is_match(stripped);
889 if has_apply || has_tailwind {
890 imports.push(ImportInfo {
891 source: "tailwindcss".to_string(),
892 imported_name: ImportedName::SideEffect,
893 local_name: String::new(),
894 is_type_only: false,
895 is_type_only_star: false,
896 from_style: false,
897 span: Span::default(),
898 source_span: Span::default(),
899 });
900 }
901
902 imports
903}
904
905pub(crate) fn parse_css_to_module(
907 file_id: FileId,
908 path: &Path,
909 source: &str,
910 content_hash: u64,
911) -> ModuleInfo {
912 let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
913 let is_scss = path
914 .extension()
915 .and_then(|e| e.to_str())
916 .is_some_and(|ext| matches!(ext, "scss" | "sass" | "less"));
917
918 let stripped = mask_css_comments(source, is_scss);
919 let imports = build_css_imports(source, &stripped, is_scss);
920
921 let exports = if is_css_module_file(path) {
922 extract_css_module_exports(source, is_scss)
923 } else {
924 Vec::new()
925 };
926
927 css_module_info(
928 file_id,
929 content_hash,
930 source,
931 parsed_suppressions,
932 imports,
933 exports,
934 )
935}
936
937fn css_module_info(
941 file_id: FileId,
942 content_hash: u64,
943 source: &str,
944 parsed_suppressions: crate::suppress::ParsedSuppressions,
945 imports: Vec<ImportInfo>,
946 exports: Vec<ExportInfo>,
947) -> ModuleInfo {
948 crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
949 file_id,
950 content_hash,
951 source,
952 parsed_suppressions,
953 imports,
954 exports,
955 })
956}
957
958#[cfg(all(test, not(miri)))]
959mod tests {
960 use super::*;
961
962 fn export_names(source: &str) -> Vec<String> {
964 extract_css_module_exports(source, false)
965 .into_iter()
966 .filter_map(|e| match e.name {
967 ExportName::Named(n) => Some(n),
968 ExportName::Default => None,
969 })
970 .collect()
971 }
972
973 #[test]
974 fn is_css_file_css() {
975 assert!(is_css_file(Path::new("styles.css")));
976 }
977
978 #[test]
979 fn is_css_file_scss() {
980 assert!(is_css_file(Path::new("styles.scss")));
981 }
982
983 #[test]
984 fn is_css_file_sass() {
985 assert!(is_css_file(Path::new("styles.sass")));
986 }
987
988 #[test]
989 fn is_css_file_less() {
990 assert!(is_css_file(Path::new("styles.less")));
991 }
992
993 #[test]
994 fn is_css_file_rejects_js() {
995 assert!(!is_css_file(Path::new("app.js")));
996 }
997
998 #[test]
999 fn is_css_file_rejects_ts() {
1000 assert!(!is_css_file(Path::new("app.ts")));
1001 }
1002
1003 #[test]
1004 fn is_css_file_rejects_no_extension() {
1005 assert!(!is_css_file(Path::new("Makefile")));
1006 }
1007
1008 #[test]
1009 fn is_css_module_file_module_css() {
1010 assert!(is_css_module_file(Path::new("Component.module.css")));
1011 }
1012
1013 #[test]
1014 fn is_css_module_file_module_scss() {
1015 assert!(is_css_module_file(Path::new("Component.module.scss")));
1016 }
1017
1018 #[test]
1019 fn is_css_module_file_rejects_plain_css() {
1020 assert!(!is_css_module_file(Path::new("styles.css")));
1021 }
1022
1023 #[test]
1024 fn is_css_module_file_rejects_plain_scss() {
1025 assert!(!is_css_module_file(Path::new("styles.scss")));
1026 }
1027
1028 #[test]
1029 fn is_css_module_file_rejects_module_js() {
1030 assert!(!is_css_module_file(Path::new("utils.module.js")));
1031 }
1032
1033 #[test]
1034 fn extracts_single_class() {
1035 let names = export_names(".foo { color: red; }");
1036 assert_eq!(names, vec!["foo"]);
1037 }
1038
1039 #[test]
1040 fn extracts_multiple_classes() {
1041 let names = export_names(".foo { } .bar { }");
1042 assert_eq!(names, vec!["foo", "bar"]);
1043 }
1044
1045 #[test]
1046 fn extracts_nested_classes() {
1047 let names = export_names(".foo .bar { color: red; }");
1048 assert!(names.contains(&"foo".to_string()));
1049 assert!(names.contains(&"bar".to_string()));
1050 }
1051
1052 #[test]
1053 fn extracts_hyphenated_class() {
1054 let names = export_names(".my-class { }");
1055 assert_eq!(names, vec!["my-class"]);
1056 }
1057
1058 #[test]
1059 fn extracts_camel_case_class() {
1060 let names = export_names(".myClass { }");
1061 assert_eq!(names, vec!["myClass"]);
1062 }
1063
1064 #[test]
1065 fn extracts_class_inside_global_pseudo() {
1066 let names = export_names(":global(.globalClass) { color: red; }");
1069 assert_eq!(names, vec!["globalClass"]);
1070 }
1071
1072 #[test]
1073 fn extracts_class_inside_local_pseudo() {
1074 let names = export_names(":local(.localClass) { color: red; }");
1075 assert_eq!(names, vec!["localClass"]);
1076 }
1077
1078 #[test]
1079 fn extracts_classes_inside_negation() {
1080 let names = export_names(".btn:not(.disabled) { }");
1081 assert!(names.contains(&"btn".to_string()), "got {names:?}");
1082 assert!(names.contains(&"disabled".to_string()), "got {names:?}");
1083 }
1084
1085 #[test]
1086 fn extracts_classes_inside_is_and_where() {
1087 let names = export_names(":is(.a, .b) :where(.c) { }");
1088 for expected in ["a", "b", "c"] {
1089 assert!(
1090 names.contains(&expected.to_string()),
1091 "missing {expected} in {names:?}"
1092 );
1093 }
1094 }
1095
1096 #[test]
1097 fn extracts_underscore_class() {
1098 let names = export_names("._hidden { } .__wrapper { }");
1099 assert!(names.contains(&"_hidden".to_string()));
1100 assert!(names.contains(&"__wrapper".to_string()));
1101 }
1102
1103 #[test]
1104 fn pseudo_selector_hover() {
1105 let names = export_names(".foo:hover { color: blue; }");
1106 assert_eq!(names, vec!["foo"]);
1107 }
1108
1109 #[test]
1110 fn pseudo_selector_focus() {
1111 let names = export_names(".input:focus { outline: none; }");
1112 assert_eq!(names, vec!["input"]);
1113 }
1114
1115 #[test]
1116 fn pseudo_element_before() {
1117 let names = export_names(".icon::before { content: ''; }");
1118 assert_eq!(names, vec!["icon"]);
1119 }
1120
1121 #[test]
1122 fn combined_pseudo_selectors() {
1123 let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
1124 assert_eq!(names, vec!["btn"]);
1125 }
1126
1127 #[test]
1128 fn classes_inside_media_query() {
1129 let names = export_names(
1130 "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
1131 );
1132 assert!(names.contains(&"mobile-nav".to_string()));
1133 assert!(names.contains(&"desktop-nav".to_string()));
1134 }
1135
1136 #[test]
1137 fn classes_inside_multi_line_media_query() {
1138 let names =
1139 export_names("@media\n screen and (min-width: 600px)\n{\n .real { color: red; }\n}");
1140 assert_eq!(names, vec!["real"]);
1141 }
1142
1143 #[test]
1144 fn at_layer_statement_does_not_export() {
1145 let names = export_names("@layer foo.bar;");
1146 assert!(names.is_empty(), "got {names:?}");
1147 let names = export_names("@layer foo.bar, foo.baz;");
1148 assert!(names.is_empty(), "got {names:?}");
1149 }
1150
1151 #[test]
1152 fn at_layer_block_keeps_body_classes() {
1153 let names = export_names("@layer foo.bar { .root { color: red; } }");
1154 assert_eq!(names, vec!["root"]);
1155 }
1156
1157 #[test]
1158 fn at_layer_multiline_prelude_keeps_body_classes() {
1159 let names = export_names("@layer\n foo.bar\n{ .root { color: red; } }");
1160 assert_eq!(names, vec!["root"]);
1161 }
1162
1163 #[test]
1164 fn at_layer_with_nested_media_keeps_body() {
1165 let names =
1166 export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
1167 assert_eq!(names, vec!["real"]);
1168 }
1169
1170 #[test]
1171 fn at_import_with_layer_attribute_does_not_export() {
1172 let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
1173 assert!(names.is_empty(), "got {names:?}");
1174 }
1175
1176 #[test]
1177 fn class_then_at_layer_does_not_leak_prelude() {
1178 let names =
1179 export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
1180 assert_eq!(names, vec!["outer", "inner"]);
1181 }
1182
1183 #[test]
1184 fn at_scope_keeps_selector_list_classes() {
1185 let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
1186 assert!(names.contains(&"parent".to_string()), "got {names:?}");
1187 assert!(names.contains(&"child".to_string()), "got {names:?}");
1188 assert!(names.contains(&"title".to_string()), "got {names:?}");
1189 }
1190
1191 #[test]
1192 fn at_keyframes_numeric_step_is_not_class() {
1193 let names = export_names(
1194 "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
1195 );
1196 assert!(names.is_empty(), "got {names:?}");
1197 }
1198
1199 #[test]
1200 fn at_webkit_keyframes_keeps_body_classes() {
1201 let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
1202 assert_eq!(names, vec!["real"]);
1203 }
1204
1205 #[test]
1206 fn deduplicates_repeated_class() {
1207 let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
1208 assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
1209 }
1210
1211 #[test]
1212 fn empty_source() {
1213 let names = export_names("");
1214 assert!(names.is_empty());
1215 }
1216
1217 #[test]
1218 fn no_classes() {
1219 let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
1220 assert!(names.is_empty());
1221 }
1222
1223 #[test]
1224 fn ignores_classes_in_block_comments() {
1225 let names = export_names("/* .fake { } */ .real { }");
1226 assert!(!names.contains(&"fake".to_string()));
1227 assert!(names.contains(&"real".to_string()));
1228 }
1229
1230 #[test]
1231 fn ignores_classes_in_scss_line_comments() {
1232 let exports = extract_css_module_exports("// .fake\n.real { }", true);
1233 let names: Vec<_> = exports
1234 .iter()
1235 .filter_map(|e| match &e.name {
1236 ExportName::Named(n) => Some(n.as_str()),
1237 ExportName::Default => None,
1238 })
1239 .collect();
1240 assert_eq!(names, vec!["real"]);
1241 }
1242
1243 #[test]
1244 fn ignores_classes_in_strings() {
1245 let names = export_names(r#".real { content: ".fake"; }"#);
1246 assert!(names.contains(&"real".to_string()));
1247 assert!(!names.contains(&"fake".to_string()));
1248 }
1249
1250 #[test]
1251 fn ignores_classes_in_url() {
1252 let names = export_names(".real { background: url(./images/hero.png); }");
1253 assert!(names.contains(&"real".to_string()));
1254 assert!(!names.contains(&"png".to_string()));
1255 }
1256
1257 #[test]
1258 fn mask_css_block_comment() {
1259 let source = "/* removed */ .kept { }";
1260 let result = mask_css_comments(source, false);
1261 assert!(!result.contains("removed"));
1262 assert_eq!(result.len(), source.len());
1263 assert_eq!(result.find(".kept"), source.find(".kept"));
1264 }
1265
1266 #[test]
1267 fn mask_scss_line_comment() {
1268 let source = "// removed\n.kept { }";
1269 let result = mask_css_comments(source, true);
1270 assert!(!result.contains("removed"));
1271 assert_eq!(result.len(), source.len());
1272 assert_eq!(result.find(".kept"), source.find(".kept"));
1273 }
1274
1275 #[test]
1276 fn mask_scss_preserves_css_outside_comments() {
1277 let source = "// line comment\n/* block comment */\n.visible { color: red; }";
1278 let result = mask_css_comments(source, true);
1279 assert!(result.contains(".visible"));
1280 }
1281
1282 #[test]
1283 fn url_import_http() {
1284 assert!(is_css_url_import("http://example.com/style.css"));
1285 }
1286
1287 #[test]
1288 fn url_import_https() {
1289 assert!(is_css_url_import("https://fonts.googleapis.com/css"));
1290 }
1291
1292 #[test]
1293 fn url_import_data() {
1294 assert!(is_css_url_import("data:text/css;base64,abc"));
1295 }
1296
1297 #[test]
1298 fn url_import_local_not_skipped() {
1299 assert!(!is_css_url_import("./local.css"));
1300 }
1301
1302 #[test]
1303 fn url_import_bare_specifier_not_skipped() {
1304 assert!(!is_css_url_import("tailwindcss"));
1305 }
1306
1307 #[test]
1308 fn normalize_relative_dot_path_unchanged() {
1309 assert_eq!(
1310 normalize_css_import_path("./reset.css".to_string(), false),
1311 "./reset.css"
1312 );
1313 }
1314
1315 #[test]
1316 fn normalize_parent_relative_path_unchanged() {
1317 assert_eq!(
1318 normalize_css_import_path("../shared.scss".to_string(), false),
1319 "../shared.scss"
1320 );
1321 }
1322
1323 #[test]
1324 fn normalize_absolute_path_unchanged() {
1325 assert_eq!(
1326 normalize_css_import_path("/styles/main.css".to_string(), false),
1327 "/styles/main.css"
1328 );
1329 }
1330
1331 #[test]
1332 fn normalize_url_unchanged() {
1333 assert_eq!(
1334 normalize_css_import_path("https://example.com/style.css".to_string(), false),
1335 "https://example.com/style.css"
1336 );
1337 }
1338
1339 #[test]
1340 fn normalize_bare_css_gets_dot_slash() {
1341 assert_eq!(
1342 normalize_css_import_path("app.css".to_string(), false),
1343 "./app.css"
1344 );
1345 }
1346
1347 #[test]
1348 fn normalize_css_package_subpath_stays_bare() {
1349 assert_eq!(
1350 normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
1351 "tailwindcss/theme.css"
1352 );
1353 }
1354
1355 #[test]
1356 fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
1357 assert_eq!(
1358 normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
1359 "highlight.js/styles/github.css"
1360 );
1361 }
1362
1363 #[test]
1364 fn normalize_bare_scss_gets_dot_slash() {
1365 assert_eq!(
1366 normalize_css_import_path("vars.scss".to_string(), false),
1367 "./vars.scss"
1368 );
1369 }
1370
1371 #[test]
1372 fn normalize_bare_sass_gets_dot_slash() {
1373 assert_eq!(
1374 normalize_css_import_path("main.sass".to_string(), false),
1375 "./main.sass"
1376 );
1377 }
1378
1379 #[test]
1380 fn normalize_bare_less_gets_dot_slash() {
1381 assert_eq!(
1382 normalize_css_import_path("theme.less".to_string(), false),
1383 "./theme.less"
1384 );
1385 }
1386
1387 #[test]
1388 fn normalize_bare_js_extension_stays_bare() {
1389 assert_eq!(
1390 normalize_css_import_path("module.js".to_string(), false),
1391 "module.js"
1392 );
1393 }
1394
1395 #[test]
1396 fn normalize_scss_bare_partial_gets_dot_slash() {
1397 assert_eq!(
1398 normalize_css_import_path("variables".to_string(), true),
1399 "./variables"
1400 );
1401 }
1402
1403 #[test]
1404 fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
1405 assert_eq!(
1406 normalize_css_import_path("base/reset".to_string(), true),
1407 "./base/reset"
1408 );
1409 }
1410
1411 #[test]
1412 fn normalize_scss_builtin_stays_bare() {
1413 assert_eq!(
1414 normalize_css_import_path("sass:math".to_string(), true),
1415 "sass:math"
1416 );
1417 }
1418
1419 #[test]
1420 fn normalize_scss_relative_path_unchanged() {
1421 assert_eq!(
1422 normalize_css_import_path("../styles/variables".to_string(), true),
1423 "../styles/variables"
1424 );
1425 }
1426
1427 #[test]
1428 fn normalize_css_bare_extensionless_stays_bare() {
1429 assert_eq!(
1430 normalize_css_import_path("tailwindcss".to_string(), false),
1431 "tailwindcss"
1432 );
1433 }
1434
1435 #[test]
1436 fn normalize_scoped_package_with_css_extension_stays_bare() {
1437 assert_eq!(
1438 normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
1439 "@fontsource/monaspace-neon/400.css"
1440 );
1441 }
1442
1443 #[test]
1444 fn normalize_scoped_package_with_scss_extension_stays_bare() {
1445 assert_eq!(
1446 normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
1447 "@company/design-system/tokens.scss"
1448 );
1449 }
1450
1451 #[test]
1452 fn normalize_scoped_package_without_extension_stays_bare() {
1453 assert_eq!(
1454 normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
1455 "@fallow/design-system/styles"
1456 );
1457 }
1458
1459 #[test]
1460 fn normalize_scoped_package_extensionless_scss_stays_bare() {
1461 assert_eq!(
1462 normalize_css_import_path("@company/tokens".to_string(), true),
1463 "@company/tokens"
1464 );
1465 }
1466
1467 #[test]
1468 fn normalize_path_alias_with_css_extension_stays_bare() {
1469 assert_eq!(
1470 normalize_css_import_path("@/components/Button.css".to_string(), false),
1471 "@/components/Button.css"
1472 );
1473 }
1474
1475 #[test]
1476 fn normalize_path_alias_extensionless_stays_bare() {
1477 assert_eq!(
1478 normalize_css_import_path("@/styles/variables".to_string(), false),
1479 "@/styles/variables"
1480 );
1481 }
1482
1483 #[test]
1484 fn mask_css_no_comments() {
1485 let source = ".foo { color: red; }";
1486 assert_eq!(mask_css_comments(source, false), source);
1487 }
1488
1489 #[test]
1490 fn mask_css_multiple_block_comments() {
1491 let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
1492 let result = mask_css_comments(source, false);
1493 assert!(!result.contains("comment-one"));
1494 assert!(!result.contains("comment-two"));
1495 assert!(result.contains(".foo"));
1496 assert!(result.contains(".bar"));
1497 }
1498
1499 #[test]
1500 fn mask_scss_does_not_affect_non_scss() {
1501 let source = "// this stays\n.foo { }";
1502 let result = mask_css_comments(source, false);
1503 assert!(result.contains("// this stays"));
1504 }
1505
1506 #[test]
1507 fn css_module_parses_suppressions() {
1508 let info = parse_css_to_module(
1509 fallow_types::discover::FileId(0),
1510 Path::new("Component.module.css"),
1511 "/* fallow-ignore-file */\n.btn { color: red; }",
1512 0,
1513 );
1514 assert!(!info.suppressions.is_empty());
1515 assert_eq!(info.suppressions[0].line, 0);
1516 }
1517
1518 #[test]
1519 fn extracts_class_starting_with_underscore() {
1520 let names = export_names("._private { } .__dunder { }");
1521 assert!(names.contains(&"_private".to_string()));
1522 assert!(names.contains(&"__dunder".to_string()));
1523 }
1524
1525 #[test]
1526 fn ignores_id_selectors() {
1527 let names = export_names("#myId { color: red; }");
1528 assert!(!names.contains(&"myId".to_string()));
1529 }
1530
1531 #[test]
1532 fn ignores_element_selectors() {
1533 let names = export_names("div { color: red; } span { }");
1534 assert!(names.is_empty());
1535 }
1536
1537 #[test]
1538 fn extract_css_imports_at_import_quoted() {
1539 let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
1540 assert_eq!(imports, vec!["./reset.css"]);
1541 }
1542
1543 #[test]
1544 fn extract_css_imports_package_subpath_stays_bare() {
1545 let imports =
1546 extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
1547 assert_eq!(imports, vec!["tailwindcss/theme.css"]);
1548 }
1549
1550 #[test]
1551 fn extract_css_imports_at_import_url() {
1552 let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
1553 assert_eq!(imports, vec!["./reset.css"]);
1554 }
1555
1556 #[test]
1557 fn extract_css_imports_skips_remote_urls() {
1558 let imports =
1559 extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
1560 assert!(imports.is_empty());
1561 }
1562
1563 #[test]
1564 fn extract_css_imports_scss_use_normalizes_partial() {
1565 let imports = extract_css_imports(r#"@use "variables";"#, true);
1566 assert_eq!(imports, vec!["./variables"]);
1567 }
1568
1569 #[test]
1570 fn extract_css_imports_scss_forward_normalizes_partial() {
1571 let imports = extract_css_imports(r#"@forward "tokens";"#, true);
1572 assert_eq!(imports, vec!["./tokens"]);
1573 }
1574
1575 #[test]
1576 fn extract_css_imports_skips_comments() {
1577 let imports = extract_css_imports(
1578 r#"/* @import "./hidden.scss"; */
1579@use "real";"#,
1580 true,
1581 );
1582 assert_eq!(imports, vec!["./real"]);
1583 }
1584
1585 #[test]
1586 fn extract_css_imports_at_plugin_keeps_package_bare() {
1587 let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1588 assert_eq!(imports, vec!["daisyui"]);
1589 }
1590
1591 #[test]
1592 fn extract_css_imports_at_plugin_tracks_relative_file() {
1593 let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1594 assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1595 }
1596
1597 #[test]
1598 fn extract_css_imports_scss_at_import_kept_relative() {
1599 let imports = extract_css_imports(r"@import 'Foo';", true);
1600 assert_eq!(imports, vec!["./Foo"]);
1601 }
1602
1603 #[test]
1604 fn extract_css_imports_additional_data_string_body() {
1605 let body = r#"@use "./src/styles/global.scss";"#;
1606 let imports = extract_css_imports(body, true);
1607 assert_eq!(imports, vec!["./src/styles/global.scss"]);
1608 }
1609
1610 #[test]
1611 fn mask_with_whitespace_preserves_byte_length() {
1612 let src = "/* hello */ .foo { }";
1613 let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1614 assert_eq!(masked.len(), src.len());
1615 assert!(masked.is_char_boundary(src.len()));
1616 }
1617
1618 #[test]
1619 fn mask_with_whitespace_preserves_offsets_around_multibyte() {
1620 let src = "/* \u{2713} */ .foo { }";
1621 let foo_offset = src.find(".foo").expect("`.foo` present");
1622 let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1623 assert_eq!(masked.len(), src.len());
1624 assert_eq!(masked.find(".foo"), Some(foo_offset));
1625 }
1626
1627 fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1630 let offsets = fallow_types::extract::compute_line_offsets(source);
1631 fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1632 }
1633
1634 #[test]
1635 fn span_points_at_real_class_declaration_line() {
1636 let source = "\n\n\n\n.foo { color: red; }\n";
1637 let exports = extract_css_module_exports(source, false);
1638 assert_eq!(exports.len(), 1);
1639 let span = exports[0].span;
1640 let (line, col) = span_line_col(source, span.start);
1641 assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1642 assert_eq!(
1643 col, 1,
1644 "column points at `f` in `.foo` (post-dot identifier)"
1645 );
1646 assert_eq!(
1647 &source[span.start as usize..span.end as usize],
1648 "foo",
1649 "span range must slice to the class identifier in the original source"
1650 );
1651 }
1652
1653 #[test]
1654 fn span_survives_multibyte_comment_prefix() {
1655 let source = "/* \u{2713} */\n.foo { }";
1656 let exports = extract_css_module_exports(source, false);
1657 assert_eq!(exports.len(), 1);
1658 let span = exports[0].span;
1659 assert!(
1660 source.is_char_boundary(span.start as usize),
1661 "span.start must lie on a UTF-8 char boundary"
1662 );
1663 assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1664 }
1665
1666 #[test]
1667 fn span_skips_at_layer_prelude_dot_segments() {
1668 let source = "@layer foo.bar { }\n.root { }\n";
1669 let exports = extract_css_module_exports(source, false);
1670 let names: Vec<_> = exports
1671 .iter()
1672 .filter_map(|e| match &e.name {
1673 ExportName::Named(n) => Some(n.as_str()),
1674 ExportName::Default => None,
1675 })
1676 .collect();
1677 assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1678 let span = exports[0].span;
1679 let (line, _col) = span_line_col(source, span.start);
1680 assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1681 assert_eq!(&source[span.start as usize..span.end as usize], "root");
1682 }
1683
1684 #[test]
1685 fn span_skips_classes_in_strings() {
1686 let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1687 let exports = extract_css_module_exports(source, false);
1688 let names: Vec<_> = exports
1689 .iter()
1690 .filter_map(|e| match &e.name {
1691 ExportName::Named(n) => Some(n.as_str()),
1692 ExportName::Default => None,
1693 })
1694 .collect();
1695 assert_eq!(names, vec!["real", "also-real"]);
1696 for export in &exports {
1697 let span = export.span;
1698 let slice = &source[span.start as usize..span.end as usize];
1699 match &export.name {
1700 ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1701 ExportName::Default => unreachable!("CSS modules emit only named exports"),
1702 }
1703 }
1704 }
1705
1706 #[test]
1707 fn span_deduplicates_to_first_occurrence() {
1708 let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1709 let exports = extract_css_module_exports(source, false);
1710 assert_eq!(exports.len(), 1);
1711 let (line, _col) = span_line_col(source, exports[0].span.start);
1712 assert_eq!(
1713 line, 1,
1714 "first occurrence wins for deduplicated class names"
1715 );
1716 }
1717
1718 #[test]
1719 fn span_inside_media_query() {
1720 let source =
1721 "@media (max-width: 768px) {\n .mobile { display: block; }\n .desktop { }\n}\n";
1722 let exports = extract_css_module_exports(source, false);
1723 let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
1724 .iter()
1725 .filter_map(|e| match &e.name {
1726 ExportName::Named(n) => Some((n.as_str(), e.span)),
1727 ExportName::Default => None,
1728 })
1729 .collect();
1730 let mobile_line = span_line_col(source, by_name["mobile"].start).0;
1731 let desktop_line = span_line_col(source, by_name["desktop"].start).0;
1732 assert_eq!(mobile_line, 2);
1733 assert_eq!(desktop_line, 3);
1734 }
1735
1736 #[test]
1737 fn at_layer_only_module_emits_no_exports() {
1738 let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
1739 assert!(exports.is_empty());
1740 }
1741
1742 #[test]
1743 fn parse_css_to_module_resolves_real_line_offsets() {
1744 let source = "\n\n\n\n.foo { color: red; }\n";
1745 let info = parse_css_to_module(
1746 fallow_types::discover::FileId(0),
1747 Path::new("Component.module.css"),
1748 source,
1749 0,
1750 );
1751 assert_eq!(info.exports.len(), 1);
1752 let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
1753 &info.line_offsets,
1754 info.exports[0].span.start,
1755 );
1756 assert_eq!(line, 5, "downstream line must equal the source line");
1757 }
1758
1759 fn theme_token_names(source: &str) -> Vec<String> {
1760 scan_theme_blocks(source)
1761 .tokens
1762 .into_iter()
1763 .map(|t| t.name)
1764 .collect()
1765 }
1766
1767 #[test]
1768 fn theme_single_block_collects_tokens() {
1769 let names = theme_token_names("@theme { --color-brand: #f00; --radius-card: 8px; }");
1770 assert_eq!(names, vec!["color-brand", "radius-card"]);
1771 }
1772
1773 #[test]
1774 fn theme_token_values_are_normalized() {
1775 let scan = scan_theme_blocks("@theme {\n --color-brand: rgb( 255 0 0 );\n}");
1776 assert_eq!(scan.tokens[0].name, "color-brand");
1777 assert_eq!(scan.tokens[0].value, "rgb( 255 0 0 )");
1778 }
1779
1780 #[test]
1781 fn theme_dashed_multi_segment_names() {
1782 let names = theme_token_names(
1783 "@theme {\n --font-weight-heavy: 900;\n --inset-shadow-glow: 0 0 4px red;\n}",
1784 );
1785 assert_eq!(names, vec!["font-weight-heavy", "inset-shadow-glow"]);
1786 }
1787
1788 #[test]
1789 fn theme_inline_and_static_modifiers() {
1790 assert_eq!(
1791 theme_token_names("@theme inline { --color-a: red; }"),
1792 vec!["color-a"]
1793 );
1794 assert_eq!(
1795 theme_token_names("@theme static { --color-b: red; }"),
1796 vec!["color-b"]
1797 );
1798 }
1799
1800 #[test]
1801 fn theme_multiple_blocks_union() {
1802 let names = theme_token_names(
1803 "@theme { --color-a: red; }\n.x { color: blue; }\n@theme { --spacing-gutter: 1rem; }",
1804 );
1805 assert_eq!(names, vec!["color-a", "spacing-gutter"]);
1806 }
1807
1808 #[test]
1809 fn theme_reset_form_excluded() {
1810 let names = theme_token_names("@theme { --color-*: initial; --color-brand: red; }");
1812 assert_eq!(names, vec!["color-brand"]);
1813 }
1814
1815 #[test]
1816 fn theme_no_block_yields_nothing() {
1817 assert!(theme_token_names(".x { --color-brand: red; }").is_empty());
1818 }
1819
1820 #[test]
1821 fn theme_line_numbers() {
1822 let scan = scan_theme_blocks("@theme {\n --color-a: red;\n --radius-b: 4px;\n}");
1823 assert_eq!(scan.tokens[0].line, 2);
1824 assert_eq!(scan.tokens[1].line, 3);
1825 }
1826
1827 #[test]
1828 fn theme_token_backs_token_via_var() {
1829 let scan = scan_theme_blocks(
1830 "@theme {\n --color-brand: #f00;\n --color-button: var(--color-brand);\n}",
1831 );
1832 assert!(
1833 scan.theme_var_reads
1834 .iter()
1835 .any(|(name, _)| name == "color-brand")
1836 );
1837 }
1838
1839 #[test]
1840 fn theme_var_read_carries_line() {
1841 let scan = scan_theme_blocks(
1844 "@theme {\n --color-brand: #f00;\n --color-button: var(--color-brand);\n}",
1845 );
1846 assert_eq!(
1847 scan.theme_var_reads,
1848 vec![("color-brand".to_string(), 3u32)]
1849 );
1850 }
1851
1852 #[test]
1853 fn css_var_reads_locate_outside_theme_and_exclude_interior() {
1854 let source = "@theme {\n --color-brand: #f00;\n --color-button: var(--color-brand);\n}\n\n.btn {\n color: var(--color-brand);\n}\n";
1858 assert_eq!(
1859 extract_css_var_reads_located(source),
1860 vec![("color-brand".to_string(), 7u32)],
1861 "only the .btn read (line 7) is a css-var; the @theme-interior read is excluded"
1862 );
1863
1864 assert!(
1866 extract_css_var_reads_located("@theme {\n --a: #fff;\n --b: var(--a);\n}",)
1867 .is_empty(),
1868 "a @theme-interior-only var() read is not a css-var consumer"
1869 );
1870 }
1871
1872 #[test]
1873 fn css_var_reads_line_match_naive_reference_on_dense_line() {
1874 use std::fmt::Write as _;
1880 let mut src = String::from(".x {");
1881 for i in 0..500 {
1882 let _ = write!(src, " color: var(--t{i});");
1883 }
1884 src.push_str(" }\n.y { color: var(--tail); }\n");
1885
1886 let got = extract_css_var_reads_located(&src);
1887
1888 let want: Vec<(String, u32)> = CSS_VAR_REF_RE
1890 .captures_iter(&src)
1891 .filter_map(|cap| cap.get(0).zip(cap.get(1)))
1892 .map(|(whole, name)| {
1893 (
1894 name.as_str().to_owned(),
1895 line_at_offset(&src, whole.start()),
1896 )
1897 })
1898 .collect();
1899
1900 assert_eq!(got, want);
1901 assert!(got.len() > 500, "expected the dense line plus the trailer");
1902 assert_eq!(got.last().map(|(_, l)| *l), Some(2));
1904 assert!(got[..got.len() - 1].iter().all(|(_, l)| *l == 1));
1905 }
1906
1907 #[test]
1908 fn theme_string_braces_do_not_truncate_block() {
1909 let scan = scan_theme_blocks(
1910 "@theme {\n --font-label: \"}\";\n --color-brand: #f00;\n --color-button: var(--color-brand);\n}",
1911 );
1912 assert_eq!(
1913 scan.tokens
1914 .iter()
1915 .map(|token| token.name.as_str())
1916 .collect::<Vec<_>>(),
1917 vec!["font-label", "color-brand", "color-button"]
1918 );
1919 assert!(
1920 scan.theme_var_reads
1921 .iter()
1922 .any(|(name, _)| name == "color-brand")
1923 );
1924 }
1925
1926 #[test]
1927 fn theme_nested_keyframes_body_not_collected() {
1928 let names = theme_token_names(
1931 "@theme {\n --animate-spin: spin 1s linear infinite;\n @keyframes spin { from { --x: 0; } to { --y: 1; } }\n}",
1932 );
1933 assert_eq!(names, vec!["animate-spin"]);
1934 }
1935
1936 #[test]
1937 fn theme_comment_block_ignored() {
1938 let names = theme_token_names("/* @theme { --color-fake: red; } */ .x { color: blue; }");
1939 assert!(names.is_empty(), "got {names:?}");
1940 }
1941
1942 #[test]
1943 fn theme_deduplicates_repeated_token() {
1944 let names = theme_token_names("@theme { --color-a: red; --color-a: blue; }");
1945 assert_eq!(names, vec!["color-a"]);
1946 }
1947
1948 #[test]
1949 fn apply_tokens_basic() {
1950 let tokens = extract_apply_tokens(".panel { @apply rounded-card font-bold; }");
1951 assert_eq!(tokens, vec!["rounded-card", "font-bold"]);
1952 }
1953
1954 #[test]
1955 fn apply_tokens_strips_important() {
1956 let tokens = extract_apply_tokens(".x { @apply text-brand! font-bold !important; }");
1957 assert_eq!(tokens, vec!["text-brand", "font-bold"]);
1958 }
1959
1960 #[test]
1961 fn apply_tokens_ignored_in_comments() {
1962 let tokens = extract_apply_tokens("/* @apply hidden-token; */ .x { color: red; }");
1963 assert!(tokens.is_empty(), "got {tokens:?}");
1964 }
1965}