microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
f22fd8bbb88a1926a43f9f42f06938154ee5b846

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/rnDebugSession.ts

296lines · 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 mkdirp from "mkdirp";
7import { logger } from "vscode-debugadapter";
8import { DebugProtocol } from "vscode-debugprotocol";
9import { ProjectVersionHelper } from "../common/projectVersionHelper";
10import { TelemetryHelper } from "../common/telemetryHelper";
11import { MultipleLifetimesAppWorker } from "./appWorker";
12import { RnCDPMessageHandler } from "../cdp-proxy/CDPMessageHandlers/rnCDPMessageHandler";
13import {
14 DebugSessionBase,
15 DebugSessionStatus,
16 IAttachRequestArgs,
17 ILaunchRequestArgs,
18} from "./debugSessionBase";
19import { JsDebugConfigAdapter } from "./jsDebugConfigAdapter";
20import { ErrorHelper } from "../common/error/errorHelper";
21import { InternalErrorCode } from "../common/error/internalErrorCode";
22import * as nls from "vscode-nls";
23nls.config({
24 messageFormat: nls.MessageFormat.bundle,
25 bundleFormat: nls.BundleFormat.standalone,
26})();
27const localize = nls.loadMessageBundle();
28
29export class RNDebugSession extends DebugSessionBase {
30 private readonly terminateCommand: string;
31
32 private appWorker: MultipleLifetimesAppWorker | null;
33 private nodeSession: vscode.DebugSession | null;
34 private onDidStartDebugSessionHandler: vscode.Disposable;
35 private onDidTerminateDebugSessionHandler: vscode.Disposable;
36
37 constructor(session: vscode.DebugSession) {
38 super(session);
39
40 // constants definition
41 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
42
43 // variables definition
44 this.appWorker = null;
45
46 this.onDidStartDebugSessionHandler = vscode.debug.onDidStartDebugSession(
47 this.handleStartDebugSession.bind(this),
48 );
49
50 this.onDidTerminateDebugSessionHandler = vscode.debug.onDidTerminateDebugSession(
51 this.handleTerminateDebugSession.bind(this),
52 );
53 }
54
55 protected async launchRequest(
56 response: DebugProtocol.LaunchResponse,
57 launchArgs: ILaunchRequestArgs,
58 // eslint-disable-next-line @typescript-eslint/no-unused-vars
59 request?: DebugProtocol.Request,
60 ): Promise<void> {
61 try {
62 try {
63 await this.initializeSettings(launchArgs);
64 logger.log("Launching the application");
65 logger.verbose(`Launching the application: ${JSON.stringify(launchArgs, null, 2)}`);
66
67 await this.appLauncher.launch(launchArgs);
68
69 if (!launchArgs.enableDebug) {
70 this.sendResponse(response);
71 // if debugging is not enabled skip attach request
72 return;
73 }
74 } catch (error) {
75 throw ErrorHelper.getInternalError(
76 InternalErrorCode.ApplicationLaunchFailed,
77 error.message || error,
78 );
79 }
80 // if debugging is enabled start attach request
81 await this.attachRequest(response, launchArgs);
82 } catch (error) {
83 this.showError(error, response);
84 }
85 }
86
87 protected async attachRequest(
88 response: DebugProtocol.AttachResponse,
89 attachArgs: IAttachRequestArgs,
90 // eslint-disable-next-line @typescript-eslint/no-unused-vars
91 request?: DebugProtocol.Request,
92 ): Promise<void> {
93 let extProps = {
94 platform: {
95 value: attachArgs.platform,
96 isPii: false,
97 },
98 };
99
100 this.previousAttachArgs = attachArgs;
101
102 return new Promise<void>(async (resolve, reject) => {
103 try {
104 await this.initializeSettings(attachArgs);
105 logger.log("Attaching to the application");
106 logger.verbose(
107 `Attaching to the application: ${JSON.stringify(attachArgs, null, 2)}`,
108 );
109
110 const versions = await ProjectVersionHelper.getReactNativeVersions(
111 this.projectRootPath,
112 ProjectVersionHelper.generateAdditionalPackagesToCheckByPlatform(attachArgs),
113 );
114 extProps = TelemetryHelper.addPlatformPropertiesToTelemetryProperties(
115 attachArgs,
116 versions,
117 extProps,
118 );
119
120 // eslint-disable-next-line @typescript-eslint/no-unused-vars
121 await TelemetryHelper.generate("attach", extProps, async generator => {
122 attachArgs.port =
123 attachArgs.port || this.appLauncher.getPackagerPort(attachArgs.cwd);
124
125 const cdpProxy = this.appLauncher.getRnCdpProxy();
126 await cdpProxy.stopServer();
127 await cdpProxy.initializeServer(
128 new RnCDPMessageHandler(),
129 this.cdpProxyLogLevel,
130 );
131
132 await this.appLauncher.getPackager().start();
133
134 logger.log(
135 localize("StartingDebuggerAppWorker", "Starting debugger app worker."),
136 );
137
138 const sourcesStoragePath = path.join(this.projectRootPath, ".vscode", ".react");
139 // Create folder if not exist to avoid problems if
140 // RN project root is not a ${workspaceFolder}
141 mkdirp.sync(sourcesStoragePath);
142
143 // If launch is invoked first time, appWorker is undefined, so create it here
144 this.appWorker = new MultipleLifetimesAppWorker(
145 attachArgs,
146 sourcesStoragePath,
147 this.projectRootPath,
148 this.cancellationTokenSource.token,
149 undefined,
150 );
151 this.appLauncher.setAppWorker(this.appWorker);
152
153 this.appWorker.on("connected", (port: number) => {
154 if (this.cancellationTokenSource.token.isCancellationRequested) {
155 return this.appWorker?.stop();
156 }
157
158 logger.log(
159 localize(
160 "DebuggerWorkerLoadedRuntimeOnPort",
161 "Debugger worker loaded runtime on port {0}",
162 port,
163 ),
164 );
165
166 cdpProxy.setApplicationTargetPort(port);
167
168 if (this.debugSessionStatus === DebugSessionStatus.ConnectionPending) {
169 return;
170 }
171
172 if (this.debugSessionStatus === DebugSessionStatus.FirstConnection) {
173 this.debugSessionStatus = DebugSessionStatus.FirstConnectionPending;
174 this.establishDebugSession(attachArgs, resolve);
175 } else if (
176 this.debugSessionStatus === DebugSessionStatus.ConnectionAllowed
177 ) {
178 if (this.nodeSession) {
179 this.debugSessionStatus = DebugSessionStatus.ConnectionPending;
180 this.nodeSession.customRequest(this.terminateCommand);
181 }
182 }
183 });
184
185 if (this.cancellationTokenSource.token.isCancellationRequested) {
186 return this.appWorker.stop();
187 }
188 return await this.appWorker.start();
189 });
190 } catch (error) {
191 reject(error);
192 }
193 }).catch(err =>
194 this.showError(
195 ErrorHelper.getInternalError(
196 InternalErrorCode.CouldNotAttachToDebugger,
197 err.message || err,
198 ),
199 response,
200 ),
201 );
202 }
203
204 protected async disconnectRequest(
205 response: DebugProtocol.DisconnectResponse,
206 args: DebugProtocol.DisconnectArguments,
207 request?: DebugProtocol.Request,
208 ): Promise<void> {
209 // The client is about to disconnect so first we need to stop app worker
210 if (this.appWorker) {
211 this.appWorker.stop();
212 }
213
214 this.onDidStartDebugSessionHandler.dispose();
215 this.onDidTerminateDebugSessionHandler.dispose();
216
217 return super.disconnectRequest(response, args, request);
218 }
219
220 protected establishDebugSession(
221 attachArgs: IAttachRequestArgs,
222 resolve?: (value?: void | PromiseLike<void> | undefined) => void,
223 ): void {
224 const attachConfiguration = JsDebugConfigAdapter.createDebuggingConfigForPureRN(
225 attachArgs,
226 this.appLauncher.getCdpProxyPort(),
227 this.session.id,
228 );
229
230 vscode.debug
231 .startDebugging(this.appLauncher.getWorkspaceFolder(), attachConfiguration, {
232 parentSession: this.session,
233 consoleMode: vscode.DebugConsoleMode.MergeWithParent,
234 })
235 .then(
236 (childDebugSessionStarted: boolean) => {
237 if (childDebugSessionStarted) {
238 this.debugSessionStatus = DebugSessionStatus.ConnectionDone;
239 this.setConnectionAllowedIfPossible();
240 if (resolve) {
241 this.debugSessionStatus = DebugSessionStatus.ConnectionAllowed;
242 resolve();
243 }
244 } else {
245 this.debugSessionStatus = DebugSessionStatus.ConnectionFailed;
246 this.setConnectionAllowedIfPossible();
247 this.resetFirstConnectionStatus();
248 throw new Error("Cannot start child debug session");
249 }
250 },
251 err => {
252 this.debugSessionStatus = DebugSessionStatus.ConnectionFailed;
253 this.setConnectionAllowedIfPossible();
254 this.resetFirstConnectionStatus();
255 throw err;
256 },
257 );
258 }
259
260 private handleStartDebugSession(debugSession: vscode.DebugSession): void {
261 if (
262 debugSession.configuration.rnDebugSessionId === this.session.id &&
263 debugSession.type === this.pwaNodeSessionName
264 ) {
265 this.nodeSession = debugSession;
266 }
267 }
268
269 private handleTerminateDebugSession(debugSession: vscode.DebugSession): void {
270 if (
271 debugSession.configuration.rnDebugSessionId === this.session.id &&
272 debugSession.type === this.pwaNodeSessionName
273 ) {
274 if (this.debugSessionStatus === DebugSessionStatus.ConnectionPending) {
275 this.establishDebugSession(this.previousAttachArgs);
276 } else {
277 vscode.commands.executeCommand(this.stopCommand, this.session);
278 }
279 }
280 }
281
282 private setConnectionAllowedIfPossible(): void {
283 if (
284 this.debugSessionStatus === DebugSessionStatus.ConnectionDone ||
285 this.debugSessionStatus === DebugSessionStatus.ConnectionFailed
286 ) {
287 this.debugSessionStatus = DebugSessionStatus.ConnectionAllowed;
288 }
289 }
290
291 private resetFirstConnectionStatus(): void {
292 if (this.debugSessionStatus === DebugSessionStatus.FirstConnectionPending) {
293 this.debugSessionStatus = DebugSessionStatus.FirstConnection;
294 }
295 }
296}
297