microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/nodeDebugWrapper.ts
316lines · modeblame
e45838cbVladimir Kotikov9 years ago | 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT license. See LICENSE file in the project root for details. | |
| 3 | | |
| 4 | import * as Q from "q"; | |
| 5 | import * as path from "path"; | |
| 6 | import * as fs from "fs"; | |
| 7 | import stripJsonComments = require("strip-json-comments"); | |
b8999098Dmitry Zinovyev9 years ago | 8 | import { Telemetry } from "../common/telemetry"; |
| 9 | import { TelemetryHelper } from "../common/telemetryHelper"; | |
| 10 | import { RemoteExtension } from "../common/remoteExtension"; | |
3a155214Artem Egorov8 years ago | 11 | import { RemoteTelemetryReporter, ReassignableTelemetryReporter } from "../common/telemetryReporters"; |
e67ace8aYuri Skorokhodov6 years ago | 12 | import { ChromeDebugSession, IChromeDebugSessionOpts, ChromeDebugAdapter, logger, Crdp, stoppedEvent, IOnPausedResult } from "vscode-chrome-debug-core"; |
e3b0fb3bChance An8 years ago | 13 | import { ContinuedEvent, TerminatedEvent, Logger, Response } from "vscode-debugadapter"; |
0a68f8dbArtem Egorov8 years ago | 14 | import { DebugProtocol } from "vscode-debugprotocol"; |
e45838cbVladimir Kotikov9 years ago | 15 | import { MultipleLifetimesAppWorker } from "./appWorker"; |
2d876061Ruslan Bikkinin8 years ago | 16 | import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper"; |
d124bf0eYuri Skorokhodov7 years ago | 17 | import * as nls from "vscode-nls"; |
| 18 | import { ErrorHelper } from "../common/error/errorHelper"; | |
| 19 | import { InternalErrorCode } from "../common/error/internalErrorCode"; | |
08722261Yuri Skorokhodov7 years ago | 20 | import { getLoggingDirectory } from "../extension/log/LogHelper"; |
3955d20aYuri Skorokhodov6 years ago | 21 | import * as mkdirp from "mkdirp"; |
d124bf0eYuri Skorokhodov7 years ago | 22 | const localize = nls.loadMessageBundle(); |
0a68f8dbArtem Egorov8 years ago | 23 | |
b8999098Dmitry Zinovyev9 years ago | 24 | export function makeSession( |
0a68f8dbArtem Egorov8 years ago | 25 | debugSessionClass: typeof ChromeDebugSession, |
| 26 | debugSessionOpts: IChromeDebugSessionOpts, | |
b8999098Dmitry Zinovyev9 years ago | 27 | telemetryReporter: ReassignableTelemetryReporter, |
0a68f8dbArtem Egorov8 years ago | 28 | appName: string, version: string): typeof ChromeDebugSession { |
e45838cbVladimir Kotikov9 years ago | 29 | |
| 30 | return class extends debugSessionClass { | |
| 31 | | |
| 32 | private projectRootPath: string; | |
| 33 | private remoteExtension: RemoteExtension; | |
5c8365a6Artem Egorov8 years ago | 34 | private appWorker: MultipleLifetimesAppWorker | null = null; |
e45838cbVladimir Kotikov9 years ago | 35 | |
| 36 | constructor(debuggerLinesAndColumnsStartAt1?: boolean, isServer?: boolean) { | |
| 37 | super(debuggerLinesAndColumnsStartAt1, isServer, debugSessionOpts); | |
| 38 | } | |
| 39 | | |
| 40 | // Override ChromeDebugSession's sendEvent to control what we will send to client | |
0a68f8dbArtem Egorov8 years ago | 41 | public sendEvent(event: DebugProtocol.Event): void { |
e45838cbVladimir Kotikov9 years ago | 42 | // Do not send "terminated" events signaling about session's restart to client as it would cause it |
| 43 | // to restart adapter's process, while we want to stay alive and don't want to interrupt connection | |
6c75098eVladimir9 years ago | 44 | // to packager. |
b8999098Dmitry Zinovyev9 years ago | 45 | |
720e992dArtem Egorov8 years ago | 46 | if (event.event === "terminated" && event.body && event.body.restart) { |
b8999098Dmitry Zinovyev9 years ago | 47 | |
| 48 | // Worker has been reloaded and switched to "continue" state | |
| 49 | // So we have to send "continued" event to client instead of "terminated" | |
| 50 | // Otherwise client might mistakenly show "stopped" state | |
0a68f8dbArtem Egorov8 years ago | 51 | let continuedEvent: ContinuedEvent = { |
b8999098Dmitry Zinovyev9 years ago | 52 | event: "continued", |
| 53 | type: "event", | |
| 54 | seq: event["seq"], // tslint:disable-line | |
| 55 | body: { threadId: event.body.threadId }, | |
| 56 | }; | |
| 57 | | |
| 58 | super.sendEvent(continuedEvent); | |
e45838cbVladimir Kotikov9 years ago | 59 | return; |
| 60 | } | |
| 61 | | |
| 62 | super.sendEvent(event); | |
| 63 | } | |
| 64 | | |
0a68f8dbArtem Egorov8 years ago | 65 | protected dispatchRequest(request: DebugProtocol.Request): void { |
e45838cbVladimir Kotikov9 years ago | 66 | if (request.command === "disconnect") |
| 67 | return this.disconnect(request); | |
| 68 | | |
| 69 | if (request.command === "attach") | |
| 70 | return this.attach(request); | |
| 71 | | |
| 72 | if (request.command === "launch") | |
| 73 | return this.launch(request); | |
| 74 | | |
| 75 | return super.dispatchRequest(request); | |
| 76 | } | |
| 77 | | |
0a68f8dbArtem Egorov8 years ago | 78 | private launch(request: DebugProtocol.Request): void { |
2d876061Ruslan Bikkinin8 years ago | 79 | this.requestSetup(request.arguments) |
| 80 | .then(() => { | |
db6fd42aRuslan Bikkinin7 years ago | 81 | logger.verbose(`Handle launch request: ${JSON.stringify(request.arguments, null , 2)}`); |
2d876061Ruslan Bikkinin8 years ago | 82 | return this.remoteExtension.launch(request); |
| 83 | }) | |
cbb0e869Artem Egorov8 years ago | 84 | .then(() => { |
18ea7d15Yuri Skorokhodov7 years ago | 85 | return this.remoteExtension.getPackagerPort(request.arguments.cwd || request.arguments.program); |
0a68f8dbArtem Egorov8 years ago | 86 | }) |
| 87 | .then((packagerPort: number) => { | |
6eeec3c0Serge Svekolnikov8 years ago | 88 | this.attachRequest({ |
| 89 | ...request, | |
| 90 | arguments: { | |
| 91 | ...request.arguments, | |
| 92 | port: packagerPort, | |
| 93 | }, | |
| 94 | }); | |
0a68f8dbArtem Egorov8 years ago | 95 | }) |
| 96 | .catch(error => { | |
748105d9Artem Egorov8 years ago | 97 | this.bailOut(error.data || error.message); |
cbb0e869Artem Egorov8 years ago | 98 | }); |
e45838cbVladimir Kotikov9 years ago | 99 | } |
| 100 | | |
0a68f8dbArtem Egorov8 years ago | 101 | private attach(request: DebugProtocol.Request): void { |
2d876061Ruslan Bikkinin8 years ago | 102 | this.requestSetup(request.arguments) |
| 103 | .then(() => { | |
dbfbebd9Yuri Skorokhodov7 years ago | 104 | logger.verbose(`Handle attach request: ${JSON.stringify(request.arguments, null , 2)}`); |
18ea7d15Yuri Skorokhodov7 years ago | 105 | return this.remoteExtension.getPackagerPort(request.arguments.cwd || request.arguments.program); |
2d876061Ruslan Bikkinin8 years ago | 106 | }) |
0a68f8dbArtem Egorov8 years ago | 107 | .then((packagerPort: number) => { |
6eeec3c0Serge Svekolnikov8 years ago | 108 | this.attachRequest({ |
| 109 | ...request, | |
| 110 | arguments: { | |
| 111 | ...request.arguments, | |
e92278b5Serge Svekolnikov8 years ago | 112 | port: request.arguments.port || packagerPort, |
6eeec3c0Serge Svekolnikov8 years ago | 113 | }, |
| 114 | }); | |
2d876061Ruslan Bikkinin8 years ago | 115 | }) |
| 116 | .catch(error => { | |
| 117 | this.bailOut(error.data || error.message); | |
cbb0e869Artem Egorov8 years ago | 118 | }); |
e45838cbVladimir Kotikov9 years ago | 119 | } |
| 120 | | |
0a68f8dbArtem Egorov8 years ago | 121 | private disconnect(request: DebugProtocol.Request): void { |
e45838cbVladimir Kotikov9 years ago | 122 | // The client is about to disconnect so first we need to stop app worker |
f920e582Vladimir Kotikov9 years ago | 123 | if (this.appWorker) { |
| 124 | this.appWorker.stop(); | |
| 125 | } | |
e45838cbVladimir Kotikov9 years ago | 126 | |
| 127 | // Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session | |
0a68f8dbArtem Egorov8 years ago | 128 | if (request.arguments.platform === "android") { |
e45838cbVladimir Kotikov9 years ago | 129 | this.remoteExtension.stopMonitoringLogcat() |
d124bf0eYuri Skorokhodov7 years ago | 130 | .catch(reason => logger.warn(localize("CouldNotStopMonitoringLogcat", "Couldn't stop monitoring logcat: {0}", reason.message || reason))) |
b8999098Dmitry Zinovyev9 years ago | 131 | .finally(() => super.dispatchRequest(request)); |
e45838cbVladimir Kotikov9 years ago | 132 | } else { |
| 133 | super.dispatchRequest(request); | |
| 134 | } | |
| 135 | } | |
| 136 | | |
2d876061Ruslan Bikkinin8 years ago | 137 | private requestSetup(args: any): Q.Promise<void> { |
08722261Yuri Skorokhodov7 years ago | 138 | // If special env variables are defined, then write process outputs to file |
| 139 | let chromeDebugCoreLogs = getLoggingDirectory(); | |
| 140 | if (chromeDebugCoreLogs) { | |
| 141 | chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "ChromeDebugCoreLogs.txt"); | |
| 142 | } | |
0a68f8dbArtem Egorov8 years ago | 143 | let logLevel: string = args.trace; |
| 144 | if (logLevel) { | |
| 145 | logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase()); | |
08722261Yuri Skorokhodov7 years ago | 146 | logger.setup(Logger.LogLevel[logLevel], chromeDebugCoreLogs || false); |
0a68f8dbArtem Egorov8 years ago | 147 | } else { |
08722261Yuri Skorokhodov7 years ago | 148 | logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false); |
0a68f8dbArtem Egorov8 years ago | 149 | } |
| 150 | | |
18ea7d15Yuri Skorokhodov7 years ago | 151 | |
135c493eYuri Skorokhodov7 years ago | 152 | if (!args.sourceMaps) { |
| 153 | args.sourceMaps = true; | |
| 154 | } | |
2d876061Ruslan Bikkinin8 years ago | 155 | const projectRootPath = getProjectRoot(args); |
| 156 | return ReactNativeProjectHelper.isReactNativeProject(projectRootPath) | |
| 157 | .then((result) => { | |
| 158 | if (!result) { | |
d124bf0eYuri Skorokhodov7 years ago | 159 | throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError); |
2d876061Ruslan Bikkinin8 years ago | 160 | } |
| 161 | this.projectRootPath = projectRootPath; | |
| 162 | this.remoteExtension = RemoteExtension.atProjectRootPath(this.projectRootPath); | |
| 163 | | |
| 164 | // Start to send telemetry | |
| 165 | telemetryReporter.reassignTo(new RemoteTelemetryReporter( | |
| 166 | appName, version, Telemetry.APPINSIGHTS_INSTRUMENTATIONKEY, this.projectRootPath)); | |
23b5fa80Yuri Skorokhodov6 years ago | 167 | |
| 168 | if (args.program) { | |
| 169 | // TODO: Remove this warning when program property will be completely removed | |
| 170 | logger.warn(localize("ProgramPropertyDeprecationWarning", "Launched debug configuration contains 'program' property which is deprecated and will be removed soon. Please replace it with: \"cwd\": \"${workspaceFolder}\"")); | |
| 171 | const useProgramEvent = TelemetryHelper.createTelemetryEvent("useProgramProperty"); | |
| 172 | Telemetry.send(useProgramEvent); | |
| 173 | } | |
| 174 | if (args.cwd) { | |
| 175 | // To match count of 'cwd' users with 'program' users. TODO: Remove when program property will be removed | |
| 176 | const useCwdEvent = TelemetryHelper.createTelemetryEvent("useCwdProperty"); | |
| 177 | Telemetry.send(useCwdEvent); | |
| 178 | } | |
2d876061Ruslan Bikkinin8 years ago | 179 | return void 0; |
| 180 | }); | |
e45838cbVladimir Kotikov9 years ago | 181 | } |
| 182 | | |
| 183 | /** | |
| 184 | * Runs logic needed to attach. | |
| 185 | * Attach should: | |
| 186 | * - Enable js debugging | |
| 187 | */ | |
0a68f8dbArtem Egorov8 years ago | 188 | // tslint:disable-next-line:member-ordering |
031832ffArtem Egorov8 years ago | 189 | protected attachRequest(request: DebugProtocol.Request): Q.Promise<void> { |
ba953e9fRedMickey6 years ago | 190 | let extProps = { |
031832ffArtem Egorov8 years ago | 191 | platform: { |
| 192 | value: request.arguments.platform, | |
| 193 | isPii: false, | |
| 194 | }, | |
| 195 | }; | |
| 196 | | |
ba953e9fRedMickey6 years ago | 197 | return ReactNativeProjectHelper.getReactNativeVersion(request.arguments.cwd) |
| 198 | .then(version => { | |
| 199 | extProps = TelemetryHelper.addReactNativeVersionToEventProperties(version, extProps); | |
| 200 | return TelemetryHelper.generate("attach", extProps, (generator) => { | |
| 201 | return Q({}) | |
| 202 | .then(() => { | |
| 203 | logger.log(localize("StartingDebuggerAppWorker", "Starting debugger app worker.")); | |
| 204 | // TODO: remove dependency on args.program - "program" property is technically | |
| 205 | // no more required in launch configuration and could be removed | |
| 206 | const workspaceRootPath = request.arguments.cwd ? path.resolve(request.arguments.cwd) : path.resolve(path.dirname(request.arguments.program), ".."); | |
| 207 | const sourcesStoragePath = path.join(workspaceRootPath, ".vscode", ".react"); | |
| 208 | // Create folder if not exist to avoid problems if | |
| 209 | // RN project root is not a ${workspaceFolder} | |
| 210 | mkdirp.sync(sourcesStoragePath); | |
| 211 | | |
| 212 | // If launch is invoked first time, appWorker is undefined, so create it here | |
| 213 | this.appWorker = new MultipleLifetimesAppWorker( | |
| 214 | request.arguments, | |
| 215 | sourcesStoragePath, | |
| 216 | this.projectRootPath, | |
| 217 | undefined); | |
| 218 | this.appWorker.on("connected", (port: number) => { | |
| 219 | logger.log(localize("DebuggerWorkerLoadedRuntimeOnPort", "Debugger worker loaded runtime on port {0}", port)); | |
| 220 | // Don't mutate original request to avoid side effects | |
| 221 | let attachArguments = Object.assign({}, request.arguments, { | |
| 222 | address: "localhost", | |
| 223 | port, | |
| 224 | restart: true, | |
| 225 | request: "attach", | |
| 226 | remoteRoot: undefined, | |
| 227 | localRoot: undefined, | |
| 228 | }); | |
| 229 | // Reinstantiate debug adapter, as the current implementation of ChromeDebugAdapter | |
| 230 | // doesn't allow us to reattach to another debug target easily. As of now it's easier | |
| 231 | // to throw previous instance out and create a new one. | |
| 232 | (this as any)._debugAdapter = new (<any>debugSessionOpts.adapter)(debugSessionOpts, this); | |
| 233 | | |
| 234 | // Explicity call _debugAdapter.attach() to prevent directly calling dispatchRequest() | |
| 235 | // yield a response as "attach" even for "launch" request. Because dispatchRequest() will | |
| 236 | // decide to do a sendResponse() aligning with the request parameter passed in. | |
| 237 | Q((this as any)._debugAdapter.attach(attachArguments, request.seq)) | |
| 238 | .then((responseBody) => { | |
| 239 | const response: DebugProtocol.Response = new Response(request); | |
| 240 | response.body = responseBody; | |
| 241 | this.sendResponse(response); | |
| 242 | }); | |
2d876061Ruslan Bikkinin8 years ago | 243 | }); |
e45838cbVladimir Kotikov9 years ago | 244 | |
ba953e9fRedMickey6 years ago | 245 | return this.appWorker.start(); |
| 246 | }) | |
| 247 | .catch(error => this.bailOut(error.message)); | |
| 248 | }); | |
| 249 | }); | |
e45838cbVladimir Kotikov9 years ago | 250 | } |
| 251 | | |
| 252 | /** | |
| 253 | * Logs error to user and finishes the debugging process. | |
| 254 | */ | |
| 255 | private bailOut(message: string): void { | |
d124bf0eYuri Skorokhodov7 years ago | 256 | logger.error(localize("CouldNotDebug", "Could not debug. {0}" , message)); |
0a68f8dbArtem Egorov8 years ago | 257 | this.sendEvent(new TerminatedEvent()); |
27710197Vladimir Kotikov8 years ago | 258 | } |
e45838cbVladimir Kotikov9 years ago | 259 | }; |
| 260 | } | |
| 261 | | |
0a68f8dbArtem Egorov8 years ago | 262 | export function makeAdapter(debugAdapterClass: typeof ChromeDebugAdapter): typeof ChromeDebugAdapter { |
e45838cbVladimir Kotikov9 years ago | 263 | return class extends debugAdapterClass { |
e67ace8aYuri Skorokhodov6 years ago | 264 | private firstStop: boolean = true; |
4f7b3bc0Anna Kocheshkova8 years ago | 265 | public doAttach(port: number, targetUrl?: string, address?: string, timeout?: number): Promise<void> { |
4b86d595Vladimir Kotikov9 years ago | 266 | // We need to overwrite ChromeDebug's _attachMode to let Node2 adapter |
e45838cbVladimir Kotikov9 years ago | 267 | // to set up breakpoints on initial pause event |
0a68f8dbArtem Egorov8 years ago | 268 | (this as any)._attachMode = false; |
e45838cbVladimir Kotikov9 years ago | 269 | return super.doAttach(port, targetUrl, address, timeout); |
| 270 | } | |
639a73d7Artem Egorov7 years ago | 271 | |
e67ace8aYuri Skorokhodov6 years ago | 272 | // Since the bundle runs inside the Node.js VM in debuggerWorker.js in runtime |
| 273 | // Node debug adapter need time to parse new added code source maps | |
| 274 | // So we added 'debugger;' statement at the start of the bundle code | |
| 275 | // and wait for the adapter to receive a signal to stop on that statement | |
| 276 | // and then wait for code bundle to be processed and then send continue request to skip the code execution stop in VS Code UI | |
| 277 | public onPaused(notification: Crdp.Debugger.PausedEvent, expectingStopReason?: stoppedEvent.ReasonType): Promise<IOnPausedResult> { | |
| 278 | // When pause on 'debugger;' statement, notification contains reason with value "other" instead of "breakpoint" | |
| 279 | if (this.firstStop && notification.reason === "other") { | |
| 280 | return new Promise<IOnPausedResult>((resolve) => { | |
| 281 | setTimeout(() => { | |
| 282 | this.firstStop = false; | |
| 283 | this.continue(); | |
| 284 | resolve({didPause: false}); | |
| 285 | }, 50); | |
| 286 | }); | |
| 287 | } else { | |
| 288 | return super.onPaused(notification, expectingStopReason); | |
| 289 | } | |
| 290 | } | |
| 291 | | |
639a73d7Artem Egorov7 years ago | 292 | public async terminate(args: DebugProtocol.TerminatedEvent) { |
| 293 | return this.disconnect({ | |
| 294 | terminateDebuggee: true, | |
| 295 | }); | |
| 296 | } | |
e45838cbVladimir Kotikov9 years ago | 297 | }; |
| 298 | } | |
| 299 | | |
| 300 | /** | |
| 301 | * Parses settings.json file for workspace root property | |
| 302 | */ | |
549baae2RedMickey6 years ago | 303 | export function getProjectRoot(args: any): string { |
31796719RedMickey6 years ago | 304 | const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../.."); |
| 305 | const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json"); | |
e45838cbVladimir Kotikov9 years ago | 306 | try { |
| 307 | let settingsContent = fs.readFileSync(settingsPath, "utf8"); | |
| 308 | settingsContent = stripJsonComments(settingsContent); | |
| 309 | let parsedSettings = JSON.parse(settingsContent); | |
9a364375Serge Svekolnikov8 years ago | 310 | let projectRootPath = parsedSettings["react-native-tools.projectRoot"] || parsedSettings["react-native-tools"].projectRoot; |
e45838cbVladimir Kotikov9 years ago | 311 | return path.resolve(vsCodeRoot, projectRootPath); |
| 312 | } catch (e) { | |
31796719RedMickey6 years ago | 313 | logger.verbose(`${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`); |
18ea7d15Yuri Skorokhodov7 years ago | 314 | return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../.."); |
e45838cbVladimir Kotikov9 years ago | 315 | } |
| 316 | } |