1use crate::{
27 error::ErrorLocation,
28 parser::DefaultAtRuleParser,
29 properties::{
30 css_modules::Specifier,
31 custom::{
32 CustomProperty, EnvironmentVariableName, TokenList, TokenOrValue, UnparsedProperty, UnresolvedColor,
33 },
34 Property,
35 },
36 rules::{
37 layer::{LayerBlockRule, LayerName},
38 Location,
39 },
40 traits::{AtRuleParser, ToCss},
41 values::ident::DashedIdentReference,
42};
43use crate::{
44 error::{Error, ParserError},
45 media_query::MediaList,
46 printer::SourceMap,
47 rules::{
48 import::ImportRule,
49 media::MediaRule,
50 supports::{SupportsCondition, SupportsRule},
51 CssRule, CssRuleList,
52 },
53 stylesheet::{ParserOptions, StyleSheet},
54};
55use dashmap::DashMap;
56use rayon::prelude::*;
57use std::{
58 collections::HashSet,
59 fs,
60 path::{Path, PathBuf},
61 sync::Mutex,
62};
63
64pub struct Bundler<'a, 's, P, T: AtRuleParser<'a>, S = ()> {
67 source_map: Option<Mutex<&'s mut S>>,
68 fs: &'a P,
69 source_indexes: DashMap<PathBuf, u32>,
70 stylesheets: Mutex<Vec<BundleStyleSheet<'a, T::AtRule>>>,
71 options: ParserOptions<'a>,
72 at_rule_parser: Mutex<AtRuleParserValue<'s, T>>,
73}
74
75enum AtRuleParserValue<'a, T> {
76 Owned(T),
77 Borrowed(&'a mut T),
78}
79
80struct BundleStyleSheet<'i, T> {
81 stylesheet: Option<StyleSheet<'i, T>>,
82 source_map_source_index: Option<u32>,
83 dependencies: Vec<Dependency>,
84 css_modules_deps: Vec<u32>,
85 parent_source_index: u32,
86 parent_dep_index: u32,
87 layer: Option<Option<LayerName<'i>>>,
88 supports: Option<SupportsCondition<'i>>,
89 media: MediaList<'i>,
90 loc: Location,
91}
92
93#[derive(Debug, Clone)]
94enum Dependency {
95 File(u32),
96 External(String),
97}
98
99#[derive(Debug)]
101#[cfg_attr(
102 any(feature = "serde", feature = "nodejs"),
103 derive(serde::Deserialize),
104 serde(rename_all = "lowercase")
105)]
106pub enum ResolveResult {
107 External(String),
109 #[cfg_attr(any(feature = "serde", feature = "nodejs"), serde(untagged))]
111 File(PathBuf),
112}
113
114impl From<PathBuf> for ResolveResult {
115 fn from(path: PathBuf) -> Self {
116 ResolveResult::File(path)
117 }
118}
119
120pub trait SourceProvider: Send + Sync {
125 type Error: std::error::Error + Send + Sync;
127
128 fn read<'a>(&'a self, file: &Path) -> Result<&'a str, Self::Error>;
130
131 fn resolve(&self, specifier: &str, originating_file: &Path) -> Result<ResolveResult, Self::Error>;
134}
135
136pub struct FileProvider {
139 inputs: Mutex<Vec<*mut String>>,
140}
141
142impl FileProvider {
143 pub fn new() -> FileProvider {
145 FileProvider {
146 inputs: Mutex::new(Vec::new()),
147 }
148 }
149}
150
151unsafe impl Sync for FileProvider {}
152unsafe impl Send for FileProvider {}
153
154impl SourceProvider for FileProvider {
155 type Error = std::io::Error;
156
157 fn read<'a>(&'a self, file: &Path) -> Result<&'a str, Self::Error> {
158 let source = fs::read_to_string(file)?;
159 let ptr = Box::into_raw(Box::new(source));
160 self.inputs.lock().unwrap().push(ptr);
161 Ok(unsafe { &*ptr })
165 }
166
167 fn resolve(&self, specifier: &str, originating_file: &Path) -> Result<ResolveResult, Self::Error> {
168 Ok(originating_file.with_file_name(specifier).into())
170 }
171}
172
173impl Drop for FileProvider {
174 fn drop(&mut self) {
175 for ptr in self.inputs.lock().unwrap().iter() {
176 std::mem::drop(unsafe { Box::from_raw(*ptr) })
177 }
178 }
179}
180
181#[derive(Debug)]
183#[cfg_attr(any(feature = "serde", feature = "nodejs"), derive(serde::Serialize))]
184pub enum BundleErrorKind<'i, T: std::error::Error> {
185 ParserError(ParserError<'i>),
187 UnsupportedImportCondition,
189 UnsupportedLayerCombination,
191 UnsupportedMediaBooleanLogic,
193 ReferencedExternalModuleWithCssModuleFrom,
195 ExternalImportAfterBundledImport,
198 ResolverError(#[cfg_attr(any(feature = "serde", feature = "nodejs"), serde(skip))] T),
200}
201
202impl<'i, T: std::error::Error> From<Error<ParserError<'i>>> for Error<BundleErrorKind<'i, T>> {
203 fn from(err: Error<ParserError<'i>>) -> Self {
204 Error {
205 kind: BundleErrorKind::ParserError(err.kind),
206 loc: err.loc,
207 }
208 }
209}
210
211impl<'i, T: std::error::Error> std::fmt::Display for BundleErrorKind<'i, T> {
212 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213 use BundleErrorKind::*;
214 match self {
215 ParserError(err) => err.fmt(f),
216 UnsupportedImportCondition => write!(f, "Unsupported import condition"),
217 UnsupportedLayerCombination => write!(f, "Unsupported layer combination in @import"),
218 UnsupportedMediaBooleanLogic => write!(f, "Unsupported boolean logic in @import media query"),
219 ReferencedExternalModuleWithCssModuleFrom => {
220 write!(f, "Referenced external module with CSS module \"from\" clause")
221 }
222 ExternalImportAfterBundledImport => write!(
223 f,
224 "An external `@import` was found after a bundled `@import`. This may result in unintended selector order."
225 ),
226 ResolverError(err) => std::fmt::Display::fmt(&err, f),
227 }
228 }
229}
230
231impl<'i, T: std::error::Error> BundleErrorKind<'i, T> {
232 #[deprecated(note = "use `BundleErrorKind::to_string()` or `std::fmt::Display` instead")]
233 #[allow(missing_docs)]
234 pub fn reason(&self) -> String {
235 self.to_string()
236 }
237}
238
239impl<'a, 's, P: SourceProvider, S: SourceMap + Send> Bundler<'a, 's, P, DefaultAtRuleParser, S> {
240 pub fn new(
244 fs: &'a P,
245 source_map: Option<&'s mut S>,
246 options: ParserOptions<'a>,
247 ) -> Bundler<'a, 's, P, DefaultAtRuleParser, S> {
248 Bundler {
249 source_map: source_map.map(Mutex::new),
250 fs,
251 source_indexes: DashMap::new(),
252 stylesheets: Mutex::new(Vec::new()),
253 options,
254 at_rule_parser: Mutex::new(AtRuleParserValue::Owned(DefaultAtRuleParser)),
255 }
256 }
257}
258
259impl<'a, 's, P: SourceProvider, T: AtRuleParser<'a> + Clone + Sync + Send, S: SourceMap + Send>
260 Bundler<'a, 's, P, T, S>
261where
262 T::AtRule: Sync + Send + ToCss + Clone,
263{
264 pub fn new_with_at_rule_parser(
268 fs: &'a P,
269 source_map: Option<&'s mut S>,
270 options: ParserOptions<'a>,
271 at_rule_parser: &'s mut T,
272 ) -> Self {
273 Bundler {
274 source_map: source_map.map(Mutex::new),
275 fs,
276 source_indexes: DashMap::new(),
277 stylesheets: Mutex::new(Vec::new()),
278 options,
279 at_rule_parser: Mutex::new(AtRuleParserValue::Borrowed(at_rule_parser)),
280 }
281 }
282
283 pub fn bundle<'e>(
285 &mut self,
286 entry: &'e Path,
287 ) -> Result<StyleSheet<'a, T::AtRule>, Error<BundleErrorKind<'a, P::Error>>> {
288 self.load_file(
290 &entry,
291 ImportRule {
292 url: "".into(),
293 layer: None,
294 supports: None,
295 media: MediaList::new(),
296 loc: Location {
297 source_index: 0,
298 line: 0,
299 column: 0,
300 },
301 },
302 )?;
303
304 self.order();
306
307 let mut rules: Vec<CssRule<'a, T::AtRule>> = Vec::new();
309 self.inline(&mut rules)?;
310
311 let sources = self
312 .stylesheets
313 .get_mut()
314 .unwrap()
315 .iter()
316 .flat_map(|s| s.stylesheet.as_ref().unwrap().sources.iter().cloned())
317 .collect();
318
319 let mut stylesheet = StyleSheet::new(sources, CssRuleList(rules), self.options.clone());
320
321 if self.source_map.is_some() {
322 stylesheet.source_map_source_indices = self
323 .stylesheets
324 .get_mut()
325 .unwrap()
326 .iter()
327 .map(|s| s.source_map_source_index)
328 .collect();
329 }
330
331 stylesheet.source_map_urls = self
332 .stylesheets
333 .get_mut()
334 .unwrap()
335 .iter()
336 .flat_map(|s| s.stylesheet.as_ref().unwrap().source_map_urls.iter().cloned())
337 .collect();
338
339 stylesheet.license_comments = self
340 .stylesheets
341 .get_mut()
342 .unwrap()
343 .iter()
344 .flat_map(|s| s.stylesheet.as_ref().unwrap().license_comments.iter().cloned())
345 .collect();
346
347 if let Some(config) = &self.options.css_modules {
348 if config.pattern.has_content_hash() {
349 stylesheet.content_hashes = Some(
350 self
351 .stylesheets
352 .get_mut()
353 .unwrap()
354 .iter()
355 .flat_map(|s| {
356 let s = s.stylesheet.as_ref().unwrap();
357 s.content_hashes.as_ref().unwrap().iter().cloned()
358 })
359 .collect(),
360 );
361 }
362 }
363
364 Ok(stylesheet)
365 }
366
367 fn find_filename(&self, source_index: u32) -> String {
368 let entry = self.source_indexes.iter().find(|x| *x.value() == source_index).unwrap();
370 entry.key().to_str().unwrap().into()
371 }
372
373 fn load_file(&self, file: &Path, rule: ImportRule<'a>) -> Result<u32, Error<BundleErrorKind<'a, P::Error>>> {
374 let mut stylesheets = self.stylesheets.lock().unwrap();
376 let source_index = match self.source_indexes.get(file) {
377 Some(source_index) => {
378 let entry = &mut stylesheets[*source_index as usize];
381
382 if (!rule.media.media_queries.is_empty() && !entry.supports.is_none())
386 || (!entry.media.media_queries.is_empty() && !rule.supports.is_none())
387 {
388 return Err(Error {
389 kind: BundleErrorKind::UnsupportedImportCondition,
390 loc: Some(ErrorLocation::new(rule.loc, self.find_filename(rule.loc.source_index))),
391 });
392 }
393
394 if rule.media.media_queries.is_empty() {
395 entry.media.media_queries.clear();
396 } else if !entry.media.media_queries.is_empty() {
397 entry.media.or(&rule.media);
398 }
399
400 if let Some(supports) = rule.supports {
401 if let Some(existing_supports) = &mut entry.supports {
402 existing_supports.or(&supports)
403 }
404 } else {
405 entry.supports = None;
406 }
407
408 if let Some(layer) = &rule.layer {
409 if let Some(existing_layer) = &entry.layer {
410 if layer != existing_layer || (layer.is_none() && existing_layer.is_none()) {
412 return Err(Error {
413 kind: BundleErrorKind::UnsupportedLayerCombination,
414 loc: Some(ErrorLocation::new(rule.loc, self.find_filename(rule.loc.source_index))),
415 });
416 }
417 } else {
418 entry.layer = rule.layer;
419 }
420 }
421
422 return Ok(*source_index);
423 }
424 None => {
425 let source_index = stylesheets.len() as u32;
426 self.source_indexes.insert(file.to_owned(), source_index);
427
428 stylesheets.push(BundleStyleSheet {
429 stylesheet: None,
430 source_map_source_index: None,
431 layer: rule.layer.clone(),
432 media: rule.media.clone(),
433 supports: rule.supports.clone(),
434 loc: rule.loc.clone(),
435 dependencies: Vec::new(),
436 css_modules_deps: Vec::new(),
437 parent_source_index: 0,
438 parent_dep_index: 0,
439 });
440
441 source_index
442 }
443 };
444
445 drop(stylesheets); let code = self.fs.read(file).map_err(|e| Error {
448 kind: BundleErrorKind::ResolverError(e),
449 loc: if rule.loc.column == 0 {
450 None
451 } else {
452 Some(ErrorLocation::new(rule.loc, self.find_filename(rule.loc.source_index)))
453 },
454 })?;
455
456 let mut opts = self.options.clone();
457 let filename = file.to_str().unwrap();
458 opts.filename = filename.to_owned();
459 opts.source_index = source_index;
460
461 let mut stylesheet = {
462 let mut at_rule_parser = self.at_rule_parser.lock().unwrap();
463 let at_rule_parser = match &mut *at_rule_parser {
464 AtRuleParserValue::Owned(owned) => owned,
465 AtRuleParserValue::Borrowed(borrowed) => *borrowed,
466 };
467
468 StyleSheet::<T::AtRule>::parse_with(code, opts, at_rule_parser)?
469 };
470
471 let mut source_map_source_index = None;
472 if let Some(source_map) = &self.source_map {
473 let sm = stylesheet.source_map_url(0);
476 if sm.is_none() || !sm.unwrap().starts_with("data") {
477 let mut source_map = source_map.lock().unwrap();
478 let source_index = source_map.add_source(filename);
479 source_map.set_source_content(source_index, code);
480 source_map_source_index = Some(source_index);
481 }
482 }
483
484 let dependencies: Result<Vec<Dependency>, _> = stylesheet
486 .rules
487 .0
488 .par_iter_mut()
489 .filter_map(|r| {
490 if let CssRule::LayerStatement(layer) = r {
492 if let Some(Some(parent_layer)) = &rule.layer {
493 for name in &mut layer.names {
494 name.0.insert_many(0, parent_layer.0.iter().cloned())
495 }
496 }
497 }
498
499 if let CssRule::Import(import) = r {
500 let specifier = &import.url;
501
502 let mut media = rule.media.clone();
505 let result = media.and(&import.media).map_err(|_| Error {
506 kind: BundleErrorKind::UnsupportedMediaBooleanLogic,
507 loc: Some(ErrorLocation::new(
508 import.loc,
509 self.find_filename(import.loc.source_index),
510 )),
511 });
512
513 if let Err(e) = result {
514 return Some(Err(e));
515 }
516
517 let layer = if (rule.layer == Some(None) && import.layer.is_some())
518 || (import.layer == Some(None) && rule.layer.is_some())
519 {
520 return Some(Err(Error {
522 kind: BundleErrorKind::UnsupportedLayerCombination,
523 loc: Some(ErrorLocation::new(
524 import.loc,
525 self.find_filename(import.loc.source_index),
526 )),
527 }));
528 } else if let Some(Some(a)) = &rule.layer {
529 if let Some(Some(b)) = &import.layer {
530 let mut name = a.clone();
531 name.0.extend(b.0.iter().cloned());
532 Some(Some(name))
533 } else {
534 Some(Some(a.clone()))
535 }
536 } else {
537 import.layer.clone()
538 };
539
540 let result = match self.fs.resolve(&specifier, file) {
541 Ok(ResolveResult::File(path)) => self
542 .load_file(
543 &path,
544 ImportRule {
545 layer,
546 media,
547 supports: combine_supports(rule.supports.clone(), &import.supports),
548 url: "".into(),
549 loc: import.loc,
550 },
551 )
552 .map(Dependency::File),
553 Ok(ResolveResult::External(url)) => Ok(Dependency::External(url)),
554 Err(err) => Err(Error {
555 kind: BundleErrorKind::ResolverError(err),
556 loc: Some(ErrorLocation::new(
557 import.loc,
558 self.find_filename(import.loc.source_index),
559 )),
560 }),
561 };
562
563 Some(result)
564 } else {
565 None
566 }
567 })
568 .collect();
569
570 let css_modules_deps: Result<Vec<u32>, _> = if self.options.css_modules.is_some() {
572 stylesheet
573 .rules
574 .0
575 .par_iter_mut()
576 .filter_map(|r| {
577 if let CssRule::Style(style) = r {
578 Some(
579 style
580 .declarations
581 .declarations
582 .par_iter_mut()
583 .chain(style.declarations.important_declarations.par_iter_mut())
584 .filter_map(|d| match d {
585 Property::Composes(composes) => self
586 .add_css_module_dep(file, &rule, style.loc, composes.loc, &mut composes.from)
587 .map(|result| rayon::iter::Either::Left(rayon::iter::once(result))),
588
589 Property::Custom(CustomProperty { value, .. })
591 | Property::Unparsed(UnparsedProperty { value, .. })
592 if matches!(&self.options.css_modules, Some(css_modules) if css_modules.dashed_idents) =>
593 {
594 Some(rayon::iter::Either::Right(visit_vars(value).filter_map(|name| {
595 self.add_css_module_dep(
596 file,
597 &rule,
598 style.loc,
599 crate::dependencies::Location {
601 line: style.loc.line,
602 column: style.loc.column,
603 },
604 &mut name.from,
605 )
606 })))
607 }
608 _ => None,
609 })
610 .flatten(),
611 )
612 } else {
613 None
614 }
615 })
616 .flatten()
617 .collect()
618 } else {
619 Ok(vec![])
620 };
621
622 let entry = &mut self.stylesheets.lock().unwrap()[source_index as usize];
623 entry.stylesheet = Some(stylesheet);
624 entry.source_map_source_index = source_map_source_index;
625 entry.dependencies = dependencies?;
626 entry.css_modules_deps = css_modules_deps?;
627
628 Ok(source_index)
629 }
630
631 fn add_css_module_dep(
632 &self,
633 file: &Path,
634 rule: &ImportRule<'a>,
635 style_loc: Location,
636 loc: crate::dependencies::Location,
637 specifier: &mut Option<Specifier>,
638 ) -> Option<Result<u32, Error<BundleErrorKind<'a, P::Error>>>> {
639 if let Some(Specifier::File(f)) = specifier {
640 let result = match self.fs.resolve(&f, file) {
641 Ok(ResolveResult::File(path)) => {
642 let res = self.load_file(
643 &path,
644 ImportRule {
645 layer: rule.layer.clone(),
646 media: rule.media.clone(),
647 supports: rule.supports.clone(),
648 url: "".into(),
649 loc: Location {
650 source_index: style_loc.source_index,
651 line: loc.line,
652 column: loc.column,
653 },
654 },
655 );
656
657 if let Ok(source_index) = res {
658 *specifier = Some(Specifier::SourceIndex(source_index));
659 }
660
661 res
662 }
663 Ok(ResolveResult::External(_)) => Err(Error {
664 kind: BundleErrorKind::ReferencedExternalModuleWithCssModuleFrom,
665 loc: Some(ErrorLocation::new(
666 style_loc,
667 self.find_filename(style_loc.source_index),
668 )),
669 }),
670 Err(err) => Err(Error {
671 kind: BundleErrorKind::ResolverError(err),
672 loc: Some(ErrorLocation::new(
673 style_loc,
674 self.find_filename(style_loc.source_index),
675 )),
676 }),
677 };
678 Some(result)
679 } else {
680 None
681 }
682 }
683
684 fn order(&mut self) {
685 process(self.stylesheets.get_mut().unwrap(), 0, &mut HashSet::new());
686
687 fn process<'i, T>(
688 stylesheets: &mut Vec<BundleStyleSheet<'i, T>>,
689 source_index: u32,
690 visited: &mut HashSet<u32>,
691 ) {
692 if visited.contains(&source_index) {
693 return;
694 }
695
696 visited.insert(source_index);
697
698 let mut dep_index = 0;
699 for i in 0..stylesheets[source_index as usize].css_modules_deps.len() {
700 let dep_source_index = stylesheets[source_index as usize].css_modules_deps[i];
701 let resolved = &mut stylesheets[dep_source_index as usize];
702
703 if !visited.contains(&dep_source_index) {
705 resolved.parent_dep_index = dep_index;
706 resolved.parent_source_index = source_index;
707 process(stylesheets, dep_source_index, visited);
708 }
709
710 dep_index += 1;
711 }
712
713 for i in 0..stylesheets[source_index as usize].dependencies.len() {
714 let Dependency::File(dep_source_index) = stylesheets[source_index as usize].dependencies[i] else {
715 continue;
716 };
717 let resolved = &mut stylesheets[dep_source_index as usize];
718
719 resolved.parent_dep_index = dep_index;
721 resolved.parent_source_index = source_index;
722
723 process(stylesheets, dep_source_index, visited);
724 dep_index += 1;
725 }
726 }
727 }
728
729 fn inline(
730 &mut self,
731 dest: &mut Vec<CssRule<'a, T::AtRule>>,
732 ) -> Result<(), Error<BundleErrorKind<'a, P::Error>>> {
733 fn process<'a, T, E: std::error::Error>(
734 stylesheets: &mut Vec<BundleStyleSheet<'a, T>>,
735 source_index: u32,
736 dest: &mut Vec<CssRule<'a, T>>,
737 filename: &String,
738 ) -> Result<(), Error<BundleErrorKind<'a, E>>> {
739 let stylesheet = &mut stylesheets[source_index as usize];
740 let mut rules = std::mem::take(&mut stylesheet.stylesheet.as_mut().unwrap().rules.0);
741
742 let mut dep_index = 0;
744 for i in 0..stylesheet.css_modules_deps.len() {
745 let dep_source_index = stylesheets[source_index as usize].css_modules_deps[i];
746 let resolved = &stylesheets[dep_source_index as usize];
747
748 if resolved.parent_source_index == source_index && resolved.parent_dep_index == dep_index as u32 {
750 process(stylesheets, dep_source_index, dest, filename)?;
751 }
752
753 dep_index += 1;
754 }
755
756 let mut import_index = 0;
757 let mut has_bundled_import = false;
758 for rule in &mut rules {
759 match rule {
760 CssRule::Import(import_rule) => {
761 let dep_source = &stylesheets[source_index as usize].dependencies[import_index];
762 match dep_source {
763 Dependency::File(dep_source_index) => {
764 let resolved = &stylesheets[*dep_source_index as usize];
765
766 if resolved.parent_source_index == source_index && resolved.parent_dep_index == dep_index {
768 has_bundled_import = true;
769 process(stylesheets, *dep_source_index, dest, filename)?;
770 }
771
772 *rule = CssRule::Ignored;
773 dep_index += 1;
774 }
775 Dependency::External(url) => {
776 if has_bundled_import {
777 return Err(Error {
778 kind: BundleErrorKind::ExternalImportAfterBundledImport,
779 loc: Some(ErrorLocation {
780 filename: filename.clone(),
781 line: import_rule.loc.line,
782 column: import_rule.loc.column,
783 }),
784 });
785 }
786 import_rule.url = url.to_owned().into();
787 let imp = std::mem::replace(rule, CssRule::Ignored);
788 dest.push(imp);
789 }
790 }
791 import_index += 1;
792 }
793 CssRule::LayerStatement(_) => {
794 let layer = std::mem::replace(rule, CssRule::Ignored);
797 dest.push(layer);
798 }
799 CssRule::Ignored => {}
800 _ => break,
801 }
802 }
803
804 let stylesheet = &mut stylesheets[source_index as usize];
806
807 if stylesheet.layer.is_some() {
808 rules = vec![CssRule::LayerBlock(LayerBlockRule {
809 name: stylesheet.layer.take().unwrap(),
810 rules: CssRuleList(rules),
811 loc: stylesheet.loc,
812 })]
813 }
814
815 if !stylesheet.media.media_queries.is_empty() {
816 rules = vec![CssRule::Media(MediaRule {
817 query: std::mem::replace(&mut stylesheet.media, MediaList::new()),
818 rules: CssRuleList(rules),
819 loc: stylesheet.loc,
820 })]
821 }
822
823 if stylesheet.supports.is_some() {
824 rules = vec![CssRule::Supports(SupportsRule {
825 condition: stylesheet.supports.take().unwrap(),
826 rules: CssRuleList(rules),
827 loc: stylesheet.loc,
828 })]
829 }
830
831 dest.extend(rules);
832 Ok(())
833 }
834
835 process(self.stylesheets.get_mut().unwrap(), 0, dest, &self.options.filename)
836 }
837}
838
839fn combine_supports<'a>(
840 a: Option<SupportsCondition<'a>>,
841 b: &Option<SupportsCondition<'a>>,
842) -> Option<SupportsCondition<'a>> {
843 if let Some(mut a) = a {
844 if let Some(b) = b {
845 a.and(b)
846 }
847 Some(a)
848 } else {
849 b.clone()
850 }
851}
852
853fn visit_vars<'a, 'b>(
854 token_list: &'b mut TokenList<'a>,
855) -> impl ParallelIterator<Item = &'b mut DashedIdentReference<'a>> {
856 let mut stack = vec![token_list.0.iter_mut()];
857 std::iter::from_fn(move || {
858 while !stack.is_empty() {
859 let iter = stack.last_mut().unwrap();
860 match iter.next() {
861 Some(TokenOrValue::Var(var)) => {
862 if let Some(fallback) = &mut var.fallback {
863 stack.push(fallback.0.iter_mut());
864 }
865 return Some(&mut var.name);
866 }
867 Some(TokenOrValue::Env(env)) => {
868 if let Some(fallback) = &mut env.fallback {
869 stack.push(fallback.0.iter_mut());
870 }
871 if let EnvironmentVariableName::Custom(name) = &mut env.name {
872 return Some(name);
873 }
874 }
875 Some(TokenOrValue::UnresolvedColor(color)) => match color {
876 UnresolvedColor::RGB { alpha, .. } | UnresolvedColor::HSL { alpha, .. } => {
877 stack.push(alpha.0.iter_mut());
878 }
879 UnresolvedColor::LightDark { light, dark } => {
880 stack.push(light.0.iter_mut());
881 stack.push(dark.0.iter_mut());
882 }
883 },
884 None => {
885 stack.pop();
886 }
887 _ => {}
888 }
889 }
890 None
891 })
892 .par_bridge()
893}
894
895#[cfg(test)]
896mod tests {
897 use super::*;
898 use crate::{
899 css_modules::{self, CssModuleExports, CssModuleReference},
900 parser::ParserFlags,
901 stylesheet::{MinifyOptions, PrinterOptions},
902 targets::{Browsers, Targets},
903 };
904 use indoc::indoc;
905 use std::collections::HashMap;
906
907 #[derive(Clone)]
908 struct TestProvider {
909 map: HashMap<PathBuf, String>,
910 }
911
912 impl SourceProvider for TestProvider {
913 type Error = std::io::Error;
914
915 fn read<'a>(&'a self, file: &Path) -> Result<&'a str, Self::Error> {
916 Ok(self.map.get(file).unwrap())
917 }
918
919 fn resolve(&self, specifier: &str, originating_file: &Path) -> Result<ResolveResult, Self::Error> {
920 if specifier.starts_with("https:") {
921 Ok(ResolveResult::External(specifier.to_owned()))
922 } else {
923 Ok(originating_file.with_file_name(specifier).into())
924 }
925 }
926 }
927
928 struct CustomProvider {
930 map: HashMap<PathBuf, String>,
931 }
932
933 impl SourceProvider for CustomProvider {
934 type Error = std::io::Error;
935
936 fn read<'a>(&'a self, file: &Path) -> Result<&'a str, Self::Error> {
938 Ok(self.map.get(file).unwrap())
939 }
940
941 fn resolve(&self, specifier: &str, _originating_file: &Path) -> Result<ResolveResult, Self::Error> {
944 if specifier.starts_with("foo:") {
945 Ok(Path::new(&specifier["foo:".len()..]).to_path_buf().into())
946 } else {
947 let err = std::io::Error::new(
948 std::io::ErrorKind::NotFound,
949 format!(
950 "Failed to resolve `{}`, specifier does not start with `foo:`.",
951 &specifier
952 ),
953 );
954
955 Err(err)
956 }
957 }
958 }
959
960 macro_rules! fs(
961 { $($key:literal: $value:expr),* } => {
962 {
963 #[allow(unused_mut)]
964 let mut m = HashMap::new();
965 $(
966 m.insert(PathBuf::from($key), $value.to_owned());
967 )*
968 m
969 }
970 };
971 );
972
973 fn bundle<P: SourceProvider>(fs: P, entry: &str) -> String {
974 let mut bundler = Bundler::<_, _, ()>::new(&fs, None, ParserOptions::default());
975 let stylesheet = bundler.bundle(Path::new(entry)).unwrap();
976 stylesheet.to_css(PrinterOptions::default(), None::<&mut ()>).unwrap().code
977 }
978
979 fn bundle_css_module<P: SourceProvider>(
980 fs: P,
981 entry: &str,
982 project_root: Option<&str>,
983 ) -> (String, CssModuleExports) {
984 bundle_css_module_with_pattern(fs, entry, project_root, "[hash]_[local]")
985 }
986
987 fn bundle_css_module_with_pattern<P: SourceProvider>(
988 fs: P,
989 entry: &str,
990 project_root: Option<&str>,
991 pattern: &'static str,
992 ) -> (String, CssModuleExports) {
993 let mut bundler = Bundler::<_, _, ()>::new(
994 &fs,
995 None,
996 ParserOptions {
997 css_modules: Some(css_modules::Config {
998 dashed_idents: true,
999 pattern: css_modules::Pattern::parse(pattern).unwrap(),
1000 ..Default::default()
1001 }),
1002 ..ParserOptions::default()
1003 },
1004 );
1005 let mut stylesheet = bundler.bundle(Path::new(entry)).unwrap();
1006 stylesheet.minify(MinifyOptions::default()).unwrap();
1007 let res = stylesheet
1008 .to_css(
1009 PrinterOptions {
1010 project_root,
1011 ..PrinterOptions::default()
1012 },
1013 None::<&mut ()>,
1014 )
1015 .unwrap();
1016 (res.code, res.exports.unwrap())
1017 }
1018
1019 fn bundle_custom_media<P: SourceProvider>(fs: P, entry: &str) -> String {
1020 let mut bundler = Bundler::<_, _, ()>::new(
1021 &fs,
1022 None,
1023 ParserOptions {
1024 flags: ParserFlags::CUSTOM_MEDIA,
1025 ..ParserOptions::default()
1026 },
1027 );
1028 let mut stylesheet = bundler.bundle(Path::new(entry)).unwrap();
1029 let targets = Targets {
1030 browsers: Some(Browsers {
1031 safari: Some(13 << 16),
1032 ..Browsers::default()
1033 }),
1034 ..Default::default()
1035 };
1036 stylesheet
1037 .minify(MinifyOptions {
1038 targets,
1039 ..MinifyOptions::default()
1040 })
1041 .unwrap();
1042 stylesheet
1043 .to_css(
1044 PrinterOptions {
1045 targets,
1046 ..PrinterOptions::default()
1047 },
1048 None::<&mut ()>,
1049 )
1050 .unwrap()
1051 .code
1052 }
1053
1054 fn error_test<P: SourceProvider>(
1055 fs: P,
1056 entry: &str,
1057 maybe_cb: Option<Box<dyn FnOnce(BundleErrorKind<P::Error>) -> ()>>,
1058 ) {
1059 let mut bundler = Bundler::<_, _, ()>::new(&fs, None, ParserOptions::default());
1060 let res = bundler.bundle(Path::new(entry));
1061 match res {
1062 Ok(_) => unreachable!(),
1063 Err(e) => {
1064 if let Some(cb) = maybe_cb {
1065 cb(e.kind);
1066 }
1067 }
1068 }
1069 }
1070
1071 fn flatten_exports(exports: CssModuleExports) -> HashMap<String, String> {
1072 let mut res = HashMap::new();
1073 for (name, export) in &exports {
1074 let mut classes = export.name.clone();
1075 for composes in &export.composes {
1076 classes.push(' ');
1077 classes.push_str(match composes {
1078 CssModuleReference::Local { name } => name,
1079 CssModuleReference::Global { name } => name,
1080 _ => unreachable!(),
1081 })
1082 }
1083 res.insert(name.clone(), classes);
1084 }
1085 res
1086 }
1087
1088 #[test]
1089 fn test_bundle() {
1090 let res = bundle(
1091 TestProvider {
1092 map: fs! {
1093 "/a.css": r#"
1094 @import "b.css";
1095 .a { color: red }
1096 "#,
1097 "/b.css": r#"
1098 .b { color: green }
1099 "#
1100 },
1101 },
1102 "/a.css",
1103 );
1104 assert_eq!(
1105 res,
1106 indoc! { r#"
1107 .b {
1108 color: green;
1109 }
1110
1111 .a {
1112 color: red;
1113 }
1114 "#}
1115 );
1116
1117 let res = bundle(
1118 TestProvider {
1119 map: fs! {
1120 "/a.css": r#"
1121 @import "b.css" print;
1122 .a { color: red }
1123 "#,
1124 "/b.css": r#"
1125 .b { color: green }
1126 "#
1127 },
1128 },
1129 "/a.css",
1130 );
1131 assert_eq!(
1132 res,
1133 indoc! { r#"
1134 @media print {
1135 .b {
1136 color: green;
1137 }
1138 }
1139
1140 .a {
1141 color: red;
1142 }
1143 "#}
1144 );
1145
1146 let res = bundle(
1147 TestProvider {
1148 map: fs! {
1149 "/a.css": r#"
1150 @import "b.css" supports(color: green);
1151 .a { color: red }
1152 "#,
1153 "/b.css": r#"
1154 .b { color: green }
1155 "#
1156 },
1157 },
1158 "/a.css",
1159 );
1160 assert_eq!(
1161 res,
1162 indoc! { r#"
1163 @supports (color: green) {
1164 .b {
1165 color: green;
1166 }
1167 }
1168
1169 .a {
1170 color: red;
1171 }
1172 "#}
1173 );
1174
1175 let res = bundle(
1176 TestProvider {
1177 map: fs! {
1178 "/a.css": r#"
1179 @import "b.css" supports(color: green) print;
1180 .a { color: red }
1181 "#,
1182 "/b.css": r#"
1183 .b { color: green }
1184 "#
1185 },
1186 },
1187 "/a.css",
1188 );
1189 assert_eq!(
1190 res,
1191 indoc! { r#"
1192 @supports (color: green) {
1193 @media print {
1194 .b {
1195 color: green;
1196 }
1197 }
1198 }
1199
1200 .a {
1201 color: red;
1202 }
1203 "#}
1204 );
1205
1206 let res = bundle(
1207 TestProvider {
1208 map: fs! {
1209 "/a.css": r#"
1210 @import "b.css" print;
1211 @import "b.css" screen;
1212 .a { color: red }
1213 "#,
1214 "/b.css": r#"
1215 .b { color: green }
1216 "#
1217 },
1218 },
1219 "/a.css",
1220 );
1221 assert_eq!(
1223 res.replacen("@media screen, print {", "@media print, screen {", 1),
1224 indoc! { r#"
1225 @media print, screen {
1226 .b {
1227 color: green;
1228 }
1229 }
1230
1231 .a {
1232 color: red;
1233 }
1234 "#}
1235 );
1236
1237 let res = bundle(
1238 TestProvider {
1239 map: fs! {
1240 "/a.css": r#"
1241 @import "b.css" supports(color: red);
1242 @import "b.css" supports(foo: bar);
1243 .a { color: red }
1244 "#,
1245 "/b.css": r#"
1246 .b { color: green }
1247 "#
1248 },
1249 },
1250 "/a.css",
1251 );
1252 assert_eq!(
1254 res.replacen(
1255 "@supports (foo: bar) or (color: red) {",
1256 "@supports (color: red) or (foo: bar) {",
1257 1
1258 ),
1259 indoc! { r#"
1260 @supports (color: red) or (foo: bar) {
1261 .b {
1262 color: green;
1263 }
1264 }
1265
1266 .a {
1267 color: red;
1268 }
1269 "#}
1270 );
1271
1272 let res = bundle(
1273 TestProvider {
1274 map: fs! {
1275 "/a.css": r#"
1276 @import "b.css" print;
1277 .a { color: red }
1278 "#,
1279 "/b.css": r#"
1280 @import "c.css" (color);
1281 .b { color: yellow }
1282 "#,
1283 "/c.css": r#"
1284 .c { color: green }
1285 "#
1286 },
1287 },
1288 "/a.css",
1289 );
1290 assert_eq!(
1291 res,
1292 indoc! { r#"
1293 @media print and (color) {
1294 .c {
1295 color: green;
1296 }
1297 }
1298
1299 @media print {
1300 .b {
1301 color: #ff0;
1302 }
1303 }
1304
1305 .a {
1306 color: red;
1307 }
1308 "#}
1309 );
1310
1311 let res = bundle(
1312 TestProvider {
1313 map: fs! {
1314 "/a.css": r#"
1315 @import "b.css";
1316 .a { color: red }
1317 "#,
1318 "/b.css": r#"
1319 @import "c.css";
1320 "#,
1321 "/c.css": r#"
1322 @import "a.css";
1323 .c { color: green }
1324 "#
1325 },
1326 },
1327 "/a.css",
1328 );
1329 assert_eq!(
1330 res,
1331 indoc! { r#"
1332 .c {
1333 color: green;
1334 }
1335
1336 .a {
1337 color: red;
1338 }
1339 "#}
1340 );
1341
1342 let res = bundle(
1343 TestProvider {
1344 map: fs! {
1345 "/a.css": r#"
1346 @import "b/c.css";
1347 .a { color: red }
1348 "#,
1349 "/b/c.css": r#"
1350 .b { color: green }
1351 "#
1352 },
1353 },
1354 "/a.css",
1355 );
1356 assert_eq!(
1357 res,
1358 indoc! { r#"
1359 .b {
1360 color: green;
1361 }
1362
1363 .a {
1364 color: red;
1365 }
1366 "#}
1367 );
1368
1369 let res = bundle(
1370 TestProvider {
1371 map: fs! {
1372 "/a.css": r#"
1373 @import "./b/c.css";
1374 .a { color: red }
1375 "#,
1376 "/b/c.css": r#"
1377 .b { color: green }
1378 "#
1379 },
1380 },
1381 "/a.css",
1382 );
1383 assert_eq!(
1384 res,
1385 indoc! { r#"
1386 .b {
1387 color: green;
1388 }
1389
1390 .a {
1391 color: red;
1392 }
1393 "#}
1394 );
1395
1396 let res = bundle_custom_media(
1397 TestProvider {
1398 map: fs! {
1399 "/a.css": r#"
1400 @import "media.css";
1401 @import "b.css";
1402 .a { color: red }
1403 "#,
1404 "/media.css": r#"
1405 @custom-media --foo print;
1406 "#,
1407 "/b.css": r#"
1408 @media (--foo) {
1409 .a { color: green }
1410 }
1411 "#
1412 },
1413 },
1414 "/a.css",
1415 );
1416 assert_eq!(
1417 res,
1418 indoc! { r#"
1419 @media print {
1420 .a {
1421 color: green;
1422 }
1423 }
1424
1425 .a {
1426 color: red;
1427 }
1428 "#}
1429 );
1430
1431 let res = bundle(
1432 TestProvider {
1433 map: fs! {
1434 "/a.css": r#"
1435 @import "b.css" layer(foo);
1436 .a { color: red }
1437 "#,
1438 "/b.css": r#"
1439 .b { color: green }
1440 "#
1441 },
1442 },
1443 "/a.css",
1444 );
1445 assert_eq!(
1446 res,
1447 indoc! { r#"
1448 @layer foo {
1449 .b {
1450 color: green;
1451 }
1452 }
1453
1454 .a {
1455 color: red;
1456 }
1457 "#}
1458 );
1459
1460 let res = bundle(
1461 TestProvider {
1462 map: fs! {
1463 "/a.css": r#"
1464 @import "b.css" layer;
1465 .a { color: red }
1466 "#,
1467 "/b.css": r#"
1468 .b { color: green }
1469 "#
1470 },
1471 },
1472 "/a.css",
1473 );
1474 assert_eq!(
1475 res,
1476 indoc! { r#"
1477 @layer {
1478 .b {
1479 color: green;
1480 }
1481 }
1482
1483 .a {
1484 color: red;
1485 }
1486 "#}
1487 );
1488
1489 let res = bundle(
1490 TestProvider {
1491 map: fs! {
1492 "/a.css": r#"
1493 @import "b.css" layer(foo);
1494 .a { color: red }
1495 "#,
1496 "/b.css": r#"
1497 @import "c.css" layer(bar);
1498 .b { color: green }
1499 "#,
1500 "/c.css": r#"
1501 .c { color: green }
1502 "#
1503 },
1504 },
1505 "/a.css",
1506 );
1507 assert_eq!(
1508 res,
1509 indoc! { r#"
1510 @layer foo.bar {
1511 .c {
1512 color: green;
1513 }
1514 }
1515
1516 @layer foo {
1517 .b {
1518 color: green;
1519 }
1520 }
1521
1522 .a {
1523 color: red;
1524 }
1525 "#}
1526 );
1527
1528 let res = bundle(
1529 TestProvider {
1530 map: fs! {
1531 "/a.css": r#"
1532 @import "b.css" layer(foo);
1533 @import "b.css" layer(foo);
1534 "#,
1535 "/b.css": r#"
1536 .b { color: green }
1537 "#
1538 },
1539 },
1540 "/a.css",
1541 );
1542 assert_eq!(
1543 res,
1544 indoc! { r#"
1545 @layer foo {
1546 .b {
1547 color: green;
1548 }
1549 }
1550 "#}
1551 );
1552
1553 let res = bundle(
1554 TestProvider {
1555 map: fs! {
1556 "/a.css": r#"
1557 @layer bar, foo;
1558 @import "b.css" layer(foo);
1559
1560 @layer bar {
1561 div {
1562 background: red;
1563 }
1564 }
1565 "#,
1566 "/b.css": r#"
1567 @layer qux, baz;
1568 @import "c.css" layer(baz);
1569
1570 @layer qux {
1571 div {
1572 background: green;
1573 }
1574 }
1575 "#,
1576 "/c.css": r#"
1577 div {
1578 background: yellow;
1579 }
1580 "#
1581 },
1582 },
1583 "/a.css",
1584 );
1585 assert_eq!(
1586 res,
1587 indoc! { r#"
1588 @layer bar, foo;
1589 @layer foo.qux, foo.baz;
1590
1591 @layer foo.baz {
1592 div {
1593 background: #ff0;
1594 }
1595 }
1596
1597 @layer foo {
1598 @layer qux {
1599 div {
1600 background: green;
1601 }
1602 }
1603 }
1604
1605 @layer bar {
1606 div {
1607 background: red;
1608 }
1609 }
1610 "#}
1611 );
1612
1613 let res = bundle(
1615 TestProvider {
1616 map: fs! {
1617 "/a.css": r#"
1618 @import "b.css" layer(bar) (min-width: 1000px);
1619
1620 @layer baz {
1621 #box { background: purple }
1622 }
1623
1624 @layer bar {
1625 #box { background: yellow }
1626 }
1627 "#,
1628 "/b.css": r#"
1629 #box { background: green }
1630 "#
1631 },
1632 },
1633 "/a.css",
1634 );
1635 assert_eq!(
1636 res,
1637 indoc! { r#"
1638 @media (width >= 1000px) {
1639 @layer bar {
1640 #box {
1641 background: green;
1642 }
1643 }
1644 }
1645
1646 @layer baz {
1647 #box {
1648 background: purple;
1649 }
1650 }
1651
1652 @layer bar {
1653 #box {
1654 background: #ff0;
1655 }
1656 }
1657 "#}
1658 );
1659
1660 let res = bundle(
1661 TestProvider {
1662 map: fs! {
1663 "/a.css": r#"
1664 @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
1665 @import './b.css';
1666 "#,
1667 "/b.css": r#"
1668 .b { color: green }
1669 "#
1670 },
1671 },
1672 "/a.css",
1673 );
1674 assert_eq!(
1675 res,
1676 indoc! { r#"
1677 @import "https://fonts.googleapis.com/css2?family=Roboto&display=swap";
1678
1679 .b {
1680 color: green;
1681 }
1682 "#}
1683 );
1684
1685 error_test(
1686 TestProvider {
1687 map: fs! {
1688 "/a.css": r#"
1689 @import './b.css';
1690 @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
1691 "#,
1692 "/b.css": r#"
1693 .b { color: green }
1694 "#
1695 },
1696 },
1697 "/a.css",
1698 Some(Box::new(|err| {
1699 assert!(matches!(err, BundleErrorKind::ExternalImportAfterBundledImport));
1700 })),
1701 );
1702
1703 error_test(
1704 TestProvider {
1705 map: fs! {
1706 "/a.css": r#"
1707 @import "b.css" layer(foo);
1708 @import "b.css" layer(bar);
1709 "#,
1710 "/b.css": r#"
1711 .b { color: red }
1712 "#
1713 },
1714 },
1715 "/a.css",
1716 Some(Box::new(|err| {
1717 assert!(matches!(err, BundleErrorKind::UnsupportedLayerCombination));
1718 })),
1719 );
1720
1721 error_test(
1722 TestProvider {
1723 map: fs! {
1724 "/a.css": r#"
1725 @import "b.css" layer;
1726 @import "b.css" layer;
1727 "#,
1728 "/b.css": r#"
1729 .b { color: red }
1730 "#
1731 },
1732 },
1733 "/a.css",
1734 Some(Box::new(|err| {
1735 assert!(matches!(err, BundleErrorKind::UnsupportedLayerCombination));
1736 })),
1737 );
1738
1739 error_test(
1740 TestProvider {
1741 map: fs! {
1742 "/a.css": r#"
1743 @import "b.css" layer;
1744 .a { color: red }
1745 "#,
1746 "/b.css": r#"
1747 @import "c.css" layer;
1748 .b { color: green }
1749 "#,
1750 "/c.css": r#"
1751 .c { color: green }
1752 "#
1753 },
1754 },
1755 "/a.css",
1756 Some(Box::new(|err| {
1757 assert!(matches!(err, BundleErrorKind::UnsupportedLayerCombination));
1758 })),
1759 );
1760
1761 error_test(
1762 TestProvider {
1763 map: fs! {
1764 "/a.css": r#"
1765 @import "b.css" layer;
1766 .a { color: red }
1767 "#,
1768 "/b.css": r#"
1769 @import "c.css" layer(foo);
1770 .b { color: green }
1771 "#,
1772 "/c.css": r#"
1773 .c { color: green }
1774 "#
1775 },
1776 },
1777 "/a.css",
1778 Some(Box::new(|err| {
1779 assert!(matches!(err, BundleErrorKind::UnsupportedLayerCombination));
1780 })),
1781 );
1782
1783 let res = bundle(
1784 TestProvider {
1785 map: fs! {
1786 "/index.css": r#"
1787 @import "a.css";
1788 @import "b.css";
1789 "#,
1790 "/a.css": r#"
1791 @import "./c.css";
1792 body { background: red; }
1793 "#,
1794 "/b.css": r#"
1795 @import "./c.css";
1796 body { color: red; }
1797 "#,
1798 "/c.css": r#"
1799 body {
1800 background: white;
1801 color: black;
1802 }
1803 "#
1804 },
1805 },
1806 "/index.css",
1807 );
1808 assert_eq!(
1809 res,
1810 indoc! { r#"
1811 body {
1812 background: red;
1813 }
1814
1815 body {
1816 background: #fff;
1817 color: #000;
1818 }
1819
1820 body {
1821 color: red;
1822 }
1823 "#}
1824 );
1825
1826 let res = bundle(
1827 TestProvider {
1828 map: fs! {
1829 "/index.css": r#"
1830 @import "a.css";
1831 @import "b.css";
1832 @import "a.css";
1833 "#,
1834 "/a.css": r#"
1835 body { background: green; }
1836 "#,
1837 "/b.css": r#"
1838 body { background: red; }
1839 "#
1840 },
1841 },
1842 "/index.css",
1843 );
1844 assert_eq!(
1845 res,
1846 indoc! { r#"
1847 body {
1848 background: red;
1849 }
1850
1851 body {
1852 background: green;
1853 }
1854 "#}
1855 );
1856
1857 let res = bundle(
1858 CustomProvider {
1859 map: fs! {
1860 "/a.css": r#"
1861 @import "foo:/b.css";
1862 .a { color: red; }
1863 "#,
1864 "/b.css": ".b { color: green; }"
1865 },
1866 },
1867 "/a.css",
1868 );
1869 assert_eq!(
1870 res,
1871 indoc! { r#"
1872 .b {
1873 color: green;
1874 }
1875
1876 .a {
1877 color: red;
1878 }
1879 "# }
1880 );
1881
1882 error_test(
1883 CustomProvider {
1884 map: fs! {
1885 "/a.css": r#"
1886 /* Forgot to prefix with `foo:`. */
1887 @import "/b.css";
1888 .a { color: red; }
1889 "#,
1890 "/b.css": ".b { color: green; }"
1891 },
1892 },
1893 "/a.css",
1894 Some(Box::new(|err| {
1895 let kind = match err {
1896 BundleErrorKind::ResolverError(ref error) => error.kind(),
1897 _ => unreachable!(),
1898 };
1899 assert!(matches!(kind, std::io::ErrorKind::NotFound));
1900 assert!(err
1901 .to_string()
1902 .contains("Failed to resolve `/b.css`, specifier does not start with `foo:`."));
1903 })),
1904 );
1905
1906 }
1931
1932 #[test]
1933 fn test_css_module() {
1934 macro_rules! map {
1935 { $($key:expr => $val:expr),* } => {
1936 HashMap::from([
1937 $(($key.to_owned(), $val.to_owned()),)*
1938 ])
1939 };
1940 }
1941
1942 let (code, exports) = bundle_css_module(
1943 TestProvider {
1944 map: fs! {
1945 "/a.css": r#"
1946 @import "b.css";
1947 .a { color: red }
1948 "#,
1949 "/b.css": r#"
1950 .a { color: green }
1951 "#
1952 },
1953 },
1954 "/a.css",
1955 None,
1956 );
1957 assert_eq!(
1958 code,
1959 indoc! { r#"
1960 ._9z6RGq_a {
1961 color: green;
1962 }
1963
1964 ._6lixEq_a {
1965 color: red;
1966 }
1967 "#}
1968 );
1969 assert_eq!(
1970 flatten_exports(exports),
1971 map! {
1972 "a" => "_6lixEq_a"
1973 }
1974 );
1975
1976 let (code, exports) = bundle_css_module(
1977 TestProvider {
1978 map: fs! {
1979 "/a.css": r#"
1980 .a { composes: x from './b.css'; color: red; }
1981 .b { color: yellow }
1982 "#,
1983 "/b.css": r#"
1984 .x { composes: y; background: green }
1985 .y { font: Helvetica }
1986 "#
1987 },
1988 },
1989 "/a.css",
1990 None,
1991 );
1992 assert_eq!(
1993 code,
1994 indoc! { r#"
1995 ._8Cs9ZG_x {
1996 background: green;
1997 }
1998
1999 ._8Cs9ZG_y {
2000 font: Helvetica;
2001 }
2002
2003 ._6lixEq_a {
2004 color: red;
2005 }
2006
2007 ._6lixEq_b {
2008 color: #ff0;
2009 }
2010 "#}
2011 );
2012 assert_eq!(
2013 flatten_exports(exports),
2014 map! {
2015 "a" => "_6lixEq_a _8Cs9ZG_x _8Cs9ZG_y",
2016 "b" => "_6lixEq_b"
2017 }
2018 );
2019
2020 let (code, exports) = bundle_css_module(
2021 TestProvider {
2022 map: fs! {
2023 "/a.css": r#"
2024 .a { composes: x from './b.css'; background: red; }
2025 "#,
2026 "/b.css": r#"
2027 .a { background: red }
2028 "#
2029 },
2030 },
2031 "/a.css",
2032 None,
2033 );
2034 assert_eq!(
2035 code,
2036 indoc! { r#"
2037 ._8Cs9ZG_a {
2038 background: red;
2039 }
2040
2041 ._6lixEq_a {
2042 background: red;
2043 }
2044 "#}
2045 );
2046 assert_eq!(
2047 flatten_exports(exports),
2048 map! {
2049 "a" => "_6lixEq_a"
2050 }
2051 );
2052
2053 let (code, exports) = bundle_css_module(
2054 TestProvider {
2055 map: fs! {
2056 "/a.css": r#"
2057 .a {
2058 background: var(--bg from "./b.css", var(--fallback from "./b.css"));
2059 color: rgb(255 255 255 / var(--opacity from "./b.css"));
2060 width: env(--env, var(--env-fallback from "./env.css"));
2061 }
2062 "#,
2063 "/b.css": r#"
2064 .b {
2065 --bg: red;
2066 --fallback: yellow;
2067 --opacity: 0.5;
2068 }
2069 "#,
2070 "/env.css": r#"
2071 .env {
2072 --env-fallback: 20px;
2073 }
2074 "#
2075 },
2076 },
2077 "/a.css",
2078 None,
2079 );
2080 assert_eq!(
2081 code,
2082 indoc! { r#"
2083 ._8Cs9ZG_b {
2084 --_8Cs9ZG_bg: red;
2085 --_8Cs9ZG_fallback: yellow;
2086 --_8Cs9ZG_opacity: .5;
2087 }
2088
2089 .GbJUva_env {
2090 --GbJUva_env-fallback: 20px;
2091 }
2092
2093 ._6lixEq_a {
2094 background: var(--_8Cs9ZG_bg, var(--_8Cs9ZG_fallback));
2095 color: rgb(255 255 255 / var(--_8Cs9ZG_opacity));
2096 width: env(--_6lixEq_env, var(--GbJUva_env-fallback));
2097 }
2098 "#}
2099 );
2100 assert_eq!(
2101 flatten_exports(exports),
2102 map! {
2103 "a" => "_6lixEq_a",
2104 "--env" => "--_6lixEq_env"
2105 }
2106 );
2107
2108 let expected = indoc! { r#"
2110 .dyGcAa_b {
2111 background: #ff0;
2112 }
2113
2114 .CK9avG_a {
2115 background: #fff;
2116 }
2117 "#};
2118
2119 let (code, _) = bundle_css_module(
2120 TestProvider {
2121 map: fs! {
2122 "/foo/bar/a.css": r#"
2123 @import "b.css";
2124 .a {
2125 background: white;
2126 }
2127 "#,
2128 "/foo/bar/b.css": r#"
2129 .b {
2130 background: yellow;
2131 }
2132 "#
2133 },
2134 },
2135 "/foo/bar/a.css",
2136 Some("/foo/bar"),
2137 );
2138 assert_eq!(code, expected);
2139
2140 let (code, _) = bundle_css_module(
2141 TestProvider {
2142 map: fs! {
2143 "/x/y/z/a.css": r#"
2144 @import "b.css";
2145 .a {
2146 background: white;
2147 }
2148 "#,
2149 "/x/y/z/b.css": r#"
2150 .b {
2151 background: yellow;
2152 }
2153 "#
2154 },
2155 },
2156 "/x/y/z/a.css",
2157 Some("/x/y/z"),
2158 );
2159 assert_eq!(code, expected);
2160
2161 let (code, _) = bundle_css_module_with_pattern(
2162 TestProvider {
2163 map: fs! {
2164 "/a.css": r#"
2165 @import "b.css";
2166 .a { color: red }
2167 "#,
2168 "/b.css": r#"
2169 .a { color: green }
2170 "#
2171 },
2172 },
2173 "/a.css",
2174 None,
2175 "[content-hash]-[local]",
2176 );
2177 assert_eq!(
2178 code,
2179 indoc! { r#"
2180 .do5n2W-a {
2181 color: green;
2182 }
2183
2184 .pP97eq-a {
2185 color: red;
2186 }
2187 "#}
2188 );
2189 }
2190
2191 #[test]
2192 #[cfg(feature = "sourcemap")]
2193 fn test_source_map() {
2194 let source = r#".imported {
2195 content: "yay, file support!";
2196 }
2197
2198 .selector {
2199 margin: 1em;
2200 background-color: #f60;
2201 }
2202
2203 .selector .nested {
2204 margin: 0.5em;
2205 }
2206
2207 /*# sourceMappingURL=data:application/json;base64,ewoJInZlcnNpb24iOiAzLAoJInNvdXJjZVJvb3QiOiAicm9vdCIsCgkiZmlsZSI6ICJzdGRvdXQiLAoJInNvdXJjZXMiOiBbCgkJInN0ZGluIiwKCQkic2Fzcy9fdmFyaWFibGVzLnNjc3MiLAoJCSJzYXNzL19kZW1vLnNjc3MiCgldLAoJInNvdXJjZXNDb250ZW50IjogWwoJCSJAaW1wb3J0IFwiX3ZhcmlhYmxlc1wiO1xuQGltcG9ydCBcIl9kZW1vXCI7XG5cbi5zZWxlY3RvciB7XG4gIG1hcmdpbjogJHNpemU7XG4gIGJhY2tncm91bmQtY29sb3I6ICRicmFuZENvbG9yO1xuXG4gIC5uZXN0ZWQge1xuICAgIG1hcmdpbjogJHNpemUgLyAyO1xuICB9XG59IiwKCQkiJGJyYW5kQ29sb3I6ICNmNjA7XG4kc2l6ZTogMWVtOyIsCgkJIi5pbXBvcnRlZCB7XG4gIGNvbnRlbnQ6IFwieWF5LCBmaWxlIHN1cHBvcnQhXCI7XG59IgoJXSwKCSJtYXBwaW5ncyI6ICJBRUFBLFNBQVMsQ0FBQztFQUNSLE9BQU8sRUFBRSxvQkFBcUI7Q0FDL0I7O0FGQ0QsU0FBUyxDQUFDO0VBQ1IsTUFBTSxFQ0hELEdBQUc7RURJUixnQkFBZ0IsRUNMTCxJQUFJO0NEVWhCOztBQVBELFNBQVMsQ0FJUCxPQUFPLENBQUM7RUFDTixNQUFNLEVDUEgsS0FBRztDRFFQIiwKCSJuYW1lcyI6IFtdCn0= */"#;
2208
2209 let fs = TestProvider {
2210 map: fs! {
2211 "/a.css": r#"
2212 @import "/b.css";
2213 .a { color: red; }
2214 "#,
2215 "/b.css": source
2216 },
2217 };
2218
2219 let mut sm = parcel_sourcemap::SourceMap::new("/");
2220 let mut bundler = Bundler::new(&fs, Some(&mut sm), ParserOptions::default());
2221 let mut stylesheet = bundler.bundle(Path::new("/a.css")).unwrap();
2222 stylesheet.minify(MinifyOptions::default()).unwrap();
2223 stylesheet
2224 .to_css(
2225 PrinterOptions {
2226 minify: true,
2227 ..PrinterOptions::default()
2228 },
2229 Some(&mut sm),
2230 )
2231 .unwrap();
2232 let map = sm.to_json(None).unwrap();
2233 assert_eq!(
2234 map,
2235 r#"{"version":3,"sourceRoot":null,"mappings":"ACAA,uCCGA,2CAAA,8BFDQ","sources":["a.css","sass/_demo.scss","stdin"],"sourcesContent":["\n @import \"/b.css\";\n .a { color: red; }\n ",".imported {\n content: \"yay, file support!\";\n}","@import \"_variables\";\n@import \"_demo\";\n\n.selector {\n margin: $size;\n background-color: $brandColor;\n\n .nested {\n margin: $size / 2;\n }\n}"],"names":[]}"#
2236 );
2237 }
2238
2239 #[test]
2240 fn test_license_comments() {
2241 let res = bundle(
2242 TestProvider {
2243 map: fs! {
2244 "/a.css": r#"
2245 /*! Copyright 2023 Someone awesome */
2246 @import "b.css";
2247 .a { color: red }
2248 "#,
2249 "/b.css": r#"
2250 /*! Copyright 2023 Someone else */
2251 .b { color: green }
2252 "#
2253 },
2254 },
2255 "/a.css",
2256 );
2257 assert_eq!(
2258 res,
2259 indoc! { r#"
2260 /*! Copyright 2023 Someone awesome */
2261 /*! Copyright 2023 Someone else */
2262 .b {
2263 color: green;
2264 }
2265
2266 .a {
2267 color: red;
2268 }
2269 "#}
2270 );
2271 }
2272}