sourcemap/
detector.rs

1use std::io::{BufRead, BufReader, Read};
2use std::str;
3
4use crate::decoder::{decode_data_url, strip_junk_header, StripHeaderReader};
5use crate::errors::Result;
6use crate::jsontypes::MinimalRawSourceMap;
7use crate::types::DecodedMap;
8
9use url::Url;
10
11/// Represents a reference to a sourcemap
12#[derive(PartialEq, Eq, Debug)]
13pub enum SourceMapRef {
14    /// A regular URL reference
15    Ref(String),
16    /// A legacy URL reference
17    LegacyRef(String),
18}
19
20fn resolve_url(ref_url: &str, minified_url: &Url) -> Option<Url> {
21    minified_url.join(ref_url).ok()
22}
23
24impl SourceMapRef {
25    /// Return the URL of the reference
26    pub fn get_url(&self) -> &str {
27        match *self {
28            SourceMapRef::Ref(ref u) => u.as_str(),
29            SourceMapRef::LegacyRef(ref u) => u.as_str(),
30        }
31    }
32
33    /// Resolves the reference.
34    ///
35    /// The given minified URL needs to be the URL of the minified file.  The
36    /// result is the fully resolved URL of where the source map can be located.
37    pub fn resolve(&self, minified_url: &str) -> Option<String> {
38        let url = self.get_url();
39        if url.starts_with("data:") {
40            return None;
41        }
42        resolve_url(url, &Url::parse(minified_url).ok()?).map(|x| x.to_string())
43    }
44
45    /// Resolves the reference against a local file path
46    ///
47    /// This is similar to `resolve` but operates on file paths.
48    #[cfg(any(unix, windows, target_os = "redox"))]
49    pub fn resolve_path(&self, minified_path: &std::path::Path) -> Option<std::path::PathBuf> {
50        let url = self.get_url();
51        if url.starts_with("data:") {
52            return None;
53        }
54        resolve_url(url, &Url::from_file_path(minified_path).ok()?)
55            .and_then(|x| x.to_file_path().ok())
56    }
57
58    /// Load an embedded sourcemap if there is a data URL.
59    pub fn get_embedded_sourcemap(&self) -> Result<Option<DecodedMap>> {
60        let url = self.get_url();
61        if url.starts_with("data:") {
62            Ok(Some(decode_data_url(url)?))
63        } else {
64            Ok(None)
65        }
66    }
67}
68
69/// Locates a sourcemap reference
70///
71/// Given a reader to a JavaScript file this tries to find the correct
72/// sourcemap reference comment and return it.
73pub fn locate_sourcemap_reference<R: Read>(rdr: R) -> Result<Option<SourceMapRef>> {
74    for line in BufReader::new(rdr).lines() {
75        let line = line?;
76        if line.starts_with("//# sourceMappingURL=") || line.starts_with("//@ sourceMappingURL=") {
77            let url = str::from_utf8(&line.as_bytes()[21..])?.trim().to_owned();
78            if line.starts_with("//@") {
79                return Ok(Some(SourceMapRef::LegacyRef(url)));
80            } else {
81                return Ok(Some(SourceMapRef::Ref(url)));
82            }
83        }
84    }
85    Ok(None)
86}
87
88/// Locates a sourcemap reference in a slice
89///
90/// This is an alternative to `locate_sourcemap_reference` that operates
91/// on slices.
92pub fn locate_sourcemap_reference_slice(slice: &[u8]) -> Result<Option<SourceMapRef>> {
93    locate_sourcemap_reference(slice)
94}
95
96fn is_sourcemap_common(rsm: MinimalRawSourceMap) -> bool {
97    (rsm.version.is_some() || rsm.file.is_some())
98        && ((rsm.sources.is_some()
99            || rsm.source_root.is_some()
100            || rsm.sources_content.is_some()
101            || rsm.names.is_some())
102            && rsm.mappings.is_some())
103        || rsm.sections.is_some()
104}
105
106fn is_sourcemap_impl<R: Read>(rdr: R) -> Result<bool> {
107    let mut rdr = StripHeaderReader::new(rdr);
108    let mut rdr = BufReader::new(&mut rdr);
109    let rsm: MinimalRawSourceMap = serde_json::from_reader(&mut rdr)?;
110    Ok(is_sourcemap_common(rsm))
111}
112
113fn is_sourcemap_slice_impl(slice: &[u8]) -> Result<bool> {
114    let content = strip_junk_header(slice)?;
115    let rsm: MinimalRawSourceMap = serde_json::from_slice(content)?;
116    Ok(is_sourcemap_common(rsm))
117}
118
119/// Checks if a valid sourcemap can be read from the given reader
120pub fn is_sourcemap<R: Read>(rdr: R) -> bool {
121    is_sourcemap_impl(rdr).unwrap_or(false)
122}
123
124/// Checks if the given byte slice contains a sourcemap
125pub fn is_sourcemap_slice(slice: &[u8]) -> bool {
126    is_sourcemap_slice_impl(slice).unwrap_or(false)
127}