1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
use parcel_sourcemap::SourceMap;
use serde::Serialize;
use crate::{rules::{Location, layer::{LayerBlockRule, LayerName}}, error::ErrorLocation};
use std::{fs, path::{Path, PathBuf}, sync::Mutex, collections::HashSet};
use rayon::prelude::*;
use dashmap::DashMap;
use crate::{
  stylesheet::{StyleSheet, ParserOptions},
  rules::{CssRule, CssRuleList,
    media::MediaRule,
    supports::{SupportsRule, SupportsCondition},
    import::ImportRule
  },
  media_query::MediaList,
  error::{Error, ParserError}
};

pub struct Bundler<'a, 's, P> {
  source_map: Option<Mutex<&'s mut SourceMap>>,
  fs: &'a P,
  source_indexes: DashMap<PathBuf, u32>,
  stylesheets: Mutex<Vec<BundleStyleSheet<'a>>>,
  options: ParserOptions
}

#[derive(Debug)]
struct BundleStyleSheet<'i> {
  stylesheet: Option<StyleSheet<'i>>,
  dependencies: Vec<u32>,
  parent_source_index: u32,
  parent_dep_index: u32,
  layer: Option<Option<LayerName<'i>>>,
  supports: Option<SupportsCondition<'i>>,
  media: MediaList<'i>,
  loc: Location
}

pub trait SourceProvider: Send + Sync {
  fn read<'a>(&'a self, file: &Path) -> std::io::Result<&'a str>;
}

pub struct FileProvider {
  inputs: Mutex<Vec<*mut String>>
}

impl FileProvider {
  pub fn new() -> FileProvider {
    FileProvider {
      inputs: Mutex::new(Vec::new()),
    }
  }
}

unsafe impl Sync for FileProvider {}
unsafe impl Send for FileProvider {}

impl SourceProvider for FileProvider {
  fn read<'a>(&'a self, file: &Path) -> std::io::Result<&'a str> {
    let source = fs::read_to_string(file)?;
    let ptr = Box::into_raw(Box::new(source));
    self.inputs.lock().unwrap().push(ptr);
    // SAFETY: this is safe because the pointer is not dropped
    // until the FileProvider is, and we never remove from the
    // list of pointers stored in the vector.
    Ok(unsafe { &*ptr })
  }
}

impl Drop for FileProvider {
  fn drop(&mut self) {
    for ptr in self.inputs.lock().unwrap().iter() {
      std::mem::drop(unsafe { Box::from_raw(*ptr) })
    }
  }
}

#[derive(Debug, Serialize)]
pub enum BundleErrorKind<'i> {
  IOError(#[serde(skip)] std::io::Error),
  ParserError(ParserError<'i>),
  UnsupportedImportCondition,
  UnsupportedMediaBooleanLogic,
  UnsupportedLayerCombination
}

impl<'i> From<Error<ParserError<'i>>> for Error<BundleErrorKind<'i>> {
  fn from(err: Error<ParserError<'i>>) -> Self {
    Error {
      kind: BundleErrorKind::ParserError(err.kind),
      loc: err.loc
    }
  }
}

impl<'i> BundleErrorKind<'i> {
  pub fn reason(&self) -> String {
    match self {
      BundleErrorKind::IOError(e) => e.to_string(),
      BundleErrorKind::ParserError(e) => e.reason(),
      BundleErrorKind::UnsupportedImportCondition => "Unsupported import condition".into(),
      BundleErrorKind::UnsupportedMediaBooleanLogic => "Unsupported boolean logic in @import media query".into(),
      BundleErrorKind::UnsupportedLayerCombination => "Unsupported layer combination in @import".into()
    }
  }
}

impl<'a, 's, P: SourceProvider> Bundler<'a, 's, P> {
  pub fn new(fs: &'a P, source_map: Option<&'s mut SourceMap>, options: ParserOptions) -> Self {
    Bundler {
      source_map: source_map.map(Mutex::new),
      fs,
      source_indexes: DashMap::new(),
      stylesheets: Mutex::new(Vec::new()),
      options
    }
  }

  pub fn bundle<'e>(&mut self, entry: &'e Path) -> Result<StyleSheet<'a>, Error<BundleErrorKind<'a>>> {
    // Phase 1: load and parse all files. This is done in parallel.
    self.load_file(&entry, ImportRule {
      url: "".into(),
      layer: None,
      supports: None,
      media: MediaList::new(),
      loc: Location {
        source_index: 0,
        line: 1,
        column: 0
      }
    })?;

    // Phase 2: determine the order that the files should be concatenated.
    self.order();

    // Phase 3: concatenate.
    let mut rules: Vec<CssRule<'a>> = Vec::new();
    self.inline(&mut rules);

    let sources = self.stylesheets.get_mut()
      .unwrap()
      .iter()
      .flat_map(|s| s.stylesheet.as_ref().unwrap().sources.iter().cloned())
      .collect();

    Ok(StyleSheet::new(
      sources,
      CssRuleList(rules), 
      self.options.clone()
    ))
  }

  fn find_filename(&self, source_index: u32) -> String {
    // This function is only used for error handling, so it's ok if this is a bit slow.
    let entry = self.source_indexes.iter()
      .find(|x| *x.value() == source_index)
      .unwrap();
    entry.key().to_str().unwrap().into()
  }

  fn load_file(&self, file: &Path, rule: ImportRule<'a>) -> Result<u32, Error<BundleErrorKind<'a>>> {
    // Check if we already loaded this file.
    let mut stylesheets = self.stylesheets.lock().unwrap();
    let source_index = match self.source_indexes.get(file) {
      Some(source_index) => {
        // If we already loaded this file, combine the media queries and supports conditions
        // from this import rule with the existing ones using a logical or operator.
        let entry = &mut stylesheets[*source_index as usize];

        // We cannot combine a media query and a supports query from different @import rules.
        // e.g. @import "a.css" print; @import "a.css" supports(color: red);
        // This would require duplicating the actual rules in the file.
        if (!rule.media.media_queries.is_empty() && !entry.supports.is_none()) || 
          (!entry.media.media_queries.is_empty() && !rule.supports.is_none()) {
          return Err(Error {
            kind: BundleErrorKind::UnsupportedImportCondition,
            loc: Some(ErrorLocation::from(
              rule.loc, 
              self.find_filename(rule.loc.source_index)
            ))
          })
        }

        if rule.media.media_queries.is_empty() {
          entry.media.media_queries.clear();
        } else if !entry.media.media_queries.is_empty() {
          entry.media.or(&rule.media);
        }

        if let Some(supports) = rule.supports {
          if let Some(existing_supports) = &mut entry.supports {
            existing_supports.or(&supports)
          }
        } else {
          entry.supports = None;
        }

        if let Some(layer) = &rule.layer {
          if let Some(existing_layer) = &entry.layer {
            // We can't OR layer names without duplicating all of the nested rules, so error for now.
            if layer != existing_layer || (layer.is_none() && existing_layer.is_none()) {
              return Err(Error {
                kind: BundleErrorKind::UnsupportedLayerCombination,
                loc: Some(ErrorLocation::from(
                  rule.loc,
                  self.find_filename(rule.loc.source_index)
                ))
              })
            }
          } else {
            entry.layer = rule.layer;
          }
        }
        
        return Ok(*source_index);
      }
      None => {
        let source_index = stylesheets.len() as u32;
        self.source_indexes.insert(file.to_owned(), source_index);

        stylesheets.push(BundleStyleSheet {
          stylesheet: None,
          layer: rule.layer.clone(),
          media: rule.media.clone(),
          supports: rule.supports.clone(),
          loc: rule.loc.clone(),
          dependencies: Vec::new(),
          parent_source_index: 0,
          parent_dep_index: 0
        });

        source_index
      }
    };

    drop(stylesheets); // ensure we aren't holding the lock anymore
    
    let code = self.fs.read(file).map_err(|e| Error {
      kind: BundleErrorKind::IOError(e),
      loc: Some(ErrorLocation::from(
        rule.loc,
        self.find_filename(rule.loc.source_index)
      ))
    })?;

    let mut opts = self.options.clone();
    opts.source_index = source_index;

    let filename = file.to_str().unwrap();
    if let Some(source_map) = &self.source_map {
      let mut source_map = source_map.lock().unwrap();
      let source_index = source_map.add_source(filename);
      let _ = source_map.set_source_content(source_index as usize, code);
    }

    let mut stylesheet = StyleSheet::parse(
      filename.into(),
      code,
      opts,
    )?;

    // Collect and load dependencies for this stylesheet in parallel.
    let dependencies: Result<Vec<u32>, _> = stylesheet.rules.0.par_iter_mut()
      .filter_map(|r| {
        // Prepend parent layer name to @layer statements.
        if let CssRule::LayerStatement(layer) = r {
          if let Some(Some(parent_layer)) = &rule.layer {
            for name in &mut layer.names {
              name.0.insert_many(0, parent_layer.0.iter().cloned())
            }
          }
        }

        if let CssRule::Import(import) = r {
          let path = file.with_file_name(&*import.url);

          // Combine media queries and supports conditions from parent 
          // stylesheet with @import rule using a logical and operator.
          let mut media = rule.media.clone();
          let result = media.and(&import.media).map_err(|_| Error {
            kind: BundleErrorKind::UnsupportedMediaBooleanLogic,
            loc: Some(ErrorLocation::from(
              import.loc,
              self.find_filename(import.loc.source_index)
            ))
          });

          if let Err(e) = result {
            return Some(Err(e))
          }

          let layer = if (rule.layer == Some(None) && import.layer.is_some()) || (import.layer == Some(None) && rule.layer.is_some()) {
            // Cannot combine anonymous layers
            return Some(Err(Error {
              kind: BundleErrorKind::UnsupportedLayerCombination,
              loc: Some(ErrorLocation::from(
                import.loc, 
                self.find_filename(import.loc.source_index)
              ))
            }))
          } else if let Some(Some(a)) = &rule.layer {
            if let Some(Some(b)) = &import.layer {
              let mut name = a.clone();
              name.0.extend(b.0.iter().cloned());
              Some(Some(name))
            } else {
              Some(Some(a.clone()))
            }
          } else {
            import.layer.clone()
          };
          
          let result = self.load_file(&path, ImportRule {
            layer,
            media,
            supports: combine_supports(rule.supports.clone(), &import.supports),
            url: "".into(),
            loc: import.loc
          });

          Some(result)
        } else {
          None
        }
      })
      .collect();
      
    let entry = &mut self.stylesheets.lock().unwrap()[source_index as usize];
    entry.stylesheet = Some(stylesheet);
    entry.dependencies = dependencies?;

    Ok(source_index)
  }

  fn order(&mut self) {
    process(
      self.stylesheets.get_mut().unwrap(),
      0, 
      &mut HashSet::new()
    );

    fn process(stylesheets: &mut Vec<BundleStyleSheet<'_>>, source_index: u32, visited: &mut HashSet<u32>) {
      if visited.contains(&source_index) {
        return
      }

      visited.insert(source_index);

      for dep_index in 0..stylesheets[source_index as usize].dependencies.len() {
        let dep_source_index = stylesheets[source_index as usize].dependencies[dep_index];
        let mut resolved = &mut stylesheets[dep_source_index as usize];

        // In browsers, every instance of an @import is evaluated, so we preserve the last.
        resolved.parent_dep_index = dep_index as u32;
        resolved.parent_source_index = source_index;

        process(stylesheets, dep_source_index, visited);
      }
    }
  }

  fn inline(&mut self, dest: &mut Vec<CssRule<'a>>) {
    process(
      self.stylesheets.get_mut().unwrap(),
      0,
      dest
    );

    fn process<'a>(stylesheets: &mut Vec<BundleStyleSheet<'a>>, source_index: u32, dest: &mut Vec<CssRule<'a>>) {
      let stylesheet = &mut stylesheets[source_index as usize];
      let mut rules = std::mem::take(&mut stylesheet.stylesheet.as_mut().unwrap().rules.0);

      let mut dep_index = 0;
      for rule in &mut rules {
        match rule {
          CssRule::Import(_) => {
            let dep_source_index = stylesheets[source_index as usize].dependencies[dep_index as usize];
            let resolved = &stylesheets[dep_source_index as usize];

            // Include the dependency if this is the last instance as computed earlier.
            if resolved.parent_source_index == source_index && resolved.parent_dep_index == dep_index {
              process(stylesheets, dep_source_index, dest);
            }

            *rule = CssRule::Ignored;
            dep_index += 1;
          }
          CssRule::LayerStatement(_) => {
            // @layer rules are the only rules that may appear before an @import.
            // We must preserve this order to ensure correctness.
            let layer = std::mem::replace(rule, CssRule::Ignored);
            dest.push(layer);
          }
          CssRule::Ignored => {}
          _ => break
        }
      }

      // Wrap rules in the appropriate @media and @supports rules.
      let stylesheet = &mut stylesheets[source_index as usize];
      if !stylesheet.media.media_queries.is_empty() {
        rules = vec![
          CssRule::Media(MediaRule {
            query: std::mem::replace(&mut stylesheet.media, MediaList::new()),
            rules: CssRuleList(rules),
            loc: stylesheet.loc
          })
        ]
      }

      if stylesheet.supports.is_some() {
        rules = vec![
          CssRule::Supports(SupportsRule {
            condition: stylesheet.supports.take().unwrap(),
            rules: CssRuleList(rules),
            loc: stylesheet.loc
          })
        ]
      }

      if stylesheet.layer.is_some() {
        rules = vec![
          CssRule::LayerBlock(LayerBlockRule {
            name: stylesheet.layer.take().unwrap(),
            rules: CssRuleList(rules),
            loc: stylesheet.loc
          })
        ]
      }

      dest.extend(rules);
    }
  }
}

fn combine_supports<'a>(a: Option<SupportsCondition<'a>>, b: &Option<SupportsCondition<'a>>) -> Option<SupportsCondition<'a>> {
  if let Some(mut a) = a {
    if let Some(b) = b {
      a.and(b)
    }
    Some(a)
  } else {
    b.clone()
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::{stylesheet::{PrinterOptions, MinifyOptions}, targets::Browsers};
  use indoc::indoc;
  use std::collections::HashMap;

  struct TestProvider {
    map: HashMap<PathBuf, String>
  }

  impl SourceProvider for TestProvider {
    fn read<'a>(&'a self, file: &Path) -> std::io::Result<&'a str> {
      Ok(self.map.get(file).unwrap())
    }
  }

  macro_rules! fs(
    { $($key:literal: $value:expr),* } => {
      {
        #[allow(unused_mut)]
        let mut m = HashMap::new();
        $(
          m.insert(PathBuf::from($key), $value.to_owned());
        )*
        TestProvider {
          map: m
        }
      }
    };
  );

  fn bundle(fs: TestProvider, entry: &str) -> String {
    let mut bundler = Bundler::new(&fs, None, ParserOptions::default());
    let stylesheet = bundler.bundle(Path::new(entry)).unwrap();
    stylesheet.to_css(PrinterOptions::default()).unwrap().code
  }

  fn bundle_css_module(fs: TestProvider, entry: &str) -> String {
    let mut bundler = Bundler::new(&fs, None, ParserOptions { css_modules: true, ..ParserOptions::default() });
    let stylesheet = bundler.bundle(Path::new(entry)).unwrap();
    stylesheet.to_css(PrinterOptions::default()).unwrap().code
  }

  fn bundle_custom_media(fs: TestProvider, entry: &str) -> String {
    let mut bundler = Bundler::new(&fs, None, ParserOptions { custom_media: true, ..ParserOptions::default() });
    let mut stylesheet = bundler.bundle(Path::new(entry)).unwrap();
    let targets = Some(Browsers { safari: Some(13 << 16 ), ..Browsers::default() });
    stylesheet.minify(MinifyOptions { targets, ..MinifyOptions::default() }).unwrap();
    stylesheet.to_css(PrinterOptions { targets, ..PrinterOptions::default() }).unwrap().code
  }

  fn error_test(fs: TestProvider, entry: &str) {
    let mut bundler = Bundler::new(&fs, None, ParserOptions::default());
    let res = bundler.bundle(Path::new(entry));
    match res {
      Ok(_) => unreachable!(),
      Err(e) => assert!(matches!(e.kind, BundleErrorKind::UnsupportedLayerCombination))
    }
  }

  #[test]
  fn test_bundle() {
    let res = bundle(fs! {
      "/a.css": r#"
        @import "b.css";
        .a { color: red }
      "#,
      "/b.css": r#"
        .b { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      .b {
        color: green;
      }
      
      .a {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @import "b.css" print;
        .a { color: red }
      "#,
      "/b.css": r#"
        .b { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      @media print {
        .b {
          color: green;
        }
      }
      
      .a {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @import "b.css" supports(color: green);
        .a { color: red }
      "#,
      "/b.css": r#"
        .b { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      @supports (color: green) {
        .b {
          color: green;
        }
      }
      
      .a {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @import "b.css" supports(color: green) print;
        .a { color: red }
      "#,
      "/b.css": r#"
        .b { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      @supports (color: green) {
        @media print {
          .b {
            color: green;
          }
        }
      }
      
      .a {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @import "b.css" print;
        @import "b.css" screen;
        .a { color: red }
      "#,
      "/b.css": r#"
        .b { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      @media print, screen {
        .b {
          color: green;
        }
      }
      
      .a {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @import "b.css" supports(color: red);
        @import "b.css" supports(foo: bar);
        .a { color: red }
      "#,
      "/b.css": r#"
        .b { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      @supports ((color: red) or (foo: bar)) {
        .b {
          color: green;
        }
      }
      
      .a {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @import "b.css" print;
        .a { color: red }
      "#,
      "/b.css": r#"
        @import "c.css" (color);
        .b { color: yellow }
      "#,
      "/c.css": r#"
        .c { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      @media print and (color) {
        .c {
          color: green;
        }
      }
      
      @media print {
        .b {
          color: #ff0;
        }
      }

      .a {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @import "b.css";
        .a { color: red }
      "#,
      "/b.css": r#"
        @import "c.css";
      "#,
      "/c.css": r#"
        @import "a.css";
        .c { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      .c {
        color: green;
      }

      .a {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @import "b/c.css";
        .a { color: red }
      "#,
      "/b/c.css": r#"
        .b { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      .b {
        color: green;
      }
      
      .a {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @import "./b/c.css";
        .a { color: red }
      "#,
      "/b/c.css": r#"
        .b { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      .b {
        color: green;
      }
      
      .a {
        color: red;
      }
    "#});

    let res = bundle_css_module(fs! {
      "/a.css": r#"
        @import "b.css";
        .a { color: red }
      "#,
      "/b.css": r#"
        .a { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      .a_6lixEq_1 {
        color: green;
      }

      .a_6lixEq {
        color: red;
      }
    "#});

    let res = bundle_custom_media(fs! {
      "/a.css": r#"
        @import "media.css";
        @import "b.css";
        .a { color: red }
      "#,
      "/media.css": r#"
        @custom-media --foo print;
      "#,
      "/b.css": r#"
        @media (--foo) {
          .a { color: green }
        }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      @media print {
        .a {
          color: green;
        }
      }

      .a {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @import "b.css" layer(foo);
        .a { color: red }
      "#,
      "/b.css": r#"
        .b { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      @layer foo {
        .b {
          color: green;
        }
      }
      
      .a {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @import "b.css" layer;
        .a { color: red }
      "#,
      "/b.css": r#"
        .b { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      @layer {
        .b {
          color: green;
        }
      }
      
      .a {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @import "b.css" layer(foo);
        .a { color: red }
      "#,
      "/b.css": r#"
        @import "c.css" layer(bar);
        .b { color: green }
      "#,
      "/c.css": r#"
        .c { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      @layer foo.bar {
        .c {
          color: green;
        }
      }

      @layer foo {
        .b {
          color: green;
        }
      }
      
      .a {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @import "b.css" layer(foo);
        @import "b.css" layer(foo);
      "#,
      "/b.css": r#"
        .b { color: green }
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      @layer foo {
        .b {
          color: green;
        }
      }
    "#});

    let res = bundle(fs! {
      "/a.css": r#"
        @layer bar, foo;
        @import "b.css" layer(foo);
        
        @layer bar {
          div {
            background: red;
          }
        }
      "#,
      "/b.css": r#"
        @layer qux, baz;
        @import "c.css" layer(baz);
        
        @layer qux {
          div {
            background: green;
          }
        }
      "#,
      "/c.css": r#"
        div {
          background: yellow;
        }      
      "#
    }, "/a.css");
    assert_eq!(res, indoc! { r#"
      @layer bar, foo;
      @layer foo.qux, foo.baz;

      @layer foo.baz {
        div {
          background: #ff0;
        }
      }

      @layer foo {
        @layer qux {
          div {
            background: green;
          }
        }
      }
      
      @layer bar {
        div {
          background: red;
        }
      }
    "#});

    error_test(fs! {
      "/a.css": r#"
        @import "b.css" layer(foo);
        @import "b.css" layer(bar);
      "#,
      "/b.css": r#"
        .b { color: red }
      "#
    }, "/a.css");

    error_test(fs! {
      "/a.css": r#"
        @import "b.css" layer;
        @import "b.css" layer;
      "#,
      "/b.css": r#"
        .b { color: red }
      "#
    }, "/a.css");
    
    error_test(fs! {
      "/a.css": r#"
        @import "b.css" layer;
        .a { color: red }
      "#,
      "/b.css": r#"
        @import "c.css" layer;
        .b { color: green }
      "#,
      "/c.css": r#"
        .c { color: green }
      "#
    }, "/a.css");

    error_test(fs! {
      "/a.css": r#"
        @import "b.css" layer;
        .a { color: red }
      "#,
      "/b.css": r#"
        @import "c.css" layer(foo);
        .b { color: green }
      "#,
      "/c.css": r#"
        .c { color: green }
      "#
    }, "/a.css");

    let res = bundle(fs! {
      "/index.css": r#"
        @import "a.css";
        @import "b.css";
      "#,
      "/a.css": r#"
        @import "./c.css";
        body { background: red; }
      "#,
      "/b.css": r#"
        @import "./c.css";
        body { color: red; }
      "#,
      "/c.css": r#"
        body {
          background: white;
          color: black; 
        }
      "#
    }, "/index.css");
    assert_eq!(res, indoc! { r#"
      body {
        background: red;
      }

      body {
        background: #fff;
        color: #000;
      }

      body {
        color: red;
      }
    "#});

    let res = bundle(fs! {
      "/index.css": r#"
        @import "a.css";
        @import "b.css";
        @import "a.css";
      "#,
      "/a.css": r#"
        body { background: green; }
      "#,
      "/b.css": r#"
        body { background: red; }
      "#
    }, "/index.css");
    assert_eq!(res, indoc! { r#"
      body {
        background: red;
      }

      body {
        background: green;
      }
    "#});

    // let res = bundle(fs! {
    //   "/a.css": r#"
    //     @import "b.css" supports(color: red) (color);
    //     @import "b.css" supports(foo: bar) (orientation: horizontal);
    //     .a { color: red }
    //   "#,
    //   "/b.css": r#"
    //     .b { color: green }
    //   "#
    // }, "/a.css");

    // let res = bundle(fs! {
    //   "/a.css": r#"
    //     @import "b.css" not print;
    //     .a { color: red }
    //   "#,
    //   "/b.css": r#"
    //     @import "c.css" not screen;
    //     .b { color: green }
    //   "#,
    //   "/c.css": r#"
    //     .c { color: yellow }
    //   "#
    // }, "/a.css");
  }
}