apoc 0.9.1

Agentic process control for LLMs
Documentation
//! Source-map translation for breakpoints set on original sources.
//!
//! V8 addresses breakpoints by the URL of the script it actually loaded, so a
//! breakpoint on `src/app.ts` never binds while the target is running a compiled
//! `dist/app.js`. Translating the location here lets a caller keep addressing the
//! source it wrote.

use serde_json::Value;

/// Decodes one Base64 VLQ field, returning the value and the bytes consumed.
fn decode_vlq(input: &[u8]) -> Option<(i64, usize)> {
    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut result: i64 = 0;
    let mut shift = 0;
    for (index, byte) in input.iter().enumerate() {
        let digit = ALPHABET.iter().position(|candidate| candidate == byte)? as i64;
        let has_continuation = digit & 32 != 0;
        result += (digit & 31) << shift;
        shift += 5;
        if !has_continuation {
            let value = if result & 1 != 0 {
                -(result >> 1)
            } else {
                result >> 1
            };
            return Some((value, index + 1));
        }
        if shift > 60 {
            return None;
        }
    }
    None
}

/// One decoded mapping from a generated line to an original source line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Mapping {
    /// Zero-based line in the generated script.
    pub generated_line: u64,
    /// Index into the map's `sources` array.
    pub source_index: usize,
    /// Zero-based line in the original source.
    pub original_line: u64,
}

/// Decodes every segment of a source map's `mappings` string.
///
/// Segments carrying only a generated column describe generated code with no
/// original counterpart and are skipped, because they cannot answer where a
/// breakpoint on an original line belongs.
pub(crate) fn decode_mappings(mappings: &str) -> Vec<Mapping> {
    let mut decoded = Vec::new();
    let mut source_index: i64 = 0;
    let mut original_line: i64 = 0;
    for (generated_line, line) in mappings.split(';').enumerate() {
        for segment in line.split(',') {
            let segment = segment.as_bytes();
            if segment.is_empty() {
                continue;
            }
            let mut offset = 0;
            let mut fields = Vec::new();
            while offset < segment.len() {
                let Some((value, used)) = decode_vlq(&segment[offset..]) else {
                    fields.clear();
                    break;
                };
                fields.push(value);
                offset += used;
            }
            if fields.len() < 4 {
                continue;
            }
            source_index += fields[1];
            original_line += fields[2];
            if source_index < 0 || original_line < 0 {
                continue;
            }
            decoded.push(Mapping {
                generated_line: generated_line as u64,
                source_index: source_index as usize,
                original_line: original_line as u64,
            });
        }
    }
    decoded
}

/// Reports whether a mapped source path names the same file as a caller's path.
///
/// Map sources are recorded relative to the generated file (`../src/app.ts`)
/// while callers address their own tree (`src/app.ts`), so the comparison walks
/// whole path segments from the right and ignores `.` and `..` steps.
fn source_matches(mapped: &str, requested: &str) -> bool {
    let normalize = |path: &str| {
        path.split('/')
            .filter(|segment| !segment.is_empty() && *segment != "." && *segment != "..")
            .map(ToString::to_string)
            .collect::<Vec<_>>()
    };
    let mapped = normalize(mapped);
    let requested = normalize(requested);
    if mapped.is_empty() || requested.is_empty() {
        return false;
    }
    requested
        .iter()
        .rev()
        .zip(mapped.iter().rev())
        .all(|(requested, mapped)| requested == mapped)
}

/// Translates a one-based original source location into a generated line.
///
/// Returns the earliest generated line that the map attributes to the requested
/// original line, or to the next mapped line after it when that exact line
/// produced no code — the same forward slide a debugger applies to a breakpoint
/// placed on a blank or comment line.
pub(crate) fn generated_line_for(
    map: &Value,
    requested_source: &str,
    original_line: u64,
) -> Option<u64> {
    if original_line == 0 {
        return None;
    }
    let sources = map.get("sources")?.as_array()?;
    let matching = sources
        .iter()
        .enumerate()
        .filter(|(_, source)| {
            source
                .as_str()
                .is_some_and(|source| source_matches(source, requested_source))
        })
        .map(|(index, _)| index)
        .collect::<Vec<_>>();
    if matching.is_empty() {
        return None;
    }
    let mappings = decode_mappings(map.get("mappings")?.as_str()?);
    let target = original_line - 1;
    let mut best: Option<(u64, u64)> = None;
    for mapping in mappings {
        if !matching.contains(&mapping.source_index) || mapping.original_line < target {
            continue;
        }
        let candidate = (mapping.original_line, mapping.generated_line);
        best = Some(match best {
            Some(current) if current <= candidate => current,
            _ => candidate,
        });
    }
    best.map(|(_, generated_line)| generated_line + 1)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn decodes_base64_vlq_fields() {
        assert_eq!(decode_vlq(b"A"), Some((0, 1)));
        assert_eq!(decode_vlq(b"C"), Some((1, 1)));
        assert_eq!(decode_vlq(b"D"), Some((-1, 1)));
        assert_eq!(decode_vlq(b"gB"), Some((16, 2)));
        assert_eq!(decode_vlq(b"!"), None);
    }

    #[test]
    fn source_matching_compares_whole_segments_through_relative_steps() {
        assert!(source_matches("../src/app.ts", "src/app.ts"));
        assert!(source_matches("../src/app.ts", "app.ts"));
        assert!(source_matches("src/app.ts", "/repo/src/app.ts"));
        assert!(!source_matches("../other/app.ts", "src/app.ts"));
        assert!(!source_matches("../src/domain.ts", "app.ts"));
        assert!(!source_matches("", "src/app.ts"));
    }

    #[test]
    fn maps_a_real_esbuild_map_onto_its_generated_lines() {
        // Mappings emitted by esbuild for a TypeScript file. The expected
        // answers were read off the two files directly, not produced by this
        // decoder, so the test cannot agree with a wrong implementation.
        //   deep.ts:3  `function tax(...)`     -> deep.js:1
        //   deep.ts:4  `const rate = 0.07;`    -> deep.js:2
        //   deep.ts:5  `return amount * rate;` -> deep.js:3
        //   deep.ts:9  `const base = ...`      -> deep.js:6
        let map = serde_json::json!({
            "version": 3,
            "sources": ["../src/deep.ts"],
            "mappings": "AAEA,SAAS,IAAI,QAAwB;AACnC,QAAM,OAAO;AACb,SAAO,SAAS;AAClB;AAEA,SAAS,SAAS,MAAoB;AACpC,QAAM,OAAO,KAAK;AAClB,UAAQ,IAAI,aAAa,KAAK,EAAE;AAChC,QAAM,MAAM,IAAI,IAAI;AACpB,QAAM,MAAM,OAAO;AACnB,SAAO;AACT;AAEA,SAAS,OAAa;AACpB,QAAM,OAAa,EAAE,IAAI,GAAG,OAAO,CAAC,OAAO,GAAG,OAAO,IAAI;AACzD,QAAM,MAAM,SAAS,IAAI;AACzB,UAAQ,IAAI,OAAO,IAAI,QAAQ,CAAC,CAAC,EAAE;AACrC;AAEA,KAAK;"
        });
        assert_eq!(generated_line_for(&map, "src/deep.ts", 3), Some(1));
        assert_eq!(generated_line_for(&map, "src/deep.ts", 4), Some(2));
        assert_eq!(generated_line_for(&map, "src/deep.ts", 5), Some(3));
        assert_eq!(generated_line_for(&map, "src/deep.ts", 9), Some(6));
    }

    #[test]
    fn maps_an_original_line_onto_its_generated_line() {
        // One source, three mapped generated lines attributed to original
        // lines 0, 2 and 4 respectively.
        let map = serde_json::json!({
            "version": 3,
            "sources": ["../src/app.ts"],
            "mappings": "AAAA;AAEA;AAEA"
        });
        assert_eq!(generated_line_for(&map, "src/app.ts", 1), Some(1));
        assert_eq!(generated_line_for(&map, "src/app.ts", 3), Some(2));
        assert_eq!(generated_line_for(&map, "src/app.ts", 5), Some(3));
        // A line that produced no code slides forward to the next mapped line.
        assert_eq!(generated_line_for(&map, "src/app.ts", 2), Some(2));
        // Past the last mapping, and unknown sources, translate to nothing.
        assert_eq!(generated_line_for(&map, "src/app.ts", 9), None);
        assert_eq!(generated_line_for(&map, "src/other.ts", 1), None);
        assert_eq!(generated_line_for(&map, "src/app.ts", 0), None);
    }
}