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 tainted_bindings: Vec::new(),
412 sanitized_sink_args: Vec::new(),
413 }
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419
420 fn export_names(source: &str) -> Vec<String> {
422 extract_css_module_exports(source, false)
423 .into_iter()
424 .filter_map(|e| match e.name {
425 ExportName::Named(n) => Some(n),
426 ExportName::Default => None,
427 })
428 .collect()
429 }
430
431 #[test]
432 fn is_css_file_css() {
433 assert!(is_css_file(Path::new("styles.css")));
434 }
435
436 #[test]
437 fn is_css_file_scss() {
438 assert!(is_css_file(Path::new("styles.scss")));
439 }
440
441 #[test]
442 fn is_css_file_rejects_js() {
443 assert!(!is_css_file(Path::new("app.js")));
444 }
445
446 #[test]
447 fn is_css_file_rejects_ts() {
448 assert!(!is_css_file(Path::new("app.ts")));
449 }
450
451 #[test]
452 fn is_css_file_rejects_less() {
453 assert!(!is_css_file(Path::new("styles.less")));
454 }
455
456 #[test]
457 fn is_css_file_rejects_no_extension() {
458 assert!(!is_css_file(Path::new("Makefile")));
459 }
460
461 #[test]
462 fn is_css_module_file_module_css() {
463 assert!(is_css_module_file(Path::new("Component.module.css")));
464 }
465
466 #[test]
467 fn is_css_module_file_module_scss() {
468 assert!(is_css_module_file(Path::new("Component.module.scss")));
469 }
470
471 #[test]
472 fn is_css_module_file_rejects_plain_css() {
473 assert!(!is_css_module_file(Path::new("styles.css")));
474 }
475
476 #[test]
477 fn is_css_module_file_rejects_plain_scss() {
478 assert!(!is_css_module_file(Path::new("styles.scss")));
479 }
480
481 #[test]
482 fn is_css_module_file_rejects_module_js() {
483 assert!(!is_css_module_file(Path::new("utils.module.js")));
484 }
485
486 #[test]
487 fn extracts_single_class() {
488 let names = export_names(".foo { color: red; }");
489 assert_eq!(names, vec!["foo"]);
490 }
491
492 #[test]
493 fn extracts_multiple_classes() {
494 let names = export_names(".foo { } .bar { }");
495 assert_eq!(names, vec!["foo", "bar"]);
496 }
497
498 #[test]
499 fn extracts_nested_classes() {
500 let names = export_names(".foo .bar { color: red; }");
501 assert!(names.contains(&"foo".to_string()));
502 assert!(names.contains(&"bar".to_string()));
503 }
504
505 #[test]
506 fn extracts_hyphenated_class() {
507 let names = export_names(".my-class { }");
508 assert_eq!(names, vec!["my-class"]);
509 }
510
511 #[test]
512 fn extracts_camel_case_class() {
513 let names = export_names(".myClass { }");
514 assert_eq!(names, vec!["myClass"]);
515 }
516
517 #[test]
518 fn extracts_underscore_class() {
519 let names = export_names("._hidden { } .__wrapper { }");
520 assert!(names.contains(&"_hidden".to_string()));
521 assert!(names.contains(&"__wrapper".to_string()));
522 }
523
524 #[test]
525 fn pseudo_selector_hover() {
526 let names = export_names(".foo:hover { color: blue; }");
527 assert_eq!(names, vec!["foo"]);
528 }
529
530 #[test]
531 fn pseudo_selector_focus() {
532 let names = export_names(".input:focus { outline: none; }");
533 assert_eq!(names, vec!["input"]);
534 }
535
536 #[test]
537 fn pseudo_element_before() {
538 let names = export_names(".icon::before { content: ''; }");
539 assert_eq!(names, vec!["icon"]);
540 }
541
542 #[test]
543 fn combined_pseudo_selectors() {
544 let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
545 assert_eq!(names, vec!["btn"]);
546 }
547
548 #[test]
549 fn classes_inside_media_query() {
550 let names = export_names(
551 "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
552 );
553 assert!(names.contains(&"mobile-nav".to_string()));
554 assert!(names.contains(&"desktop-nav".to_string()));
555 }
556
557 #[test]
558 fn classes_inside_multi_line_media_query() {
559 let names =
560 export_names("@media\n screen and (min-width: 600px)\n{\n .real { color: red; }\n}");
561 assert_eq!(names, vec!["real"]);
562 }
563
564 #[test]
565 fn at_layer_statement_does_not_export() {
566 let names = export_names("@layer foo.bar;");
567 assert!(names.is_empty(), "got {names:?}");
568 let names = export_names("@layer foo.bar, foo.baz;");
569 assert!(names.is_empty(), "got {names:?}");
570 }
571
572 #[test]
573 fn at_layer_block_keeps_body_classes() {
574 let names = export_names("@layer foo.bar { .root { color: red; } }");
575 assert_eq!(names, vec!["root"]);
576 }
577
578 #[test]
579 fn at_layer_multiline_prelude_keeps_body_classes() {
580 let names = export_names("@layer\n foo.bar\n{ .root { color: red; } }");
581 assert_eq!(names, vec!["root"]);
582 }
583
584 #[test]
585 fn at_layer_with_nested_media_keeps_body() {
586 let names =
587 export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
588 assert_eq!(names, vec!["real"]);
589 }
590
591 #[test]
592 fn at_import_with_layer_attribute_does_not_export() {
593 let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
594 assert!(names.is_empty(), "got {names:?}");
595 }
596
597 #[test]
598 fn class_then_at_layer_does_not_leak_prelude() {
599 let names =
600 export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
601 assert_eq!(names, vec!["outer", "inner"]);
602 }
603
604 #[test]
605 fn at_scope_keeps_selector_list_classes() {
606 let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
607 assert!(names.contains(&"parent".to_string()), "got {names:?}");
608 assert!(names.contains(&"child".to_string()), "got {names:?}");
609 assert!(names.contains(&"title".to_string()), "got {names:?}");
610 }
611
612 #[test]
613 fn at_keyframes_numeric_step_is_not_class() {
614 let names = export_names(
615 "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
616 );
617 assert!(names.is_empty(), "got {names:?}");
618 }
619
620 #[test]
621 fn at_webkit_keyframes_keeps_body_classes() {
622 let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
623 assert_eq!(names, vec!["real"]);
624 }
625
626 #[test]
627 fn deduplicates_repeated_class() {
628 let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
629 assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
630 }
631
632 #[test]
633 fn empty_source() {
634 let names = export_names("");
635 assert!(names.is_empty());
636 }
637
638 #[test]
639 fn no_classes() {
640 let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
641 assert!(names.is_empty());
642 }
643
644 #[test]
645 fn ignores_classes_in_block_comments() {
646 let names = export_names("/* .fake { } */ .real { }");
647 assert!(!names.contains(&"fake".to_string()));
648 assert!(names.contains(&"real".to_string()));
649 }
650
651 #[test]
652 fn ignores_classes_in_scss_line_comments() {
653 let exports = extract_css_module_exports("// .fake\n.real { }", true);
654 let names: Vec<_> = exports
655 .iter()
656 .filter_map(|e| match &e.name {
657 ExportName::Named(n) => Some(n.as_str()),
658 ExportName::Default => None,
659 })
660 .collect();
661 assert_eq!(names, vec!["real"]);
662 }
663
664 #[test]
665 fn ignores_classes_in_strings() {
666 let names = export_names(r#".real { content: ".fake"; }"#);
667 assert!(names.contains(&"real".to_string()));
668 assert!(!names.contains(&"fake".to_string()));
669 }
670
671 #[test]
672 fn ignores_classes_in_url() {
673 let names = export_names(".real { background: url(./images/hero.png); }");
674 assert!(names.contains(&"real".to_string()));
675 assert!(!names.contains(&"png".to_string()));
676 }
677
678 #[test]
679 fn strip_css_block_comment() {
680 let result = strip_css_comments("/* removed */ .kept { }", false);
681 assert!(!result.contains("removed"));
682 assert!(result.contains(".kept"));
683 }
684
685 #[test]
686 fn strip_scss_line_comment() {
687 let result = strip_css_comments("// removed\n.kept { }", true);
688 assert!(!result.contains("removed"));
689 assert!(result.contains(".kept"));
690 }
691
692 #[test]
693 fn strip_scss_preserves_css_outside_comments() {
694 let source = "// line comment\n/* block comment */\n.visible { color: red; }";
695 let result = strip_css_comments(source, true);
696 assert!(result.contains(".visible"));
697 }
698
699 #[test]
700 fn url_import_http() {
701 assert!(is_css_url_import("http://example.com/style.css"));
702 }
703
704 #[test]
705 fn url_import_https() {
706 assert!(is_css_url_import("https://fonts.googleapis.com/css"));
707 }
708
709 #[test]
710 fn url_import_data() {
711 assert!(is_css_url_import("data:text/css;base64,abc"));
712 }
713
714 #[test]
715 fn url_import_local_not_skipped() {
716 assert!(!is_css_url_import("./local.css"));
717 }
718
719 #[test]
720 fn url_import_bare_specifier_not_skipped() {
721 assert!(!is_css_url_import("tailwindcss"));
722 }
723
724 #[test]
725 fn normalize_relative_dot_path_unchanged() {
726 assert_eq!(
727 normalize_css_import_path("./reset.css".to_string(), false),
728 "./reset.css"
729 );
730 }
731
732 #[test]
733 fn normalize_parent_relative_path_unchanged() {
734 assert_eq!(
735 normalize_css_import_path("../shared.scss".to_string(), false),
736 "../shared.scss"
737 );
738 }
739
740 #[test]
741 fn normalize_absolute_path_unchanged() {
742 assert_eq!(
743 normalize_css_import_path("/styles/main.css".to_string(), false),
744 "/styles/main.css"
745 );
746 }
747
748 #[test]
749 fn normalize_url_unchanged() {
750 assert_eq!(
751 normalize_css_import_path("https://example.com/style.css".to_string(), false),
752 "https://example.com/style.css"
753 );
754 }
755
756 #[test]
757 fn normalize_bare_css_gets_dot_slash() {
758 assert_eq!(
759 normalize_css_import_path("app.css".to_string(), false),
760 "./app.css"
761 );
762 }
763
764 #[test]
765 fn normalize_css_package_subpath_stays_bare() {
766 assert_eq!(
767 normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
768 "tailwindcss/theme.css"
769 );
770 }
771
772 #[test]
773 fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
774 assert_eq!(
775 normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
776 "highlight.js/styles/github.css"
777 );
778 }
779
780 #[test]
781 fn normalize_bare_scss_gets_dot_slash() {
782 assert_eq!(
783 normalize_css_import_path("vars.scss".to_string(), false),
784 "./vars.scss"
785 );
786 }
787
788 #[test]
789 fn normalize_bare_sass_gets_dot_slash() {
790 assert_eq!(
791 normalize_css_import_path("main.sass".to_string(), false),
792 "./main.sass"
793 );
794 }
795
796 #[test]
797 fn normalize_bare_less_gets_dot_slash() {
798 assert_eq!(
799 normalize_css_import_path("theme.less".to_string(), false),
800 "./theme.less"
801 );
802 }
803
804 #[test]
805 fn normalize_bare_js_extension_stays_bare() {
806 assert_eq!(
807 normalize_css_import_path("module.js".to_string(), false),
808 "module.js"
809 );
810 }
811
812 #[test]
813 fn normalize_scss_bare_partial_gets_dot_slash() {
814 assert_eq!(
815 normalize_css_import_path("variables".to_string(), true),
816 "./variables"
817 );
818 }
819
820 #[test]
821 fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
822 assert_eq!(
823 normalize_css_import_path("base/reset".to_string(), true),
824 "./base/reset"
825 );
826 }
827
828 #[test]
829 fn normalize_scss_builtin_stays_bare() {
830 assert_eq!(
831 normalize_css_import_path("sass:math".to_string(), true),
832 "sass:math"
833 );
834 }
835
836 #[test]
837 fn normalize_scss_relative_path_unchanged() {
838 assert_eq!(
839 normalize_css_import_path("../styles/variables".to_string(), true),
840 "../styles/variables"
841 );
842 }
843
844 #[test]
845 fn normalize_css_bare_extensionless_stays_bare() {
846 assert_eq!(
847 normalize_css_import_path("tailwindcss".to_string(), false),
848 "tailwindcss"
849 );
850 }
851
852 #[test]
853 fn normalize_scoped_package_with_css_extension_stays_bare() {
854 assert_eq!(
855 normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
856 "@fontsource/monaspace-neon/400.css"
857 );
858 }
859
860 #[test]
861 fn normalize_scoped_package_with_scss_extension_stays_bare() {
862 assert_eq!(
863 normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
864 "@company/design-system/tokens.scss"
865 );
866 }
867
868 #[test]
869 fn normalize_scoped_package_without_extension_stays_bare() {
870 assert_eq!(
871 normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
872 "@fallow/design-system/styles"
873 );
874 }
875
876 #[test]
877 fn normalize_scoped_package_extensionless_scss_stays_bare() {
878 assert_eq!(
879 normalize_css_import_path("@company/tokens".to_string(), true),
880 "@company/tokens"
881 );
882 }
883
884 #[test]
885 fn normalize_path_alias_with_css_extension_stays_bare() {
886 assert_eq!(
887 normalize_css_import_path("@/components/Button.css".to_string(), false),
888 "@/components/Button.css"
889 );
890 }
891
892 #[test]
893 fn normalize_path_alias_extensionless_stays_bare() {
894 assert_eq!(
895 normalize_css_import_path("@/styles/variables".to_string(), false),
896 "@/styles/variables"
897 );
898 }
899
900 #[test]
901 fn strip_css_no_comments() {
902 let source = ".foo { color: red; }";
903 assert_eq!(strip_css_comments(source, false), source);
904 }
905
906 #[test]
907 fn strip_css_multiple_block_comments() {
908 let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
909 let result = strip_css_comments(source, false);
910 assert!(!result.contains("comment-one"));
911 assert!(!result.contains("comment-two"));
912 assert!(result.contains(".foo"));
913 assert!(result.contains(".bar"));
914 }
915
916 #[test]
917 fn strip_scss_does_not_affect_non_scss() {
918 let source = "// this stays\n.foo { }";
919 let result = strip_css_comments(source, false);
920 assert!(result.contains("// this stays"));
921 }
922
923 #[test]
924 fn css_module_parses_suppressions() {
925 let info = parse_css_to_module(
926 fallow_types::discover::FileId(0),
927 Path::new("Component.module.css"),
928 "/* fallow-ignore-file */\n.btn { color: red; }",
929 0,
930 );
931 assert!(!info.suppressions.is_empty());
932 assert_eq!(info.suppressions[0].line, 0);
933 }
934
935 #[test]
936 fn extracts_class_starting_with_underscore() {
937 let names = export_names("._private { } .__dunder { }");
938 assert!(names.contains(&"_private".to_string()));
939 assert!(names.contains(&"__dunder".to_string()));
940 }
941
942 #[test]
943 fn ignores_id_selectors() {
944 let names = export_names("#myId { color: red; }");
945 assert!(!names.contains(&"myId".to_string()));
946 }
947
948 #[test]
949 fn ignores_element_selectors() {
950 let names = export_names("div { color: red; } span { }");
951 assert!(names.is_empty());
952 }
953
954 #[test]
955 fn extract_css_imports_at_import_quoted() {
956 let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
957 assert_eq!(imports, vec!["./reset.css"]);
958 }
959
960 #[test]
961 fn extract_css_imports_package_subpath_stays_bare() {
962 let imports =
963 extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
964 assert_eq!(imports, vec!["tailwindcss/theme.css"]);
965 }
966
967 #[test]
968 fn extract_css_imports_at_import_url() {
969 let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
970 assert_eq!(imports, vec!["./reset.css"]);
971 }
972
973 #[test]
974 fn extract_css_imports_skips_remote_urls() {
975 let imports =
976 extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
977 assert!(imports.is_empty());
978 }
979
980 #[test]
981 fn extract_css_imports_scss_use_normalizes_partial() {
982 let imports = extract_css_imports(r#"@use "variables";"#, true);
983 assert_eq!(imports, vec!["./variables"]);
984 }
985
986 #[test]
987 fn extract_css_imports_scss_forward_normalizes_partial() {
988 let imports = extract_css_imports(r#"@forward "tokens";"#, true);
989 assert_eq!(imports, vec!["./tokens"]);
990 }
991
992 #[test]
993 fn extract_css_imports_skips_comments() {
994 let imports = extract_css_imports(
995 r#"/* @import "./hidden.scss"; */
996@use "real";"#,
997 true,
998 );
999 assert_eq!(imports, vec!["./real"]);
1000 }
1001
1002 #[test]
1003 fn extract_css_imports_at_plugin_keeps_package_bare() {
1004 let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1005 assert_eq!(imports, vec!["daisyui"]);
1006 }
1007
1008 #[test]
1009 fn extract_css_imports_at_plugin_tracks_relative_file() {
1010 let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1011 assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1012 }
1013
1014 #[test]
1015 fn extract_css_imports_scss_at_import_kept_relative() {
1016 let imports = extract_css_imports(r"@import 'Foo';", true);
1017 assert_eq!(imports, vec!["./Foo"]);
1018 }
1019
1020 #[test]
1021 fn extract_css_imports_additional_data_string_body() {
1022 let body = r#"@use "./src/styles/global.scss";"#;
1023 let imports = extract_css_imports(body, true);
1024 assert_eq!(imports, vec!["./src/styles/global.scss"]);
1025 }
1026
1027 #[test]
1028 fn mask_with_whitespace_preserves_byte_length() {
1029 let src = "/* hello */ .foo { }";
1030 let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1031 assert_eq!(masked.len(), src.len());
1032 assert!(masked.is_char_boundary(src.len()));
1033 }
1034
1035 #[test]
1036 fn mask_with_whitespace_preserves_offsets_around_multibyte() {
1037 let src = "/* \u{2713} */ .foo { }";
1038 let foo_offset = src.find(".foo").expect("`.foo` present");
1039 let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1040 assert_eq!(masked.len(), src.len());
1041 assert_eq!(masked.find(".foo"), Some(foo_offset));
1042 }
1043
1044 fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1047 let offsets = fallow_types::extract::compute_line_offsets(source);
1048 fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1049 }
1050
1051 #[test]
1052 fn span_points_at_real_class_declaration_line() {
1053 let source = "\n\n\n\n.foo { color: red; }\n";
1054 let exports = extract_css_module_exports(source, false);
1055 assert_eq!(exports.len(), 1);
1056 let span = exports[0].span;
1057 let (line, col) = span_line_col(source, span.start);
1058 assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1059 assert_eq!(
1060 col, 1,
1061 "column points at `f` in `.foo` (post-dot identifier)"
1062 );
1063 assert_eq!(
1064 &source[span.start as usize..span.end as usize],
1065 "foo",
1066 "span range must slice to the class identifier in the original source"
1067 );
1068 }
1069
1070 #[test]
1071 fn span_survives_multibyte_comment_prefix() {
1072 let source = "/* \u{2713} */\n.foo { }";
1073 let exports = extract_css_module_exports(source, false);
1074 assert_eq!(exports.len(), 1);
1075 let span = exports[0].span;
1076 assert!(
1077 source.is_char_boundary(span.start as usize),
1078 "span.start must lie on a UTF-8 char boundary"
1079 );
1080 assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1081 }
1082
1083 #[test]
1084 fn span_skips_at_layer_prelude_dot_segments() {
1085 let source = "@layer foo.bar { }\n.root { }\n";
1086 let exports = extract_css_module_exports(source, false);
1087 let names: Vec<_> = exports
1088 .iter()
1089 .filter_map(|e| match &e.name {
1090 ExportName::Named(n) => Some(n.as_str()),
1091 ExportName::Default => None,
1092 })
1093 .collect();
1094 assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1095 let span = exports[0].span;
1096 let (line, _col) = span_line_col(source, span.start);
1097 assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1098 assert_eq!(&source[span.start as usize..span.end as usize], "root");
1099 }
1100
1101 #[test]
1102 fn span_skips_classes_in_strings() {
1103 let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1104 let exports = extract_css_module_exports(source, false);
1105 let names: Vec<_> = exports
1106 .iter()
1107 .filter_map(|e| match &e.name {
1108 ExportName::Named(n) => Some(n.as_str()),
1109 ExportName::Default => None,
1110 })
1111 .collect();
1112 assert_eq!(names, vec!["real", "also-real"]);
1113 for export in &exports {
1114 let span = export.span;
1115 let slice = &source[span.start as usize..span.end as usize];
1116 match &export.name {
1117 ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1118 ExportName::Default => unreachable!("CSS modules emit only named exports"),
1119 }
1120 }
1121 }
1122
1123 #[test]
1124 fn span_deduplicates_to_first_occurrence() {
1125 let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1126 let exports = extract_css_module_exports(source, false);
1127 assert_eq!(exports.len(), 1);
1128 let (line, _col) = span_line_col(source, exports[0].span.start);
1129 assert_eq!(
1130 line, 1,
1131 "first occurrence wins for deduplicated class names"
1132 );
1133 }
1134
1135 #[test]
1136 fn span_inside_media_query() {
1137 let source =
1138 "@media (max-width: 768px) {\n .mobile { display: block; }\n .desktop { }\n}\n";
1139 let exports = extract_css_module_exports(source, false);
1140 let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
1141 .iter()
1142 .filter_map(|e| match &e.name {
1143 ExportName::Named(n) => Some((n.as_str(), e.span)),
1144 ExportName::Default => None,
1145 })
1146 .collect();
1147 let mobile_line = span_line_col(source, by_name["mobile"].start).0;
1148 let desktop_line = span_line_col(source, by_name["desktop"].start).0;
1149 assert_eq!(mobile_line, 2);
1150 assert_eq!(desktop_line, 3);
1151 }
1152
1153 #[test]
1154 fn at_layer_only_module_emits_no_exports() {
1155 let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
1156 assert!(exports.is_empty());
1157 }
1158
1159 #[test]
1160 fn parse_css_to_module_resolves_real_line_offsets() {
1161 let source = "\n\n\n\n.foo { color: red; }\n";
1162 let info = parse_css_to_module(
1163 fallow_types::discover::FileId(0),
1164 Path::new("Component.module.css"),
1165 source,
1166 0,
1167 );
1168 assert_eq!(info.exports.len(), 1);
1169 let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
1170 &info.line_offsets,
1171 info.exports[0].span.start,
1172 );
1173 assert_eq!(line, 5, "downstream line must equal the source line");
1174 }
1175}