Skip to content

Commit

Permalink
feat: add SourceMap::to_data_url (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
underfin authored Mar 8, 2024
1 parent eff3dc0 commit 77023a8
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ if_chain = "1.0.0"
scroll = { version = "0.10.1", features = ["derive"], optional = true }
data-encoding = "2.3.3"
debugid = {version = "0.8.0", features = ["serde"] }
base64-simd = { version = "0.7" }

[build-dependencies]
rustc_version = "0.2.3"
Expand Down
23 changes: 23 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,29 @@ impl SourceMap {
encode(self, w)
}

/// Encode a sourcemap into a data url.
///
/// ```rust
/// # use sourcemap::SourceMap;
/// # let input: &[_] = b"{
/// # \"version\":3,
/// # \"sources\":[\"coolstuff.js\"],
/// # \"names\":[\"x\",\"alert\"],
/// # \"mappings\":\"AAAA,GAAIA,GAAI,EACR,IAAIA,GAAK,EAAG,CACVC,MAAM\"
/// # }";
/// let sm = SourceMap::from_reader(input).unwrap();
/// sm.to_data_url().unwrap();
/// ```
pub fn to_data_url(&self) -> Result<String> {
let mut buf = vec![];
encode(self, &mut buf)?;
let b64 = base64_simd::Base64::STANDARD.encode_to_boxed_str(&buf);
Ok(format!(
"data:application/json;charset=utf-8;base64,{}",
b64
))
}

/// Creates a sourcemap from a reader over a JSON byte slice in UTF-8
/// format. Optionally a "garbage header" as defined by the
/// sourcemap draft specification is supported. In case an indexed
Expand Down
7 changes: 7 additions & 0 deletions tests/test_encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,10 @@ fn test_basic_sourcemap() {
assert_eq!(tok1, tok2);
}
}

#[test]
fn test_sourcemap_data_url() {
let input: &[_] = br#"{"version":3,"file":"build/foo.min.js","sources":["src/foo.js"],"names":[],"mappings":"AAAA","sourceRoot":"/"}"#;
let sm = SourceMap::from_reader(input).unwrap();
assert_eq!(sm.to_data_url().unwrap(), "data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJzb3VyY2VSb290IjoiLyIsIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBIn0=");
}

0 comments on commit 77023a8

Please sign in to comment.