microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
1c2424f4d9af42a0cefcacb0fcb9670b5aa292cd

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/debugger/debugSessionBase.ts

254lines · 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
4import * as vscode from "vscode";
5import * as path from "path";
6import * as fs from "fs";
7import stripJsonComments = require("strip-json-comments");
8import { LoggingDebugSession, Logger, logger, ErrorDestination } from "vscode-debugadapter";
9import { DebugProtocol } from "vscode-debugprotocol";
10import { getLoggingDirectory, LogHelper } from "../extension/log/LogHelper";
11import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper";
12import { ErrorHelper } from "../common/error/errorHelper";
13import { InternalErrorCode } from "../common/error/internalErrorCode";
14import { InternalError, NestedError } from "../common/error/internalError";
15import { IRunOptions, PlatformType } from "../extension/launchArgs";
16import { AppLauncher } from "../extension/appLauncher";
17import { LogLevel } from "../extension/log/LogHelper";
18import * as nls from "vscode-nls";
19nls.config({
20 messageFormat: nls.MessageFormat.bundle,
21 bundleFormat: nls.BundleFormat.standalone,
22})();
23const localize = nls.loadMessageBundle();
24
25/**
26 * Enum of possible statuses of debug session
27 */
28export 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
43export interface TerminateEventArgs {
44 debugSession: vscode.DebugSession;
45 args: any;
46}
47
48export interface IAttachRequestArgs
49 extends DebugProtocol.AttachRequestArguments,
50 IRunOptions,
51 vscode.DebugConfiguration {
52 webkitRangeMax: number;
53 webkitRangeMin: number;
54 cwd: string /* Automatically set by VS Code to the currently opened folder */;
55 port: number;
56 url?: string;
57 useHermesEngine: boolean;
58 address?: string;
59 trace?: string;
60 skipFiles?: [];
61 sourceMaps?: boolean;
62 sourceMapPathOverrides?: { [key: string]: string };
63}
64
65export interface ILaunchRequestArgs
66 extends DebugProtocol.LaunchRequestArguments,
67 IAttachRequestArgs {}
68
69export abstract class DebugSessionBase extends LoggingDebugSession {
70 protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> = new vscode.EventEmitter<TerminateEventArgs>();
71 public static readonly onDidTerminateRootDebugSession =
72 DebugSessionBase.rootSessionTerminatedEventEmitter.event;
73
74 protected readonly stopCommand: string;
75 protected readonly pwaNodeSessionName: string;
76
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;
84 protected cancellationTokenSource: vscode.CancellationTokenSource;
85
86 constructor(session: vscode.DebugSession) {
87 super();
88
89 // constants definition
90 this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension
91 this.stopCommand = "workbench.action.debug.stop"; // the command which simulates a click on the "Stop" button
92
93 // variables definition
94 this.session = session;
95 this.isSettingsInitialized = false;
96 this.debugSessionStatus = DebugSessionStatus.FirstConnection;
97 this.cancellationTokenSource = new vscode.CancellationTokenSource();
98 }
99
100 protected initializeRequest(
101 response: DebugProtocol.InitializeResponse,
102 // eslint-disable-next-line @typescript-eslint/no-unused-vars
103 args: DebugProtocol.InitializeRequestArguments,
104 ): void {
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);
113 }
114
115 protected abstract establishDebugSession(
116 attachArgs: IAttachRequestArgs,
117 resolve?: (value?: void | PromiseLike<void> | undefined) => void,
118 ): void;
119
120 protected initializeSettings(args: any): Promise<void> {
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);
130 this.cdpProxyLogLevel =
131 LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None;
132 } else {
133 logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false);
134 this.cdpProxyLogLevel =
135 LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None;
136 }
137
138 if (typeof args.sourceMaps !== "boolean") {
139 args.sourceMaps = true;
140 }
141
142 if (typeof args.enableDebug !== "boolean") {
143 args.enableDebug = true;
144 }
145
146 const projectRootPath = getProjectRoot(args);
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 );
170 } else {
171 return Promise.resolve();
172 }
173 }
174
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> {
181 if (this.appLauncher) {
182 await this.appLauncher.getRnCdpProxy().stopServer();
183 }
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
189 if (this.previousAttachArgs && this.previousAttachArgs.platform === PlatformType.Android) {
190 try {
191 this.appLauncher.getMobilePlatform().dispose();
192 } catch (err) {
193 logger.warn(
194 localize(
195 "CouldNotStopMonitoringLogcat",
196 "Couldn't stop monitoring logcat: {0}",
197 err.message || err,
198 ),
199 );
200 }
201 }
202
203 await logger.dispose();
204
205 DebugSessionBase.rootSessionTerminatedEventEmitter.fire({
206 debugSession: this.session,
207 args: {
208 forcedStop: !!(<any>args).forcedStop,
209 },
210 });
211
212 this.sendResponse(response);
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.
217 if (
218 (error instanceof InternalError || error instanceof NestedError) &&
219 error.errorCode === InternalErrorCode.CancellationTokenTriggered
220 ) {
221 return;
222 }
223
224 this.sendErrorResponse(
225 response,
226 { format: error.message, id: 1 },
227 undefined,
228 undefined,
229 ErrorDestination.User,
230 );
231 }
232}
233
234/**
235 * Parses settings.json file for workspace root property
236 */
237export 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);
244 let projectRootPath =
245 parsedSettings["react-native-tools.projectRoot"] ||
246 parsedSettings["react-native-tools"].projectRoot;
247 return path.resolve(vsCodeRoot, projectRootPath);
248 } catch (e) {
249 logger.verbose(
250 `${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`,
251 );
252 return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
253 }
254}