microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/debugSessionBase.ts
332lines · modeblame
2c19da7fRedMickey6 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 path from "path"; | |
| 5 | import * as fs from "fs"; | |
09f6024fHeniker4 years ago | 6 | import * as vscode from "vscode"; |
623be8a6Ezio Li2 years ago | 7 | import { LoggingDebugSession, Logger, logger, ErrorDestination } from "@vscode/debugadapter"; |
2c19da7fRedMickey6 years ago | 8 | import { DebugProtocol } from "vscode-debugprotocol"; |
09f6024fHeniker4 years ago | 9 | import * as nls from "vscode-nls"; |
dc94981bQuan Jin3 years ago | 10 | import { stripJsonTrailingComma } from "../common/utils"; |
09f6024fHeniker4 years ago | 11 | import { getLoggingDirectory, LogHelper, LogLevel } from "../extension/log/LogHelper"; |
2c19da7fRedMickey6 years ago | 12 | import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper"; |
| 13 | import { ErrorHelper } from "../common/error/errorHelper"; | |
| 14 | import { InternalErrorCode } from "../common/error/internalErrorCode"; | |
e23d1841RedMickey6 years ago | 15 | import { InternalError, NestedError } from "../common/error/internalError"; |
bfcc8a29Samriel4 years ago | 16 | import { ILaunchArgs, IRunOptions, PlatformType } from "../extension/launchArgs"; |
2c19da7fRedMickey6 years ago | 17 | import { AppLauncher } from "../extension/appLauncher"; |
bfcc8a29Samriel4 years ago | 18 | import { RNPackageVersions } from "../common/projectVersionHelper"; |
43e6ccc3JiglioNero4 years ago | 19 | import { SettingsHelper } from "../extension/settingsHelper"; |
19df32dcRedMickey4 years ago | 20 | import { OutputChannelLogger } from "../extension/log/OutputChannelLogger"; |
d93677adRedMickey4 years ago | 21 | import { RNSession } from "./debugSessionWrapper"; |
bfcc8a29Samriel4 years ago | 22 | |
34472878RedMickey5 years ago | 23 | nls.config({ |
| 24 | messageFormat: nls.MessageFormat.bundle, | |
| 25 | bundleFormat: nls.BundleFormat.standalone, | |
| 26 | })(); | |
e23d1841RedMickey6 years ago | 27 | const localize = nls.loadMessageBundle(); |
2c19da7fRedMickey6 years ago | 28 | |
| 29 | /** | |
| 30 | * Enum of possible statuses of debug session | |
| 31 | */ | |
| 32 | export enum DebugSessionStatus { | |
| 33 | /** A session has been just created */ | |
| 34 | FirstConnection, | |
| 35 | /** This status is required in order to exclude the possible creation of several debug sessions at the first start */ | |
| 36 | FirstConnectionPending, | |
| 37 | /** This status means that an application can be reloaded */ | |
| 38 | ConnectionAllowed, | |
| 39 | /** This status means that an application is reloading now, and we shouldn't terminate the current debug session */ | |
| 40 | ConnectionPending, | |
| 41 | /** A debuggee connected successfully */ | |
| 42 | ConnectionDone, | |
| 43 | /** A debuggee failed to connect */ | |
| 44 | ConnectionFailed, | |
19df32dcRedMickey4 years ago | 45 | /** The session is handling disconnect request now */ |
| 46 | Stopping, | |
| 47 | /** The session is stopped */ | |
| 48 | Stopped, | |
2c19da7fRedMickey6 years ago | 49 | } |
| 50 | | |
ebbd64f1RedMickey6 years ago | 51 | export interface TerminateEventArgs { |
| 52 | debugSession: vscode.DebugSession; | |
| 53 | args: any; | |
| 54 | } | |
| 55 | | |
5471436aRedMickey5 years ago | 56 | export interface IAttachRequestArgs |
| 57 | extends DebugProtocol.AttachRequestArguments, | |
| 58 | IRunOptions, | |
| 59 | vscode.DebugConfiguration { | |
259c018fYuri Skorokhodov5 years ago | 60 | webkitRangeMax: number; |
| 61 | webkitRangeMin: number; | |
34472878RedMickey5 years ago | 62 | cwd: string /* Automatically set by VS Code to the currently opened folder */; |
2c19da7fRedMickey6 years ago | 63 | port: number; |
| 64 | url?: string; | |
6f9a0779JiglioNero5 years ago | 65 | useHermesEngine: boolean; |
2c19da7fRedMickey6 years ago | 66 | address?: string; |
| 67 | trace?: string; | |
5d47053fRedMickey6 years ago | 68 | skipFiles?: []; |
1bdccb66RedMickey6 years ago | 69 | sourceMaps?: boolean; |
| 70 | sourceMapPathOverrides?: { [key: string]: string }; | |
2d89fb47Ezio Li3 years ago | 71 | jsDebugTrace?: boolean; |
9f8c460dEzio Li2 years ago | 72 | browserTarget?: string; |
2c19da7fRedMickey6 years ago | 73 | } |
| 74 | | |
34472878RedMickey5 years ago | 75 | export interface ILaunchRequestArgs |
| 76 | extends DebugProtocol.LaunchRequestArguments, | |
| 77 | IAttachRequestArgs {} | |
2c19da7fRedMickey6 years ago | 78 | |
| 79 | export abstract class DebugSessionBase extends LoggingDebugSession { | |
09f6024fHeniker4 years ago | 80 | protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> = |
| 81 | new vscode.EventEmitter<TerminateEventArgs>(); | |
34472878RedMickey5 years ago | 82 | public static readonly onDidTerminateRootDebugSession = |
| 83 | DebugSessionBase.rootSessionTerminatedEventEmitter.event; | |
ebbd64f1RedMickey6 years ago | 84 | |
a2ddbba5RedMickey5 years ago | 85 | protected readonly stopCommand: string; |
19df32dcRedMickey4 years ago | 86 | protected readonly terminateCommand: string; |
ebbd64f1RedMickey6 years ago | 87 | protected readonly pwaNodeSessionName: string; |
| 88 | | |
2c19da7fRedMickey6 years ago | 89 | protected appLauncher: AppLauncher; |
| 90 | protected projectRootPath: string; | |
| 91 | protected isSettingsInitialized: boolean; // used to prevent parameters reinitialization when attach is called from launch function | |
| 92 | protected previousAttachArgs: IAttachRequestArgs; | |
| 93 | protected cdpProxyLogLevel: LogLevel; | |
| 94 | protected debugSessionStatus: DebugSessionStatus; | |
19df32dcRedMickey4 years ago | 95 | protected nodeSession: vscode.DebugSession | null; |
d93677adRedMickey4 years ago | 96 | protected rnSession: RNSession; |
| 97 | protected vsCodeDebugSession: vscode.DebugSession; | |
e23d1841RedMickey6 years ago | 98 | protected cancellationTokenSource: vscode.CancellationTokenSource; |
2c19da7fRedMickey6 years ago | 99 | |
d93677adRedMickey4 years ago | 100 | constructor(rnSession: RNSession) { |
2c19da7fRedMickey6 years ago | 101 | super(); |
| 102 | | |
ebbd64f1RedMickey6 years ago | 103 | // constants definition |
| 104 | this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension | |
a2ddbba5RedMickey5 years ago | 105 | this.stopCommand = "workbench.action.debug.stop"; // the command which simulates a click on the "Stop" button |
19df32dcRedMickey4 years ago | 106 | this.terminateCommand = "terminate"; // the "terminate" command is sent from the client to the debug adapter in order to give the debuggee a chance for terminating itself |
ebbd64f1RedMickey6 years ago | 107 | |
| 108 | // variables definition | |
d93677adRedMickey4 years ago | 109 | this.rnSession = rnSession; |
| 110 | this.vsCodeDebugSession = rnSession.vsCodeDebugSession; | |
2c19da7fRedMickey6 years ago | 111 | this.isSettingsInitialized = false; |
| 112 | this.debugSessionStatus = DebugSessionStatus.FirstConnection; | |
e23d1841RedMickey6 years ago | 113 | this.cancellationTokenSource = new vscode.CancellationTokenSource(); |
19df32dcRedMickey4 years ago | 114 | this.nodeSession = null; |
e23d1841RedMickey6 years ago | 115 | } |
| 116 | | |
34472878RedMickey5 years ago | 117 | protected initializeRequest( |
| 118 | response: DebugProtocol.InitializeResponse, | |
| 119 | // eslint-disable-next-line @typescript-eslint/no-unused-vars | |
| 120 | args: DebugProtocol.InitializeRequestArguments, | |
| 121 | ): void { | |
e23d1841RedMickey6 years ago | 122 | response.body = response.body || {}; |
| 123 | | |
| 124 | response.body.supportsConfigurationDoneRequest = true; | |
| 125 | response.body.supportsEvaluateForHovers = true; | |
| 126 | response.body.supportTerminateDebuggee = true; | |
| 127 | response.body.supportsCancelRequest = true; | |
| 128 | | |
1bb1a217EzioLi2 years ago | 129 | response.body.exceptionBreakpointFilters = [ |
| 130 | { | |
| 131 | filter: "all", | |
| 132 | label: "Caught Exceptions", | |
| 133 | default: false, | |
| 134 | supportsCondition: true, | |
| 135 | description: "Breaks on all throw errors, even if they're caught later.", | |
| 136 | // eslint-disable-next-line @typescript-eslint/quotes | |
| 137 | conditionDescription: 'error.name == "MyError"', | |
| 138 | }, | |
| 139 | { | |
| 140 | filter: "uncaught", | |
| 141 | label: "Uncaught Exceptions", | |
| 142 | default: false, | |
| 143 | supportsCondition: true, | |
| 144 | description: "Breaks only on errors or promise rejections that are not handled.", | |
| 145 | // eslint-disable-next-line @typescript-eslint/quotes | |
| 146 | conditionDescription: 'error.name == "MyError"', | |
| 147 | }, | |
| 148 | ]; | |
| 149 | | |
e23d1841RedMickey6 years ago | 150 | this.sendResponse(response); |
2c19da7fRedMickey6 years ago | 151 | } |
| 152 | | |
34472878RedMickey5 years ago | 153 | protected abstract establishDebugSession( |
| 154 | attachArgs: IAttachRequestArgs, | |
| 155 | resolve?: (value?: void | PromiseLike<void> | undefined) => void, | |
| 156 | ): void; | |
b7451aefRedMickey6 years ago | 157 | |
0d77292aJiglioNero4 years ago | 158 | protected async initializeSettings(args: any): Promise<void> { |
2c19da7fRedMickey6 years ago | 159 | if (!this.isSettingsInitialized) { |
| 160 | let chromeDebugCoreLogs = getLoggingDirectory(); | |
| 161 | if (chromeDebugCoreLogs) { | |
| 162 | chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "DebugSessionLogs.txt"); | |
| 163 | } | |
| 164 | let logLevel: string = args.trace; | |
| 165 | if (logLevel) { | |
| 166 | logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase()); | |
5b09cf97Zhen Zhen Yuan (BEYONDSOFT CONSULTING INC)7 months ago | 167 | logger.setup((Logger.LogLevel as any)[logLevel], chromeDebugCoreLogs || false); |
34472878RedMickey5 years ago | 168 | this.cdpProxyLogLevel = |
5b09cf97Zhen Zhen Yuan (BEYONDSOFT CONSULTING INC)7 months ago | 169 | (LogLevel as any)[logLevel] === LogLevel.Verbose |
| 170 | ? LogLevel.Custom | |
| 171 | : LogLevel.None; | |
2c19da7fRedMickey6 years ago | 172 | } else { |
| 173 | logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false); | |
34472878RedMickey5 years ago | 174 | this.cdpProxyLogLevel = |
| 175 | LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None; | |
2c19da7fRedMickey6 years ago | 176 | } |
| 177 | | |
2db9ac85Yuri Skorokhodov5 years ago | 178 | if (typeof args.sourceMaps !== "boolean") { |
2c19da7fRedMickey6 years ago | 179 | args.sourceMaps = true; |
| 180 | } | |
| 181 | | |
5514e287RedMickey6 years ago | 182 | if (typeof args.enableDebug !== "boolean") { |
| 183 | args.enableDebug = true; | |
| 184 | } | |
| 185 | | |
81fc1822JiglioNero4 years ago | 186 | // Now there is a problem with processing time of 'createFromSourceMap' function of js-debug |
| 187 | // So we disable this functionality by default https://github.com/microsoft/vscode-js-debug/issues/1033 | |
| 188 | if (typeof args.sourceMapRenames !== "boolean") { | |
| 189 | args.sourceMapRenames = false; | |
| 190 | } | |
| 191 | | |
43e6ccc3JiglioNero4 years ago | 192 | const projectRootPath = SettingsHelper.getReactNativeProjectRoot(args.cwd); |
0d77292aJiglioNero4 years ago | 193 | const isReactProject = await ReactNativeProjectHelper.isReactNativeProject( |
| 194 | projectRootPath, | |
| 195 | ); | |
| 196 | if (!isReactProject) { | |
| 197 | throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError); | |
| 198 | } | |
4dfb1c4cetatanova5 years ago | 199 | |
0d77292aJiglioNero4 years ago | 200 | const appLauncher = await AppLauncher.getOrCreateAppLauncherByProjectRootPath( |
| 201 | projectRootPath, | |
4dfb1c4cetatanova5 years ago | 202 | ); |
0d77292aJiglioNero4 years ago | 203 | this.appLauncher = appLauncher; |
| 204 | this.projectRootPath = projectRootPath; | |
| 205 | this.isSettingsInitialized = true; | |
| 206 | this.appLauncher.getOrUpdateNodeModulesRoot(true); | |
d93677adRedMickey4 years ago | 207 | if (this.vsCodeDebugSession.workspaceFolder) { |
0d77292aJiglioNero4 years ago | 208 | this.appLauncher.updateDebugConfigurationRoot( |
d93677adRedMickey4 years ago | 209 | this.vsCodeDebugSession.workspaceFolder.uri.fsPath, |
0d77292aJiglioNero4 years ago | 210 | ); |
| 211 | } | |
b84470b5Ezio Li2 years ago | 212 | const settingsPort = this.appLauncher.getPackagerPort(projectRootPath); |
| 213 | if (this.appLauncher.getPackager().getPort() != settingsPort) { | |
| 214 | this.appLauncher.getPackager().resetToSettingsPort(); | |
| 215 | } | |
2c19da7fRedMickey6 years ago | 216 | } |
| 217 | } | |
984ca036RedMickey6 years ago | 218 | |
34472878RedMickey5 years ago | 219 | protected async disconnectRequest( |
| 220 | response: DebugProtocol.DisconnectResponse, | |
| 221 | args: DebugProtocol.DisconnectArguments, | |
| 222 | // eslint-disable-next-line @typescript-eslint/no-unused-vars | |
| 223 | request?: DebugProtocol.Request, | |
| 224 | ): Promise<void> { | |
a32e1e1fYuri Skorokhodov5 years ago | 225 | if (this.appLauncher) { |
| 226 | await this.appLauncher.getRnCdpProxy().stopServer(); | |
| 227 | } | |
e23d1841RedMickey6 years ago | 228 | |
| 229 | this.cancellationTokenSource.cancel(); | |
| 230 | this.cancellationTokenSource.dispose(); | |
| 231 | | |
| 232 | // Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session | |
259c018fYuri Skorokhodov5 years ago | 233 | if (this.previousAttachArgs && this.previousAttachArgs.platform === PlatformType.Android) { |
e23d1841RedMickey6 years ago | 234 | try { |
8df5011eYuri Skorokhodov5 years ago | 235 | this.appLauncher.getMobilePlatform().dispose(); |
e23d1841RedMickey6 years ago | 236 | } catch (err) { |
34472878RedMickey5 years ago | 237 | logger.warn( |
| 238 | localize( | |
| 239 | "CouldNotStopMonitoringLogcat", | |
| 240 | "Couldn't stop monitoring logcat: {0}", | |
| 241 | err.message || err, | |
| 242 | ), | |
| 243 | ); | |
e23d1841RedMickey6 years ago | 244 | } |
| 245 | } | |
| 246 | | |
19df32dcRedMickey4 years ago | 247 | this.debugSessionStatus = DebugSessionStatus.Stopped; |
67ffa5b4RedMickey6 years ago | 248 | await logger.dispose(); |
| 249 | | |
ebbd64f1RedMickey6 years ago | 250 | DebugSessionBase.rootSessionTerminatedEventEmitter.fire({ |
d93677adRedMickey4 years ago | 251 | debugSession: this.vsCodeDebugSession, |
ebbd64f1RedMickey6 years ago | 252 | args: { |
a2ddbba5RedMickey5 years ago | 253 | forcedStop: !!(<any>args).forcedStop, |
ebbd64f1RedMickey6 years ago | 254 | }, |
| 255 | }); | |
| 256 | | |
| 257 | this.sendResponse(response); | |
e23d1841RedMickey6 years ago | 258 | } |
| 259 | | |
19df32dcRedMickey4 years ago | 260 | protected terminateWithErrorResponse(error: Error, response: DebugProtocol.Response): void { |
e23d1841RedMickey6 years ago | 261 | // We can't print error messages after the debugging session is stopped. This could break the extension work. |
34472878RedMickey5 years ago | 262 | if ( |
| 263 | (error instanceof InternalError || error instanceof NestedError) && | |
| 264 | error.errorCode === InternalErrorCode.CancellationTokenTriggered | |
e23d1841RedMickey6 years ago | 265 | ) { |
| 266 | return; | |
| 267 | } | |
| 268 | | |
28ceac00RedMickey4 years ago | 269 | logger.error(error.message); |
| 270 | | |
984ca036RedMickey6 years ago | 271 | this.sendErrorResponse( |
| 272 | response, | |
e23d1841RedMickey6 years ago | 273 | { format: error.message, id: 1 }, |
984ca036RedMickey6 years ago | 274 | undefined, |
| 275 | undefined, | |
34472878RedMickey5 years ago | 276 | ErrorDestination.User, |
984ca036RedMickey6 years ago | 277 | ); |
| 278 | } | |
2c19da7fRedMickey6 years ago | 279 | |
bfcc8a29Samriel4 years ago | 280 | protected async preparePackagerBeforeAttach( |
| 281 | args: IAttachRequestArgs, | |
| 282 | reactNativeVersions: RNPackageVersions, | |
| 283 | ): Promise<void> { | |
| 284 | if (!(await this.appLauncher.getPackager().isRunning())) { | |
| 285 | const runOptions: ILaunchArgs = Object.assign( | |
| 286 | { reactNativeVersions }, | |
| 287 | this.appLauncher.prepareBaseRunOptions(args), | |
| 288 | ); | |
| 289 | this.appLauncher.getPackager().setRunOptions(runOptions); | |
| 290 | await this.appLauncher.getPackager().start(); | |
| 291 | } | |
| 292 | } | |
19df32dcRedMickey4 years ago | 293 | |
| 294 | protected showError(error: Error): void { | |
| 295 | void vscode.window.showErrorMessage(error.message, { | |
| 296 | modal: true, | |
| 297 | }); | |
| 298 | // We can't print error messages via debug session logger after the session is stopped. This could break the extension work. | |
| 299 | if (this.debugSessionStatus === DebugSessionStatus.Stopped) { | |
| 300 | OutputChannelLogger.getMainChannel().error(error.message); | |
| 301 | return; | |
| 302 | } | |
| 303 | logger.error(error.message); | |
| 304 | } | |
| 305 | | |
| 306 | protected async terminate(): Promise<void> { | |
| 307 | await vscode.commands.executeCommand(this.stopCommand, undefined, { | |
| 308 | sessionId: this.vsCodeDebugSession.id, | |
| 309 | }); | |
| 310 | } | |
2c19da7fRedMickey6 years ago | 311 | } |
dc94981bQuan Jin3 years ago | 312 | |
| 313 | /** | |
| 314 | * Parses settings.json file for workspace root property | |
| 315 | */ | |
| 316 | export function getProjectRoot(args: any): string { | |
| 317 | const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../.."); | |
| 318 | const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json"); | |
| 319 | try { | |
| 320 | const settingsContent = fs.readFileSync(settingsPath, "utf8"); | |
| 321 | const parsedSettings = stripJsonTrailingComma(settingsContent); | |
| 322 | const projectRootPath = | |
| 323 | parsedSettings["react-native-tools.projectRoot"] || | |
| 324 | parsedSettings["react-native-tools"].projectRoot; | |
| 325 | return path.resolve(vsCodeRoot, projectRootPath); | |
| 326 | } catch (e) { | |
| 327 | logger.verbose( | |
| 328 | `${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`, | |
| 329 | ); | |
| 330 | return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../.."); | |
| 331 | } | |
| 332 | } |