Skip to main content

fallow_engine/health/coverage_v8/
source_map_cache.rs

1//! The `source-map-cache` of a V8 coverage dump: its entries, and the rules
2//! that turn a source of a map into a file path. The health coverage reader
3//! and the runtime-coverage remapper of the CLI both use these rules.
4
5use std::path::{Path, PathBuf};
6
7use fallow_types::path_util::{is_absolute_path_any_platform, looks_like_windows_absolute_path};
8use rustc_hash::FxHashMap;
9use serde::Deserialize;
10use url::Url;
11
12/// One `source-map-cache` entry of a V8 dump.
13#[derive(Debug, Clone, Deserialize)]
14pub struct SourceMapCacheEntry {
15    /// The URL of an external map. Node writes `null` when it loaded the map.
16    #[serde(default)]
17    pub url: Option<String>,
18    /// The source map as JSON.
19    pub data: serde_json::Value,
20    /// UTF-16 length of each line of the generated code.
21    #[serde(default, rename = "lineLengths")]
22    pub line_lengths: Vec<u32>,
23}
24
25/// Decodes each entry of a `source-map-cache` object on its own, keyed by
26/// script URL. An entry that does not decode is left out, so one bad entry
27/// does not remove the other maps. A value that is not an object gives an
28/// empty map.
29pub fn parse_source_map_cache(raw: &serde_json::Value) -> FxHashMap<String, SourceMapCacheEntry> {
30    let Some(entries) = raw.as_object() else {
31        return FxHashMap::default();
32    };
33    entries
34        .iter()
35        .filter_map(|(url, entry)| {
36            Some((url.clone(), SourceMapCacheEntry::deserialize(entry).ok()?))
37        })
38        .collect()
39}
40
41/// The path of a `file://` URL or of an absolute path. `None` for each other
42/// URL and for a relative path.
43pub fn file_url_to_path(value: &str) -> Option<PathBuf> {
44    if let Ok(url) = Url::parse(value) {
45        return if url.scheme() == "file" {
46            url.to_file_path().ok()
47        } else {
48            None
49        };
50    }
51    let path = PathBuf::from(value);
52    (is_absolute_path_any_platform(&path) || looks_like_windows_absolute_path(value))
53        .then_some(path)
54}
55
56/// The directory that relative and virtual sources resolve from: the
57/// directory of the external map when the entry names one, else the
58/// directory of the generated script. `None` when the script is not a local
59/// file or the map is remote.
60pub fn source_map_base_dir(generated_url: &str, source_map_url: Option<&str>) -> Option<PathBuf> {
61    let generated_path = file_url_to_path(generated_url)?;
62    let generated_dir = generated_path.parent()?.to_path_buf();
63    let Some(source_map_url) = source_map_url.filter(|url| !url.is_empty()) else {
64        return Some(generated_dir);
65    };
66    if let Some(path) = file_url_to_path(source_map_url) {
67        return path.parent().map(Path::to_path_buf);
68    }
69    let candidate = PathBuf::from(source_map_url);
70    if is_absolute_path_any_platform(&candidate) || looks_like_windows_absolute_path(source_map_url)
71    {
72        return candidate.parent().map(Path::to_path_buf);
73    }
74    if Url::parse(source_map_url).is_ok() {
75        return None;
76    }
77    generated_dir
78        .join(candidate)
79        .parent()
80        .map(Path::to_path_buf)
81}
82
83/// The file path of one source of a map. A `file://` URL and an absolute
84/// path resolve without a base directory. A relative path joins the base
85/// directory. A `webpack://` or `vite://` source resolves to the first
86/// existing file in the base directory or one of its ancestors. Each other
87/// URL gives `None`.
88pub fn resolve_original_source(raw_source: &str, base_dir: Option<&Path>) -> Option<PathBuf> {
89    if raw_source.is_empty() {
90        return None;
91    }
92    if let Some(path) = file_url_to_path(raw_source) {
93        return Some(path);
94    }
95    let source_path = PathBuf::from(raw_source);
96    // `C:/repo/a.ts` also parses as a URL with the scheme `c`.
97    if is_absolute_path_any_platform(&source_path) || looks_like_windows_absolute_path(raw_source) {
98        return Some(source_path);
99    }
100    if let Ok(url) = Url::parse(raw_source) {
101        return match url.scheme() {
102            "webpack" | "vite" => {
103                resolve_virtual_candidate(&virtual_source_candidates(&url), base_dir?)
104            }
105            _ => None,
106        };
107    }
108    Some(base_dir?.join(source_path))
109}
110
111/// The relative paths that a virtual source can name, in lookup order: the
112/// namespace plus the path, then the path alone. The decoded form of the
113/// path comes first. The raw form follows, for a file name that holds a
114/// literal `%XX`.
115fn virtual_source_candidates(url: &Url) -> Vec<PathBuf> {
116    let raw = url.path().trim_start_matches('/');
117    let namespace = url
118        .host_str()
119        .map(|host| host.trim_matches('/'))
120        .filter(|host| !host.is_empty() && !matches!(*host, "." | "_N_E"));
121    let decoded = crate::url_path::decode_path(raw);
122    let mut candidates = Vec::new();
123    for path in [decoded.as_deref(), Some(raw)].into_iter().flatten() {
124        if let Some(namespace) = namespace {
125            push_candidate(&mut candidates, PathBuf::from(namespace).join(path));
126        }
127        push_candidate(&mut candidates, PathBuf::from(path));
128    }
129    candidates
130}
131
132fn push_candidate(candidates: &mut Vec<PathBuf>, candidate: PathBuf) {
133    if !candidate.as_os_str().is_empty() && !candidates.contains(&candidate) {
134        candidates.push(candidate);
135    }
136}
137
138fn resolve_virtual_candidate(candidates: &[PathBuf], base_dir: &Path) -> Option<PathBuf> {
139    for base in base_dir.ancestors() {
140        for candidate in candidates {
141            let resolved = base.join(candidate);
142            if resolved.is_file() {
143                return Some(resolved);
144            }
145        }
146    }
147    None
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    fn file_url(path: &Path) -> String {
155        Url::from_file_path(path).unwrap().to_string()
156    }
157
158    fn resolve(source: &str, generated: &str, map_url: Option<&str>) -> Option<PathBuf> {
159        resolve_original_source(source, source_map_base_dir(generated, map_url).as_deref())
160    }
161
162    /// A tempdir with an empty `dist` directory and each file of `files`.
163    fn project(files: &[&str]) -> tempfile::TempDir {
164        let dir = tempfile::tempdir().unwrap();
165        std::fs::create_dir_all(dir.path().join("dist")).unwrap();
166        for file in files {
167            let path = dir.path().join(file);
168            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
169            std::fs::write(path, "export const a = 1;\n").unwrap();
170        }
171        dir
172    }
173
174    fn resolve_virtual(dir: &tempfile::TempDir, source: &str) -> Option<PathBuf> {
175        resolve_original_source(source, Some(&dir.path().join("dist")))
176    }
177
178    #[test]
179    fn preserves_windows_absolute_source_map_sources() {
180        let generated = "file:///C:/repo/dist/bundle.js";
181        assert_eq!(
182            resolve("C:/repo/src/app.ts", generated, Some("bundle.js.map")),
183            Some(PathBuf::from("C:/repo/src/app.ts"))
184        );
185        assert_eq!(
186            resolve(r"C:\repo\src\app.ts", generated, Some("bundle.js.map")),
187            Some(PathBuf::from(r"C:\repo\src\app.ts"))
188        );
189    }
190
191    #[test]
192    fn file_url_to_path_accepts_file_urls_and_absolute_paths_only() {
193        let dir = tempfile::tempdir().unwrap();
194        let path = dir.path().join("app.js");
195        assert_eq!(file_url_to_path(&file_url(&path)), Some(path));
196        assert_eq!(file_url_to_path("https://example.com/app.js"), None);
197        assert_eq!(file_url_to_path("relative/app.js"), None);
198    }
199
200    #[test]
201    fn resolve_source_map_base_handles_inline_relative_and_remote_urls() {
202        let dir = tempfile::tempdir().unwrap();
203        let generated = file_url(&dir.path().join("app.js"));
204        assert_eq!(
205            source_map_base_dir(&generated, None),
206            Some(dir.path().to_path_buf())
207        );
208        assert_eq!(
209            source_map_base_dir(&generated, Some("app.js.map")),
210            Some(dir.path().to_path_buf())
211        );
212        assert_eq!(
213            source_map_base_dir(&generated, Some("https://cdn.example.com/app.js.map")),
214            None
215        );
216    }
217
218    #[test]
219    fn resolve_original_source_path_handles_file_absolute_and_relative_sources() {
220        let dir = tempfile::tempdir().unwrap();
221        let source = dir.path().join("src/app.ts");
222        let generated = file_url(&dir.path().join("dist/app.js"));
223        assert_eq!(resolve("", &generated, None), None);
224        assert_eq!(
225            resolve(&file_url(&source), &generated, None),
226            Some(source.clone())
227        );
228        assert_eq!(
229            resolve(source.to_str().unwrap(), &generated, None),
230            Some(source)
231        );
232        assert_eq!(
233            resolve("src/app.ts", &generated, None),
234            Some(dir.path().join("dist/src/app.ts"))
235        );
236    }
237
238    #[test]
239    fn resolve_original_source_path_resolves_virtual_sources_from_ancestors() {
240        let dir = project(&["src/app.ts"]);
241        let generated = file_url(&dir.path().join("dist/chunks/app.js"));
242        assert_eq!(
243            resolve("webpack://app/src/app.ts", &generated, None),
244            Some(dir.path().join("src/app.ts"))
245        );
246    }
247
248    #[test]
249    fn virtual_source_candidates_strip_known_pseudo_hosts() {
250        let url = Url::parse("webpack://_N_E/./src/app.ts").unwrap();
251        let candidates = virtual_source_candidates(&url);
252        // The `_N_E` pseudo-host is dropped and the url crate normalizes the
253        // `/.` segment, leaving the path-only candidate.
254        assert!(
255            candidates.contains(&PathBuf::from("src/app.ts")),
256            "got: {candidates:?}"
257        );
258        assert!(!candidates.iter().any(|c| c.starts_with("_N_E")));
259    }
260
261    #[test]
262    fn resolve_virtual_source_path_ignores_non_virtual_schemes() {
263        let dir = tempfile::tempdir().unwrap();
264        assert_eq!(
265            resolve_original_source("https://example.com/app.ts", Some(dir.path())),
266            None
267        );
268    }
269
270    #[test]
271    fn parse_keeps_good_entries_beside_a_bad_one() {
272        let raw = serde_json::json!({
273            "file:///good.js": { "data": { "version": 3 }, "lineLengths": [1] },
274            "file:///string.js": "oops",
275            "file:///lengths.js": { "data": {}, "lineLengths": "x" },
276        });
277        let cache = parse_source_map_cache(&raw);
278        let keys: Vec<&String> = cache.keys().collect();
279        assert_eq!(keys, vec!["file:///good.js"]);
280        assert!(parse_source_map_cache(&serde_json::json!("not a cache object")).is_empty());
281    }
282
283    #[test]
284    fn entry_without_line_lengths_or_url_decodes() {
285        let bare: SourceMapCacheEntry =
286            serde_json::from_value(serde_json::json!({ "data": { "version": 3 } })).unwrap();
287        assert!(bare.line_lengths.is_empty());
288        assert_eq!(bare.url, None);
289        let full: SourceMapCacheEntry = serde_json::from_value(
290            serde_json::json!({ "url": null, "data": {}, "lineLengths": [1] }),
291        )
292        .unwrap();
293        assert_eq!(full.line_lengths, vec![1]);
294    }
295
296    #[test]
297    fn base_dir_follows_an_external_map_in_another_directory() {
298        let dir = tempfile::tempdir().unwrap();
299        let generated = file_url(&dir.path().join("dist/app.js"));
300        let base = source_map_base_dir(&generated, Some("../maps/app.js.map"));
301        let expected = dir.path().join("dist").join("../maps");
302        assert_eq!(base.as_deref(), Some(expected.as_path()));
303        assert_eq!(
304            resolve_original_source("../src/a.ts", base.as_deref()),
305            Some(expected.join("../src/a.ts"))
306        );
307    }
308
309    #[test]
310    fn virtual_source_with_an_escaped_space_resolves() {
311        let dir = project(&["src dir/my file.ts"]);
312        assert_eq!(
313            resolve_virtual(&dir, "webpack://app/src%20dir/my%20file.ts"),
314            Some(dir.path().join("src dir/my file.ts"))
315        );
316    }
317
318    #[test]
319    fn virtual_source_with_a_plain_space_resolves() {
320        let dir = project(&["src dir/my file.ts"]);
321        assert_eq!(
322            resolve_virtual(&dir, "webpack://app/./src dir/my file.ts"),
323            Some(dir.path().join("src dir/my file.ts"))
324        );
325    }
326
327    #[test]
328    fn virtual_source_with_a_literal_percent_resolves() {
329        let dir = project(&["src/100%.ts", "src/a%20b.ts"]);
330        for file in ["src/100%.ts", "src/a%20b.ts"] {
331            assert_eq!(
332                resolve_virtual(&dir, &format!("webpack://app/{file}")),
333                Some(dir.path().join(file))
334            );
335        }
336    }
337
338    #[test]
339    fn virtual_source_with_an_escaped_separator_is_not_resolved() {
340        let dir = project(&["src/a.ts"]);
341        assert_eq!(resolve_virtual(&dir, "webpack://app/src%2Fa.ts"), None);
342    }
343}