Debian Codegraph @

packages/babel-parser/test/helpers/to-contextual-syntax-error.js

raw
1 import { codeFrameColumns } from "@babel/code-frame";
2 import { runInThisContext } from "vm";
3
4 export default function toContextualSyntaxError(
5 error,
6 source,
7 filename,
8 options,
9 ) {
10 if (!(error instanceof SyntaxError)) return error;
11
12 const { startLine = 1, startColumn = 0 } = options || {};
13 const line = error.loc.line - startLine + 1;
14 const column =
15 1 + (line === 1 ? error.loc.column - startColumn : error.loc.column);
16 const frame = codeFrameColumns(
17 source,
18 { start: { line, column } },
19 { highlightCode: true },
20 );
21
22 // We make this a lazy property since we don't want pay the price of creating
23 // this new error unless we are going to display it.
24 Object.defineProperty(error, "context", {
25 get() {
26 const message = JSON.stringify(`${error.message}\n${frame}`);
27 const originalStackTraceLimit = Error.stackTraceLimit;
28
29 // Limit this stack trace to 1. Everything after that is just stuff from
30 // the test.
31 Error.stackTraceLimit = 1;
32
33 // The only way to manipulate the file in which a SyntaxError reports it
34 // is coming from is to roundtrip through vm.runInThisContext. If v8
35 // supported Firefox's non-standard Error.fileName property, that could be
36 // used instead, but unfortunately it does not.
37 const context = runInThisContext(`SyntaxError(${message})`, { filename });
38
39 Error.stackTraceLimit = originalStackTraceLimit;
40
41 return Object.assign(context, { cause: this });
42 },
43 });
44
45 return error;
46 }