|
1 | 1 | import { type StackTrace } from './types'; |
| 2 | +import { parse as parseStackTrace } from 'stacktrace-parser'; |
2 | 3 |
|
3 | 4 | export const getStackTrace = (): StackTrace => { |
4 | | - const oldStackTraceLimit = Error.stackTraceLimit; |
5 | | - const oldPrepareStackTrace = Error.prepareStackTrace; |
6 | | - |
7 | | - Error.prepareStackTrace = (error, structuredStackTrace) => { |
8 | | - return structuredStackTrace; |
9 | | - }; |
10 | | - |
11 | | - const honeypot: { stack: NodeJS.CallSite[] } = { |
12 | | - stack: [], |
13 | | - }; |
14 | | - |
15 | | - Error.captureStackTrace(honeypot); |
16 | | - |
17 | | - const callSites = honeypot.stack; |
18 | | - |
19 | | - Error.stackTraceLimit = oldStackTraceLimit; |
20 | | - Error.prepareStackTrace = oldPrepareStackTrace; |
21 | | - |
22 | | - const trail: readonly NodeJS.CallSite[] = callSites.slice(1); |
23 | | - |
24 | | - return { |
25 | | - callSites: trail.map((callSite) => { |
| 5 | + // The reason we are parsing the stack trace rather than |
| 6 | + // using captureStackTrace is because captureStackTrace |
| 7 | + // does not resolve source maps, i.e. the stack trace |
| 8 | + // will contain the compiled code references rather than |
| 9 | + // the original source code references. |
| 10 | + // |
| 11 | + // eslint-disable-next-line unicorn/error-message |
| 12 | + const stackTrace = new Error().stack; |
| 13 | + |
| 14 | + if (!stackTrace) { |
| 15 | + throw new Error('Could not get stack trace'); |
| 16 | + } |
| 17 | + |
| 18 | + return parseStackTrace(stackTrace) |
| 19 | + .map((stackFrame) => { |
26 | 20 | return { |
27 | | - columnNumber: callSite.getColumnNumber(), |
28 | | - fileName: callSite.getFileName() ?? null, |
29 | | - functionName: callSite.getFunctionName(), |
30 | | - lineNumber: callSite.getLineNumber(), |
| 21 | + arguments: stackFrame.arguments, |
| 22 | + columnNumber: stackFrame.column, |
| 23 | + fileName: stackFrame.file, |
| 24 | + functionName: stackFrame.methodName, |
| 25 | + lineNumber: stackFrame.lineNumber, |
31 | 26 | }; |
32 | | - }), |
33 | | - }; |
| 27 | + }) |
| 28 | + .slice(1); |
34 | 29 | }; |
0 commit comments