microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/nodeDebugWrapper.ts
288lines · 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 | |
| 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"); |
| 8 | |
| 9 | import { Telemetry } from "../common/telemetry"; |
| 10 | import { TelemetryHelper } from "../common/telemetryHelper"; |
| 11 | import { RemoteExtension } from "../common/remoteExtension"; |
| 12 | import { PlatformResolver } from "./platformResolver"; |
| 13 | import { IRunOptions } from "../common/launchArgs"; |
| 14 | import { TargetPlatformHelper } from "../common/targetPlatformHelper"; |
| 15 | import { ExtensionTelemetryReporter, ReassignableTelemetryReporter } from "../common/telemetryReporters"; |
| 16 | import { NodeDebugAdapterLogger } from "../common/log/loggers"; |
| 17 | import { Log } from "../common/log/log"; |
| 18 | import { LogLevel } from "../common/log/logHelper"; |
| 19 | import { GeneralMobilePlatform } from "../common/generalMobilePlatform"; |
| 20 | |
| 21 | import { MultipleLifetimesAppWorker } from "./appWorker"; |
| 22 | |
| 23 | export function makeSession( |
| 24 | debugSessionClass: typeof ChromeDebuggerCorePackage.ChromeDebugSession, |
| 25 | debugSessionOpts: ChromeDebuggerCorePackage.IChromeDebugSessionOpts, |
| 26 | debugAdapterPackage: typeof VSCodeDebugAdapterPackage, |
| 27 | telemetryReporter: ReassignableTelemetryReporter, |
| 28 | appName: string, version: string): typeof ChromeDebuggerCorePackage.ChromeDebugSession { |
| 29 | |
| 30 | return class extends debugSessionClass { |
| 31 | |
| 32 | private projectRootPath: string; |
| 33 | private remoteExtension: RemoteExtension; |
| 34 | private mobilePlatformOptions: IRunOptions; |
| 35 | private appWorker: MultipleLifetimesAppWorker | null = null; |
| 36 | |
| 37 | constructor(debuggerLinesAndColumnsStartAt1?: boolean, isServer?: boolean) { |
| 38 | super(debuggerLinesAndColumnsStartAt1, isServer, debugSessionOpts); |
| 39 | } |
| 40 | |
| 41 | // Override ChromeDebugSession's sendEvent to control what we will send to client |
| 42 | public sendEvent(event: VSCodeDebugAdapterPackage.Event): void { |
| 43 | // Do not send "terminated" events signaling about session's restart to client as it would cause it |
| 44 | // to restart adapter's process, while we want to stay alive and don't want to interrupt connection |
| 45 | // to packager. |
| 46 | |
| 47 | if (event.event === "terminated" && event.body && event.body.restart) { |
| 48 | |
| 49 | // Worker has been reloaded and switched to "continue" state |
| 50 | // So we have to send "continued" event to client instead of "terminated" |
| 51 | // Otherwise client might mistakenly show "stopped" state |
| 52 | let continuedEvent: VSCodeDebugAdapterPackage.ContinuedEvent = { |
| 53 | event: "continued", |
| 54 | type: "event", |
| 55 | seq: event["seq"], // tslint:disable-line |
| 56 | body: { threadId: event.body.threadId }, |
| 57 | }; |
| 58 | |
| 59 | super.sendEvent(continuedEvent); |
| 60 | return; |
| 61 | } |
| 62 | |
| 63 | super.sendEvent(event); |
| 64 | } |
| 65 | |
| 66 | protected dispatchRequest(request: VSCodeDebugAdapterPackage.Request): void { |
| 67 | if (request.command === "disconnect") |
| 68 | return this.disconnect(request); |
| 69 | |
| 70 | if (request.command === "attach") |
| 71 | return this.attach(request); |
| 72 | |
| 73 | if (request.command === "launch") |
| 74 | return this.launch(request); |
| 75 | |
| 76 | return super.dispatchRequest(request); |
| 77 | } |
| 78 | |
| 79 | private launch(request: VSCodeDebugAdapterPackage.Request): void { |
| 80 | this.requestSetup(request.arguments) |
| 81 | .then(() => { |
| 82 | // We add the parameter if it's defined (adapter crashes otherwise) |
| 83 | if (!isNullOrUndefined(request.arguments.logCatArguments)) { |
| 84 | this.mobilePlatformOptions.logCatArguments = [parseLogCatArguments(request.arguments.logCatArguments)]; |
| 85 | } |
| 86 | |
| 87 | if (!isNullOrUndefined(request.arguments.variant)) { |
| 88 | this.mobilePlatformOptions.variant = request.arguments.variant; |
| 89 | } |
| 90 | |
| 91 | if (!isNullOrUndefined(request.arguments.scheme)) { |
| 92 | this.mobilePlatformOptions.scheme = request.arguments.scheme; |
| 93 | } |
| 94 | |
| 95 | TelemetryHelper.generate("launch", (generator) => { |
| 96 | return this.remoteExtension.getPackagerPort() |
| 97 | .then((packagerPort: number) => { |
| 98 | this.mobilePlatformOptions.packagerPort = packagerPort; |
| 99 | const mobilePlatform = new PlatformResolver() |
| 100 | .resolveMobilePlatform(request.arguments.platform, this.mobilePlatformOptions); |
| 101 | |
| 102 | generator.step("checkPlatformCompatibility"); |
| 103 | TargetPlatformHelper.checkTargetPlatformSupport(this.mobilePlatformOptions.platform); |
| 104 | generator.step("startPackager"); |
| 105 | return mobilePlatform.startPackager() |
| 106 | .then(() => { |
| 107 | // We've seen that if we don't prewarm the bundle cache, the app fails on the first attempt to connect to the debugger logic |
| 108 | // and the user needs to Reload JS manually. We prewarm it to prevent that issue |
| 109 | generator.step("prewarmBundleCache"); |
| 110 | Log.logMessage("Prewarming bundle cache. This may take a while ..."); |
| 111 | return mobilePlatform.prewarmBundleCache(); |
| 112 | }) |
| 113 | .then(() => { |
| 114 | generator.step("mobilePlatform.runApp"); |
| 115 | Log.logMessage("Building and running application."); |
| 116 | return mobilePlatform.runApp(); |
| 117 | }) |
| 118 | .then(() => { |
| 119 | return this.attachRequest(request, packagerPort, mobilePlatform); |
| 120 | }); |
| 121 | }) |
| 122 | .catch(error => this.bailOut(error.message)); |
| 123 | }); |
| 124 | }); |
| 125 | } |
| 126 | |
| 127 | private attach(request: VSCodeDebugAdapterPackage.Request): void { |
| 128 | this.requestSetup(request.arguments) |
| 129 | .then(() => { |
| 130 | this.remoteExtension.getPackagerPort() |
| 131 | .then((packagerPort: number) => this.attachRequest(request, packagerPort)); |
| 132 | }); |
| 133 | } |
| 134 | |
| 135 | private disconnect(request: VSCodeDebugAdapterPackage.Request): void { |
| 136 | // The client is about to disconnect so first we need to stop app worker |
| 137 | if (this.appWorker) { |
| 138 | this.appWorker.stop(); |
| 139 | } |
| 140 | |
| 141 | // Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session |
| 142 | if (this.mobilePlatformOptions.platform === "android") { |
| 143 | this.remoteExtension.stopMonitoringLogcat() |
| 144 | .catch(reason => Log.logError(`WARNING: Couldn't stop monitoring logcat: ${reason.message || reason}\n`)) |
| 145 | .finally(() => super.dispatchRequest(request)); |
| 146 | } else { |
| 147 | super.dispatchRequest(request); |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | private requestSetup(args: any): Q.Promise<void> { |
| 152 | this.projectRootPath = getProjectRoot(args); |
| 153 | this.remoteExtension = RemoteExtension.atProjectRootPath(this.projectRootPath); |
| 154 | this.mobilePlatformOptions = { |
| 155 | projectRoot: this.projectRootPath, |
| 156 | platform: args.platform, |
| 157 | targetType: args.targetType || "simulator", |
| 158 | }; |
| 159 | |
| 160 | // Start to send telemetry |
| 161 | telemetryReporter.reassignTo(new ExtensionTelemetryReporter( |
| 162 | appName, version, Telemetry.APPINSIGHTS_INSTRUMENTATIONKEY, this.projectRootPath)); |
| 163 | |
| 164 | Log.SetGlobalLogger(new NodeDebugAdapterLogger(debugAdapterPackage, this)); |
| 165 | |
| 166 | if (!args.runArguments) { |
| 167 | return this.remoteExtension.getRunArgs(args.platform, args.targetType || "simulator") |
| 168 | .then(runArgs => { |
| 169 | this.mobilePlatformOptions.runArguments = runArgs; |
| 170 | }); |
| 171 | } |
| 172 | |
| 173 | return Q.resolve(void 0); |
| 174 | } |
| 175 | |
| 176 | /** |
| 177 | * Runs logic needed to attach. |
| 178 | * Attach should: |
| 179 | * - Enable js debugging |
| 180 | */ |
| 181 | private attachRequest( |
| 182 | request: VSCodeDebugAdapterPackage.Request, |
| 183 | packagerPort: number, |
| 184 | mobilePlatform?: GeneralMobilePlatform): Q.Promise<void> { |
| 185 | return TelemetryHelper.generate("attach", (generator) => { |
| 186 | return Q({}) |
| 187 | .then(() => { |
| 188 | generator.step("mobilePlatform.enableJSDebuggingMode"); |
| 189 | if (mobilePlatform) { |
| 190 | return mobilePlatform.enableJSDebuggingMode(); |
| 191 | } else { |
| 192 | Log.logMessage("Debugger ready. Enable remote debugging in app."); |
| 193 | return void 0; |
| 194 | } |
| 195 | }) |
| 196 | .then(() => { |
| 197 | |
| 198 | Log.logMessage("Starting debugger app worker."); |
| 199 | // TODO: remove dependency on args.program - "program" property is technically |
| 200 | // no more required in launch configuration and could be removed |
| 201 | const workspaceRootPath = path.resolve(path.dirname(request.arguments.program), ".."); |
| 202 | const sourcesStoragePath = path.join(workspaceRootPath, ".vscode", ".react"); |
| 203 | |
| 204 | // If launch is invoked first time, appWorker is undefined, so create it here |
| 205 | this.appWorker = new MultipleLifetimesAppWorker(packagerPort, sourcesStoragePath); |
| 206 | this.appWorker.on("connected", (port: number) => { |
| 207 | Log.logMessage("Debugger worker loaded runtime on port " + port); |
| 208 | // Don't mutate original request to avoid side effects |
| 209 | let attachArguments = Object.assign({}, request.arguments, { port, restart: true, request: "attach" }); |
| 210 | let attachRequest = Object.assign({}, request, { command: "attach", arguments: attachArguments }); |
| 211 | |
| 212 | // Reinstantiate debug adapter, as the current implementation of ChromeDebugAdapter |
| 213 | // doesn't allow us to reattach to another debug target easily. As of now it's easier |
| 214 | // to throw previous instance out and create a new one. |
| 215 | this._debugAdapter = new (<any>debugSessionOpts.adapter)(debugSessionOpts, this); |
| 216 | super.dispatchRequest(attachRequest); |
| 217 | }); |
| 218 | |
| 219 | return this.appWorker.start(); |
| 220 | }) |
| 221 | .catch(error => this.bailOut(error.message)); |
| 222 | }); |
| 223 | } |
| 224 | |
| 225 | /** |
| 226 | * Logs error to user and finishes the debugging process. |
| 227 | */ |
| 228 | private bailOut(message: string): void { |
| 229 | Log.logError(`Could not debug. ${message}`); |
| 230 | this.sendEvent(new debugAdapterPackage.TerminatedEvent()); |
| 231 | } |
| 232 | }; |
| 233 | } |
| 234 | |
| 235 | export function makeAdapter(debugAdapterClass: typeof Node2DebugAdapterPackage.Node2DebugAdapter): typeof Node2DebugAdapterPackage.Node2DebugAdapter { |
| 236 | return class extends debugAdapterClass { |
| 237 | public doAttach(port: number, targetUrl?: string, address?: string, timeout?: number): Promise<void> { |
| 238 | // We need to overwrite ChromeDebug's _attachMode to let Node2 adapter |
| 239 | // to set up breakpoints on initial pause event |
| 240 | this._attachMode = false; |
| 241 | return super.doAttach(port, targetUrl, address, timeout); |
| 242 | } |
| 243 | |
| 244 | public setBreakpoints(args: any, requestSeq: number, ids?: number[]): Promise<Node2DebugAdapterPackage.ISetBreakpointsResponseBody> { |
| 245 | // We need to overwrite ChromeDebug's setBreakpoints to get rid unhandled rejections |
| 246 | // when breakpoints are being set up unsuccessfully |
| 247 | return super.setBreakpoints(args, requestSeq, ids).catch((err) => { |
| 248 | Log.logInternalMessage(LogLevel.Error, err.message); |
| 249 | return { |
| 250 | breakpoints: [], |
| 251 | }; |
| 252 | }); |
| 253 | } |
| 254 | }; |
| 255 | } |
| 256 | |
| 257 | /** |
| 258 | * Parses log cat arguments to a string |
| 259 | */ |
| 260 | function parseLogCatArguments(userProvidedLogCatArguments: any): string { |
| 261 | return Array.isArray(userProvidedLogCatArguments) |
| 262 | ? userProvidedLogCatArguments.join(" ") // If it's an array, we join the arguments |
| 263 | : userProvidedLogCatArguments; // If not, we leave it as-is |
| 264 | } |
| 265 | |
| 266 | /** |
| 267 | * Helper method to know if a value is either null or undefined |
| 268 | */ |
| 269 | function isNullOrUndefined(value: any): boolean { |
| 270 | return typeof value === "undefined" || value === null; |
| 271 | } |
| 272 | |
| 273 | /** |
| 274 | * Parses settings.json file for workspace root property |
| 275 | */ |
| 276 | function getProjectRoot(args: any): string { |
| 277 | try { |
| 278 | let vsCodeRoot = path.resolve(args.program, "../.."); |
| 279 | let settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json"); |
| 280 | let settingsContent = fs.readFileSync(settingsPath, "utf8"); |
| 281 | settingsContent = stripJsonComments(settingsContent); |
| 282 | let parsedSettings = JSON.parse(settingsContent); |
| 283 | let projectRootPath = parsedSettings["react-native-tools"].projectRoot; |
| 284 | return path.resolve(vsCodeRoot, projectRootPath); |
| 285 | } catch (e) { |
| 286 | return path.resolve(args.program, "../.."); |
| 287 | } |
| 288 | } |