microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
9fc07913967868b1545f83c005e792a1778bce4b

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/debugSessionBase.ts

205lines · 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 { ILaunchArgs } from "../extension/launchArgs";
16import { AppLauncher } from "../extension/appLauncher";
17import { LogLevel } from "../extension/log/LogHelper";
18import * as nls from "vscode-nls";
19nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
20const localize = nls.loadMessageBundle();
21
22/**
23 * Enum of possible statuses of debug session
24 */
25export enum DebugSessionStatus {
26 /** A session has been just created */
27 FirstConnection,
28 /** This status is required in order to exclude the possible creation of several debug sessions at the first start */
29 FirstConnectionPending,
30 /** This status means that an application can be reloaded */
31 ConnectionAllowed,
32 /** This status means that an application is reloading now, and we shouldn't terminate the current debug session */
33 ConnectionPending,
34 /** A debuggee connected successfully */
35 ConnectionDone,
36 /** A debuggee failed to connect */
37 ConnectionFailed,
38}
39
40export interface TerminateEventArgs {
41 debugSession: vscode.DebugSession;
42 args: any;
43}
44
45export interface IAttachRequestArgs extends DebugProtocol.AttachRequestArguments, ILaunchArgs {
46 cwd: string; /* Automatically set by VS Code to the currently opened folder */
47 port: number;
48 url?: string;
49 address?: string;
50 trace?: string;
51 skipFiles?: [];
52 sourceMaps?: boolean;
53 sourceMapPathOverrides?: { [key: string]: string };
54}
55
56export interface ILaunchRequestArgs extends DebugProtocol.LaunchRequestArguments, IAttachRequestArgs { }
57
58export abstract class DebugSessionBase extends LoggingDebugSession {
59
60 protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> = new vscode.EventEmitter<TerminateEventArgs>();
61 public static readonly onDidTerminateRootDebugSession = DebugSessionBase.rootSessionTerminatedEventEmitter.event;
62
63 protected readonly disconnectCommand: string;
64 protected readonly pwaNodeSessionName: string;
65
66 protected appLauncher: AppLauncher;
67 protected projectRootPath: string;
68 protected isSettingsInitialized: boolean; // used to prevent parameters reinitialization when attach is called from launch function
69 protected previousAttachArgs: IAttachRequestArgs;
70 protected cdpProxyLogLevel: LogLevel;
71 protected debugSessionStatus: DebugSessionStatus;
72 protected session: vscode.DebugSession;
73 protected cancellationTokenSource: vscode.CancellationTokenSource;
74
75 constructor(session: vscode.DebugSession) {
76 super();
77
78 // constants definition
79 this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension
80 this.disconnectCommand = "disconnect";
81
82 // variables definition
83 this.session = session;
84 this.isSettingsInitialized = false;
85 this.debugSessionStatus = DebugSessionStatus.FirstConnection;
86 this.cancellationTokenSource = new vscode.CancellationTokenSource();
87 }
88
89 protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
90 response.body = response.body || {};
91
92 response.body.supportsConfigurationDoneRequest = true;
93 response.body.supportsEvaluateForHovers = true;
94 response.body.supportTerminateDebuggee = true;
95 response.body.supportsCancelRequest = true;
96
97 this.sendResponse(response);
98 }
99
100 protected abstract establishDebugSession(attachArgs: IAttachRequestArgs, resolve?: (value?: void | PromiseLike<void> | undefined) => void): void;
101
102 protected initializeSettings(args: any): Promise<any> {
103 if (!this.isSettingsInitialized) {
104 let chromeDebugCoreLogs = getLoggingDirectory();
105 if (chromeDebugCoreLogs) {
106 chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "DebugSessionLogs.txt");
107 }
108 let logLevel: string = args.trace;
109 if (logLevel) {
110 logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase());
111 logger.setup(Logger.LogLevel[logLevel], chromeDebugCoreLogs || false);
112 this.cdpProxyLogLevel = LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None;
113 } else {
114 logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false);
115 this.cdpProxyLogLevel = LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None;
116 }
117
118 if (!args.sourceMaps) {
119 args.sourceMaps = true;
120 }
121
122 if (typeof args.enableDebug !== "boolean") {
123 args.enableDebug = true;
124 }
125
126 const projectRootPath = getProjectRoot(args);
127 return ReactNativeProjectHelper.isReactNativeProject(projectRootPath)
128 .then((result) => {
129 if (!result) {
130 throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError);
131 }
132 this.projectRootPath = projectRootPath;
133 this.appLauncher = AppLauncher.getAppLauncherByProjectRootPath(projectRootPath);
134 this.isSettingsInitialized = true;
135
136 return void 0;
137 });
138 } else {
139 return Promise.resolve();
140 }
141 }
142
143 protected async disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments, request?: DebugProtocol.Request): Promise<void> {
144 await this.appLauncher.getRnCdpProxy().stopServer();
145
146 this.cancellationTokenSource.cancel();
147 this.cancellationTokenSource.dispose();
148
149 // Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session
150 if (this.previousAttachArgs && this.previousAttachArgs.platform === "android") {
151 try {
152 this.appLauncher.stopMonitoringLogCat();
153 } catch (err) {
154 logger.warn(localize("CouldNotStopMonitoringLogcat", "Couldn't stop monitoring logcat: {0}", err.message || err));
155 }
156 }
157
158 await logger.dispose();
159
160 DebugSessionBase.rootSessionTerminatedEventEmitter.fire({
161 debugSession: this.session,
162 args: {
163 forcedStop: (<any>args).forcedStop,
164 },
165 });
166
167 this.sendResponse(response);
168 }
169
170 protected showError(error: Error, response: DebugProtocol.Response): void {
171
172 // We can't print error messages after the debugging session is stopped. This could break the extension work.
173 if ((error instanceof InternalError || error instanceof NestedError)
174 && error.errorCode === InternalErrorCode.CancellationTokenTriggered
175 ) {
176 return;
177 }
178
179 this.sendErrorResponse(
180 response,
181 { format: error.message, id: 1 },
182 undefined,
183 undefined,
184 ErrorDestination.User
185 );
186 }
187}
188
189/**
190 * Parses settings.json file for workspace root property
191 */
192export function getProjectRoot(args: any): string {
193 const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
194 const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json");
195 try {
196 let settingsContent = fs.readFileSync(settingsPath, "utf8");
197 settingsContent = stripJsonComments(settingsContent);
198 let parsedSettings = JSON.parse(settingsContent);
199 let projectRootPath = parsedSettings["react-native-tools.projectRoot"] || parsedSettings["react-native-tools"].projectRoot;
200 return path.resolve(vsCodeRoot, projectRootPath);
201 } catch (e) {
202 logger.verbose(`${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`);
203 return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
204 }
205}
206