Skip to main content

bynk_driver/
coverage.rs

1//! `bynkc test --coverage` — remap V8 line coverage onto `.bynk` source.
2//!
3//! The test runner already owns the two artefacts a coverage tool needs and a
4//! user cannot reconstruct: it launches the `node` process that executes the
5//! suite, and it holds the source maps from `.bynk` → emitted `.ts`. This module
6//! is the "one genuinely new piece" the coverage proposal (issue #854, ADR
7//! recorded at merge) calls out: it reads the raw V8 coverage the runtime writes
8//! to `NODE_V8_COVERAGE`, and attributes each executed / unexecuted line back to
9//! `.bynk` source through **two** line-level source-map hops:
10//!
11//! 1. `out-js/**/*.js.map` — tsc's map, `.js` line → emitted `.ts` line. `tsc`
12//!    does **not** chain input maps, so this hop only reaches the `.ts`.
13//! 2. `out/**/*.ts.map` — the emitter's map (ADR 0103), `.ts` line → `.bynk`
14//!    line. Statement-anchored and line-level (generated column always 0).
15//!
16//! Composed, a covered `.js` line lands on a `.bynk` line. Emitted glue with no
17//! `.bynk` origin (codec wrappers, capability injection, the module header) is
18//! **unmapped** in hop 2, so it contributes nothing — it is counted as
19//! out-of-scope, never as uncovered user code (the proposal's map-fidelity
20//! mitigation, for free).
21//!
22//! **Decisions realised here** (recorded in the ADR): line/statement coverage
23//! only, no branch coverage (DECISION B) — a `.bynk` line is *covered* if any
24//! generated line mapping to it executed; and the measured set excludes the
25//! `tests/` tree and the workers scaffold (DECISION D), filtered once on the
26//! `out-js`-relative path of the executed `.js` — the emitted tree's own
27//! top-level `tests/`/`workers/` dirs — before the maps are even consulted. The
28//! `.bynk` side is deliberately *not* re-filtered, so a user source that merely
29//! lives under a dir named `tests`/`workers` is still measured.
30
31use std::collections::{BTreeMap, HashMap};
32use std::path::{Component, Path, PathBuf};
33
34use serde::Deserialize;
35
36/// Per-`.bynk`-file line coverage, keyed by a project-relative display path.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct FileCoverage {
39    /// Project-relative `.bynk` path (forward-slashed), e.g. `src/limiter.bynk`.
40    pub path: String,
41    /// Covered executable lines (1-based count).
42    pub covered: u32,
43    /// Total executable lines attributed to this file (1-based count).
44    pub total: u32,
45    /// The uncovered executable lines, 1-based and ascending — the exact set the
46    /// proposal's fixtures pin.
47    pub uncovered: Vec<u32>,
48    /// The covered executable lines, 1-based and ascending (#2104): with
49    /// `uncovered`, every executable line, so an editor can mark both.
50    pub covered_lines: Vec<u32>,
51}
52
53/// A whole-run coverage report: one [`FileCoverage`] per measured `.bynk` file,
54/// sorted by path, plus the derived totals.
55#[derive(Debug, Clone, PartialEq, Eq, Default)]
56pub struct CoverageReport {
57    pub files: Vec<FileCoverage>,
58}
59
60impl CoverageReport {
61    /// Total covered executable lines across every measured file.
62    pub fn total_covered(&self) -> u32 {
63        self.files.iter().map(|f| f.covered).sum()
64    }
65
66    /// Total executable lines across every measured file.
67    pub fn total_lines(&self) -> u32 {
68        self.files.iter().map(|f| f.total).sum()
69    }
70
71    /// Whole-run percentage (0–100), rounded to the nearest integer. A run that
72    /// attributed no executable line is reported as 100% (nothing to cover).
73    pub fn total_percent(&self) -> u32 {
74        percent(self.total_covered(), self.total_lines())
75    }
76
77    /// Whether the report attributed no `.bynk` line at all — an empty measured
78    /// set (e.g. an integration-only project whose only executed code is the
79    /// workers scaffold DECISION D drops).
80    pub fn is_empty(&self) -> bool {
81        self.files.is_empty()
82    }
83}
84
85/// Coverage percentage of `covered`/`total`, rounded; `total == 0` → 100. Only a
86/// genuinely complete run reads 100%: round-half-up would report `995/1000` as
87/// `100%` while lines are still uncovered — self-contradicting in the table and
88/// a false green for a CI gate keyed on the JSON `percent` — so a run with any
89/// uncovered line is clamped to at most 99.
90pub fn percent(covered: u32, total: u32) -> u32 {
91    if total == 0 || covered >= total {
92        100
93    } else {
94        let rounded = (covered as u64 * 100 + total as u64 / 2) / total as u64;
95        (rounded as u32).min(99)
96    }
97}
98
99// -- V8 coverage JSON (the `NODE_V8_COVERAGE` output shape) --
100
101#[derive(Deserialize)]
102struct V8Document {
103    #[serde(default)]
104    result: Vec<V8Script>,
105}
106
107#[derive(Deserialize)]
108struct V8Script {
109    url: String,
110    #[serde(default)]
111    functions: Vec<V8Function>,
112}
113
114#[derive(Deserialize)]
115struct V8Function {
116    #[serde(default)]
117    ranges: Vec<V8Range>,
118}
119
120#[derive(Deserialize)]
121struct V8Range {
122    #[serde(rename = "startOffset")]
123    start: usize,
124    #[serde(rename = "endOffset")]
125    end: usize,
126    count: i64,
127}
128
129/// Collect coverage from a finished run and attribute it to `.bynk` source.
130///
131/// - `v8_dir` — the directory `NODE_V8_COVERAGE` was pointed at.
132/// - `out_js_root` — where the executed `.js` and tsc's `.js.map` live.
133/// - `out_root` — where the emitted `.ts` and the emitter's `.ts.map` live.
134/// - `source_root` — the project root the `.bynk` paths are relativised against.
135///
136/// Any file it cannot read or parse is skipped rather than failing the run —
137/// coverage is a report *about* a run that already happened, so a partial map
138/// should degrade the numbers, never abort. Reading the V8 directory is the one
139/// hard error surfaced (it is the runner's own temp dir).
140pub fn collect_coverage(
141    v8_dir: &Path,
142    out_js_root: &Path,
143    out_root: &Path,
144    source_root: &Path,
145) -> std::io::Result<CoverageReport> {
146    let canonical_root = source_root.canonicalize().ok();
147    // 1. Fold every V8 document into per-script merged ranges. A single-process
148    //    run writes one file, but Node may split across several; merging the
149    //    ranges (and taking the innermost at lookup time) is correct either way.
150    let mut scripts: HashMap<PathBuf, Vec<V8Range>> = HashMap::new();
151    for entry in std::fs::read_dir(v8_dir)? {
152        let path = entry?.path();
153        if path.extension().and_then(|e| e.to_str()) != Some("json") {
154            continue;
155        }
156        let Ok(text) = std::fs::read_to_string(&path) else {
157            continue;
158        };
159        let Ok(doc) = serde_json::from_str::<V8Document>(&text) else {
160            continue;
161        };
162        for script in doc.result {
163            let Some(fs_path) = file_url_to_path(&script.url) else {
164                continue;
165            };
166            let canon = std::fs::canonicalize(&fs_path).unwrap_or(fs_path);
167            let ranges = scripts.entry(canon).or_default();
168            for func in script.functions {
169                ranges.extend(func.ranges);
170            }
171        }
172    }
173
174    let out_js_canon =
175        std::fs::canonicalize(out_js_root).unwrap_or_else(|_| out_js_root.to_path_buf());
176
177    // Accumulate per `.bynk` file: the executable lines seen, and which executed.
178    let mut acc: BTreeMap<String, FileAcc> = BTreeMap::new();
179
180    for (script_path, ranges) in &scripts {
181        let Ok(rel) = script_path.strip_prefix(&out_js_canon) else {
182            continue;
183        };
184        // DECISION D: drop the workers scaffold, the emitted test modules, and
185        // the runtime — before the maps are consulted. These are the emitted
186        // `out-js` paths, so the filter is on the generated tree, not `.bynk`.
187        if !is_measurable_emitted(rel) {
188            continue;
189        }
190        let Ok(js_text) = std::fs::read_to_string(script_path) else {
191            continue;
192        };
193        // Hop 1: tsc's `.js.map` sits beside the `.js`.
194        let js_map_path = append_ext(script_path, "map");
195        let Some(js_map) = std::fs::read_to_string(&js_map_path)
196            .ok()
197            .and_then(|s| SourceMap::parse(&s))
198        else {
199            continue;
200        };
201        // Hop 2: the emitter's `.ts.map`, mirrored under `out/` at the same rel
202        // path (tsc's `rootDir: "."`, `outDir: "../out-js"` keeps the tree 1:1).
203        let ts_rel = rel.with_extension("ts");
204        let ts_map_path = append_ext(&out_root.join(&ts_rel), "map");
205        let Some(ts_map) = std::fs::read_to_string(&ts_map_path)
206            .ok()
207            .and_then(|s| SourceMap::parse(&s))
208        else {
209            continue;
210        };
211
212        let line_reps = line_representatives(&js_text);
213        for (js_line, rep_off) in line_reps.iter().enumerate() {
214            let Some(off) = rep_off else { continue };
215            // The verdict for this generated line is the *tightest* V8 range
216            // covering it — see [`innermost_range`]. A generated line covered by
217            // no range (the trailing `sourceMappingURL` comments) attributes
218            // nothing.
219            let Some((span, count)) = innermost_range(*off, ranges) else {
220                continue;
221            };
222            let Some(js_segs) = js_map.lines.get(js_line) else {
223                continue;
224            };
225            for &(_js_src, ts_line) in js_segs {
226                let Some(ts_segs) = ts_map.lines.get(ts_line as usize) else {
227                    continue;
228                };
229                for &(bynk_src, bynk_line) in ts_segs {
230                    let Some(bynk_abs) = ts_map.sources.get(bynk_src) else {
231                        continue;
232                    };
233                    let disp = relativise(bynk_abs, source_root, canonical_root.as_deref());
234                    // DECISION D is enforced once, authoritatively, on the emitted
235                    // tree by `is_measurable_emitted` (the `tests/` and `workers/`
236                    // top-level dirs of `out-js`). We deliberately do *not* re-filter
237                    // on the `.bynk` side: a user source that merely lives under a
238                    // dir named `tests`/`workers` (e.g. `src/workers/helpers.bynk`)
239                    // is real code whose `.js` already passed the emitted filter, so
240                    // dropping it here would silently omit it from coverage.
241                    let file = acc.entry(disp).or_default();
242                    // Lines are 1-based in every report the user sees. A `.bynk`
243                    // line's verdict is decided by the *most specific* (smallest-
244                    // span) generated range mapping to it: a function body's
245                    // range beats the whole-module range, so a hoisted
246                    // `exports.f = f;` (which runs at load and maps back to the
247                    // declaration line) never masks an uncalled function.
248                    let line1 = bynk_line + 1;
249                    file.observe(line1, span, count);
250                }
251            }
252        }
253    }
254
255    let files = acc
256        .into_iter()
257        .map(|(path, a)| {
258            let total = a.lines.len() as u32;
259            let mut covered_lines = Vec::new();
260            let mut uncovered = Vec::new();
261            for (&line, &(_, count)) in &a.lines {
262                if count > 0 {
263                    covered_lines.push(line);
264                } else {
265                    uncovered.push(line);
266                }
267            }
268            FileCoverage {
269                path,
270                covered: covered_lines.len() as u32,
271                total,
272                uncovered,
273                covered_lines,
274            }
275        })
276        .collect();
277    Ok(CoverageReport { files })
278}
279
280#[derive(Default)]
281struct FileAcc {
282    /// Per 1-based `.bynk` line: the tightest generated range's `(span, count)`
283    /// observed for it. `BTreeMap` keeps the uncovered list ascending for free.
284    lines: BTreeMap<u32, (usize, i64)>,
285}
286
287impl FileAcc {
288    /// Record that a generated position inside a range of `span`/`count` maps to
289    /// `line`. The tightest span wins; on a span tie the larger count wins (a
290    /// position two coverage files agree ran is covered).
291    fn observe(&mut self, line: u32, span: usize, count: i64) {
292        let slot = self.lines.entry(line).or_insert((usize::MAX, 0));
293        if span < slot.0 || (span == slot.0 && count > slot.1) {
294            *slot = (span, count);
295        }
296    }
297}
298
299/// The **innermost** (smallest-span) V8 range containing `off`, as `(span,
300/// count)`. V8 block coverage nests a not-taken block's `count: 0` range inside
301/// its enclosing function's `count: N` range, so the smallest containing range
302/// is the precise verdict for that position. `None` if no range contains `off`.
303fn innermost_range(off: usize, ranges: &[V8Range]) -> Option<(usize, i64)> {
304    let mut best: Option<(usize, i64)> = None;
305    for r in ranges {
306        if r.start <= off && off < r.end {
307            let span = r.end - r.start;
308            match best {
309                Some((bs, bc)) if span > bs || (span == bs && r.count <= bc) => {}
310                _ => best = Some((span, r.count)),
311            }
312        }
313    }
314    best
315}
316
317/// For each generated line, the **UTF-16 offset** of its first non-whitespace
318/// char — the position sampled against the V8 ranges. `None` for a blank line
319/// (nothing to attribute; such lines carry no mapping anyway).
320///
321/// #2146: a leading `export ` is skipped. The runner compiles to ES modules, so
322/// a function line reads `export function f(…) {`, and V8's range for `f`
323/// starts at `function`: sampling the `export` keyword would land in the
324/// module's range, which ran at load, and count an uncalled function's
325/// declaration line as covered.
326///
327/// V8 coverage `startOffset`/`endOffset` index the source as a JS string, i.e.
328/// in UTF-16 code units, not UTF-8 bytes (the same space `v8-to-istanbul`/`c8`
329/// use). For ASCII-only output the two coincide, but a single non-ASCII char
330/// earlier in the file (a Unicode `.bynk` string literal carried into the `.js`)
331/// shifts every later byte offset relative to V8's counting, which would select
332/// the wrong range. So offsets are accumulated in UTF-16 units to match.
333fn line_representatives(text: &str) -> Vec<Option<usize>> {
334    let mut out = Vec::new();
335    let mut u16_off = 0usize;
336    for line in text.split_inclusive('\n') {
337        let mut rep = None;
338        let mut o = u16_off;
339        for c in line.chars() {
340            if c.is_whitespace() {
341                o += c.len_utf16();
342            } else {
343                rep = Some(o);
344                break;
345            }
346        }
347        if let Some(start) = rep {
348            let rest = line.trim_start();
349            if let Some(after) = rest.strip_prefix("export ")
350                && !after.trim().is_empty()
351            {
352                // `export ` and the spaces after it are ASCII, so the bytes
353                // skipped are as many UTF-16 units.
354                rep = Some(start + rest.len() - after.trim_start().len());
355            }
356        }
357        out.push(rep);
358        u16_off += line.chars().map(char::len_utf16).sum::<usize>();
359    }
360    out
361}
362
363/// Whether an emitted `out-js`-relative path is a file we measure: not the
364/// `tests/` tree, not the `workers/` scaffold, not the shared runtime, and a
365/// `.js` module (DECISION D).
366fn is_measurable_emitted(rel: &Path) -> bool {
367    if rel.extension().and_then(|e| e.to_str()) != Some("js") {
368        return false;
369    }
370    let mut comps = rel.components();
371    match comps.next() {
372        Some(Component::Normal(c)) if c == "tests" || c == "workers" => return false,
373        _ => {}
374    }
375    // The runtime helpers are framework code, never user source.
376    if rel == Path::new("runtime.js") {
377        return false;
378    }
379    true
380}
381
382/// Relativise an absolute `.bynk` source path against the project root, forward-
383/// slashed. Falls back to the file name, then the path verbatim, so an
384/// out-of-tree source (a synthetic unit) still renders something legible.
385///
386/// `canonical_root` is `source_root` canonicalised (#2104): a relative root
387/// (`bynk test .`) never prefixes an absolute map source, which collapsed
388/// `src/window.bynk` to `window.bynk`, so the absolute form is tried too.
389fn relativise(abs: &str, source_root: &Path, canonical_root: Option<&Path>) -> String {
390    let p = Path::new(abs);
391    for root in std::iter::once(source_root).chain(canonical_root) {
392        if let Ok(rel) = p.strip_prefix(root) {
393            return forward_slash(rel);
394        }
395    }
396    // The map source is stored forward-slashed absolute; the root may be a
397    // different textual form of the same dir. Fall back to the file name.
398    p.file_name()
399        .map(|n| n.to_string_lossy().into_owned())
400        .unwrap_or_else(|| abs.to_string())
401}
402
403fn forward_slash(p: &Path) -> String {
404    p.components()
405        .filter_map(|c| match c {
406            Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
407            _ => None,
408        })
409        .collect::<Vec<_>>()
410        .join("/")
411}
412
413/// Convert a `file://` URL to a filesystem path, minimally percent-decoding.
414/// Returns `None` for a non-`file:` URL (e.g. `node:internal/...`).
415fn file_url_to_path(url: &str) -> Option<PathBuf> {
416    let rest = url.strip_prefix("file://")?;
417    // `file:///abs` → `/abs`; a host part is not expected for local coverage.
418    let path = rest
419        .strip_prefix('/')
420        .map(|r| format!("/{r}"))
421        .unwrap_or_else(|| rest.to_string());
422    Some(PathBuf::from(percent_decode(&path)))
423}
424
425/// Minimal `%XX` percent-decoding — enough for paths with spaces in a temp dir.
426fn percent_decode(s: &str) -> String {
427    let bytes = s.as_bytes();
428    let mut out = Vec::with_capacity(bytes.len());
429    let mut i = 0;
430    while i < bytes.len() {
431        if bytes[i] == b'%' && i + 2 < bytes.len() {
432            let hi = (bytes[i + 1] as char).to_digit(16);
433            let lo = (bytes[i + 2] as char).to_digit(16);
434            if let (Some(h), Some(l)) = (hi, lo) {
435                out.push((h * 16 + l) as u8);
436                i += 3;
437                continue;
438            }
439        }
440        out.push(bytes[i]);
441        i += 1;
442    }
443    String::from_utf8_lossy(&out).into_owned()
444}
445
446/// Append `.ext` to a path's file name (`foo.js` + `map` → `foo.js.map`), unlike
447/// [`Path::with_extension`] which would replace `js`.
448fn append_ext(path: &Path, ext: &str) -> PathBuf {
449    let mut name = path
450        .file_name()
451        .map(|n| n.to_os_string())
452        .unwrap_or_default();
453    name.push(".");
454    name.push(ext);
455    path.with_file_name(name)
456}
457
458// -- Source-map v3 (the subset needed for line attribution) --
459
460/// A decoded source-map: its `sources` list and, per generated line (0-based),
461/// the segments on that line as `(source_index, source_line_0based)`. Generated
462/// and source columns are decoded to keep the VLQ deltas honest, then dropped —
463/// attribution is line-level on both hops.
464struct SourceMap {
465    sources: Vec<String>,
466    lines: Vec<Vec<(usize, u32)>>,
467}
468
469impl SourceMap {
470    fn parse(json: &str) -> Option<SourceMap> {
471        #[derive(Deserialize)]
472        struct Raw {
473            #[serde(default)]
474            sources: Vec<String>,
475            #[serde(default)]
476            mappings: String,
477        }
478        let raw: Raw = serde_json::from_str(json).ok()?;
479        Some(SourceMap {
480            sources: raw.sources,
481            lines: decode_line_mappings(&raw.mappings),
482        })
483    }
484}
485
486/// Decode a v3 `mappings` string into, per generated line, its `(src_idx,
487/// src_line)` segments (both 0-based). Follows the VLQ delta rules: the source
488/// index/line/column deltas persist across segments *and* lines; the generated
489/// column resets at each line boundary. A one-field segment (generated column
490/// only, no source) carries no attribution and is skipped.
491fn decode_line_mappings(mappings: &str) -> Vec<Vec<(usize, u32)>> {
492    let mut lines = Vec::new();
493    // Source index and source line are independent running totals that persist
494    // across segments and lines (the source column would be a third, but line
495    // attribution never needs it). The generated column resets each line and is
496    // irrelevant here, so it is decoded but discarded.
497    let (mut src, mut src_line) = (0i64, 0i64);
498    for seg_line in mappings.split(';') {
499        let mut segs = Vec::new();
500        for seg in seg_line.split(',') {
501            if seg.is_empty() {
502                continue;
503            }
504            let fields = vlq_decode(seg);
505            if fields.len() >= 4 {
506                src += fields[1];
507                src_line += fields[2];
508                if src >= 0 && src_line >= 0 {
509                    segs.push((src as usize, src_line as u32));
510                }
511            }
512        }
513        lines.push(segs);
514    }
515    lines
516}
517
518/// Base64-VLQ-decode one segment into its signed fields.
519fn vlq_decode(seg: &str) -> Vec<i64> {
520    const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
521    let mut out = Vec::new();
522    let (mut shift, mut acc) = (0u32, 0i64);
523    for &c in seg.as_bytes() {
524        let Some(d) = B64.iter().position(|&b| b == c).map(|p| p as i64) else {
525            continue;
526        };
527        acc += (d & 0b11111) << shift;
528        if d & 0b100000 != 0 {
529            shift += 5;
530        } else {
531            let value = if acc & 1 == 1 { -(acc >> 1) } else { acc >> 1 };
532            out.push(value);
533            shift = 0;
534            acc = 0;
535        }
536    }
537    out
538}
539
540// -- Rich rendering --
541
542/// Render the human coverage summary — a per-file bar, percentage, covered/total
543/// line count, and the uncovered-line ranges — plus a total row. Trailing
544/// newline. An empty report renders a single "no coverage attributed" note.
545pub fn render_rich(report: &CoverageReport) -> String {
546    let mut out = String::new();
547    out.push_str("\nCoverage\n");
548    if report.is_empty() {
549        out.push_str("  (no executable `.bynk` lines were attributed)\n");
550        return out;
551    }
552    let name_w = report
553        .files
554        .iter()
555        .map(|f| f.path.len())
556        .max()
557        .unwrap_or(0)
558        .max(5);
559    for f in &report.files {
560        let pct = percent(f.covered, f.total);
561        out.push_str(&format!(
562            "  {:<name_w$}  {}  {:>3}%   ({}/{} lines)",
563            f.path,
564            bar(f.covered, f.total),
565            pct,
566            f.covered,
567            f.total,
568        ));
569        if !f.uncovered.is_empty() {
570            out.push_str(&format!("  uncovered: {}", format_ranges(&f.uncovered)));
571        }
572        out.push('\n');
573    }
574    let dashes = "─".repeat(name_w + 24);
575    out.push_str(&format!("  {dashes}\n"));
576    out.push_str(&format!(
577        "  {:<name_w$}  {}  {:>3}%   ({}/{} lines)\n",
578        "total",
579        bar(report.total_covered(), report.total_lines()),
580        report.total_percent(),
581        report.total_covered(),
582        report.total_lines(),
583    ));
584    out
585}
586
587/// An 8-cell coverage bar: filled `▓` proportional to the covered fraction, the
588/// remainder `·`.
589fn bar(covered: u32, total: u32) -> String {
590    const CELLS: u32 = 8;
591    let filled = if total == 0 {
592        CELLS
593    } else {
594        (covered as u64 * CELLS as u64 / total as u64) as u32
595    };
596    let mut s = String::new();
597    for _ in 0..filled {
598        s.push('▓');
599    }
600    for _ in filled..CELLS {
601        s.push('·');
602    }
603    s
604}
605
606/// Compress a sorted line list into comma-separated ranges: `[6,7,8,51]` →
607/// `"6-8, 51"`.
608pub fn format_ranges(lines: &[u32]) -> String {
609    let mut parts = Vec::new();
610    let mut i = 0;
611    while i < lines.len() {
612        let start = lines[i];
613        let mut end = start;
614        while i + 1 < lines.len() && lines[i + 1] == end + 1 {
615            end += 1;
616            i += 1;
617        }
618        if start == end {
619            parts.push(format!("{start}"));
620        } else {
621            parts.push(format!("{start}-{end}"));
622        }
623        i += 1;
624    }
625    parts.join(", ")
626}
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631
632    #[test]
633    fn a_relative_root_still_relativises_through_its_canonical_form() {
634        // #2104: `bynk test .` hands a relative root; the map's sources are
635        // absolute, so only the canonical root prefixes them.
636        let abs = "/work/shop/src/window.bynk";
637        assert_eq!(
638            relativise(abs, Path::new("."), Some(Path::new("/work/shop"))),
639            "src/window.bynk"
640        );
641        assert_eq!(
642            relativise(abs, Path::new("/work/shop"), None),
643            "src/window.bynk"
644        );
645        // Outside the root: the file name, as before.
646        assert_eq!(
647            relativise(abs, Path::new("."), Some(Path::new("/elsewhere"))),
648            "window.bynk"
649        );
650    }
651
652    #[test]
653    fn vlq_decodes_signed_fields() {
654        // "AAAA" → [0,0,0,0]; "AAEA" → [0,0,2,0]; "AACE" → [0,0,1,2]; "D" → [-1].
655        assert_eq!(vlq_decode("AAAA"), vec![0, 0, 0, 0]);
656        assert_eq!(vlq_decode("AAEA"), vec![0, 0, 2, 0]);
657        assert_eq!(vlq_decode("AACE"), vec![0, 0, 1, 2]);
658        assert_eq!(vlq_decode("D"), vec![-1]);
659    }
660
661    #[test]
662    fn line_mappings_track_running_source_line() {
663        // The emitter's `.ts.map` for the two-fn spike: 5 blank lines, then
664        // src lines 2,3,3,6,7,8 (0-based) — running deltas across lines.
665        let m = ";;;;;AAEA;AACE;AAAA;AAGF;AACE;AACA";
666        let lines = decode_line_mappings(m);
667        assert_eq!(lines[0], vec![]);
668        assert_eq!(lines[5], vec![(0, 2)]);
669        assert_eq!(lines[6], vec![(0, 3)]);
670        assert_eq!(lines[7], vec![(0, 3)]);
671        assert_eq!(lines[8], vec![(0, 6)]);
672        assert_eq!(lines[9], vec![(0, 7)]);
673        assert_eq!(lines[10], vec![(0, 8)]);
674    }
675
676    #[test]
677    fn innermost_range_prefers_the_tightest_span() {
678        // A module range (count 1) with a nested uncalled-fn range (count 0):
679        // a position inside the fn is uncovered, one outside it is covered.
680        let ranges = vec![
681            V8Range {
682                start: 0,
683                end: 100,
684                count: 1,
685            },
686            V8Range {
687                start: 40,
688                end: 60,
689                count: 0,
690            },
691        ];
692        assert_eq!(innermost_range(10, &ranges), Some((100, 1)));
693        assert_eq!(innermost_range(50, &ranges), Some((20, 0)));
694        assert_eq!(innermost_range(200, &ranges), None); // outside every range
695    }
696
697    #[test]
698    fn file_acc_lets_the_tightest_range_decide() {
699        // The hoisted-export hazard: a `.bynk` line reached both by a wide
700        // module range that ran (the `exports.f = f;` line) and a tight function
701        // range that did not (the never-called body). The tight range wins →
702        // uncovered, not falsely covered.
703        let mut acc = FileAcc::default();
704        acc.observe(7, 352, 1); // module-level hoisted export, executed
705        acc.observe(7, 61, 0); // the function body's own range, never run
706        assert_eq!(acc.lines.get(&7), Some(&(61, 0)));
707    }
708
709    #[test]
710    fn line_representatives_pick_first_nonspace() {
711        let reps = line_representatives("ab\n    cd\n\n  \nx");
712        assert_eq!(reps[0], Some(0)); // "ab"
713        assert_eq!(reps[1], Some(7)); // "    cd" → 'c' at 3+4
714        assert_eq!(reps[2], None); // blank
715        assert_eq!(reps[3], None); // whitespace-only
716        assert_eq!(reps[4], Some(14)); // "x"
717    }
718
719    #[test]
720    fn line_representatives_skip_a_leading_export() {
721        // #2146: an ES module's `export function f() {` samples at `function`,
722        // where V8's range for `f` starts, not at `export` (the module range).
723        let reps = line_representatives("export function f() {\n  export  const x = 1;\nexport\n");
724        assert_eq!(reps[0], Some(7)); // "function"
725        assert_eq!(reps[1], Some(32)); // 22 + 2 indent + "export  " → 'c'
726        assert_eq!(reps[2], Some(45)); // a bare `export` keeps its own offset
727    }
728
729    #[test]
730    fn line_representatives_count_utf16_units_not_bytes() {
731        // An em-dash (`—`, U+2014: 3 UTF-8 bytes, 1 UTF-16 unit) on line 0 must
732        // not shift line 1's offset — V8 counts UTF-16 units, so a byte-based
733        // accumulator would report 9 (7 + 2) here and mis-sample the ranges.
734        let reps = line_representatives("a — b\nx");
735        assert_eq!(reps[0], Some(0)); // "a — b"
736        // "a — b\n" = 6 UTF-16 units (byte length would be 8: '—' is 3 bytes).
737        assert_eq!(reps[1], Some(6)); // "x" at UTF-16 offset 6, not byte 8
738        // An astral char (`🎉`, 2 UTF-16 units) shifts by 2, matching V8.
739        let reps = line_representatives("🎉\ny");
740        assert_eq!(reps[0], Some(0));
741        assert_eq!(reps[1], Some(3)); // 🎉(2) + '\n'(1) = 3
742    }
743
744    #[test]
745    fn format_ranges_compresses_runs() {
746        assert_eq!(format_ranges(&[6, 7, 8, 51]), "6-8, 51");
747        assert_eq!(format_ranges(&[3]), "3");
748        assert_eq!(format_ranges(&[1, 2, 4, 5, 6]), "1-2, 4-6");
749        assert_eq!(format_ranges(&[]), "");
750    }
751
752    #[test]
753    fn percent_rounds_and_guards_zero() {
754        assert_eq!(percent(0, 0), 100);
755        assert_eq!(percent(42, 49), 86);
756        assert_eq!(percent(2, 5), 40);
757        assert_eq!(percent(11, 11), 100);
758    }
759
760    #[test]
761    fn percent_never_reports_100_for_an_incomplete_run() {
762        // Round-half-up would give 100 here; a run with any uncovered line must
763        // read at most 99 so the table and the JSON `percent` never falsely green.
764        assert_eq!(percent(995, 1000), 99);
765        assert_eq!(percent(199, 200), 99);
766        assert_eq!(percent(1000, 1000), 100); // genuinely complete
767        assert_eq!(percent(0, 5), 0);
768    }
769
770    #[test]
771    fn measurable_filter_drops_tests_workers_runtime() {
772        assert!(is_measurable_emitted(Path::new("src/limiter.js")));
773        assert!(is_measurable_emitted(Path::new("limiter.js")));
774        assert!(!is_measurable_emitted(Path::new("tests/main.js")));
775        assert!(!is_measurable_emitted(Path::new("workers/api/handlers.js")));
776        assert!(!is_measurable_emitted(Path::new("runtime.js")));
777        assert!(!is_measurable_emitted(Path::new("src/limiter.js.map")));
778    }
779
780    #[test]
781    fn file_url_round_trips_to_path() {
782        assert_eq!(
783            file_url_to_path("file:///private/tmp/a%20b/out-js/m.js"),
784            Some(PathBuf::from("/private/tmp/a b/out-js/m.js"))
785        );
786        assert_eq!(file_url_to_path("node:internal/modules"), None);
787    }
788}