Skip to main content

brrrty_node/
stack.rs

1//! Where a JavaScript error happened, from V8's stack text: the first frame
2//! inside the project and outside `node_modules`, else the first frame.
3
4use std::path::{Path, PathBuf};
5
6/// One stack frame's place.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct Frame {
9    pub file: PathBuf,
10    pub line: u32,
11    pub column: Option<u32>,
12}
13
14/// The frames of `stack`, in order, that name a file. Forms read:
15/// `at fn (file:///abs/x.js:14:9)`, `at file:///abs/x.js:14:9`,
16/// `at /abs/x.js:14:9`, `at fn (/abs/x.js:14:9)`, `at async fn (...)`.
17pub fn frames(stack: &str) -> Vec<Frame> {
18    stack
19        .lines()
20        .filter_map(|l| l.trim().strip_prefix("at "))
21        .filter_map(|rest| {
22            // The place is inside the last parentheses, or is the rest.
23            let place = match (rest.rfind('('), rest.ends_with(')')) {
24                (Some(open), true) => &rest[open + 1..rest.len() - 1],
25                _ => rest,
26            };
27            place_of(place, true)
28        })
29        .collect()
30}
31
32/// `file:///abs/x.js:14:9` or `/abs/x.js:14:9`; the column is optional
33/// unless `need_column`.
34fn place_of(text: &str, need_column: bool) -> Option<Frame> {
35    let path_text = |p: &str| -> Option<PathBuf> {
36        if let Some(rest) = p.strip_prefix("file://") {
37            let decoded = percent_decode(rest.split('?').next().unwrap_or(rest));
38            Some(PathBuf::from(decoded))
39        } else if p.starts_with('/') {
40            Some(PathBuf::from(p))
41        } else {
42            None
43        }
44    };
45    let (head, last) = text.rsplit_once(':')?;
46    let last: u32 = last.parse().ok()?;
47    if let Some((file, line)) = head.rsplit_once(':')
48        && let Ok(line) = line.parse::<u32>()
49        && let Some(file) = path_text(file)
50    {
51        return Some(Frame {
52            file,
53            line,
54            column: Some(last),
55        });
56    }
57    if need_column {
58        return None;
59    }
60    Some(Frame {
61        file: path_text(head)?,
62        line: last,
63        column: None,
64    })
65}
66
67/// A SyntaxError's place, from the first line of `util.inspect(error)`:
68/// `file:///abs/x.mjs:3` (ES modules) or `/abs/x.js:3` (CommonJS).
69pub fn syntax_header(inspect: &str) -> Option<Frame> {
70    let first = inspect.lines().next()?.trim();
71    if first.contains(' ') {
72        return None;
73    }
74    place_of(first, false)
75}
76
77/// The frame to report: the first inside `root` and outside `node_modules`,
78/// else the first.
79pub fn pick(frames: &[Frame], root: &Path) -> Option<Frame> {
80    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
81    frames
82        .iter()
83        .find(|f| {
84            let file = f.file.canonicalize().unwrap_or_else(|_| f.file.clone());
85            file.starts_with(&root) && !file.components().any(|c| c.as_os_str() == "node_modules")
86        })
87        .or_else(|| frames.first())
88        .cloned()
89}
90
91fn percent_decode(s: &str) -> String {
92    let bytes = s.as_bytes();
93    let mut out = Vec::with_capacity(bytes.len());
94    let mut i = 0;
95    while i < bytes.len() {
96        if bytes[i] == b'%'
97            && i + 2 < bytes.len()
98            && bytes[i + 1].is_ascii_hexdigit()
99            && bytes[i + 2].is_ascii_hexdigit()
100            && let Ok(hex) = std::str::from_utf8(&bytes[i + 1..i + 3])
101            && let Ok(b) = u8::from_str_radix(hex, 16)
102        {
103            out.push(b);
104            i += 3;
105            continue;
106        }
107        out.push(bytes[i]);
108        i += 1;
109    }
110    String::from_utf8_lossy(&out).into_owned()
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    fn f(file: &str, line: u32, column: Option<u32>) -> Frame {
118        Frame {
119            file: file.into(),
120            line,
121            column,
122        }
123    }
124
125    #[test]
126    fn a_percent_before_a_multibyte_character_is_kept() {
127        assert_eq!(percent_decode("x%a\u{e9}y%41"), "x%a\u{e9}yA");
128        assert_eq!(percent_decode("%\u{e9}"), "%\u{e9}");
129        assert_eq!(frames("at file:///x%a\u{e9}:1:1").len(), 1);
130    }
131
132    #[test]
133    fn every_frame_form_is_read() {
134        let stack = "TypeError: x\n    at fn (file:///abs/a%20b.js:14:9)\n    at file:///abs/c.mjs:2:3\n    at /abs/d.js:4:5\n    at g (/abs/e.cjs:6:7)\n    at async Promise.all (index 0)\n    at node:internal/modules/esm/loader:1:1\n    at async h (file:///abs/f.js?x=1:8:9)";
135        assert_eq!(
136            frames(stack),
137            vec![
138                f("/abs/a b.js", 14, Some(9)),
139                f("/abs/c.mjs", 2, Some(3)),
140                f("/abs/d.js", 4, Some(5)),
141                f("/abs/e.cjs", 6, Some(7)),
142                f("/abs/f.js", 8, Some(9)),
143            ]
144        );
145    }
146
147    #[test]
148    fn syntax_error_headers_are_read() {
149        assert_eq!(
150            syntax_header("file:///abs/x.mjs:3\nexport default {\n^\n\nSyntaxError: ..."),
151            Some(f("/abs/x.mjs", 3, None))
152        );
153        assert_eq!(
154            syntax_header("/abs/x.js:3\n}}\n^"),
155            Some(f("/abs/x.js", 3, None))
156        );
157        assert_eq!(syntax_header("SyntaxError: Unexpected token"), None);
158    }
159
160    #[test]
161    fn the_first_project_frame_outside_node_modules_wins() {
162        let t = tempfile::tempdir().unwrap();
163        let root = t.path().canonicalize().unwrap();
164        let in_nm = root.join("node_modules/lib/index.js");
165        let mine = root.join("src/_data/x.js");
166        let outside = PathBuf::from("/elsewhere/y.js");
167        let list = vec![
168            Frame {
169                file: outside.clone(),
170                line: 1,
171                column: Some(1),
172            },
173            Frame {
174                file: in_nm,
175                line: 2,
176                column: Some(2),
177            },
178            Frame {
179                file: mine.clone(),
180                line: 3,
181                column: Some(3),
182            },
183        ];
184        assert_eq!(pick(&list, &root).unwrap().file, mine);
185        assert_eq!(pick(&list[..2], &root).unwrap().file, outside);
186        assert_eq!(pick(&[], &root), None);
187    }
188}