microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
d3897897910e9b3fe5fea5c60a8d8fc5c5a99bbe

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/debugger/nodeDebugWrapper.ts

178lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4import * as fs from "fs";
5import * as path from "path";
6import * as http from "http";
7
8import {Telemetry} from "../common/telemetry";
9import {TelemetryHelper} from "../common/telemetryHelper";
10import {ExtensionMessageSender, ExtensionMessage} from "../common/extensionMessaging";
11
12// These typings do not reflect the typings as intended to be used
13// but rather as they exist in truth, so we can reach into the internals
14// and access what we need.
15declare module VSCodeDebugAdapter {
16 class DebugSession {
17 public static run: Function;
18 public sendEvent(event: VSCodeDebugAdapter.InitializedEvent): void;
19 public start(input: any, output: any): void;
20 public launchRequest(response: any, args: any): void;
21 public disconnectRequest(response: any, args: any): void;
22 }
23 class InitializedEvent {
24 constructor();
25 }
26 class OutputEvent {
27 constructor(message: string, destination?: string);
28 }
29 class TerminatedEvent {
30 constructor();
31 }
32}
33
34declare class SourceMaps {
35 public _sourceToGeneratedMaps: {};
36 public _generatedToSourceMaps: {};
37 public _allSourceMaps: {};
38}
39
40declare class NodeDebugSession extends VSCodeDebugAdapter.DebugSession {
41 public _sourceMaps: SourceMaps;
42}
43
44interface ILaunchArgs {
45 platform: string;
46 target?: string;
47 internalDebuggerPort?: any;
48 args: string[];
49 logCatArguments: any;
50}
51
52let version = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "..", "package.json"), "utf-8")).version;
53
54function bailOut(reason: string): void {
55 // Things have gone wrong in initialization: Report the error to telemetry and exit
56 TelemetryHelper.sendSimpleEvent(reason);
57 Telemetry.sendPendingData().finally(() => {
58 process.exit(1);
59 });
60}
61
62// Enable telemetry
63Telemetry.init("react-native-debug-adapter", version, true).then(() => {
64 let nodeDebugFolder: string;
65 let vscodeDebugAdapterPackage: typeof VSCodeDebugAdapter;
66
67 /* tslint:disable:no-var-requires */
68
69 // nodeDebugLocation.json is dynamically generated on extension activation.
70 // If it fails, we must not have been in a react native project
71 try {
72 nodeDebugFolder = require("./nodeDebugLocation.json").nodeDebugPath;
73 vscodeDebugAdapterPackage = require(path.join(nodeDebugFolder, "node_modules", "vscode-debugadapter"));
74 } catch (e) {
75 // Nothing we can do here: can't even communicate back because we don't know how to speak debug adapter
76 return bailOut("cannotFindDebugAdapter");
77 }
78
79 // Temporarily dummy out the DebugSession.run function so we do not start the debug adapter until we are ready
80 const originalDebugSessionRun = vscodeDebugAdapterPackage.DebugSession.run;
81 vscodeDebugAdapterPackage.DebugSession.run = function() { };
82
83 let nodeDebug: { NodeDebugSession: typeof NodeDebugSession };
84
85 try {
86 nodeDebug = require(path.join(nodeDebugFolder, "out", "node", "nodeDebug"));
87 } catch (e) {
88 // Unable to find nodeDebug, but we can make our own communication channel now
89 const debugSession = new vscodeDebugAdapterPackage.DebugSession();
90 // Note: this will not work in the context of debugging the debug adapter and communicating over a socket,
91 // but in that case we have much better ways to investigate errors.
92 debugSession.start(process.stdin, process.stdout);
93 debugSession.sendEvent(new vscodeDebugAdapterPackage.OutputEvent("Unable to start debug adapter: " + e.toString(), "stderr"));
94 debugSession.sendEvent(new vscodeDebugAdapterPackage.TerminatedEvent());
95
96 return bailOut("cannotFindNodeDebugAdapter");
97 }
98
99 /* tslint:enable:no-var-requires */
100
101 vscodeDebugAdapterPackage.DebugSession.run = originalDebugSessionRun;
102
103 // Intecept the "launchRequest" instance method of NodeDebugSession to interpret arguments
104 const originalNodeDebugSessionLaunchRequest = nodeDebug.NodeDebugSession.prototype.launchRequest;
105 nodeDebug.NodeDebugSession.prototype.launchRequest = function(request: any, args: ILaunchArgs) {
106 // Create a server waiting for messages to re-initialize the debug session;
107 const reinitializeServer = http.createServer((req, res) => {
108 res.statusCode = 404;
109 if (req.url === "/refreshBreakpoints") {
110 res.statusCode = 200;
111 if (this) {
112 const sourceMaps = this._sourceMaps;
113 if (sourceMaps) {
114 // Flush any cached source maps
115 sourceMaps._allSourceMaps = {};
116 sourceMaps._generatedToSourceMaps = {};
117 sourceMaps._sourceToGeneratedMaps = {};
118 }
119 // Send an "initialized" event to trigger breakpoints to be re-sent
120 this.sendEvent(new vscodeDebugAdapterPackage.InitializedEvent());
121 }
122 }
123 res.end();
124 });
125 const debugServerListeningPort = parseInt(args.internalDebuggerPort, 10) || 9090;
126
127 reinitializeServer.listen(debugServerListeningPort);
128 reinitializeServer.on("error", (err: Error) => {
129 TelemetryHelper.sendSimpleEvent("reinitializeServerError");
130 this.sendEvent(new vscodeDebugAdapterPackage.OutputEvent("Error in debug adapter server: " + err.toString(), "stderr"));
131 this.sendEvent(new vscodeDebugAdapterPackage.OutputEvent("Breakpoints may not update. Consider restarting and specifying a different 'internalDebuggerPort' in launch.json"));
132 });
133
134 // We do not permit arbitrary args to be passed to our process
135 args.args = [
136 args.platform,
137 debugServerListeningPort.toString(),
138 args.target || "simulator"
139 ];
140
141 if (!isNullOrUndefined(args.logCatArguments)) { // We add the parameter if it's defined (adapter crashes otherwise)
142 args.args = args.args.concat([parseLogCatArguments(args.logCatArguments)]);
143 }
144
145 originalNodeDebugSessionLaunchRequest.call(this, request, args);
146 };
147
148 // Intecept the "launchRequest" instance method of NodeDebugSession to interpret arguments
149 const originalNodeDebugSessionDisconnectRequest = nodeDebug.NodeDebugSession.prototype.disconnectRequest;
150 function customDisconnectRequest(response: any, args: any): void {
151 try {
152 // First we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session
153 const extensionMessageSender = new ExtensionMessageSender();
154 extensionMessageSender.sendMessage(ExtensionMessage.STOP_MONITORING_LOGCAT)
155 .finally(() => originalNodeDebugSessionDisconnectRequest.call(this, response, args))
156 .done(() => {}, reason => // We just print a warning if something fails
157 process.stderr.write(`WARNING: Couldn't stop monitoring logcat: ${reason.message || reason}\n`));
158 } catch (exception) {
159 // This is a "nice to have" feature, so we just fire the message and forget. We don't event handle
160 // errors in the response promise
161 process.stderr.write(`WARNING: Couldn't stop monitoring logcat. Sync exception: ${exception.message || exception}\n`);
162 originalNodeDebugSessionDisconnectRequest.call(this, response, args);
163 }
164 }
165 nodeDebug.NodeDebugSession.prototype.disconnectRequest = customDisconnectRequest;
166
167 vscodeDebugAdapterPackage.DebugSession.run(nodeDebug.NodeDebugSession);
168});
169
170function parseLogCatArguments(userProvidedLogCatArguments: any) {
171 return Array.isArray(userProvidedLogCatArguments)
172 ? userProvidedLogCatArguments.join(" ") // If it's an array, we join the arguments
173 : userProvidedLogCatArguments; // If not, we leave it as-is
174}
175
176function isNullOrUndefined(value: any): boolean {
177 return typeof value === "undefined" || value === null;
178}