microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
8df5011e47ada44be3951868ba32e5fae98f48bb

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/rnDebugSession.ts

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