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