Skip to main content

rspack_lightningcss/
bundler.rs

1//! CSS bundling.
2//!
3//! A [Bundler](Bundler) can be used to combine a CSS file and all of its dependencies
4//! into a single merged style sheet. It works together with a [SourceProvider](SourceProvider)
5//! (e.g. [FileProvider](FileProvider)) to read files from the file system or another source,
6//! and returns a [StyleSheet](super::stylesheet::StyleSheet) containing the rules from all
7//! of the dependencies of the entry file, recursively.
8//!
9//! Rules are bundled following `@import` order, and wrapped in the necessary `@media`, `@supports`,
10//! and `@layer` rules as appropriate to preserve the authored behavior.
11//!
12//! # Example
13//!
14//! ```no_run
15//! use std::path::Path;
16//! use rspack_lightningcss::{
17//!   bundler::{Bundler, FileProvider},
18//!   stylesheet::ParserOptions
19//! };
20//!
21//! let fs = FileProvider::new();
22//! let mut bundler = Bundler::new(&fs, None::<&mut ()>, ParserOptions::default());
23//! let stylesheet = bundler.bundle(Path::new("style.css")).unwrap();
24//! ```
25
26use 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
64/// A Bundler combines a CSS file and all imported dependencies together into
65/// a single merged style sheet.
66pub 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/// The result of [SourceProvider::resolve].
100#[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  /// An external URL.
108  External(String),
109  /// A file path.
110  #[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
120/// A trait to provide the contents of files to a Bundler.
121///
122/// See [FileProvider](FileProvider) for an implementation that uses the
123/// file system.
124pub trait SourceProvider: Send + Sync {
125  /// A custom error.
126  type Error: std::error::Error + Send + Sync;
127
128  /// Reads the contents of the given file path to a string.
129  fn read<'a>(&'a self, file: &Path) -> Result<&'a str, Self::Error>;
130
131  /// Resolves the given import specifier to a file path given the file
132  /// which the import originated from.
133  fn resolve(&self, specifier: &str, originating_file: &Path) -> Result<ResolveResult, Self::Error>;
134}
135
136/// Provides an implementation of [SourceProvider](SourceProvider)
137/// that reads files from the file system.
138pub struct FileProvider {
139  inputs: Mutex<Vec<*mut String>>,
140}
141
142impl FileProvider {
143  /// Creates a new FileProvider.
144  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    // SAFETY: this is safe because the pointer is not dropped
162    // until the FileProvider is, and we never remove from the
163    // list of pointers stored in the vector.
164    Ok(unsafe { &*ptr })
165  }
166
167  fn resolve(&self, specifier: &str, originating_file: &Path) -> Result<ResolveResult, Self::Error> {
168    // Assume the specifier is a relative file path and join it with current path.
169    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/// An error that could occur during bundling.
182#[derive(Debug)]
183#[cfg_attr(any(feature = "serde", feature = "nodejs"), derive(serde::Serialize))]
184pub enum BundleErrorKind<'i, T: std::error::Error> {
185  /// A parser error occurred.
186  ParserError(ParserError<'i>),
187  /// An unsupported `@import` condition was encountered.
188  UnsupportedImportCondition,
189  /// An unsupported cascade layer combination was encountered.
190  UnsupportedLayerCombination,
191  /// Unsupported media query boolean logic was encountered.
192  UnsupportedMediaBooleanLogic,
193  /// An external module was referenced with a CSS module "from" clause.
194  ReferencedExternalModuleWithCssModuleFrom,
195  /// An external `@import` was found after a bundled `@import`.
196  /// This may result in unintended selector order.
197  ExternalImportAfterBundledImport,
198  /// A custom resolver error.
199  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  /// Creates a new Bundler using the given source provider.
241  /// If a source map is given, the content of each source file included in the bundle will
242  /// be added accordingly.
243  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  /// Creates a new Bundler using the given source provider.
265  /// If a source map is given, the content of each source file included in the bundle will
266  /// be added accordingly.
267  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  /// Bundles the given entry file and all dependencies into a single style sheet.
284  pub fn bundle<'e>(
285    &mut self,
286    entry: &'e Path,
287  ) -> Result<StyleSheet<'a, T::AtRule>, Error<BundleErrorKind<'a, P::Error>>> {
288    // Phase 1: load and parse all files. This is done in parallel.
289    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    // Phase 2: determine the order that the files should be concatenated.
305    self.order();
306
307    // Phase 3: concatenate.
308    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    // This function is only used for error handling, so it's ok if this is a bit slow.
369    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    // Check if we already loaded this file.
375    let mut stylesheets = self.stylesheets.lock().unwrap();
376    let source_index = match self.source_indexes.get(file) {
377      Some(source_index) => {
378        // If we already loaded this file, combine the media queries and supports conditions
379        // from this import rule with the existing ones using a logical or operator.
380        let entry = &mut stylesheets[*source_index as usize];
381
382        // We cannot combine a media query and a supports query from different @import rules.
383        // e.g. @import "a.css" print; @import "a.css" supports(color: red);
384        // This would require duplicating the actual rules in the file.
385        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            // We can't OR layer names without duplicating all of the nested rules, so error for now.
411            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); // ensure we aren't holding the lock anymore
446
447    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      // Only omit the CSS source when the input source map can actually be read.
474      // Otherwise, the printer needs this index as a fallback for generated mappings.
475      if stylesheet.source_map::<S>(0).is_none() {
476        let mut source_map = source_map.lock().unwrap();
477        let source_index = source_map.add_source(filename);
478        source_map.set_source_content(source_index, code);
479        source_map_source_index = Some(source_index);
480      }
481    }
482
483    // Collect and load dependencies for this stylesheet in parallel.
484    let dependencies: Result<Vec<Dependency>, _> = stylesheet
485      .rules
486      .0
487      .par_iter_mut()
488      .filter_map(|r| {
489        // Prepend parent layer name to @layer statements.
490        if let CssRule::LayerStatement(layer) = r {
491          if let Some(Some(parent_layer)) = &rule.layer {
492            for name in &mut layer.names {
493              name.0.insert_many(0, parent_layer.0.iter().cloned())
494            }
495          }
496        }
497
498        if let CssRule::Import(import) = r {
499          let specifier = &import.url;
500
501          // Combine media queries and supports conditions from parent
502          // stylesheet with @import rule using a logical and operator.
503          let mut media = rule.media.clone();
504          let result = media.and(&import.media).map_err(|_| Error {
505            kind: BundleErrorKind::UnsupportedMediaBooleanLogic,
506            loc: Some(ErrorLocation::new(
507              import.loc,
508              self.find_filename(import.loc.source_index),
509            )),
510          });
511
512          if let Err(e) = result {
513            return Some(Err(e));
514          }
515
516          let layer = if (rule.layer == Some(None) && import.layer.is_some())
517            || (import.layer == Some(None) && rule.layer.is_some())
518          {
519            // Cannot combine anonymous layers
520            return Some(Err(Error {
521              kind: BundleErrorKind::UnsupportedLayerCombination,
522              loc: Some(ErrorLocation::new(
523                import.loc,
524                self.find_filename(import.loc.source_index),
525              )),
526            }));
527          } else if let Some(Some(a)) = &rule.layer {
528            if let Some(Some(b)) = &import.layer {
529              let mut name = a.clone();
530              name.0.extend(b.0.iter().cloned());
531              Some(Some(name))
532            } else {
533              Some(Some(a.clone()))
534            }
535          } else {
536            import.layer.clone()
537          };
538
539          let result = match self.fs.resolve(&specifier, file) {
540            Ok(ResolveResult::File(path)) => self
541              .load_file(
542                &path,
543                ImportRule {
544                  layer,
545                  media,
546                  supports: combine_supports(rule.supports.clone(), &import.supports),
547                  url: "".into(),
548                  loc: import.loc,
549                },
550              )
551              .map(Dependency::File),
552            Ok(ResolveResult::External(url)) => Ok(Dependency::External(url)),
553            Err(err) => Err(Error {
554              kind: BundleErrorKind::ResolverError(err),
555              loc: Some(ErrorLocation::new(
556                import.loc,
557                self.find_filename(import.loc.source_index),
558              )),
559            }),
560          };
561
562          Some(result)
563        } else {
564          None
565        }
566      })
567      .collect();
568
569    // Collect CSS modules dependencies from the `composes` property.
570    let css_modules_deps: Result<Vec<u32>, _> = if self.options.css_modules.is_some() {
571      stylesheet
572        .rules
573        .0
574        .par_iter_mut()
575        .filter_map(|r| {
576          if let CssRule::Style(style) = r {
577            Some(
578              style
579                .declarations
580                .declarations
581                .par_iter_mut()
582                .chain(style.declarations.important_declarations.par_iter_mut())
583                .filter_map(|d| match d {
584                  Property::Composes(composes) => self
585                    .add_css_module_dep(file, &rule, style.loc, composes.loc, &mut composes.from)
586                    .map(|result| rayon::iter::Either::Left(rayon::iter::once(result))),
587
588                  // Handle variable references if the dashed_idents option is present.
589                  Property::Custom(CustomProperty { value, .. })
590                  | Property::Unparsed(UnparsedProperty { value, .. })
591                    if matches!(&self.options.css_modules, Some(css_modules) if css_modules.dashed_idents) =>
592                  {
593                    Some(rayon::iter::Either::Right(visit_vars(value).filter_map(|name| {
594                      self.add_css_module_dep(
595                        file,
596                        &rule,
597                        style.loc,
598                        // TODO: store loc in variable reference?
599                        crate::dependencies::Location {
600                          line: style.loc.line,
601                          column: style.loc.column,
602                        },
603                        &mut name.from,
604                      )
605                    })))
606                  }
607                  _ => None,
608                })
609                .flatten(),
610            )
611          } else {
612            None
613          }
614        })
615        .flatten()
616        .collect()
617    } else {
618      Ok(vec![])
619    };
620
621    let entry = &mut self.stylesheets.lock().unwrap()[source_index as usize];
622    entry.stylesheet = Some(stylesheet);
623    entry.source_map_source_index = source_map_source_index;
624    entry.dependencies = dependencies?;
625    entry.css_modules_deps = css_modules_deps?;
626
627    Ok(source_index)
628  }
629
630  fn add_css_module_dep(
631    &self,
632    file: &Path,
633    rule: &ImportRule<'a>,
634    style_loc: Location,
635    loc: crate::dependencies::Location,
636    specifier: &mut Option<Specifier>,
637  ) -> Option<Result<u32, Error<BundleErrorKind<'a, P::Error>>>> {
638    if let Some(Specifier::File(f)) = specifier {
639      let result = match self.fs.resolve(&f, file) {
640        Ok(ResolveResult::File(path)) => {
641          let res = self.load_file(
642            &path,
643            ImportRule {
644              layer: rule.layer.clone(),
645              media: rule.media.clone(),
646              supports: rule.supports.clone(),
647              url: "".into(),
648              loc: Location {
649                source_index: style_loc.source_index,
650                line: loc.line,
651                column: loc.column,
652              },
653            },
654          );
655
656          if let Ok(source_index) = res {
657            *specifier = Some(Specifier::SourceIndex(source_index));
658          }
659
660          res
661        }
662        Ok(ResolveResult::External(_)) => Err(Error {
663          kind: BundleErrorKind::ReferencedExternalModuleWithCssModuleFrom,
664          loc: Some(ErrorLocation::new(
665            style_loc,
666            self.find_filename(style_loc.source_index),
667          )),
668        }),
669        Err(err) => Err(Error {
670          kind: BundleErrorKind::ResolverError(err),
671          loc: Some(ErrorLocation::new(
672            style_loc,
673            self.find_filename(style_loc.source_index),
674          )),
675        }),
676      };
677      Some(result)
678    } else {
679      None
680    }
681  }
682
683  fn order(&mut self) {
684    process(self.stylesheets.get_mut().unwrap(), 0, &mut HashSet::new());
685
686    fn process<'i, T>(
687      stylesheets: &mut Vec<BundleStyleSheet<'i, T>>,
688      source_index: u32,
689      visited: &mut HashSet<u32>,
690    ) {
691      if visited.contains(&source_index) {
692        return;
693      }
694
695      visited.insert(source_index);
696
697      let mut dep_index = 0;
698      for i in 0..stylesheets[source_index as usize].css_modules_deps.len() {
699        let dep_source_index = stylesheets[source_index as usize].css_modules_deps[i];
700        let resolved = &mut stylesheets[dep_source_index as usize];
701
702        // CSS modules preserve the first instance of composed stylesheets.
703        if !visited.contains(&dep_source_index) {
704          resolved.parent_dep_index = dep_index;
705          resolved.parent_source_index = source_index;
706          process(stylesheets, dep_source_index, visited);
707        }
708
709        dep_index += 1;
710      }
711
712      for i in 0..stylesheets[source_index as usize].dependencies.len() {
713        let Dependency::File(dep_source_index) = stylesheets[source_index as usize].dependencies[i] else {
714          continue;
715        };
716        let resolved = &mut stylesheets[dep_source_index as usize];
717
718        // In browsers, every instance of an @import is evaluated, so we preserve the last.
719        resolved.parent_dep_index = dep_index;
720        resolved.parent_source_index = source_index;
721
722        process(stylesheets, dep_source_index, visited);
723        dep_index += 1;
724      }
725    }
726  }
727
728  fn inline(
729    &mut self,
730    dest: &mut Vec<CssRule<'a, T::AtRule>>,
731  ) -> Result<(), Error<BundleErrorKind<'a, P::Error>>> {
732    fn process<'a, T, E: std::error::Error>(
733      stylesheets: &mut Vec<BundleStyleSheet<'a, T>>,
734      source_index: u32,
735      dest: &mut Vec<CssRule<'a, T>>,
736      filename: &String,
737    ) -> Result<(), Error<BundleErrorKind<'a, E>>> {
738      let stylesheet = &mut stylesheets[source_index as usize];
739      let mut rules = std::mem::take(&mut stylesheet.stylesheet.as_mut().unwrap().rules.0);
740
741      // Hoist css modules deps
742      let mut dep_index = 0;
743      for i in 0..stylesheet.css_modules_deps.len() {
744        let dep_source_index = stylesheets[source_index as usize].css_modules_deps[i];
745        let resolved = &stylesheets[dep_source_index as usize];
746
747        // Include the dependency if this is the first instance as computed earlier.
748        if resolved.parent_source_index == source_index && resolved.parent_dep_index == dep_index as u32 {
749          process(stylesheets, dep_source_index, dest, filename)?;
750        }
751
752        dep_index += 1;
753      }
754
755      let mut import_index = 0;
756      let mut has_bundled_import = false;
757      for rule in &mut rules {
758        match rule {
759          CssRule::Import(import_rule) => {
760            let dep_source = &stylesheets[source_index as usize].dependencies[import_index];
761            match dep_source {
762              Dependency::File(dep_source_index) => {
763                let resolved = &stylesheets[*dep_source_index as usize];
764
765                // Include the dependency if this is the last instance as computed earlier.
766                if resolved.parent_source_index == source_index && resolved.parent_dep_index == dep_index {
767                  has_bundled_import = true;
768                  process(stylesheets, *dep_source_index, dest, filename)?;
769                }
770
771                *rule = CssRule::Ignored;
772                dep_index += 1;
773              }
774              Dependency::External(url) => {
775                if has_bundled_import {
776                  return Err(Error {
777                    kind: BundleErrorKind::ExternalImportAfterBundledImport,
778                    loc: Some(ErrorLocation {
779                      filename: filename.clone(),
780                      line: import_rule.loc.line,
781                      column: import_rule.loc.column,
782                    }),
783                  });
784                }
785                import_rule.url = url.to_owned().into();
786                let imp = std::mem::replace(rule, CssRule::Ignored);
787                dest.push(imp);
788              }
789            }
790            import_index += 1;
791          }
792          CssRule::LayerStatement(_) => {
793            // @layer rules are the only rules that may appear before an @import.
794            // We must preserve this order to ensure correctness.
795            let layer = std::mem::replace(rule, CssRule::Ignored);
796            dest.push(layer);
797          }
798          CssRule::Ignored => {}
799          _ => break,
800        }
801      }
802
803      // Wrap rules in the appropriate @layer, @media, and @supports rules.
804      let stylesheet = &mut stylesheets[source_index as usize];
805
806      if stylesheet.layer.is_some() {
807        rules = vec![CssRule::LayerBlock(LayerBlockRule {
808          name: stylesheet.layer.take().unwrap(),
809          rules: CssRuleList(rules),
810          loc: stylesheet.loc,
811        })]
812      }
813
814      if !stylesheet.media.media_queries.is_empty() {
815        rules = vec![CssRule::Media(MediaRule {
816          query: std::mem::replace(&mut stylesheet.media, MediaList::new()),
817          rules: CssRuleList(rules),
818          loc: stylesheet.loc,
819        })]
820      }
821
822      if stylesheet.supports.is_some() {
823        rules = vec![CssRule::Supports(SupportsRule {
824          condition: stylesheet.supports.take().unwrap(),
825          rules: CssRuleList(rules),
826          loc: stylesheet.loc,
827        })]
828      }
829
830      dest.extend(rules);
831      Ok(())
832    }
833
834    process(self.stylesheets.get_mut().unwrap(), 0, dest, &self.options.filename)
835  }
836}
837
838fn combine_supports<'a>(
839  a: Option<SupportsCondition<'a>>,
840  b: &Option<SupportsCondition<'a>>,
841) -> Option<SupportsCondition<'a>> {
842  if let Some(mut a) = a {
843    if let Some(b) = b {
844      a.and(b)
845    }
846    Some(a)
847  } else {
848    b.clone()
849  }
850}
851
852fn visit_vars<'a, 'b>(
853  token_list: &'b mut TokenList<'a>,
854) -> impl ParallelIterator<Item = &'b mut DashedIdentReference<'a>> {
855  let mut stack = vec![token_list.0.iter_mut()];
856  std::iter::from_fn(move || {
857    while !stack.is_empty() {
858      let iter = stack.last_mut().unwrap();
859      match iter.next() {
860        Some(TokenOrValue::Var(var)) => {
861          if let Some(fallback) = &mut var.fallback {
862            stack.push(fallback.0.iter_mut());
863          }
864          return Some(&mut var.name);
865        }
866        Some(TokenOrValue::Env(env)) => {
867          if let Some(fallback) = &mut env.fallback {
868            stack.push(fallback.0.iter_mut());
869          }
870          if let EnvironmentVariableName::Custom(name) = &mut env.name {
871            return Some(name);
872          }
873        }
874        Some(TokenOrValue::UnresolvedColor(color)) => match color {
875          UnresolvedColor::RGB { alpha, .. } | UnresolvedColor::HSL { alpha, .. } => {
876            stack.push(alpha.0.iter_mut());
877          }
878          UnresolvedColor::LightDark { light, dark } => {
879            stack.push(light.0.iter_mut());
880            stack.push(dark.0.iter_mut());
881          }
882        },
883        None => {
884          stack.pop();
885        }
886        _ => {}
887      }
888    }
889    None
890  })
891  .par_bridge()
892}
893
894#[cfg(test)]
895mod tests {
896  use super::*;
897  use crate::{
898    css_modules::{self, CssModuleExports, CssModuleReference},
899    parser::ParserFlags,
900    stylesheet::{MinifyOptions, PrinterOptions},
901    targets::{Browsers, Targets},
902  };
903  use indoc::indoc;
904  use std::collections::HashMap;
905
906  #[derive(Clone)]
907  struct TestProvider {
908    map: HashMap<PathBuf, String>,
909  }
910
911  impl SourceProvider for TestProvider {
912    type Error = std::io::Error;
913
914    fn read<'a>(&'a self, file: &Path) -> Result<&'a str, Self::Error> {
915      Ok(self.map.get(file).unwrap())
916    }
917
918    fn resolve(&self, specifier: &str, originating_file: &Path) -> Result<ResolveResult, Self::Error> {
919      if specifier.starts_with("https:") {
920        Ok(ResolveResult::External(specifier.to_owned()))
921      } else {
922        Ok(originating_file.with_file_name(specifier).into())
923      }
924    }
925  }
926
927  /// Stand-in for a user-authored `SourceProvider` with application-specific logic.
928  struct CustomProvider {
929    map: HashMap<PathBuf, String>,
930  }
931
932  impl SourceProvider for CustomProvider {
933    type Error = std::io::Error;
934
935    /// Read files from in-memory map.
936    fn read<'a>(&'a self, file: &Path) -> Result<&'a str, Self::Error> {
937      Ok(self.map.get(file).unwrap())
938    }
939
940    /// Resolve by stripping a `foo:` prefix off any import. Specifiers without
941    /// this prefix fail with an error.
942    fn resolve(&self, specifier: &str, _originating_file: &Path) -> Result<ResolveResult, Self::Error> {
943      if specifier.starts_with("foo:") {
944        Ok(Path::new(&specifier["foo:".len()..]).to_path_buf().into())
945      } else {
946        let err = std::io::Error::new(
947          std::io::ErrorKind::NotFound,
948          format!(
949            "Failed to resolve `{}`, specifier does not start with `foo:`.",
950            &specifier
951          ),
952        );
953
954        Err(err)
955      }
956    }
957  }
958
959  macro_rules! fs(
960    { $($key:literal: $value:expr),* } => {
961      {
962        #[allow(unused_mut)]
963        let mut m = HashMap::new();
964        $(
965          m.insert(PathBuf::from($key), $value.to_owned());
966        )*
967        m
968      }
969    };
970  );
971
972  fn bundle<P: SourceProvider>(fs: P, entry: &str) -> String {
973    let mut bundler = Bundler::<_, _, ()>::new(&fs, None, ParserOptions::default());
974    let stylesheet = bundler.bundle(Path::new(entry)).unwrap();
975    stylesheet.to_css(PrinterOptions::default()).unwrap().code
976  }
977
978  fn bundle_css_module<P: SourceProvider>(
979    fs: P,
980    entry: &str,
981    project_root: Option<&str>,
982  ) -> (String, CssModuleExports) {
983    bundle_css_module_with_pattern(fs, entry, project_root, "[hash]_[local]")
984  }
985
986  fn bundle_css_module_with_pattern<P: SourceProvider>(
987    fs: P,
988    entry: &str,
989    project_root: Option<&str>,
990    pattern: &'static str,
991  ) -> (String, CssModuleExports) {
992    let mut bundler = Bundler::<_, _, ()>::new(
993      &fs,
994      None,
995      ParserOptions {
996        css_modules: Some(css_modules::Config {
997          dashed_idents: true,
998          pattern: css_modules::Pattern::parse(pattern).unwrap(),
999          ..Default::default()
1000        }),
1001        ..ParserOptions::default()
1002      },
1003    );
1004    let mut stylesheet = bundler.bundle(Path::new(entry)).unwrap();
1005    stylesheet.minify(MinifyOptions::default()).unwrap();
1006    let res = stylesheet
1007      .to_css(PrinterOptions {
1008        project_root,
1009        ..PrinterOptions::default()
1010      })
1011      .unwrap();
1012    (res.code, res.exports.unwrap())
1013  }
1014
1015  fn bundle_custom_media<P: SourceProvider>(fs: P, entry: &str) -> String {
1016    let mut bundler = Bundler::<_, _, ()>::new(
1017      &fs,
1018      None,
1019      ParserOptions {
1020        flags: ParserFlags::CUSTOM_MEDIA,
1021        ..ParserOptions::default()
1022      },
1023    );
1024    let mut stylesheet = bundler.bundle(Path::new(entry)).unwrap();
1025    let targets = Targets {
1026      browsers: Some(Browsers {
1027        safari: Some(13 << 16),
1028        ..Browsers::default()
1029      }),
1030      ..Default::default()
1031    };
1032    stylesheet
1033      .minify(MinifyOptions {
1034        targets,
1035        ..MinifyOptions::default()
1036      })
1037      .unwrap();
1038    stylesheet
1039      .to_css(PrinterOptions {
1040        targets,
1041        ..PrinterOptions::default()
1042      })
1043      .unwrap()
1044      .code
1045  }
1046
1047  fn error_test<P: SourceProvider>(
1048    fs: P,
1049    entry: &str,
1050    maybe_cb: Option<Box<dyn FnOnce(BundleErrorKind<P::Error>) -> ()>>,
1051  ) {
1052    let mut bundler = Bundler::<_, _, ()>::new(&fs, None, ParserOptions::default());
1053    let res = bundler.bundle(Path::new(entry));
1054    match res {
1055      Ok(_) => unreachable!(),
1056      Err(e) => {
1057        if let Some(cb) = maybe_cb {
1058          cb(e.kind);
1059        }
1060      }
1061    }
1062  }
1063
1064  fn flatten_exports(exports: CssModuleExports) -> HashMap<String, String> {
1065    let mut res = HashMap::new();
1066    for (name, export) in &exports {
1067      let mut classes = export.name.clone();
1068      for composes in &export.composes {
1069        classes.push(' ');
1070        classes.push_str(match composes {
1071          CssModuleReference::Local { name } => name,
1072          CssModuleReference::Global { name } => name,
1073          _ => unreachable!(),
1074        })
1075      }
1076      res.insert(name.clone(), classes);
1077    }
1078    res
1079  }
1080
1081  #[test]
1082  fn test_bundle() {
1083    let res = bundle(
1084      TestProvider {
1085        map: fs! {
1086          "/a.css": r#"
1087          @import "b.css";
1088          .a { color: red }
1089        "#,
1090          "/b.css": r#"
1091          .b { color: green }
1092        "#
1093        },
1094      },
1095      "/a.css",
1096    );
1097    assert_eq!(
1098      res,
1099      indoc! { r#"
1100      .b {
1101        color: green;
1102      }
1103
1104      .a {
1105        color: red;
1106      }
1107    "#}
1108    );
1109
1110    let res = bundle(
1111      TestProvider {
1112        map: fs! {
1113          "/a.css": r#"
1114          @import "b.css" print;
1115          .a { color: red }
1116        "#,
1117          "/b.css": r#"
1118          .b { color: green }
1119        "#
1120        },
1121      },
1122      "/a.css",
1123    );
1124    assert_eq!(
1125      res,
1126      indoc! { r#"
1127      @media print {
1128        .b {
1129          color: green;
1130        }
1131      }
1132
1133      .a {
1134        color: red;
1135      }
1136    "#}
1137    );
1138
1139    let res = bundle(
1140      TestProvider {
1141        map: fs! {
1142          "/a.css": r#"
1143          @import "b.css" supports(color: green);
1144          .a { color: red }
1145        "#,
1146          "/b.css": r#"
1147          .b { color: green }
1148        "#
1149        },
1150      },
1151      "/a.css",
1152    );
1153    assert_eq!(
1154      res,
1155      indoc! { r#"
1156      @supports (color: green) {
1157        .b {
1158          color: green;
1159        }
1160      }
1161
1162      .a {
1163        color: red;
1164      }
1165    "#}
1166    );
1167
1168    let res = bundle(
1169      TestProvider {
1170        map: fs! {
1171          "/a.css": r#"
1172          @import "b.css" supports(color: green) print;
1173          .a { color: red }
1174        "#,
1175          "/b.css": r#"
1176          .b { color: green }
1177        "#
1178        },
1179      },
1180      "/a.css",
1181    );
1182    assert_eq!(
1183      res,
1184      indoc! { r#"
1185      @supports (color: green) {
1186        @media print {
1187          .b {
1188            color: green;
1189          }
1190        }
1191      }
1192
1193      .a {
1194        color: red;
1195      }
1196    "#}
1197    );
1198
1199    let res = bundle(
1200      TestProvider {
1201        map: fs! {
1202          "/a.css": r#"
1203          @import "b.css" print;
1204          @import "b.css" screen;
1205          .a { color: red }
1206        "#,
1207          "/b.css": r#"
1208          .b { color: green }
1209        "#
1210        },
1211      },
1212      "/a.css",
1213    );
1214    // Parallel imports may merge these commutative conditions in either order.
1215    assert_eq!(
1216      res.replacen("@media screen, print {", "@media print, screen {", 1),
1217      indoc! { r#"
1218      @media print, screen {
1219        .b {
1220          color: green;
1221        }
1222      }
1223
1224      .a {
1225        color: red;
1226      }
1227    "#}
1228    );
1229
1230    let res = bundle(
1231      TestProvider {
1232        map: fs! {
1233          "/a.css": r#"
1234          @import "b.css" supports(color: red);
1235          @import "b.css" supports(foo: bar);
1236          .a { color: red }
1237        "#,
1238          "/b.css": r#"
1239          .b { color: green }
1240        "#
1241        },
1242      },
1243      "/a.css",
1244    );
1245    // Parallel imports may merge these commutative conditions in either order.
1246    assert_eq!(
1247      res.replacen(
1248        "@supports (foo: bar) or (color: red) {",
1249        "@supports (color: red) or (foo: bar) {",
1250        1
1251      ),
1252      indoc! { r#"
1253      @supports (color: red) or (foo: bar) {
1254        .b {
1255          color: green;
1256        }
1257      }
1258
1259      .a {
1260        color: red;
1261      }
1262    "#}
1263    );
1264
1265    let res = bundle(
1266      TestProvider {
1267        map: fs! {
1268          "/a.css": r#"
1269          @import "b.css" print;
1270          .a { color: red }
1271        "#,
1272          "/b.css": r#"
1273          @import "c.css" (color);
1274          .b { color: yellow }
1275        "#,
1276          "/c.css": r#"
1277          .c { color: green }
1278        "#
1279        },
1280      },
1281      "/a.css",
1282    );
1283    assert_eq!(
1284      res,
1285      indoc! { r#"
1286      @media print and (color) {
1287        .c {
1288          color: green;
1289        }
1290      }
1291
1292      @media print {
1293        .b {
1294          color: #ff0;
1295        }
1296      }
1297
1298      .a {
1299        color: red;
1300      }
1301    "#}
1302    );
1303
1304    let res = bundle(
1305      TestProvider {
1306        map: fs! {
1307          "/a.css": r#"
1308          @import "b.css";
1309          .a { color: red }
1310        "#,
1311          "/b.css": r#"
1312          @import "c.css";
1313        "#,
1314          "/c.css": r#"
1315          @import "a.css";
1316          .c { color: green }
1317        "#
1318        },
1319      },
1320      "/a.css",
1321    );
1322    assert_eq!(
1323      res,
1324      indoc! { r#"
1325      .c {
1326        color: green;
1327      }
1328
1329      .a {
1330        color: red;
1331      }
1332    "#}
1333    );
1334
1335    let res = bundle(
1336      TestProvider {
1337        map: fs! {
1338          "/a.css": r#"
1339          @import "b/c.css";
1340          .a { color: red }
1341        "#,
1342          "/b/c.css": r#"
1343          .b { color: green }
1344        "#
1345        },
1346      },
1347      "/a.css",
1348    );
1349    assert_eq!(
1350      res,
1351      indoc! { r#"
1352      .b {
1353        color: green;
1354      }
1355
1356      .a {
1357        color: red;
1358      }
1359    "#}
1360    );
1361
1362    let res = bundle(
1363      TestProvider {
1364        map: fs! {
1365          "/a.css": r#"
1366          @import "./b/c.css";
1367          .a { color: red }
1368        "#,
1369          "/b/c.css": r#"
1370          .b { color: green }
1371        "#
1372        },
1373      },
1374      "/a.css",
1375    );
1376    assert_eq!(
1377      res,
1378      indoc! { r#"
1379      .b {
1380        color: green;
1381      }
1382
1383      .a {
1384        color: red;
1385      }
1386    "#}
1387    );
1388
1389    let res = bundle_custom_media(
1390      TestProvider {
1391        map: fs! {
1392          "/a.css": r#"
1393          @import "media.css";
1394          @import "b.css";
1395          .a { color: red }
1396        "#,
1397          "/media.css": r#"
1398          @custom-media --foo print;
1399        "#,
1400          "/b.css": r#"
1401          @media (--foo) {
1402            .a { color: green }
1403          }
1404        "#
1405        },
1406      },
1407      "/a.css",
1408    );
1409    assert_eq!(
1410      res,
1411      indoc! { r#"
1412      @media print {
1413        .a {
1414          color: green;
1415        }
1416      }
1417
1418      .a {
1419        color: red;
1420      }
1421    "#}
1422    );
1423
1424    let res = bundle(
1425      TestProvider {
1426        map: fs! {
1427          "/a.css": r#"
1428          @import "b.css" layer(foo);
1429          .a { color: red }
1430        "#,
1431          "/b.css": r#"
1432          .b { color: green }
1433        "#
1434        },
1435      },
1436      "/a.css",
1437    );
1438    assert_eq!(
1439      res,
1440      indoc! { r#"
1441      @layer foo {
1442        .b {
1443          color: green;
1444        }
1445      }
1446
1447      .a {
1448        color: red;
1449      }
1450    "#}
1451    );
1452
1453    let res = bundle(
1454      TestProvider {
1455        map: fs! {
1456          "/a.css": r#"
1457          @import "b.css" layer;
1458          .a { color: red }
1459        "#,
1460          "/b.css": r#"
1461          .b { color: green }
1462        "#
1463        },
1464      },
1465      "/a.css",
1466    );
1467    assert_eq!(
1468      res,
1469      indoc! { r#"
1470      @layer {
1471        .b {
1472          color: green;
1473        }
1474      }
1475
1476      .a {
1477        color: red;
1478      }
1479    "#}
1480    );
1481
1482    let res = bundle(
1483      TestProvider {
1484        map: fs! {
1485          "/a.css": r#"
1486          @import "b.css" layer(foo);
1487          .a { color: red }
1488        "#,
1489          "/b.css": r#"
1490          @import "c.css" layer(bar);
1491          .b { color: green }
1492        "#,
1493          "/c.css": r#"
1494          .c { color: green }
1495        "#
1496        },
1497      },
1498      "/a.css",
1499    );
1500    assert_eq!(
1501      res,
1502      indoc! { r#"
1503      @layer foo.bar {
1504        .c {
1505          color: green;
1506        }
1507      }
1508
1509      @layer foo {
1510        .b {
1511          color: green;
1512        }
1513      }
1514
1515      .a {
1516        color: red;
1517      }
1518    "#}
1519    );
1520
1521    let res = bundle(
1522      TestProvider {
1523        map: fs! {
1524          "/a.css": r#"
1525          @import "b.css" layer(foo);
1526          @import "b.css" layer(foo);
1527        "#,
1528          "/b.css": r#"
1529          .b { color: green }
1530        "#
1531        },
1532      },
1533      "/a.css",
1534    );
1535    assert_eq!(
1536      res,
1537      indoc! { r#"
1538      @layer foo {
1539        .b {
1540          color: green;
1541        }
1542      }
1543    "#}
1544    );
1545
1546    let res = bundle(
1547      TestProvider {
1548        map: fs! {
1549          "/a.css": r#"
1550          @layer bar, foo;
1551          @import "b.css" layer(foo);
1552
1553          @layer bar {
1554            div {
1555              background: red;
1556            }
1557          }
1558        "#,
1559          "/b.css": r#"
1560          @layer qux, baz;
1561          @import "c.css" layer(baz);
1562
1563          @layer qux {
1564            div {
1565              background: green;
1566            }
1567          }
1568        "#,
1569          "/c.css": r#"
1570          div {
1571            background: yellow;
1572          }
1573        "#
1574        },
1575      },
1576      "/a.css",
1577    );
1578    assert_eq!(
1579      res,
1580      indoc! { r#"
1581      @layer bar, foo;
1582      @layer foo.qux, foo.baz;
1583
1584      @layer foo.baz {
1585        div {
1586          background: #ff0;
1587        }
1588      }
1589
1590      @layer foo {
1591        @layer qux {
1592          div {
1593            background: green;
1594          }
1595        }
1596      }
1597
1598      @layer bar {
1599        div {
1600          background: red;
1601        }
1602      }
1603    "#}
1604    );
1605
1606    // Layer order depends on @import conditions.
1607    let res = bundle(
1608      TestProvider {
1609        map: fs! {
1610          "/a.css": r#"
1611          @import "b.css" layer(bar) (min-width: 1000px);
1612
1613          @layer baz {
1614            #box { background: purple }
1615          }
1616
1617          @layer bar {
1618            #box { background: yellow }
1619          }
1620        "#,
1621          "/b.css": r#"
1622          #box { background: green }
1623        "#
1624        },
1625      },
1626      "/a.css",
1627    );
1628    assert_eq!(
1629      res,
1630      indoc! { r#"
1631      @media (width >= 1000px) {
1632        @layer bar {
1633          #box {
1634            background: green;
1635          }
1636        }
1637      }
1638
1639      @layer baz {
1640        #box {
1641          background: purple;
1642        }
1643      }
1644
1645      @layer bar {
1646        #box {
1647          background: #ff0;
1648        }
1649      }
1650    "#}
1651    );
1652
1653    let res = bundle(
1654      TestProvider {
1655        map: fs! {
1656          "/a.css": r#"
1657          @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
1658          @import './b.css';
1659        "#,
1660          "/b.css": r#"
1661          .b { color: green }
1662        "#
1663        },
1664      },
1665      "/a.css",
1666    );
1667    assert_eq!(
1668      res,
1669      indoc! { r#"
1670        @import "https://fonts.googleapis.com/css2?family=Roboto&display=swap";
1671
1672        .b {
1673          color: green;
1674        }
1675    "#}
1676    );
1677
1678    error_test(
1679      TestProvider {
1680        map: fs! {
1681          "/a.css": r#"
1682          @import './b.css';
1683          @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
1684        "#,
1685          "/b.css": r#"
1686          .b { color: green }
1687        "#
1688        },
1689      },
1690      "/a.css",
1691      Some(Box::new(|err| {
1692        assert!(matches!(err, BundleErrorKind::ExternalImportAfterBundledImport));
1693      })),
1694    );
1695
1696    error_test(
1697      TestProvider {
1698        map: fs! {
1699          "/a.css": r#"
1700          @import "b.css" layer(foo);
1701          @import "b.css" layer(bar);
1702        "#,
1703          "/b.css": r#"
1704          .b { color: red }
1705        "#
1706        },
1707      },
1708      "/a.css",
1709      Some(Box::new(|err| {
1710        assert!(matches!(err, BundleErrorKind::UnsupportedLayerCombination));
1711      })),
1712    );
1713
1714    error_test(
1715      TestProvider {
1716        map: fs! {
1717          "/a.css": r#"
1718          @import "b.css" layer;
1719          @import "b.css" layer;
1720        "#,
1721          "/b.css": r#"
1722          .b { color: red }
1723        "#
1724        },
1725      },
1726      "/a.css",
1727      Some(Box::new(|err| {
1728        assert!(matches!(err, BundleErrorKind::UnsupportedLayerCombination));
1729      })),
1730    );
1731
1732    error_test(
1733      TestProvider {
1734        map: fs! {
1735          "/a.css": r#"
1736          @import "b.css" layer;
1737          .a { color: red }
1738        "#,
1739          "/b.css": r#"
1740          @import "c.css" layer;
1741          .b { color: green }
1742        "#,
1743          "/c.css": r#"
1744          .c { color: green }
1745        "#
1746        },
1747      },
1748      "/a.css",
1749      Some(Box::new(|err| {
1750        assert!(matches!(err, BundleErrorKind::UnsupportedLayerCombination));
1751      })),
1752    );
1753
1754    error_test(
1755      TestProvider {
1756        map: fs! {
1757          "/a.css": r#"
1758          @import "b.css" layer;
1759          .a { color: red }
1760        "#,
1761          "/b.css": r#"
1762          @import "c.css" layer(foo);
1763          .b { color: green }
1764        "#,
1765          "/c.css": r#"
1766          .c { color: green }
1767        "#
1768        },
1769      },
1770      "/a.css",
1771      Some(Box::new(|err| {
1772        assert!(matches!(err, BundleErrorKind::UnsupportedLayerCombination));
1773      })),
1774    );
1775
1776    let res = bundle(
1777      TestProvider {
1778        map: fs! {
1779          "/index.css": r#"
1780          @import "a.css";
1781          @import "b.css";
1782        "#,
1783          "/a.css": r#"
1784          @import "./c.css";
1785          body { background: red; }
1786        "#,
1787          "/b.css": r#"
1788          @import "./c.css";
1789          body { color: red; }
1790        "#,
1791          "/c.css": r#"
1792          body {
1793            background: white;
1794            color: black;
1795          }
1796        "#
1797        },
1798      },
1799      "/index.css",
1800    );
1801    assert_eq!(
1802      res,
1803      indoc! { r#"
1804      body {
1805        background: red;
1806      }
1807
1808      body {
1809        background: #fff;
1810        color: #000;
1811      }
1812
1813      body {
1814        color: red;
1815      }
1816    "#}
1817    );
1818
1819    let res = bundle(
1820      TestProvider {
1821        map: fs! {
1822          "/index.css": r#"
1823          @import "a.css";
1824          @import "b.css";
1825          @import "a.css";
1826        "#,
1827          "/a.css": r#"
1828          body { background: green; }
1829        "#,
1830          "/b.css": r#"
1831          body { background: red; }
1832        "#
1833        },
1834      },
1835      "/index.css",
1836    );
1837    assert_eq!(
1838      res,
1839      indoc! { r#"
1840      body {
1841        background: red;
1842      }
1843
1844      body {
1845        background: green;
1846      }
1847    "#}
1848    );
1849
1850    let res = bundle(
1851      CustomProvider {
1852        map: fs! {
1853          "/a.css": r#"
1854            @import "foo:/b.css";
1855            .a { color: red; }
1856          "#,
1857          "/b.css": ".b { color: green; }"
1858        },
1859      },
1860      "/a.css",
1861    );
1862    assert_eq!(
1863      res,
1864      indoc! { r#"
1865        .b {
1866          color: green;
1867        }
1868
1869        .a {
1870          color: red;
1871        }
1872      "# }
1873    );
1874
1875    error_test(
1876      CustomProvider {
1877        map: fs! {
1878          "/a.css": r#"
1879            /* Forgot to prefix with `foo:`. */
1880            @import "/b.css";
1881            .a { color: red; }
1882          "#,
1883          "/b.css": ".b { color: green; }"
1884        },
1885      },
1886      "/a.css",
1887      Some(Box::new(|err| {
1888        let kind = match err {
1889          BundleErrorKind::ResolverError(ref error) => error.kind(),
1890          _ => unreachable!(),
1891        };
1892        assert!(matches!(kind, std::io::ErrorKind::NotFound));
1893        assert!(err
1894          .to_string()
1895          .contains("Failed to resolve `/b.css`, specifier does not start with `foo:`."));
1896      })),
1897    );
1898
1899    // let res = bundle(fs! {
1900    //   "/a.css": r#"
1901    //     @import "b.css" supports(color: red) (color);
1902    //     @import "b.css" supports(foo: bar) (orientation: horizontal);
1903    //     .a { color: red }
1904    //   "#,
1905    //   "/b.css": r#"
1906    //     .b { color: green }
1907    //   "#
1908    // }, "/a.css");
1909
1910    // let res = bundle(fs! {
1911    //   "/a.css": r#"
1912    //     @import "b.css" not print;
1913    //     .a { color: red }
1914    //   "#,
1915    //   "/b.css": r#"
1916    //     @import "c.css" not screen;
1917    //     .b { color: green }
1918    //   "#,
1919    //   "/c.css": r#"
1920    //     .c { color: yellow }
1921    //   "#
1922    // }, "/a.css");
1923  }
1924
1925  #[test]
1926  fn test_css_module() {
1927    macro_rules! map {
1928      { $($key:expr => $val:expr),* } => {
1929        HashMap::from([
1930          $(($key.to_owned(), $val.to_owned()),)*
1931        ])
1932      };
1933    }
1934
1935    let (code, exports) = bundle_css_module(
1936      TestProvider {
1937        map: fs! {
1938          "/a.css": r#"
1939          @import "b.css";
1940          .a { color: red }
1941        "#,
1942          "/b.css": r#"
1943          .a { color: green }
1944        "#
1945        },
1946      },
1947      "/a.css",
1948      None,
1949    );
1950    assert_eq!(
1951      code,
1952      indoc! { r#"
1953      ._9z6RGq_a {
1954        color: green;
1955      }
1956
1957      ._6lixEq_a {
1958        color: red;
1959      }
1960    "#}
1961    );
1962    assert_eq!(
1963      flatten_exports(exports),
1964      map! {
1965        "a" => "_6lixEq_a"
1966      }
1967    );
1968
1969    let (code, exports) = bundle_css_module(
1970      TestProvider {
1971        map: fs! {
1972          "/a.css": r#"
1973          .a { composes: x from './b.css'; color: red; }
1974          .b { color: yellow }
1975        "#,
1976          "/b.css": r#"
1977          .x { composes: y; background: green }
1978          .y { font: Helvetica }
1979        "#
1980        },
1981      },
1982      "/a.css",
1983      None,
1984    );
1985    assert_eq!(
1986      code,
1987      indoc! { r#"
1988      ._8Cs9ZG_x {
1989        background: green;
1990      }
1991
1992      ._8Cs9ZG_y {
1993        font: Helvetica;
1994      }
1995
1996      ._6lixEq_a {
1997        color: red;
1998      }
1999
2000      ._6lixEq_b {
2001        color: #ff0;
2002      }
2003    "#}
2004    );
2005    assert_eq!(
2006      flatten_exports(exports),
2007      map! {
2008        "a" => "_6lixEq_a _8Cs9ZG_x _8Cs9ZG_y",
2009        "b" => "_6lixEq_b"
2010      }
2011    );
2012
2013    let (code, exports) = bundle_css_module(
2014      TestProvider {
2015        map: fs! {
2016          "/a.css": r#"
2017          .a { composes: x from './b.css'; background: red; }
2018        "#,
2019          "/b.css": r#"
2020          .a { background: red }
2021        "#
2022        },
2023      },
2024      "/a.css",
2025      None,
2026    );
2027    assert_eq!(
2028      code,
2029      indoc! { r#"
2030      ._8Cs9ZG_a {
2031        background: red;
2032      }
2033
2034      ._6lixEq_a {
2035        background: red;
2036      }
2037    "#}
2038    );
2039    assert_eq!(
2040      flatten_exports(exports),
2041      map! {
2042        "a" => "_6lixEq_a"
2043      }
2044    );
2045
2046    let (code, exports) = bundle_css_module(
2047      TestProvider {
2048        map: fs! {
2049          "/a.css": r#"
2050          .a {
2051            background: var(--bg from "./b.css", var(--fallback from "./b.css"));
2052            color: rgb(255 255 255 / var(--opacity from "./b.css"));
2053            width: env(--env, var(--env-fallback from "./env.css"));
2054          }
2055        "#,
2056          "/b.css": r#"
2057          .b {
2058            --bg: red;
2059            --fallback: yellow;
2060            --opacity: 0.5;
2061          }
2062        "#,
2063          "/env.css": r#"
2064          .env {
2065            --env-fallback: 20px;
2066          }
2067        "#
2068        },
2069      },
2070      "/a.css",
2071      None,
2072    );
2073    assert_eq!(
2074      code,
2075      indoc! { r#"
2076      ._8Cs9ZG_b {
2077        --_8Cs9ZG_bg: red;
2078        --_8Cs9ZG_fallback: yellow;
2079        --_8Cs9ZG_opacity: .5;
2080      }
2081
2082      .GbJUva_env {
2083        --GbJUva_env-fallback: 20px;
2084      }
2085
2086      ._6lixEq_a {
2087        background: var(--_8Cs9ZG_bg, var(--_8Cs9ZG_fallback));
2088        color: rgb(255 255 255 / var(--_8Cs9ZG_opacity));
2089        width: env(--_6lixEq_env, var(--GbJUva_env-fallback));
2090      }
2091    "#}
2092    );
2093    assert_eq!(
2094      flatten_exports(exports),
2095      map! {
2096        "a" => "_6lixEq_a",
2097        "--env" => "--_6lixEq_env"
2098      }
2099    );
2100
2101    // Hashes are stable between project roots.
2102    let expected = indoc! { r#"
2103    .dyGcAa_b {
2104      background: #ff0;
2105    }
2106
2107    .CK9avG_a {
2108      background: #fff;
2109    }
2110  "#};
2111
2112    let (code, _) = bundle_css_module(
2113      TestProvider {
2114        map: fs! {
2115          "/foo/bar/a.css": r#"
2116        @import "b.css";
2117        .a {
2118          background: white;
2119        }
2120      "#,
2121          "/foo/bar/b.css": r#"
2122        .b {
2123          background: yellow;
2124        }
2125      "#
2126        },
2127      },
2128      "/foo/bar/a.css",
2129      Some("/foo/bar"),
2130    );
2131    assert_eq!(code, expected);
2132
2133    let (code, _) = bundle_css_module(
2134      TestProvider {
2135        map: fs! {
2136          "/x/y/z/a.css": r#"
2137      @import "b.css";
2138      .a {
2139        background: white;
2140      }
2141    "#,
2142          "/x/y/z/b.css": r#"
2143      .b {
2144        background: yellow;
2145      }
2146    "#
2147        },
2148      },
2149      "/x/y/z/a.css",
2150      Some("/x/y/z"),
2151    );
2152    assert_eq!(code, expected);
2153
2154    let (code, _) = bundle_css_module_with_pattern(
2155      TestProvider {
2156        map: fs! {
2157          "/a.css": r#"
2158          @import "b.css";
2159          .a { color: red }
2160        "#,
2161          "/b.css": r#"
2162          .a { color: green }
2163        "#
2164        },
2165      },
2166      "/a.css",
2167      None,
2168      "[content-hash]-[local]",
2169    );
2170    assert_eq!(
2171      code,
2172      indoc! { r#"
2173      .do5n2W-a {
2174        color: green;
2175      }
2176
2177      .pP97eq-a {
2178        color: red;
2179      }
2180    "#}
2181    );
2182  }
2183
2184  #[test]
2185  #[cfg(feature = "sourcemap")]
2186  fn test_source_map() {
2187    let source = r#".imported {
2188      content: "yay, file support!";
2189    }
2190
2191    .selector {
2192      margin: 1em;
2193      background-color: #f60;
2194    }
2195
2196    .selector .nested {
2197      margin: 0.5em;
2198    }
2199
2200    /*# sourceMappingURL=data:application/json;base64,ewoJInZlcnNpb24iOiAzLAoJInNvdXJjZVJvb3QiOiAicm9vdCIsCgkiZmlsZSI6ICJzdGRvdXQiLAoJInNvdXJjZXMiOiBbCgkJInN0ZGluIiwKCQkic2Fzcy9fdmFyaWFibGVzLnNjc3MiLAoJCSJzYXNzL19kZW1vLnNjc3MiCgldLAoJInNvdXJjZXNDb250ZW50IjogWwoJCSJAaW1wb3J0IFwiX3ZhcmlhYmxlc1wiO1xuQGltcG9ydCBcIl9kZW1vXCI7XG5cbi5zZWxlY3RvciB7XG4gIG1hcmdpbjogJHNpemU7XG4gIGJhY2tncm91bmQtY29sb3I6ICRicmFuZENvbG9yO1xuXG4gIC5uZXN0ZWQge1xuICAgIG1hcmdpbjogJHNpemUgLyAyO1xuICB9XG59IiwKCQkiJGJyYW5kQ29sb3I6ICNmNjA7XG4kc2l6ZTogMWVtOyIsCgkJIi5pbXBvcnRlZCB7XG4gIGNvbnRlbnQ6IFwieWF5LCBmaWxlIHN1cHBvcnQhXCI7XG59IgoJXSwKCSJtYXBwaW5ncyI6ICJBRUFBLFNBQVMsQ0FBQztFQUNSLE9BQU8sRUFBRSxvQkFBcUI7Q0FDL0I7O0FGQ0QsU0FBUyxDQUFDO0VBQ1IsTUFBTSxFQ0hELEdBQUc7RURJUixnQkFBZ0IsRUNMTCxJQUFJO0NEVWhCOztBQVBELFNBQVMsQ0FJUCxPQUFPLENBQUM7RUFDTixNQUFNLEVDUEgsS0FBRztDRFFQIiwKCSJuYW1lcyI6IFtdCn0= */"#;
2201
2202    let fs = TestProvider {
2203      map: fs! {
2204        "/a.css": r#"
2205        @import "/b.css";
2206        .a { color: red; }
2207      "#,
2208        "/b.css": source
2209      },
2210    };
2211
2212    let mut sm = parcel_sourcemap::SourceMap::new("/");
2213    let mut bundler = Bundler::new(&fs, Some(&mut sm), ParserOptions::default());
2214    let mut stylesheet = bundler.bundle(Path::new("/a.css")).unwrap();
2215    stylesheet.minify(MinifyOptions::default()).unwrap();
2216    stylesheet
2217      .to_css(PrinterOptions {
2218        minify: true,
2219        ..PrinterOptions::default().with_source_map(&mut sm)
2220      })
2221      .unwrap();
2222    let map = sm.to_json(None).unwrap();
2223    assert_eq!(
2224      map,
2225      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":[]}"#
2226    );
2227  }
2228
2229  #[test]
2230  fn test_license_comments() {
2231    let res = bundle(
2232      TestProvider {
2233        map: fs! {
2234          "/a.css": r#"
2235          /*! Copyright 2023 Someone awesome */
2236          @import "b.css";
2237          .a { color: red }
2238        "#,
2239          "/b.css": r#"
2240          /*! Copyright 2023 Someone else */
2241          .b { color: green }
2242        "#
2243        },
2244      },
2245      "/a.css",
2246    );
2247    assert_eq!(
2248      res,
2249      indoc! { r#"
2250      /*! Copyright 2023 Someone awesome */
2251      /*! Copyright 2023 Someone else */
2252      .b {
2253        color: green;
2254      }
2255
2256      .a {
2257        color: red;
2258      }
2259    "#}
2260    );
2261  }
2262}