microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/debugSessionBase.ts
254lines · 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 vscode from "vscode"; | |
| 5 | import * as path from "path"; | |
| 6 | import * as fs from "fs"; | |
| 7 | import stripJsonComments = require("strip-json-comments"); | |
984ca036RedMickey6 years ago | 8 | import { LoggingDebugSession, Logger, logger, ErrorDestination } from "vscode-debugadapter"; |
2c19da7fRedMickey6 years ago | 9 | import { DebugProtocol } from "vscode-debugprotocol"; |
| 10 | import { getLoggingDirectory, LogHelper } from "../extension/log/LogHelper"; | |
| 11 | import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper"; | |
| 12 | import { ErrorHelper } from "../common/error/errorHelper"; | |
| 13 | import { InternalErrorCode } from "../common/error/internalErrorCode"; | |
e23d1841RedMickey6 years ago | 14 | import { InternalError, NestedError } from "../common/error/internalError"; |
5471436aRedMickey5 years ago | 15 | import { IRunOptions, PlatformType } from "../extension/launchArgs"; |
2c19da7fRedMickey6 years ago | 16 | import { AppLauncher } from "../extension/appLauncher"; |
| 17 | import { LogLevel } from "../extension/log/LogHelper"; | |
e23d1841RedMickey6 years ago | 18 | import * as nls from "vscode-nls"; |
34472878RedMickey5 years ago | 19 | nls.config({ |
| 20 | messageFormat: nls.MessageFormat.bundle, | |
| 21 | bundleFormat: nls.BundleFormat.standalone, | |
| 22 | })(); | |
e23d1841RedMickey6 years ago | 23 | const localize = nls.loadMessageBundle(); |
2c19da7fRedMickey6 years ago | 24 | |
| 25 | /** | |
| 26 | * Enum of possible statuses of debug session | |
| 27 | */ | |
| 28 | export enum DebugSessionStatus { | |
| 29 | /** A session has been just created */ | |
| 30 | FirstConnection, | |
| 31 | /** This status is required in order to exclude the possible creation of several debug sessions at the first start */ | |
| 32 | FirstConnectionPending, | |
| 33 | /** This status means that an application can be reloaded */ | |
| 34 | ConnectionAllowed, | |
| 35 | /** This status means that an application is reloading now, and we shouldn't terminate the current debug session */ | |
| 36 | ConnectionPending, | |
| 37 | /** A debuggee connected successfully */ | |
| 38 | ConnectionDone, | |
| 39 | /** A debuggee failed to connect */ | |
| 40 | ConnectionFailed, | |
| 41 | } | |
| 42 | | |
ebbd64f1RedMickey6 years ago | 43 | export interface TerminateEventArgs { |
| 44 | debugSession: vscode.DebugSession; | |
| 45 | args: any; | |
| 46 | } | |
| 47 | | |
5471436aRedMickey5 years ago | 48 | export interface IAttachRequestArgs |
| 49 | extends DebugProtocol.AttachRequestArguments, | |
| 50 | IRunOptions, | |
| 51 | vscode.DebugConfiguration { | |
259c018fYuri Skorokhodov5 years ago | 52 | webkitRangeMax: number; |
| 53 | webkitRangeMin: number; | |
34472878RedMickey5 years ago | 54 | cwd: string /* Automatically set by VS Code to the currently opened folder */; |
2c19da7fRedMickey6 years ago | 55 | port: number; |
| 56 | url?: string; | |
6f9a0779JiglioNero5 years ago | 57 | useHermesEngine: boolean; |
2c19da7fRedMickey6 years ago | 58 | address?: string; |
| 59 | trace?: string; | |
5d47053fRedMickey6 years ago | 60 | skipFiles?: []; |
1bdccb66RedMickey6 years ago | 61 | sourceMaps?: boolean; |
| 62 | sourceMapPathOverrides?: { [key: string]: string }; | |
2c19da7fRedMickey6 years ago | 63 | } |
| 64 | | |
34472878RedMickey5 years ago | 65 | export interface ILaunchRequestArgs |
| 66 | extends DebugProtocol.LaunchRequestArguments, | |
| 67 | IAttachRequestArgs {} | |
2c19da7fRedMickey6 years ago | 68 | |
| 69 | export abstract class DebugSessionBase extends LoggingDebugSession { | |
ebbd64f1RedMickey6 years ago | 70 | protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> = new vscode.EventEmitter<TerminateEventArgs>(); |
34472878RedMickey5 years ago | 71 | public static readonly onDidTerminateRootDebugSession = |
| 72 | DebugSessionBase.rootSessionTerminatedEventEmitter.event; | |
ebbd64f1RedMickey6 years ago | 73 | |
a2ddbba5RedMickey5 years ago | 74 | protected readonly stopCommand: string; |
ebbd64f1RedMickey6 years ago | 75 | protected readonly pwaNodeSessionName: string; |
| 76 | | |
2c19da7fRedMickey6 years ago | 77 | protected appLauncher: AppLauncher; |
| 78 | protected projectRootPath: string; | |
| 79 | protected isSettingsInitialized: boolean; // used to prevent parameters reinitialization when attach is called from launch function | |
| 80 | protected previousAttachArgs: IAttachRequestArgs; | |
| 81 | protected cdpProxyLogLevel: LogLevel; | |
| 82 | protected debugSessionStatus: DebugSessionStatus; | |
| 83 | protected session: vscode.DebugSession; | |
e23d1841RedMickey6 years ago | 84 | protected cancellationTokenSource: vscode.CancellationTokenSource; |
2c19da7fRedMickey6 years ago | 85 | |
| 86 | constructor(session: vscode.DebugSession) { | |
| 87 | super(); | |
| 88 | | |
ebbd64f1RedMickey6 years ago | 89 | // constants definition |
| 90 | this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension | |
a2ddbba5RedMickey5 years ago | 91 | this.stopCommand = "workbench.action.debug.stop"; // the command which simulates a click on the "Stop" button |
ebbd64f1RedMickey6 years ago | 92 | |
| 93 | // variables definition | |
2c19da7fRedMickey6 years ago | 94 | this.session = session; |
| 95 | this.isSettingsInitialized = false; | |
| 96 | this.debugSessionStatus = DebugSessionStatus.FirstConnection; | |
e23d1841RedMickey6 years ago | 97 | this.cancellationTokenSource = new vscode.CancellationTokenSource(); |
| 98 | } | |
| 99 | | |
34472878RedMickey5 years ago | 100 | protected initializeRequest( |
| 101 | response: DebugProtocol.InitializeResponse, | |
| 102 | // eslint-disable-next-line @typescript-eslint/no-unused-vars | |
| 103 | args: DebugProtocol.InitializeRequestArguments, | |
| 104 | ): void { | |
e23d1841RedMickey6 years ago | 105 | response.body = response.body || {}; |
| 106 | | |
| 107 | response.body.supportsConfigurationDoneRequest = true; | |
| 108 | response.body.supportsEvaluateForHovers = true; | |
| 109 | response.body.supportTerminateDebuggee = true; | |
| 110 | response.body.supportsCancelRequest = true; | |
| 111 | | |
| 112 | this.sendResponse(response); | |
2c19da7fRedMickey6 years ago | 113 | } |
| 114 | | |
34472878RedMickey5 years ago | 115 | protected abstract establishDebugSession( |
| 116 | attachArgs: IAttachRequestArgs, | |
| 117 | resolve?: (value?: void | PromiseLike<void> | undefined) => void, | |
| 118 | ): void; | |
b7451aefRedMickey6 years ago | 119 | |
4dfb1c4cetatanova5 years ago | 120 | protected initializeSettings(args: any): Promise<void> { |
2c19da7fRedMickey6 years ago | 121 | if (!this.isSettingsInitialized) { |
| 122 | let chromeDebugCoreLogs = getLoggingDirectory(); | |
| 123 | if (chromeDebugCoreLogs) { | |
| 124 | chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "DebugSessionLogs.txt"); | |
| 125 | } | |
| 126 | let logLevel: string = args.trace; | |
| 127 | if (logLevel) { | |
| 128 | logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase()); | |
| 129 | logger.setup(Logger.LogLevel[logLevel], chromeDebugCoreLogs || false); | |
34472878RedMickey5 years ago | 130 | this.cdpProxyLogLevel = |
| 131 | LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None; | |
2c19da7fRedMickey6 years ago | 132 | } else { |
| 133 | logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false); | |
34472878RedMickey5 years ago | 134 | this.cdpProxyLogLevel = |
| 135 | LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None; | |
2c19da7fRedMickey6 years ago | 136 | } |
| 137 | | |
2db9ac85Yuri Skorokhodov5 years ago | 138 | if (typeof args.sourceMaps !== "boolean") { |
2c19da7fRedMickey6 years ago | 139 | args.sourceMaps = true; |
| 140 | } | |
| 141 | | |
5514e287RedMickey6 years ago | 142 | if (typeof args.enableDebug !== "boolean") { |
| 143 | args.enableDebug = true; | |
| 144 | } | |
| 145 | | |
2c19da7fRedMickey6 years ago | 146 | const projectRootPath = getProjectRoot(args); |
4dfb1c4cetatanova5 years ago | 147 | |
| 148 | return ReactNativeProjectHelper.isReactNativeProject(projectRootPath).then( | |
| 149 | (result: boolean) => { | |
| 150 | if (!result) { | |
| 151 | throw ErrorHelper.getInternalError( | |
| 152 | InternalErrorCode.NotInReactNativeFolderError, | |
| 153 | ); | |
| 154 | } | |
| 155 | return AppLauncher.getOrCreateAppLauncherByProjectRootPath( | |
| 156 | projectRootPath, | |
| 157 | ).then((appLauncher: AppLauncher) => { | |
| 158 | this.appLauncher = appLauncher; | |
| 159 | this.projectRootPath = projectRootPath; | |
| 160 | this.isSettingsInitialized = true; | |
| 161 | this.appLauncher.getOrUpdateNodeModulesRoot(true); | |
| 162 | if (this.session.workspaceFolder) { | |
| 163 | this.appLauncher.updateDebugConfigurationRoot( | |
| 164 | this.session.workspaceFolder.uri.fsPath, | |
| 165 | ); | |
| 166 | } | |
| 167 | }); | |
| 168 | }, | |
| 169 | ); | |
2c19da7fRedMickey6 years ago | 170 | } else { |
ce5e88eeYuri Skorokhodov5 years ago | 171 | return Promise.resolve(); |
2c19da7fRedMickey6 years ago | 172 | } |
| 173 | } | |
984ca036RedMickey6 years ago | 174 | |
34472878RedMickey5 years ago | 175 | protected async disconnectRequest( |
| 176 | response: DebugProtocol.DisconnectResponse, | |
| 177 | args: DebugProtocol.DisconnectArguments, | |
| 178 | // eslint-disable-next-line @typescript-eslint/no-unused-vars | |
| 179 | request?: DebugProtocol.Request, | |
| 180 | ): Promise<void> { | |
a32e1e1fYuri Skorokhodov5 years ago | 181 | if (this.appLauncher) { |
| 182 | await this.appLauncher.getRnCdpProxy().stopServer(); | |
| 183 | } | |
e23d1841RedMickey6 years ago | 184 | |
| 185 | this.cancellationTokenSource.cancel(); | |
| 186 | this.cancellationTokenSource.dispose(); | |
| 187 | | |
| 188 | // Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session | |
259c018fYuri Skorokhodov5 years ago | 189 | if (this.previousAttachArgs && this.previousAttachArgs.platform === PlatformType.Android) { |
e23d1841RedMickey6 years ago | 190 | try { |
8df5011eYuri Skorokhodov5 years ago | 191 | this.appLauncher.getMobilePlatform().dispose(); |
e23d1841RedMickey6 years ago | 192 | } catch (err) { |
34472878RedMickey5 years ago | 193 | logger.warn( |
| 194 | localize( | |
| 195 | "CouldNotStopMonitoringLogcat", | |
| 196 | "Couldn't stop monitoring logcat: {0}", | |
| 197 | err.message || err, | |
| 198 | ), | |
| 199 | ); | |
e23d1841RedMickey6 years ago | 200 | } |
| 201 | } | |
| 202 | | |
67ffa5b4RedMickey6 years ago | 203 | await logger.dispose(); |
| 204 | | |
ebbd64f1RedMickey6 years ago | 205 | DebugSessionBase.rootSessionTerminatedEventEmitter.fire({ |
| 206 | debugSession: this.session, | |
| 207 | args: { | |
a2ddbba5RedMickey5 years ago | 208 | forcedStop: !!(<any>args).forcedStop, |
ebbd64f1RedMickey6 years ago | 209 | }, |
| 210 | }); | |
| 211 | | |
| 212 | this.sendResponse(response); | |
e23d1841RedMickey6 years ago | 213 | } |
| 214 | | |
| 215 | protected showError(error: Error, response: DebugProtocol.Response): void { | |
| 216 | // We can't print error messages after the debugging session is stopped. This could break the extension work. | |
34472878RedMickey5 years ago | 217 | if ( |
| 218 | (error instanceof InternalError || error instanceof NestedError) && | |
| 219 | error.errorCode === InternalErrorCode.CancellationTokenTriggered | |
e23d1841RedMickey6 years ago | 220 | ) { |
| 221 | return; | |
| 222 | } | |
| 223 | | |
984ca036RedMickey6 years ago | 224 | this.sendErrorResponse( |
| 225 | response, | |
e23d1841RedMickey6 years ago | 226 | { format: error.message, id: 1 }, |
984ca036RedMickey6 years ago | 227 | undefined, |
| 228 | undefined, | |
34472878RedMickey5 years ago | 229 | ErrorDestination.User, |
984ca036RedMickey6 years ago | 230 | ); |
| 231 | } | |
2c19da7fRedMickey6 years ago | 232 | } |
| 233 | | |
| 234 | /** | |
| 235 | * Parses settings.json file for workspace root property | |
| 236 | */ | |
| 237 | export function getProjectRoot(args: any): string { | |
| 238 | const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../.."); | |
| 239 | const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json"); | |
| 240 | try { | |
| 241 | let settingsContent = fs.readFileSync(settingsPath, "utf8"); | |
| 242 | settingsContent = stripJsonComments(settingsContent); | |
| 243 | let parsedSettings = JSON.parse(settingsContent); | |
34472878RedMickey5 years ago | 244 | let projectRootPath = |
| 245 | parsedSettings["react-native-tools.projectRoot"] || | |
| 246 | parsedSettings["react-native-tools"].projectRoot; | |
2c19da7fRedMickey6 years ago | 247 | return path.resolve(vsCodeRoot, projectRootPath); |
| 248 | } catch (e) { | |
34472878RedMickey5 years ago | 249 | logger.verbose( |
| 250 | `${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`, | |
| 251 | ); | |
2c19da7fRedMickey6 years ago | 252 | return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../.."); |
| 253 | } | |
| 254 | } |