Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ use crate::jsontypes::RawSourceMap;
use crate::types::{DecodedMap, RawToken, SourceMap, SourceMapIndex, SourceMapSection};
use crate::vlq::parse_vlq_segment_into;

const DATA_PREAMBLE: &str = "data:application/json;base64,";

#[derive(PartialEq, Eq)]
enum HeaderState {
Undecided,
Expand Down Expand Up @@ -339,12 +337,22 @@ pub fn decode_slice(slice: &[u8]) -> Result<DecodedMap> {
decode_common(rsm)
}

/// Loads a sourcemap from a data URL
/// Loads a sourcemap from a data URL.
///
/// The URL should match the regex
/// `data:application/json;(charset=utf-?8;)?base64,(?<base64sourcemap>.+)`.
pub fn decode_data_url(url: &str) -> Result<DecodedMap> {
if !url.starts_with(DATA_PREAMBLE) {
return Err(Error::InvalidDataUrl);
}
let data_b64 = &url[DATA_PREAMBLE.len()..];
let rest = url
.strip_prefix("data:application/json")
.ok_or(Error::InvalidDataUrl)?;
let rest = match rest.strip_prefix(";charset=") {
Some(rest) => rest
.strip_prefix("utf-8")
.or_else(|| rest.strip_prefix("utf8"))
.ok_or(Error::InvalidDataUrl)?,
None => rest,
};
let data_b64 = rest.strip_prefix(";base64,").ok_or(Error::InvalidDataUrl)?;
let data = data_encoding::BASE64
.decode(data_b64.as_bytes())
.map_err(|_| Error::InvalidDataUrl)?;
Expand Down
9 changes: 6 additions & 3 deletions tests/test_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,11 @@ fn test_basic_sourcemap_source_root_logic() {

#[test]
fn test_sourcemap_data_url() {
let url = "data:application/json;base64,\
let base64 = "\
eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImNvb2xzdHVmZi5qcyJdLCJzb3VyY2VSb290I\
joieCIsIm5hbWVzIjpbIngiLCJhbGVydCJdLCJtYXBwaW5ncyI6IkFBQUEsR0FBSUEsR0\
FBSSxFQUNSLElBQUlBLEdBQUssRUFBRyxDQUNWQyxNQUFNIn0=";
match decode_data_url(url).unwrap() {
let test_url = |prefix: &str| match decode_data_url(&[prefix, base64].concat()).unwrap() {
DecodedMap::Regular(sm) => {
let mut iter = sm.tokens().filter(Token::has_name);
assert_eq!(
Expand All @@ -140,7 +140,10 @@ fn test_sourcemap_data_url() {
_ => {
panic!("did not get sourcemap");
}
}
};
test_url("data:application/json;base64,");
test_url("data:application/json;charset=utf-8;base64,");
test_url("data:application/json;charset=utf8;base64,");
}

#[test]
Expand Down