1use 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
14static CSS_IMPORT_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
17 crate::static_regex(
18 r#"@import\s+(?:url\(\s*(?:["']([^"']+)["']|([^)]+))\s*\)|["']([^"']+)["'])"#,
19 )
20});
21
22static SCSS_USE_RE: LazyLock<regex::Regex> =
25 LazyLock::new(|| crate::static_regex(r#"@(?:use|forward)\s+["']([^"']+)["']"#));
26
27static CSS_PLUGIN_RE: LazyLock<regex::Regex> =
30 LazyLock::new(|| crate::static_regex(r#"@plugin\s+["']([^"']+)["']"#));
31
32static CSS_APPLY_RE: LazyLock<regex::Regex> =
35 LazyLock::new(|| crate::static_regex(r"@apply\s+[^;}\n]+"));
36
37static CSS_TAILWIND_RE: LazyLock<regex::Regex> =
40 LazyLock::new(|| crate::static_regex(r"@tailwind\s+\w+"));
41
42static CSS_COMMENT_RE: LazyLock<regex::Regex> =
44 LazyLock::new(|| crate::static_regex(r"(?s)/\*.*?\*/"));
45
46static SCSS_LINE_COMMENT_RE: LazyLock<regex::Regex> =
48 LazyLock::new(|| crate::static_regex(r"//[^\n]*"));
49
50static CSS_CLASS_RE: LazyLock<regex::Regex> =
53 LazyLock::new(|| crate::static_regex(r"\.([a-zA-Z_][a-zA-Z0-9_-]*)"));
54
55static CSS_NON_SELECTOR_RE: LazyLock<regex::Regex> =
58 LazyLock::new(|| crate::static_regex(r#"(?s)"[^"]*"|'[^']*'|url\([^)]*\)"#));
59
60static CSS_AT_RULE_PRELUDE_RE: LazyLock<regex::Regex> =
72 LazyLock::new(|| crate::static_regex(r"@(?:layer|import)\b[^;{]*"));
73
74pub(crate) fn is_css_file(path: &Path) -> bool {
75 path.extension()
76 .and_then(|e| e.to_str())
77 .is_some_and(|ext| ext == "css" || ext == "scss")
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct CssImportSource {
83 pub raw: String,
85 pub normalized: String,
87 pub is_plugin: bool,
89 pub span: Span,
91}
92
93fn is_css_module_file(path: &Path) -> bool {
94 is_css_file(path)
95 && path
96 .file_stem()
97 .and_then(|s| s.to_str())
98 .is_some_and(|stem| stem.ends_with(".module"))
99}
100
101fn is_css_url_import(source: &str) -> bool {
103 source.starts_with("http://") || source.starts_with("https://") || source.starts_with("data:")
104}
105
106fn normalize_css_import_path(path: String, is_scss: bool) -> String {
119 if path.starts_with('.') || path.starts_with('/') || path.contains("://") {
120 return path;
121 }
122 if path.starts_with('@') && path.contains('/') {
123 return path;
124 }
125 let path_ref = std::path::Path::new(&path);
126 if !is_scss
127 && path.contains('/')
128 && path_ref
129 .extension()
130 .and_then(|e| e.to_str())
131 .is_some_and(is_style_extension)
132 {
133 return path;
134 }
135 let ext = std::path::Path::new(&path)
136 .extension()
137 .and_then(|e| e.to_str());
138 match ext {
139 Some(e) if is_style_extension(e) => format!("./{path}"),
140 _ => {
141 if is_scss && !path.contains(':') {
142 format!("./{path}")
143 } else {
144 path
145 }
146 }
147 }
148}
149
150fn is_style_extension(ext: &str) -> bool {
151 ext.eq_ignore_ascii_case("css")
152 || ext.eq_ignore_ascii_case("scss")
153 || ext.eq_ignore_ascii_case("sass")
154 || ext.eq_ignore_ascii_case("less")
155}
156
157#[cfg(test)]
159fn strip_css_comments(source: &str, is_scss: bool) -> String {
160 let stripped = CSS_COMMENT_RE.replace_all(source, "");
161 if is_scss {
162 SCSS_LINE_COMMENT_RE.replace_all(&stripped, "").into_owned()
163 } else {
164 stripped.into_owned()
165 }
166}
167
168fn mask_css_comments(source: &str, is_scss: bool) -> String {
169 let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
170 if is_scss {
171 masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
172 }
173 masked
174}
175
176fn normalize_css_plugin_path(path: String) -> String {
182 path
183}
184
185#[must_use]
191pub fn extract_css_import_sources(source: &str, is_scss: bool) -> Vec<CssImportSource> {
192 let stripped = mask_css_comments(source, is_scss);
193 let mut out = Vec::new();
194
195 for cap in CSS_IMPORT_RE.captures_iter(&stripped) {
196 let raw = cap.get(1).or_else(|| cap.get(2)).or_else(|| cap.get(3));
197 if let Some(m) = raw {
198 let (src, span) = trimmed_match_with_span(m);
199 if !src.is_empty() && !is_css_url_import(&src) {
200 out.push(CssImportSource {
201 normalized: normalize_css_import_path(src.clone(), is_scss),
202 raw: src,
203 is_plugin: false,
204 span,
205 });
206 }
207 }
208 }
209
210 if is_scss {
211 for cap in SCSS_USE_RE.captures_iter(&stripped) {
212 if let Some(m) = cap.get(1) {
213 let (raw, span) = trimmed_match_with_span(m);
214 out.push(CssImportSource {
215 normalized: normalize_css_import_path(raw.clone(), true),
216 raw,
217 is_plugin: false,
218 span,
219 });
220 }
221 }
222 }
223
224 for cap in CSS_PLUGIN_RE.captures_iter(&stripped) {
225 if let Some(m) = cap.get(1) {
226 let (raw, span) = trimmed_match_with_span(m);
227 if !raw.is_empty() && !is_css_url_import(&raw) {
228 out.push(CssImportSource {
229 normalized: normalize_css_plugin_path(raw.clone()),
230 raw,
231 is_plugin: true,
232 span,
233 });
234 }
235 }
236 }
237
238 out
239}
240
241fn trimmed_match_with_span(m: regex::Match<'_>) -> (String, Span) {
242 let raw = m.as_str();
243 let trimmed_start = raw.len() - raw.trim_start().len();
244 let trimmed_end = raw.trim_end().len();
245 let start = m.start() + trimmed_start;
246 let end = m.start() + trimmed_end;
247 (raw.trim().to_string(), Span::new(start as u32, end as u32))
248}
249
250#[must_use]
257pub fn extract_css_imports(source: &str, is_scss: bool) -> Vec<String> {
258 extract_css_import_sources(source, is_scss)
259 .into_iter()
260 .map(|source| source.normalized)
261 .collect()
262}
263
264fn mask_with_whitespace(src: &str, re: ®ex::Regex) -> String {
274 let mut out = String::with_capacity(src.len());
275 let mut cursor = 0;
276 for m in re.find_iter(src) {
277 out.push_str(&src[cursor..m.start()]);
278 for _ in m.start()..m.end() {
279 out.push(' ');
280 }
281 cursor = m.end();
282 }
283 out.push_str(&src[cursor..]);
284 out
285}
286
287pub fn extract_css_module_exports(source: &str, is_scss: bool) -> Vec<ExportInfo> {
294 let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
295 if is_scss {
296 masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
297 }
298 masked = mask_with_whitespace(&masked, &CSS_NON_SELECTOR_RE);
299 masked = mask_with_whitespace(&masked, &CSS_AT_RULE_PRELUDE_RE);
300
301 let mut seen = rustc_hash::FxHashSet::default();
302 let mut exports = Vec::new();
303 for cap in CSS_CLASS_RE.captures_iter(&masked) {
304 if let Some(m) = cap.get(1) {
305 let class_name = m.as_str().to_string();
306 if seen.insert(class_name.clone()) {
307 #[expect(
308 clippy::cast_possible_truncation,
309 reason = "CSS files exceeding u32::MAX bytes are not a realistic input"
310 )]
311 let span = Span::new(m.start() as u32, m.end() as u32);
312 exports.push(ExportInfo {
313 name: ExportName::Named(class_name),
314 local_name: None,
315 is_type_only: false,
316 visibility: VisibilityTag::None,
317 span,
318 members: Vec::new(),
319 is_side_effect_used: false,
320 super_class: None,
321 });
322 }
323 }
324 }
325 exports
326}
327
328pub(crate) fn parse_css_to_module(
330 file_id: FileId,
331 path: &Path,
332 source: &str,
333 content_hash: u64,
334) -> ModuleInfo {
335 let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
336 let is_scss = path
337 .extension()
338 .and_then(|e| e.to_str())
339 .is_some_and(|ext| ext == "scss");
340
341 let stripped = mask_css_comments(source, is_scss);
342
343 let mut imports = Vec::new();
344
345 for source in extract_css_import_sources(source, is_scss) {
346 imports.push(ImportInfo {
347 source: source.normalized,
348 imported_name: if source.is_plugin {
349 ImportedName::Default
350 } else {
351 ImportedName::SideEffect
352 },
353 local_name: String::new(),
354 is_type_only: false,
355 from_style: false,
356 span: source.span,
357 source_span: source.span,
358 });
359 }
360
361 let has_apply = CSS_APPLY_RE.is_match(&stripped);
362 let has_tailwind = CSS_TAILWIND_RE.is_match(&stripped);
363 if has_apply || has_tailwind {
364 imports.push(ImportInfo {
365 source: "tailwindcss".to_string(),
366 imported_name: ImportedName::SideEffect,
367 local_name: String::new(),
368 is_type_only: false,
369 from_style: false,
370 span: Span::default(),
371 source_span: Span::default(),
372 });
373 }
374
375 let exports = if is_css_module_file(path) {
376 extract_css_module_exports(source, is_scss)
377 } else {
378 Vec::new()
379 };
380
381 ModuleInfo {
382 file_id,
383 exports,
384 imports,
385 re_exports: Vec::new(),
386 dynamic_imports: Vec::new(),
387 dynamic_import_patterns: Vec::new(),
388 require_calls: Vec::new(),
389 member_accesses: Vec::new(),
390 whole_object_uses: Vec::new(),
391 has_cjs_exports: false,
392 has_angular_component_template_url: false,
393 content_hash,
394 suppressions: parsed_suppressions.suppressions,
395 unknown_suppression_kinds: parsed_suppressions.unknown_kinds,
396 unused_import_bindings: Vec::new(),
397 type_referenced_import_bindings: Vec::new(),
398 value_referenced_import_bindings: Vec::new(),
399 line_offsets: fallow_types::extract::compute_line_offsets(source),
400 complexity: Vec::new(),
401 flag_uses: Vec::new(),
402 class_heritage: vec![],
403 local_type_declarations: Vec::new(),
404 public_signature_type_references: Vec::new(),
405 namespace_object_aliases: Vec::new(),
406 iconify_prefixes: Vec::new(),
407 auto_import_candidates: Vec::new(),
408 directives: Vec::new(),
409 security_sinks: Vec::new(),
410 security_sinks_skipped: 0,
411 }
412}
413
414#[cfg(test)]
415mod tests {
416 use super::*;
417
418 fn export_names(source: &str) -> Vec<String> {
420 extract_css_module_exports(source, false)
421 .into_iter()
422 .filter_map(|e| match e.name {
423 ExportName::Named(n) => Some(n),
424 ExportName::Default => None,
425 })
426 .collect()
427 }
428
429 #[test]
430 fn is_css_file_css() {
431 assert!(is_css_file(Path::new("styles.css")));
432 }
433
434 #[test]
435 fn is_css_file_scss() {
436 assert!(is_css_file(Path::new("styles.scss")));
437 }
438
439 #[test]
440 fn is_css_file_rejects_js() {
441 assert!(!is_css_file(Path::new("app.js")));
442 }
443
444 #[test]
445 fn is_css_file_rejects_ts() {
446 assert!(!is_css_file(Path::new("app.ts")));
447 }
448
449 #[test]
450 fn is_css_file_rejects_less() {
451 assert!(!is_css_file(Path::new("styles.less")));
452 }
453
454 #[test]
455 fn is_css_file_rejects_no_extension() {
456 assert!(!is_css_file(Path::new("Makefile")));
457 }
458
459 #[test]
460 fn is_css_module_file_module_css() {
461 assert!(is_css_module_file(Path::new("Component.module.css")));
462 }
463
464 #[test]
465 fn is_css_module_file_module_scss() {
466 assert!(is_css_module_file(Path::new("Component.module.scss")));
467 }
468
469 #[test]
470 fn is_css_module_file_rejects_plain_css() {
471 assert!(!is_css_module_file(Path::new("styles.css")));
472 }
473
474 #[test]
475 fn is_css_module_file_rejects_plain_scss() {
476 assert!(!is_css_module_file(Path::new("styles.scss")));
477 }
478
479 #[test]
480 fn is_css_module_file_rejects_module_js() {
481 assert!(!is_css_module_file(Path::new("utils.module.js")));
482 }
483
484 #[test]
485 fn extracts_single_class() {
486 let names = export_names(".foo { color: red; }");
487 assert_eq!(names, vec!["foo"]);
488 }
489
490 #[test]
491 fn extracts_multiple_classes() {
492 let names = export_names(".foo { } .bar { }");
493 assert_eq!(names, vec!["foo", "bar"]);
494 }
495
496 #[test]
497 fn extracts_nested_classes() {
498 let names = export_names(".foo .bar { color: red; }");
499 assert!(names.contains(&"foo".to_string()));
500 assert!(names.contains(&"bar".to_string()));
501 }
502
503 #[test]
504 fn extracts_hyphenated_class() {
505 let names = export_names(".my-class { }");
506 assert_eq!(names, vec!["my-class"]);
507 }
508
509 #[test]
510 fn extracts_camel_case_class() {
511 let names = export_names(".myClass { }");
512 assert_eq!(names, vec!["myClass"]);
513 }
514
515 #[test]
516 fn extracts_underscore_class() {
517 let names = export_names("._hidden { } .__wrapper { }");
518 assert!(names.contains(&"_hidden".to_string()));
519 assert!(names.contains(&"__wrapper".to_string()));
520 }
521
522 #[test]
523 fn pseudo_selector_hover() {
524 let names = export_names(".foo:hover { color: blue; }");
525 assert_eq!(names, vec!["foo"]);
526 }
527
528 #[test]
529 fn pseudo_selector_focus() {
530 let names = export_names(".input:focus { outline: none; }");
531 assert_eq!(names, vec!["input"]);
532 }
533
534 #[test]
535 fn pseudo_element_before() {
536 let names = export_names(".icon::before { content: ''; }");
537 assert_eq!(names, vec!["icon"]);
538 }
539
540 #[test]
541 fn combined_pseudo_selectors() {
542 let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
543 assert_eq!(names, vec!["btn"]);
544 }
545
546 #[test]
547 fn classes_inside_media_query() {
548 let names = export_names(
549 "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
550 );
551 assert!(names.contains(&"mobile-nav".to_string()));
552 assert!(names.contains(&"desktop-nav".to_string()));
553 }
554
555 #[test]
556 fn classes_inside_multi_line_media_query() {
557 let names =
558 export_names("@media\n screen and (min-width: 600px)\n{\n .real { color: red; }\n}");
559 assert_eq!(names, vec!["real"]);
560 }
561
562 #[test]
563 fn at_layer_statement_does_not_export() {
564 let names = export_names("@layer foo.bar;");
565 assert!(names.is_empty(), "got {names:?}");
566 let names = export_names("@layer foo.bar, foo.baz;");
567 assert!(names.is_empty(), "got {names:?}");
568 }
569
570 #[test]
571 fn at_layer_block_keeps_body_classes() {
572 let names = export_names("@layer foo.bar { .root { color: red; } }");
573 assert_eq!(names, vec!["root"]);
574 }
575
576 #[test]
577 fn at_layer_multiline_prelude_keeps_body_classes() {
578 let names = export_names("@layer\n foo.bar\n{ .root { color: red; } }");
579 assert_eq!(names, vec!["root"]);
580 }
581
582 #[test]
583 fn at_layer_with_nested_media_keeps_body() {
584 let names =
585 export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
586 assert_eq!(names, vec!["real"]);
587 }
588
589 #[test]
590 fn at_import_with_layer_attribute_does_not_export() {
591 let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
592 assert!(names.is_empty(), "got {names:?}");
593 }
594
595 #[test]
596 fn class_then_at_layer_does_not_leak_prelude() {
597 let names =
598 export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
599 assert_eq!(names, vec!["outer", "inner"]);
600 }
601
602 #[test]
603 fn at_scope_keeps_selector_list_classes() {
604 let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
605 assert!(names.contains(&"parent".to_string()), "got {names:?}");
606 assert!(names.contains(&"child".to_string()), "got {names:?}");
607 assert!(names.contains(&"title".to_string()), "got {names:?}");
608 }
609
610 #[test]
611 fn at_keyframes_numeric_step_is_not_class() {
612 let names = export_names(
613 "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
614 );
615 assert!(names.is_empty(), "got {names:?}");
616 }
617
618 #[test]
619 fn at_webkit_keyframes_keeps_body_classes() {
620 let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
621 assert_eq!(names, vec!["real"]);
622 }
623
624 #[test]
625 fn deduplicates_repeated_class() {
626 let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
627 assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
628 }
629
630 #[test]
631 fn empty_source() {
632 let names = export_names("");
633 assert!(names.is_empty());
634 }
635
636 #[test]
637 fn no_classes() {
638 let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
639 assert!(names.is_empty());
640 }
641
642 #[test]
643 fn ignores_classes_in_block_comments() {
644 let names = export_names("/* .fake { } */ .real { }");
645 assert!(!names.contains(&"fake".to_string()));
646 assert!(names.contains(&"real".to_string()));
647 }
648
649 #[test]
650 fn ignores_classes_in_scss_line_comments() {
651 let exports = extract_css_module_exports("// .fake\n.real { }", true);
652 let names: Vec<_> = exports
653 .iter()
654 .filter_map(|e| match &e.name {
655 ExportName::Named(n) => Some(n.as_str()),
656 ExportName::Default => None,
657 })
658 .collect();
659 assert_eq!(names, vec!["real"]);
660 }
661
662 #[test]
663 fn ignores_classes_in_strings() {
664 let names = export_names(r#".real { content: ".fake"; }"#);
665 assert!(names.contains(&"real".to_string()));
666 assert!(!names.contains(&"fake".to_string()));
667 }
668
669 #[test]
670 fn ignores_classes_in_url() {
671 let names = export_names(".real { background: url(./images/hero.png); }");
672 assert!(names.contains(&"real".to_string()));
673 assert!(!names.contains(&"png".to_string()));
674 }
675
676 #[test]
677 fn strip_css_block_comment() {
678 let result = strip_css_comments("/* removed */ .kept { }", false);
679 assert!(!result.contains("removed"));
680 assert!(result.contains(".kept"));
681 }
682
683 #[test]
684 fn strip_scss_line_comment() {
685 let result = strip_css_comments("// removed\n.kept { }", true);
686 assert!(!result.contains("removed"));
687 assert!(result.contains(".kept"));
688 }
689
690 #[test]
691 fn strip_scss_preserves_css_outside_comments() {
692 let source = "// line comment\n/* block comment */\n.visible { color: red; }";
693 let result = strip_css_comments(source, true);
694 assert!(result.contains(".visible"));
695 }
696
697 #[test]
698 fn url_import_http() {
699 assert!(is_css_url_import("http://example.com/style.css"));
700 }
701
702 #[test]
703 fn url_import_https() {
704 assert!(is_css_url_import("https://fonts.googleapis.com/css"));
705 }
706
707 #[test]
708 fn url_import_data() {
709 assert!(is_css_url_import("data:text/css;base64,abc"));
710 }
711
712 #[test]
713 fn url_import_local_not_skipped() {
714 assert!(!is_css_url_import("./local.css"));
715 }
716
717 #[test]
718 fn url_import_bare_specifier_not_skipped() {
719 assert!(!is_css_url_import("tailwindcss"));
720 }
721
722 #[test]
723 fn normalize_relative_dot_path_unchanged() {
724 assert_eq!(
725 normalize_css_import_path("./reset.css".to_string(), false),
726 "./reset.css"
727 );
728 }
729
730 #[test]
731 fn normalize_parent_relative_path_unchanged() {
732 assert_eq!(
733 normalize_css_import_path("../shared.scss".to_string(), false),
734 "../shared.scss"
735 );
736 }
737
738 #[test]
739 fn normalize_absolute_path_unchanged() {
740 assert_eq!(
741 normalize_css_import_path("/styles/main.css".to_string(), false),
742 "/styles/main.css"
743 );
744 }
745
746 #[test]
747 fn normalize_url_unchanged() {
748 assert_eq!(
749 normalize_css_import_path("https://example.com/style.css".to_string(), false),
750 "https://example.com/style.css"
751 );
752 }
753
754 #[test]
755 fn normalize_bare_css_gets_dot_slash() {
756 assert_eq!(
757 normalize_css_import_path("app.css".to_string(), false),
758 "./app.css"
759 );
760 }
761
762 #[test]
763 fn normalize_css_package_subpath_stays_bare() {
764 assert_eq!(
765 normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
766 "tailwindcss/theme.css"
767 );
768 }
769
770 #[test]
771 fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
772 assert_eq!(
773 normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
774 "highlight.js/styles/github.css"
775 );
776 }
777
778 #[test]
779 fn normalize_bare_scss_gets_dot_slash() {
780 assert_eq!(
781 normalize_css_import_path("vars.scss".to_string(), false),
782 "./vars.scss"
783 );
784 }
785
786 #[test]
787 fn normalize_bare_sass_gets_dot_slash() {
788 assert_eq!(
789 normalize_css_import_path("main.sass".to_string(), false),
790 "./main.sass"
791 );
792 }
793
794 #[test]
795 fn normalize_bare_less_gets_dot_slash() {
796 assert_eq!(
797 normalize_css_import_path("theme.less".to_string(), false),
798 "./theme.less"
799 );
800 }
801
802 #[test]
803 fn normalize_bare_js_extension_stays_bare() {
804 assert_eq!(
805 normalize_css_import_path("module.js".to_string(), false),
806 "module.js"
807 );
808 }
809
810 #[test]
811 fn normalize_scss_bare_partial_gets_dot_slash() {
812 assert_eq!(
813 normalize_css_import_path("variables".to_string(), true),
814 "./variables"
815 );
816 }
817
818 #[test]
819 fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
820 assert_eq!(
821 normalize_css_import_path("base/reset".to_string(), true),
822 "./base/reset"
823 );
824 }
825
826 #[test]
827 fn normalize_scss_builtin_stays_bare() {
828 assert_eq!(
829 normalize_css_import_path("sass:math".to_string(), true),
830 "sass:math"
831 );
832 }
833
834 #[test]
835 fn normalize_scss_relative_path_unchanged() {
836 assert_eq!(
837 normalize_css_import_path("../styles/variables".to_string(), true),
838 "../styles/variables"
839 );
840 }
841
842 #[test]
843 fn normalize_css_bare_extensionless_stays_bare() {
844 assert_eq!(
845 normalize_css_import_path("tailwindcss".to_string(), false),
846 "tailwindcss"
847 );
848 }
849
850 #[test]
851 fn normalize_scoped_package_with_css_extension_stays_bare() {
852 assert_eq!(
853 normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
854 "@fontsource/monaspace-neon/400.css"
855 );
856 }
857
858 #[test]
859 fn normalize_scoped_package_with_scss_extension_stays_bare() {
860 assert_eq!(
861 normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
862 "@company/design-system/tokens.scss"
863 );
864 }
865
866 #[test]
867 fn normalize_scoped_package_without_extension_stays_bare() {
868 assert_eq!(
869 normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
870 "@fallow/design-system/styles"
871 );
872 }
873
874 #[test]
875 fn normalize_scoped_package_extensionless_scss_stays_bare() {
876 assert_eq!(
877 normalize_css_import_path("@company/tokens".to_string(), true),
878 "@company/tokens"
879 );
880 }
881
882 #[test]
883 fn normalize_path_alias_with_css_extension_stays_bare() {
884 assert_eq!(
885 normalize_css_import_path("@/components/Button.css".to_string(), false),
886 "@/components/Button.css"
887 );
888 }
889
890 #[test]
891 fn normalize_path_alias_extensionless_stays_bare() {
892 assert_eq!(
893 normalize_css_import_path("@/styles/variables".to_string(), false),
894 "@/styles/variables"
895 );
896 }
897
898 #[test]
899 fn strip_css_no_comments() {
900 let source = ".foo { color: red; }";
901 assert_eq!(strip_css_comments(source, false), source);
902 }
903
904 #[test]
905 fn strip_css_multiple_block_comments() {
906 let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
907 let result = strip_css_comments(source, false);
908 assert!(!result.contains("comment-one"));
909 assert!(!result.contains("comment-two"));
910 assert!(result.contains(".foo"));
911 assert!(result.contains(".bar"));
912 }
913
914 #[test]
915 fn strip_scss_does_not_affect_non_scss() {
916 let source = "// this stays\n.foo { }";
917 let result = strip_css_comments(source, false);
918 assert!(result.contains("// this stays"));
919 }
920
921 #[test]
922 fn css_module_parses_suppressions() {
923 let info = parse_css_to_module(
924 fallow_types::discover::FileId(0),
925 Path::new("Component.module.css"),
926 "/* fallow-ignore-file */\n.btn { color: red; }",
927 0,
928 );
929 assert!(!info.suppressions.is_empty());
930 assert_eq!(info.suppressions[0].line, 0);
931 }
932
933 #[test]
934 fn extracts_class_starting_with_underscore() {
935 let names = export_names("._private { } .__dunder { }");
936 assert!(names.contains(&"_private".to_string()));
937 assert!(names.contains(&"__dunder".to_string()));
938 }
939
940 #[test]
941 fn ignores_id_selectors() {
942 let names = export_names("#myId { color: red; }");
943 assert!(!names.contains(&"myId".to_string()));
944 }
945
946 #[test]
947 fn ignores_element_selectors() {
948 let names = export_names("div { color: red; } span { }");
949 assert!(names.is_empty());
950 }
951
952 #[test]
953 fn extract_css_imports_at_import_quoted() {
954 let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
955 assert_eq!(imports, vec!["./reset.css"]);
956 }
957
958 #[test]
959 fn extract_css_imports_package_subpath_stays_bare() {
960 let imports =
961 extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
962 assert_eq!(imports, vec!["tailwindcss/theme.css"]);
963 }
964
965 #[test]
966 fn extract_css_imports_at_import_url() {
967 let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
968 assert_eq!(imports, vec!["./reset.css"]);
969 }
970
971 #[test]
972 fn extract_css_imports_skips_remote_urls() {
973 let imports =
974 extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
975 assert!(imports.is_empty());
976 }
977
978 #[test]
979 fn extract_css_imports_scss_use_normalizes_partial() {
980 let imports = extract_css_imports(r#"@use "variables";"#, true);
981 assert_eq!(imports, vec!["./variables"]);
982 }
983
984 #[test]
985 fn extract_css_imports_scss_forward_normalizes_partial() {
986 let imports = extract_css_imports(r#"@forward "tokens";"#, true);
987 assert_eq!(imports, vec!["./tokens"]);
988 }
989
990 #[test]
991 fn extract_css_imports_skips_comments() {
992 let imports = extract_css_imports(
993 r#"/* @import "./hidden.scss"; */
994@use "real";"#,
995 true,
996 );
997 assert_eq!(imports, vec!["./real"]);
998 }
999
1000 #[test]
1001 fn extract_css_imports_at_plugin_keeps_package_bare() {
1002 let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1003 assert_eq!(imports, vec!["daisyui"]);
1004 }
1005
1006 #[test]
1007 fn extract_css_imports_at_plugin_tracks_relative_file() {
1008 let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1009 assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1010 }
1011
1012 #[test]
1013 fn extract_css_imports_scss_at_import_kept_relative() {
1014 let imports = extract_css_imports(r"@import 'Foo';", true);
1015 assert_eq!(imports, vec!["./Foo"]);
1016 }
1017
1018 #[test]
1019 fn extract_css_imports_additional_data_string_body() {
1020 let body = r#"@use "./src/styles/global.scss";"#;
1021 let imports = extract_css_imports(body, true);
1022 assert_eq!(imports, vec!["./src/styles/global.scss"]);
1023 }
1024
1025 #[test]
1026 fn mask_with_whitespace_preserves_byte_length() {
1027 let src = "/* hello */ .foo { }";
1028 let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1029 assert_eq!(masked.len(), src.len());
1030 assert!(masked.is_char_boundary(src.len()));
1031 }
1032
1033 #[test]
1034 fn mask_with_whitespace_preserves_offsets_around_multibyte() {
1035 let src = "/* \u{2713} */ .foo { }";
1036 let foo_offset = src.find(".foo").expect("`.foo` present");
1037 let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1038 assert_eq!(masked.len(), src.len());
1039 assert_eq!(masked.find(".foo"), Some(foo_offset));
1040 }
1041
1042 fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1045 let offsets = fallow_types::extract::compute_line_offsets(source);
1046 fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1047 }
1048
1049 #[test]
1050 fn span_points_at_real_class_declaration_line() {
1051 let source = "\n\n\n\n.foo { color: red; }\n";
1052 let exports = extract_css_module_exports(source, false);
1053 assert_eq!(exports.len(), 1);
1054 let span = exports[0].span;
1055 let (line, col) = span_line_col(source, span.start);
1056 assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1057 assert_eq!(
1058 col, 1,
1059 "column points at `f` in `.foo` (post-dot identifier)"
1060 );
1061 assert_eq!(
1062 &source[span.start as usize..span.end as usize],
1063 "foo",
1064 "span range must slice to the class identifier in the original source"
1065 );
1066 }
1067
1068 #[test]
1069 fn span_survives_multibyte_comment_prefix() {
1070 let source = "/* \u{2713} */\n.foo { }";
1071 let exports = extract_css_module_exports(source, false);
1072 assert_eq!(exports.len(), 1);
1073 let span = exports[0].span;
1074 assert!(
1075 source.is_char_boundary(span.start as usize),
1076 "span.start must lie on a UTF-8 char boundary"
1077 );
1078 assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1079 }
1080
1081 #[test]
1082 fn span_skips_at_layer_prelude_dot_segments() {
1083 let source = "@layer foo.bar { }\n.root { }\n";
1084 let exports = extract_css_module_exports(source, false);
1085 let names: Vec<_> = exports
1086 .iter()
1087 .filter_map(|e| match &e.name {
1088 ExportName::Named(n) => Some(n.as_str()),
1089 ExportName::Default => None,
1090 })
1091 .collect();
1092 assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1093 let span = exports[0].span;
1094 let (line, _col) = span_line_col(source, span.start);
1095 assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1096 assert_eq!(&source[span.start as usize..span.end as usize], "root");
1097 }
1098
1099 #[test]
1100 fn span_skips_classes_in_strings() {
1101 let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1102 let exports = extract_css_module_exports(source, false);
1103 let names: Vec<_> = exports
1104 .iter()
1105 .filter_map(|e| match &e.name {
1106 ExportName::Named(n) => Some(n.as_str()),
1107 ExportName::Default => None,
1108 })
1109 .collect();
1110 assert_eq!(names, vec!["real", "also-real"]);
1111 for export in &exports {
1112 let span = export.span;
1113 let slice = &source[span.start as usize..span.end as usize];
1114 match &export.name {
1115 ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1116 ExportName::Default => unreachable!("CSS modules emit only named exports"),
1117 }
1118 }
1119 }
1120
1121 #[test]
1122 fn span_deduplicates_to_first_occurrence() {
1123 let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1124 let exports = extract_css_module_exports(source, false);
1125 assert_eq!(exports.len(), 1);
1126 let (line, _col) = span_line_col(source, exports[0].span.start);
1127 assert_eq!(
1128 line, 1,
1129 "first occurrence wins for deduplicated class names"
1130 );
1131 }
1132
1133 #[test]
1134 fn span_inside_media_query() {
1135 let source =
1136 "@media (max-width: 768px) {\n .mobile { display: block; }\n .desktop { }\n}\n";
1137 let exports = extract_css_module_exports(source, false);
1138 let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
1139 .iter()
1140 .filter_map(|e| match &e.name {
1141 ExportName::Named(n) => Some((n.as_str(), e.span)),
1142 ExportName::Default => None,
1143 })
1144 .collect();
1145 let mobile_line = span_line_col(source, by_name["mobile"].start).0;
1146 let desktop_line = span_line_col(source, by_name["desktop"].start).0;
1147 assert_eq!(mobile_line, 2);
1148 assert_eq!(desktop_line, 3);
1149 }
1150
1151 #[test]
1152 fn at_layer_only_module_emits_no_exports() {
1153 let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
1154 assert!(exports.is_empty());
1155 }
1156
1157 #[test]
1158 fn parse_css_to_module_resolves_real_line_offsets() {
1159 let source = "\n\n\n\n.foo { color: red; }\n";
1160 let info = parse_css_to_module(
1161 fallow_types::discover::FileId(0),
1162 Path::new("Component.module.css"),
1163 source,
1164 0,
1165 );
1166 assert_eq!(info.exports.len(), 1);
1167 let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
1168 &info.line_offsets,
1169 info.exports[0].span.start,
1170 );
1171 assert_eq!(line, 5, "downstream line must equal the source line");
1172 }
1173}