Skip to main content

tokencompact_builtins/diagnostics/
javascript.rs

1use std::collections::BTreeSet;
2
3use crate::{Diagnostic, DiagnosticClass, Location, Severity};
4
5use super::common::{bounded_text, normalize_path};
6
7#[derive(Debug, Default)]
8pub(crate) struct SwcParseOutput {
9    pub(crate) diagnostics: Vec<Diagnostic>,
10    pub(crate) consumed_lines: BTreeSet<String>,
11}
12
13pub(super) fn reduce_swc(input: &str, output: &mut SwcParseOutput) {
14    *output = parse_swc_diagnostics(input);
15}
16
17pub(crate) fn parse_swc_diagnostics(input: &str) -> SwcParseOutput {
18    const MAX_HEADER_DISTANCE: usize = 3;
19    const MAX_FRAME_LINES: usize = 8;
20
21    let lines = input.lines().collect::<Vec<_>>();
22    let mut output = SwcParseOutput::default();
23    for (location_index, line) in lines.iter().enumerate() {
24        let Some(location) = parse_swc_source_frame_location(line) else {
25            continue;
26        };
27        let Some((header_index, severity, message)) = lines[..location_index]
28            .iter()
29            .enumerate()
30            .rev()
31            .take(MAX_HEADER_DISTANCE)
32            .find_map(|(index, line)| {
33                parse_swc_message_header(line).map(|(severity, message)| (index, severity, message))
34            })
35        else {
36            continue;
37        };
38
39        let mut frame_end = location_index;
40        let mut source_line = None;
41        let mut first_source_line = None;
42        let mut caret_line = None;
43        for (index, frame_line) in lines
44            .iter()
45            .enumerate()
46            .skip(location_index + 1)
47            .take(MAX_FRAME_LINES)
48        {
49            if parse_swc_message_header(frame_line).is_some()
50                || parse_swc_source_frame_location(frame_line).is_some()
51            {
52                break;
53            }
54            frame_end = index;
55            output.consumed_lines.insert(frame_line.trim().to_owned());
56            if let Some(line_number) = swc_source_line_number(frame_line) {
57                let bounded = bounded_text(frame_line.trim(), 256);
58                first_source_line.get_or_insert_with(|| bounded.clone());
59                if location.line == Some(line_number) {
60                    source_line = Some(bounded);
61                }
62            } else if caret_line.is_none() && is_swc_caret_line(frame_line) {
63                caret_line = Some(bounded_text(frame_line.trim(), 256));
64            }
65            if is_swc_frame_terminator(frame_line) {
66                break;
67            }
68        }
69
70        output
71            .consumed_lines
72            .insert(lines[header_index].trim().to_owned());
73        output
74            .consumed_lines
75            .insert(lines[location_index].trim().to_owned());
76        let (context, context_lines) = swc_failure_context(&lines, header_index, frame_end);
77        for context_line in context_lines {
78            output
79                .consumed_lines
80                .insert(lines[context_line].trim().to_owned());
81        }
82
83        let mut message = bounded_text(message, 1_024);
84        if let Some(context) = context {
85            message.push_str("\nSWC context: ");
86            message.push_str(&bounded_text(&context, 512));
87        }
88        if let Some(source_line) = source_line.or(first_source_line) {
89            message.push('\n');
90            message.push_str(&source_line);
91        }
92        if let Some(caret_line) = caret_line {
93            message.push('\n');
94            message.push_str(&caret_line);
95        }
96        output.diagnostics.push(Diagnostic {
97            severity,
98            class: DiagnosticClass::Compiler,
99            code: Some("swc.parser".to_owned()),
100            provenance: None,
101            message,
102            location: Some(location),
103            quality: crate::EvidenceQuality::Located,
104            repetition_count: 1,
105        });
106    }
107    output
108}
109
110fn parse_swc_message_header(line: &str) -> Option<(Severity, &str)> {
111    let line = line.trim();
112    let (severity, message) = if let Some(message) = line.strip_prefix("error:") {
113        (Severity::Error, message)
114    } else if let Some(message) = line.strip_prefix("warning:") {
115        (Severity::Warning, message)
116    } else if let Some(message) = strip_swc_icon(line, 'x').or_else(|| strip_swc_icon(line, '×')) {
117        (Severity::Error, message)
118    } else {
119        (Severity::Warning, strip_swc_icon(line, '!')?)
120    };
121    let message = message.trim();
122    (!message.is_empty()).then_some((severity, message))
123}
124
125fn strip_swc_icon(line: &str, icon: char) -> Option<&str> {
126    let remainder = line.strip_prefix(icon)?;
127    remainder
128        .chars()
129        .next()
130        .is_some_and(char::is_whitespace)
131        .then(|| remainder.trim_start())
132}
133
134fn parse_swc_source_frame_location(line: &str) -> Option<Location> {
135    let line = line.trim();
136    let opening = line.find('[')?;
137    let marker = line[..opening].trim_end();
138    if !marker.ends_with(",-") && !marker.ends_with("╭─") {
139        return None;
140    }
141    let closing = line[opening + 1..].find(']')? + opening + 1;
142    let coordinates = &line[opening + 1..closing];
143    let (path_and_line, column) = coordinates.rsplit_once(':')?;
144    let (path, line_number) = path_and_line.rsplit_once(':')?;
145    if path.trim().is_empty() {
146        return None;
147    }
148    Some(Location {
149        path: compact_path(path.trim()),
150        line: Some(line_number.parse::<u32>().ok()?),
151        column: Some(column.parse::<u32>().ok()?),
152    })
153}
154
155fn swc_source_line_number(line: &str) -> Option<u32> {
156    let line = line.trim();
157    let (line_number, _) = line.split_once('|').or_else(|| line.split_once('│'))?;
158    let line_number = line_number.trim();
159    (!line_number.is_empty() && line_number.bytes().all(|byte| byte.is_ascii_digit()))
160        .then(|| line_number.parse::<u32>().ok())
161        .flatten()
162}
163
164fn is_swc_caret_line(line: &str) -> bool {
165    let line = line.trim();
166    line.contains('^')
167        && (line.starts_with(':')
168            || line
169                .split_once('|')
170                .is_some_and(|(prefix, _)| prefix.trim().is_empty()))
171}
172
173fn is_swc_frame_terminator(line: &str) -> bool {
174    let line = line.trim();
175    (line.starts_with('`') && line.contains("---")) || (line.starts_with('╰') && line.contains('─'))
176}
177
178fn swc_failure_context(
179    lines: &[&str],
180    header_index: usize,
181    frame_end: usize,
182) -> (Option<String>, Vec<usize>) {
183    const MAX_CONTEXT_DISTANCE: usize = 12;
184    const MAX_CONTEXT_ITEMS: usize = 2;
185
186    let mut contexts = Vec::new();
187    let mut consumed = Vec::new();
188    let preceding_start = header_index.saturating_sub(MAX_CONTEXT_DISTANCE);
189    for (index, line) in lines
190        .iter()
191        .enumerate()
192        .take(header_index)
193        .skip(preceding_start)
194    {
195        if let Some(context) = parse_swc_context_line(line)
196            && !contexts.contains(&context)
197        {
198            contexts.push(context);
199            consumed.push(index);
200        }
201        if contexts.len() >= MAX_CONTEXT_ITEMS {
202            break;
203        }
204    }
205    for (index, line) in lines
206        .iter()
207        .enumerate()
208        .skip(frame_end + 1)
209        .take(MAX_CONTEXT_DISTANCE)
210    {
211        if parse_swc_message_header(line).is_some()
212            || parse_swc_source_frame_location(line).is_some()
213        {
214            break;
215        }
216        if let Some(context) = parse_swc_context_line(line)
217            && !contexts.contains(&context)
218        {
219            contexts.push(context);
220            consumed.push(index);
221        }
222        if contexts.len() >= MAX_CONTEXT_ITEMS {
223            break;
224        }
225    }
226    contexts.truncate(MAX_CONTEXT_ITEMS);
227    (
228        (!contexts.is_empty()).then(|| contexts.join("; ")),
229        consumed,
230    )
231}
232
233fn parse_swc_context_line(line: &str) -> Option<String> {
234    if parse_swc_message_header(line).is_some() {
235        return None;
236    }
237    let mut line = line.trim();
238    if let Some(remainder) = line.strip_prefix("Caused by:") {
239        line = remainder.trim();
240    }
241    if let Some((number, remainder)) = line.split_once(": ")
242        && !number.is_empty()
243        && number.bytes().all(|byte| byte.is_ascii_digit())
244    {
245        line = remainder.trim();
246    }
247    let lower = line.to_ascii_lowercase();
248    let is_context = lower.starts_with("failed to process")
249        || lower.starts_with("failed to parse")
250        || lower.starts_with("failed to transform")
251        || lower.starts_with("failed to invoke plugin")
252        || lower.starts_with("failed to handle")
253        || (lower.contains("plugin") && lower.contains("failed"));
254    (is_context && !line.is_empty()).then(|| line.to_owned())
255}
256
257pub(super) fn is_swc_action_wrapper(line: &str) -> bool {
258    let line = line.trim();
259    let lower = line.to_ascii_lowercase();
260    line.starts_with("ERROR:")
261        && (lower.contains("build did not complete successfully")
262            || lower.contains("failed: error executing")
263            || (lower.contains("swc")
264                && (lower.contains("failed:") || lower.contains("action failed"))))
265}
266
267pub(super) fn reduce_tests(
268    input: &str,
269    diagnostics: &mut Vec<Diagnostic>,
270    messages: &mut BTreeSet<String>,
271) {
272    let mut parser = JavaScriptTestDiagnosticParser::default();
273    for line in input.lines() {
274        if let Some(diagnostic) = parser.observe_line(line) {
275            messages.insert(diagnostic.message.clone());
276            diagnostics.push(diagnostic);
277        }
278    }
279    if let Some(diagnostic) = parser.finish() {
280        messages.insert(diagnostic.message.clone());
281        diagnostics.push(diagnostic);
282    }
283}
284
285/// Stateful extractor for Node.js exceptions and their application frames.
286#[derive(Debug, Default)]
287pub struct JavaScriptTestDiagnosticParser {
288    leading_location: Option<Location>,
289    pending: Option<Diagnostic>,
290    frames_seen: usize,
291}
292
293impl JavaScriptTestDiagnosticParser {
294    const MAX_STACK_FRAMES: usize = 64;
295
296    /// Observes one normalized test-log line and emits an exception after a
297    /// JavaScript source header or application stack frame confirms it.
298    pub fn observe_line(&mut self, line: &str) -> Option<Diagnostic> {
299        if !line.trim_start().starts_with("at ")
300            && let Some(location) = parse_location(line.trim())
301        {
302            let previous = self.take_confirmed();
303            self.leading_location = Some(location);
304            return previous;
305        }
306        if let Some(message) = exception_message(line) {
307            let leading_location = self.leading_location.take();
308            let previous = self.take_confirmed();
309            self.pending = Some(Diagnostic {
310                severity: Severity::Error,
311                class: DiagnosticClass::Test,
312                code: None,
313                provenance: None,
314                message: message.to_owned(),
315                location: leading_location,
316                quality: crate::EvidenceQuality::Structured,
317                repetition_count: 1,
318            });
319            self.frames_seen = 0;
320            return previous;
321        }
322        self.pending.as_ref()?;
323        if let Some(location) = parse_stack_frame(line) {
324            self.frames_seen = self.frames_seen.saturating_add(1);
325            if let Some(location) = location {
326                let mut diagnostic = self.pending.take()?;
327                diagnostic.location = Some(location);
328                self.frames_seen = 0;
329                return Some(diagnostic);
330            }
331            if self.frames_seen >= Self::MAX_STACK_FRAMES {
332                return self.take_confirmed();
333            }
334            return None;
335        }
336        if line.trim().is_empty() {
337            return None;
338        }
339        self.take_confirmed()
340    }
341
342    /// Emits a confirmed exception that reached end-of-file.
343    pub fn finish(&mut self) -> Option<Diagnostic> {
344        self.take_confirmed()
345    }
346
347    fn take_confirmed(&mut self) -> Option<Diagnostic> {
348        let confirmed = self
349            .pending
350            .as_ref()
351            .is_some_and(|diagnostic| diagnostic.location.is_some())
352            || self.frames_seen > 0;
353        self.frames_seen = 0;
354        self.leading_location = None;
355        if confirmed {
356            self.pending.take()
357        } else {
358            self.pending = None;
359            None
360        }
361    }
362}
363
364pub(super) fn exception_message(line: &str) -> Option<&str> {
365    let line = line.trim();
366    let exception_type = line.split_once(':').map_or(line, |(name, _)| name);
367    let class_name = exception_type.split_whitespace().next()?;
368    (!class_name.is_empty()
369        && class_name
370            .bytes()
371            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'$'))
372        && (class_name.ends_with("Error") || class_name.ends_with("Exception")))
373    .then_some(line)
374}
375
376fn parse_stack_frame(line: &str) -> Option<Option<Location>> {
377    let frame = line.trim().strip_prefix("at ")?;
378    let source = if let Some((_, source)) = frame.rsplit_once('(') {
379        source.strip_suffix(')')?
380    } else {
381        frame.split_whitespace().last()?
382    };
383    if source.starts_with("node:") || matches!(source, "native" | "<anonymous>") {
384        return Some(None);
385    }
386    let location = parse_location(source)?;
387    let framework = location.path.contains("/node_modules/")
388        || location.path.starts_with("node_modules/")
389        || location.path.contains("/external/");
390    Some((!framework).then_some(location))
391}
392
393fn parse_location(value: &str) -> Option<Location> {
394    let value = value.trim().trim_matches('"');
395    let path_end = path_end(value)?;
396    let coordinates = value[path_end..].strip_prefix(':')?;
397    let (line_number, column) = if let Some((line_number, column)) = coordinates.split_once(':') {
398        (
399            line_number.parse::<u32>().ok()?,
400            Some(column.parse::<u32>().ok()?),
401        )
402    } else {
403        (coordinates.parse::<u32>().ok()?, None)
404    };
405    Some(Location {
406        path: compact_path(&value[..path_end]),
407        line: Some(line_number),
408        column,
409    })
410}
411
412fn path_end(value: &str) -> Option<usize> {
413    const EXTENSIONS: [&str; 8] = [".tsx", ".mts", ".cts", ".ts", ".jsx", ".mjs", ".cjs", ".js"];
414    EXTENSIONS
415        .iter()
416        .filter_map(|extension| {
417            let marker = format!("{extension}:");
418            value.rfind(&marker).map(|index| index + extension.len())
419        })
420        .max()
421}
422
423pub(super) fn compact_path(path: &str) -> String {
424    let path = path
425        .trim_matches('"')
426        .strip_prefix("file://")
427        .unwrap_or(path)
428        .to_owned();
429    normalize_path(&path)
430}