|
| 1 | +import { TraceMap, originalPositionFor } from '@jridgewell/trace-mapping'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Remaps an error stack trace using inline source maps to show original source locations. |
| 5 | + * |
| 6 | + * @param stack - The error stack trace to remap |
| 7 | + * @param filename - The workflow filename to match in stack frames |
| 8 | + * @param workflowCode - The workflow bundle code containing inline source maps |
| 9 | + * @returns The remapped stack trace with original source locations |
| 10 | + */ |
| 11 | +export function remapErrorStack( |
| 12 | + stack: string, |
| 13 | + filename: string, |
| 14 | + workflowCode: string |
| 15 | +): string { |
| 16 | + // Extract inline source map from workflow code |
| 17 | + const sourceMapMatch = workflowCode.match( |
| 18 | + /\/\/# sourceMappingURL=data:application\/json;base64,(.+)/ |
| 19 | + ); |
| 20 | + if (!sourceMapMatch) { |
| 21 | + return stack; // No source map found |
| 22 | + } |
| 23 | + |
| 24 | + try { |
| 25 | + const base64 = sourceMapMatch[1]; |
| 26 | + const sourceMapJson = Buffer.from(base64, 'base64').toString('utf-8'); |
| 27 | + const sourceMapData = JSON.parse(sourceMapJson); |
| 28 | + |
| 29 | + // Use TraceMap (pure JS, no WASM required) |
| 30 | + const tracer = new TraceMap(sourceMapData); |
| 31 | + |
| 32 | + // Parse and remap each line in the stack trace |
| 33 | + const lines = stack.split('\n'); |
| 34 | + const remappedLines = lines.map((line) => { |
| 35 | + // Match stack frames: "at functionName (filename:line:column)" or "at filename:line:column" |
| 36 | + const frameMatch = line.match( |
| 37 | + /^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/ |
| 38 | + ); |
| 39 | + if (!frameMatch) { |
| 40 | + return line; // Not a stack frame, return as-is |
| 41 | + } |
| 42 | + |
| 43 | + const [, functionName, file, lineStr, colStr] = frameMatch; |
| 44 | + |
| 45 | + // Only remap frames from our workflow file |
| 46 | + if (!file.includes(filename)) { |
| 47 | + return line; |
| 48 | + } |
| 49 | + |
| 50 | + const lineNumber = parseInt(lineStr, 10); |
| 51 | + const columnNumber = parseInt(colStr, 10); |
| 52 | + |
| 53 | + // Map to original source position |
| 54 | + const original = originalPositionFor(tracer, { |
| 55 | + line: lineNumber, |
| 56 | + column: columnNumber, |
| 57 | + }); |
| 58 | + |
| 59 | + if (original.source && original.line !== null) { |
| 60 | + const func = functionName || original.name || 'anonymous'; |
| 61 | + const col = original.column !== null ? original.column : columnNumber; |
| 62 | + return ` at ${func} (${original.source}:${original.line}:${col})`; |
| 63 | + } |
| 64 | + |
| 65 | + return line; // Couldn't map, return original |
| 66 | + }); |
| 67 | + |
| 68 | + return remappedLines.join('\n'); |
| 69 | + } catch (e) { |
| 70 | + // If source map processing fails, return original stack |
| 71 | + return stack; |
| 72 | + } |
| 73 | +} |
0 commit comments