Repository navigation
Expand file tree
/
Copy pathdebugger.ts
More file actions
55 lines (48 loc) · 1.83 KB
/
Copy pathdebugger.ts
File metadata and controls
55 lines (48 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import type { StackFrame } from '@sentry/types';
import { createDebugPauseMessageHandler } from '@sentry/utils';
import type { Debugger } from 'inspector';
import { getModuleFromFilename } from '../module';
import { createWebSocketClient } from './websocket';
// The only messages we care about
type DebugMessage =
| {
method: 'Debugger.scriptParsed';
params: Debugger.ScriptParsedEventDataType;
}
| { method: 'Debugger.paused'; params: Debugger.PausedEventDataType };
/**
* Wraps a websocket connection with the basic logic of the Node debugger protocol.
* @param url The URL to connect to
* @param onMessage A callback that will be called with each return message from the debugger
* @returns A function that can be used to send commands to the debugger
*/
async function webSocketDebugger(
url: string,
onMessage: (message: DebugMessage) => void,
): Promise<(method: string) => void> {
let id = 0;
const webSocket = await createWebSocketClient(url);
webSocket.on('message', (data: Buffer) => {
const message = JSON.parse(data.toString()) as DebugMessage;
onMessage(message);
});
return (method: string) => {
webSocket.send(JSON.stringify({ id: id++, method }));
};
}
/**
* Captures stack traces from the Node debugger.
* @param url The URL to connect to
* @param callback A callback that will be called with the stack frames
* @returns A function that triggers the debugger to pause and capture a stack trace
*/
export async function captureStackTrace(url: string, callback: (frames: StackFrame[]) => void): Promise<() => void> {
const sendCommand: (method: string) => void = await webSocketDebugger(
url,
createDebugPauseMessageHandler(cmd => sendCommand(cmd), getModuleFromFilename, callback),
);
return () => {
sendCommand('Debugger.enable');
sendCommand('Debugger.pause');
};
}