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
use std::{
  fmt::Debug,
  path::{Path, PathBuf},
};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::{
  protocol::{
    self,
    outbound_message::{
      compile_response::{self, CompileSuccess},
      CompileResponse,
    },
  },
  Exception, Result, Url,
};

/// Options that can be passed to [Sass::compile].
///
/// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Options)
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug)]
pub struct Options {
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Options#alertAscii)
  pub alert_ascii: bool,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Options#alertColor)
  pub alert_color: Option<bool>,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Options#importers)
  #[cfg_attr(feature = "serde", serde(skip))]
  pub importers: Vec<SassImporter>,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Options#loadPaths)
  pub load_paths: Vec<PathBuf>,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Options#logger)
  #[cfg_attr(feature = "serde", serde(skip))]
  pub logger: Option<BoxLogger>,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Options#quietDeps)
  pub quiet_deps: bool,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Options#sourceMap)
  pub source_map: bool,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Options#sourceMapIncludeSources)
  pub source_map_include_sources: bool,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Options#style)
  pub style: OutputStyle,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Options#verbose)
  pub verbose: bool,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Options#charset)
  pub charset: bool,
}

impl Default for Options {
  fn default() -> Self {
    Self {
      alert_ascii: false,
      alert_color: None,
      load_paths: Vec::new(),
      importers: Vec::new(),
      logger: None,
      quiet_deps: false,
      source_map: false,
      source_map_include_sources: false,
      style: OutputStyle::default(),
      verbose: false,
      charset: true,
    }
  }
}

/// A builder for [Options].
#[derive(Debug, Default)]
pub struct OptionsBuilder {
  options: Options,
}

impl OptionsBuilder {
  /// Creates a new [OptionsBuilder].
  pub fn new() -> Self {
    Self::default()
  }

  /// Build the [Options].
  pub fn build(self) -> Options {
    self.options
  }

  /// Sets the [Options]'s [alert_ascii] field.
  pub fn alert_ascii(mut self, arg: impl Into<bool>) -> Self {
    self.options.alert_ascii = arg.into();
    self
  }

  /// Sets the [Options]'s [alert_color] field.
  pub fn alert_color(mut self, arg: impl Into<bool>) -> Self {
    self.options.alert_color = Some(arg.into());
    self
  }

  /// Sets the [Options]'s [load_paths] field.
  pub fn load_paths<P: AsRef<Path>>(mut self, arg: impl AsRef<[P]>) -> Self {
    self.options.load_paths =
      arg.as_ref().iter().map(|p| p.as_ref().to_owned()).collect();
    self
  }

  /// Adds a load_path to the [Options]'s [load_paths] field.
  pub fn load_path(mut self, arg: impl AsRef<Path>) -> Self {
    self.options.load_paths.push(arg.as_ref().to_owned());
    self
  }

  /// Sets the [Options]'s [quiet_deps] field.
  pub fn quiet_deps(mut self, arg: impl Into<bool>) -> Self {
    self.options.quiet_deps = arg.into();
    self
  }

  /// Sets the [Options]'s [source_map] field.
  pub fn source_map(mut self, arg: impl Into<bool>) -> Self {
    self.options.source_map = arg.into();
    self
  }

  /// Sets the [Options]'s [source_map_include_sources] field.
  pub fn source_map_include_sources(mut self, arg: impl Into<bool>) -> Self {
    self.options.source_map_include_sources = arg.into();
    self
  }

  /// Sets the [Options]'s [style] field.
  pub fn style(mut self, arg: impl Into<OutputStyle>) -> Self {
    self.options.style = arg.into();
    self
  }

  /// Sets the [Options]'s [verbose] field.
  pub fn verbose(mut self, arg: impl Into<bool>) -> Self {
    self.options.verbose = arg.into();
    self
  }

  /// Sets the [Options]'s [charset] field.
  pub fn charset(mut self, arg: impl Into<bool>) -> Self {
    self.options.charset = arg.into();
    self
  }

  /// Sets the [Options]'s [logger] field.
  pub fn logger<L: 'static + Logger>(mut self, arg: L) -> Self {
    self.options.logger = Some(Box::new(arg));
    self
  }

  /// Adds a [SassImporter] to the [Options]'s [importers] field.
  pub fn sass_importer(mut self, arg: impl Into<SassImporter>) -> Self {
    self.options.importers.push(arg.into());
    self
  }

  /// Sets the [Options]'s [importers] field.
  pub fn sass_importers(
    mut self,
    arg: impl IntoIterator<Item = impl Into<SassImporter>>,
  ) -> Self {
    self.options.importers = arg.into_iter().map(|i| i.into()).collect();
    self
  }

  /// Adds a [Importer] to the [Options]'s [importers] field.
  pub fn importer<I: 'static + Importer>(mut self, arg: I) -> Self {
    self
      .options
      .importers
      .push(SassImporter::Importer(Box::new(arg) as Box<dyn Importer>));
    self
  }

  /// Adds a [FileImporter] to the [Options]'s [importers] field.
  pub fn file_importer<I: 'static + FileImporter>(mut self, arg: I) -> Self {
    self.options.importers.push(SassImporter::FileImporter(
      Box::new(arg) as Box<dyn FileImporter>
    ));
    self
  }
}

/// Options that can be passed to [Sass::compile_string].
///
/// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/modules#StringOptions)
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Default)]
pub struct StringOptions {
  /// Field for [Options]
  pub common: Options,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/StringOptionsWithImporter#importer)
  #[cfg_attr(feature = "serde", serde(skip))]
  pub input_importer: Option<SassImporter>,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/StringOptionsWithoutImporter#syntax)
  pub syntax: Syntax,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/StringOptionsWithoutImporter#url)
  pub url: Option<Url>,
}

/// A builder for [StringOptions].
#[derive(Debug, Default)]
pub struct StringOptionsBuilder {
  options: Options,
  input_importer: Option<SassImporter>,
  syntax: Syntax,
  url: Option<Url>,
}

impl StringOptionsBuilder {
  /// Creates a new [StringOptionsBuilder].
  pub fn new() -> Self {
    Self::default()
  }

  /// Build the [StringOptions].
  pub fn build(self) -> StringOptions {
    StringOptions {
      common: self.options,
      input_importer: self.input_importer,
      syntax: self.syntax,
      url: self.url,
    }
  }

  /// Sets the [StringOptions]'s [input_importer] field with a [SassImporter].
  pub fn input_sass_importer(mut self, arg: impl Into<SassImporter>) -> Self {
    self.input_importer = Some(arg.into());
    self
  }

  /// Sets the [StringOptions]'s [input_importer] field with a [Importer].
  pub fn input_importer<I: 'static + Importer>(mut self, arg: I) -> Self {
    self.input_importer = Some(SassImporter::Importer(Box::new(arg)));
    self
  }

  /// Sets the [StringOptions]'s [input_importer] field with a [FileImporter].
  pub fn input_file_importer<I: 'static + FileImporter>(
    mut self,
    arg: I,
  ) -> Self {
    self.input_importer = Some(SassImporter::FileImporter(Box::new(arg)));
    self
  }

  /// Sets the [StringOptions]'s [syntax] field.
  pub fn syntax(mut self, arg: impl Into<Syntax>) -> Self {
    self.syntax = arg.into();
    self
  }

  /// Sets the [StringOptions]'s [url] field.
  pub fn url(mut self, arg: impl Into<Url>) -> Self {
    self.url = Some(arg.into());
    self
  }

  /// Sets the [StringOptions]'s [alert_ascii] field.
  pub fn alert_ascii(mut self, arg: impl Into<bool>) -> Self {
    self.options.alert_ascii = arg.into();
    self
  }

  /// Sets the [StringOptions]'s [alert_color] field.
  pub fn alert_color(mut self, arg: impl Into<bool>) -> Self {
    self.options.alert_color = Some(arg.into());
    self
  }

  /// Sets the [StringOptions]'s [load_paths] field.
  pub fn load_paths<P: AsRef<Path>>(mut self, arg: impl AsRef<[P]>) -> Self {
    self.options.load_paths =
      arg.as_ref().iter().map(|p| p.as_ref().to_owned()).collect();
    self
  }

  /// Adds a [Path] to the [StringOptions]'s [load_paths] field.
  pub fn load_path(mut self, arg: impl AsRef<Path>) -> Self {
    self.options.load_paths.push(arg.as_ref().to_owned());
    self
  }

  /// Sets the [StringOptions]'s [quiet_deps] field.
  pub fn quiet_deps(mut self, arg: impl Into<bool>) -> Self {
    self.options.quiet_deps = arg.into();
    self
  }

  /// Sets the [StringOptions]'s [source_map] field.
  pub fn source_map(mut self, arg: impl Into<bool>) -> Self {
    self.options.source_map = arg.into();
    self
  }

  /// Sets the [StringOptions]'s [source_map_include_sources] field.
  pub fn source_map_include_sources(mut self, arg: impl Into<bool>) -> Self {
    self.options.source_map_include_sources = arg.into();
    self
  }

  /// Sets the [StringOptions]'s [style] field.
  pub fn style(mut self, arg: impl Into<OutputStyle>) -> Self {
    self.options.style = arg.into();
    self
  }

  /// Sets the [StringOptions]'s [verbose] field.
  pub fn verbose(mut self, arg: impl Into<bool>) -> Self {
    self.options.verbose = arg.into();
    self
  }

  /// Sets the [StringOptions]'s [charset] field.
  pub fn charset(mut self, arg: impl Into<bool>) -> Self {
    self.options.charset = arg.into();
    self
  }

  /// Sets the [StringOptions]'s [logger] field.
  pub fn logger<L: 'static + Logger>(mut self, arg: L) -> Self {
    self.options.logger = Some(Box::new(arg));
    self
  }

  /// Adds a [SassImporter] to the [StringOptions]'s [importers] field.
  pub fn sass_importer(mut self, arg: impl Into<SassImporter>) -> Self {
    self.options.importers.push(arg.into());
    self
  }

  /// Sets the [StringOptions]'s [importers] field with [SassImporter]s.
  pub fn sass_importers(
    mut self,
    arg: impl IntoIterator<Item = impl Into<SassImporter>>,
  ) -> Self {
    self.options.importers = arg.into_iter().map(|i| i.into()).collect();
    self
  }

  /// Adds a [Importer] to the [StringOptions]'s [importers] field.
  pub fn importer<I: 'static + Importer>(mut self, arg: I) -> Self {
    self
      .options
      .importers
      .push(SassImporter::Importer(Box::new(arg)));
    self
  }

  /// Adds a [FileImporter] to the [StringOptions]'s [importers] field.
  pub fn file_importer<I: 'static + FileImporter>(mut self, arg: I) -> Self {
    self
      .options
      .importers
      .push(SassImporter::FileImporter(Box::new(arg)));
    self
  }
}

/// A type alias for [Box<dyn Logger>].
pub type BoxLogger = Box<dyn Logger>;

/// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Logger)
pub trait Logger: Debug + Send + Sync {
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Logger#warn)
  fn warn(&self, _message: &str, options: &LoggerWarnOptions) {
    eprintln!("{}", options.formatted);
  }

  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Logger#debug)
  fn debug(&self, _message: &str, options: &LoggerDebugOptions) {
    eprintln!("{}", options.formatted);
  }
}

/// Options for [Logger::warn].
///
/// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Logger#warn)
pub struct LoggerWarnOptions {
  /// Whether this is a deprecation warning.
  pub deprecation: bool,
  /// The location in the Sass source code that generated this warning.
  pub span: Option<SourceSpan>,
  /// The Sass stack trace at the point the warning was issued.
  pub stack: Option<String>,
  pub(crate) formatted: String,
}

/// Options for [Logger::debug].
///
/// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Logger#debug)
pub struct LoggerDebugOptions {
  /// The location in the Sass source code that generated this debug message.
  pub span: Option<SourceSpan>,
  pub(crate) formatted: String,
}

/// Enum wrapper for [BoxImporter] and [BoxFileImporter].
#[derive(Debug)]
pub enum SassImporter {
  /// A [BoxImporter].
  Importer(BoxImporter),
  /// A [BoxFileImporter].
  FileImporter(BoxFileImporter),
}

/// A type alias for [Box<dyn Importer>].
pub type BoxImporter = Box<dyn Importer>;

/// A type alias for [Box<dyn FileImporter>].
pub type BoxFileImporter = Box<dyn FileImporter>;

/// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Importer)
pub trait Importer: Debug + Send + Sync {
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Importer#canonicalize)
  fn canonicalize(
    &self,
    url: &str,
    options: &ImporterOptions,
  ) -> Result<Option<Url>>;

  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Importer#load)
  fn load(&self, canonical_url: &Url) -> Result<Option<ImporterResult>>;
}

/// Options for [Importer::canonicalize] or [Importer::load].
///
/// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/Importer#canonicalize)
pub struct ImporterOptions {
  /// Whether this is being invoked because of a Sass @import rule, as opposed to a @use
  /// or @forward rule.
  pub from_import: bool,
}

/// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/FileImporter)
pub trait FileImporter: Debug + Send + Sync {
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/FileImporter#findFileUrl)
  fn find_file_url(
    &self,
    url: &str,
    options: &ImporterOptions,
  ) -> Result<Option<Url>>;
}

/// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/ImporterResult)
pub struct ImporterResult {
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/ImporterResult#contents)
  pub contents: String,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/ImporterResult#sourceMapUrl)
  pub source_map_url: Option<Url>,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/ImporterResult#syntax)
  pub syntax: Syntax,
}

/// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/CompileResult)
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct CompileResult {
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/CompileResult#css)
  pub css: String,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/CompileResult#loadedUrls)
  pub loaded_urls: Vec<Url>,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/CompileResult#sourceMap)
  pub source_map: Option<String>,
}

impl TryFrom<CompileResponse> for CompileResult {
  type Error = Exception;

  fn try_from(response: CompileResponse) -> Result<Self> {
    let res = response.result.unwrap();
    match res {
      compile_response::Result::Success(success) => Ok(success.into()),
      compile_response::Result::Failure(failure) => {
        Err(Exception::from(failure))
      }
    }
  }
}

impl From<CompileSuccess> for CompileResult {
  fn from(s: CompileSuccess) -> Self {
    Self {
      css: s.css,
      loaded_urls: s
        .loaded_urls
        .iter()
        .map(|url| Url::parse(url).unwrap())
        .collect(),
      source_map: if s.source_map.is_empty() {
        None
      } else {
        Some(s.source_map)
      },
    }
  }
}

/// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/modules#OutputStyle)
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug)]
pub enum OutputStyle {
  /// Writes each selector and declaration on its own line.
  Expanded,
  /// Removes as many extra characters as possible, and writes the entire stylesheet on a single line.
  Compressed,
}

impl Default for OutputStyle {
  fn default() -> Self {
    Self::Expanded
  }
}

impl From<OutputStyle> for protocol::OutputStyle {
  fn from(o: OutputStyle) -> Self {
    match o {
      OutputStyle::Expanded => Self::Expanded,
      OutputStyle::Compressed => Self::Compressed,
    }
  }
}

/// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/modules#Syntax)
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug)]
pub enum Syntax {
  /// the [scss syntax](https://sass-lang.com/documentation/syntax#scss)
  Scss,
  /// the [indented syntax](https://sass-lang.com/documentation/syntax#the-indented-syntax)
  Indented,
  /// the plain css syntax, which is parsed like SCSS but forbids the use of any special Sass features.
  Css,
}

impl Default for Syntax {
  fn default() -> Self {
    Self::Scss
  }
}

impl From<Syntax> for protocol::Syntax {
  fn from(s: Syntax) -> Self {
    match s {
      Syntax::Scss => Self::Scss,
      Syntax::Indented => Self::Indented,
      Syntax::Css => Self::Css,
    }
  }
}

/// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/SourceSpan)
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug)]
pub struct SourceSpan {
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/SourceSpan#context)
  pub context: Option<String>,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/SourceSpan#end)
  pub end: SourceLocation,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/SourceSpan#start)
  pub start: SourceLocation,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/SourceSpan#url)
  pub url: Option<Url>,
  /// More information: [Sass documentation](https://sass-lang.com/documentation/js-api/interfaces/SourceSpan#text)
  pub text: String,
}

impl From<protocol::SourceSpan> for SourceSpan {
  fn from(span: protocol::SourceSpan) -> Self {
    let start = span.start.unwrap();
    Self {
      context: if span.context.is_empty() {
        None
      } else {
        Some(span.context)
      },
      end: span.end.unwrap_or_else(|| start.clone()).into(),
      start: start.into(),
      url: if span.url.is_empty() {
        None
      } else {
        Some(Url::parse(&span.url).unwrap())
      },
      text: span.text,
    }
  }
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug)]
pub struct SourceLocation {
  pub offset: usize,
  pub line: usize,
  pub column: usize,
}

impl From<protocol::source_span::SourceLocation> for SourceLocation {
  fn from(location: protocol::source_span::SourceLocation) -> Self {
    Self {
      offset: location.offset as usize,
      line: location.line as usize,
      column: location.column as usize,
    }
  }
}