microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/extension/extensionServer.ts
333lines · 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 | |
| 4 | import * as Q from "q"; |
| 5 | import * as vscode from "vscode"; |
| 6 | import {MessagingHelper}from "../common/extensionMessaging"; |
| 7 | import {OutputChannelLogger} from "./log/OutputChannelLogger"; |
| 8 | import {Packager} from "../common/packager"; |
| 9 | import {ReactNativeProjectHelper} from "../common/reactNativeProjectHelper"; |
| 10 | import {LogCatMonitor} from "./android/logCatMonitor"; |
| 11 | import {FileSystem} from "../common/node/fileSystem"; |
| 12 | import {SettingsHelper} from "./settingsHelper"; |
| 13 | import {Telemetry} from "../common/telemetry"; |
| 14 | import {PlatformResolver} from "./platformResolver"; |
| 15 | import {TelemetryHelper} from "../common/telemetryHelper"; |
| 16 | import {ErrorHelper} from "../common/error/errorHelper"; |
| 17 | import {InternalErrorCode} from "../common/error/internalErrorCode"; |
| 18 | import {TargetPlatformHelper} from "../common/targetPlatformHelper"; |
| 19 | import {MobilePlatformDeps} from "./generalMobilePlatform"; |
| 20 | import {IRemoteExtension, OpenFileRequest} from "../common/remoteExtension"; |
| 21 | import * as rpc from "noice-json-rpc"; |
| 22 | import * as WebSocket from "ws"; |
| 23 | import WebSocketServer = WebSocket.Server; |
| 24 | import * as nls from "vscode-nls"; |
| 25 | import {CommandExecutor} from "../common/commandExecutor"; |
| 26 | const localize = nls.loadMessageBundle(); |
| 27 | |
| 28 | export class ExtensionServer implements vscode.Disposable { |
| 29 | public api: IRemoteExtension; |
| 30 | public isDisposed: boolean = false; |
| 31 | private serverInstance: WebSocketServer | null; |
| 32 | private reactNativePackager: Packager; |
| 33 | private pipePath: string; |
| 34 | private logCatMonitor: LogCatMonitor | null = null; |
| 35 | private logger: OutputChannelLogger = OutputChannelLogger.getMainChannel(); |
| 36 | |
| 37 | public constructor(projectRootPath: string, reactNativePackager: Packager) { |
| 38 | this.pipePath = MessagingHelper.getPath(projectRootPath); |
| 39 | this.reactNativePackager = reactNativePackager; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Starts the server. |
| 44 | */ |
| 45 | public setup(): Q.Promise<void> { |
| 46 | this.isDisposed = false; |
| 47 | |
| 48 | return Q.Promise((resolve, reject) => { |
| 49 | this._setup(resolve, reject); |
| 50 | }); |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Stops the server. |
| 55 | */ |
| 56 | public dispose(): void { |
| 57 | this.isDisposed = true; |
| 58 | if (this.serverInstance) { |
| 59 | this.serverInstance.close(); |
| 60 | this.serverInstance = null; |
| 61 | } |
| 62 | |
| 63 | this.reactNativePackager.statusIndicator.dispose(); |
| 64 | this.reactNativePackager.stop(true); |
| 65 | this.stopMonitoringLogCat(); |
| 66 | } |
| 67 | |
| 68 | private _setup(resolve: (val: void | Q.IPromise<void>) => void, reject: (reason: any) => void): void { |
| 69 | const errorCallback = this.recoverServer.bind(this, resolve, reject); |
| 70 | let launchCallback = (done: (val: void | Q.IPromise<void>) => void) => { |
| 71 | this.logger.debug(`Extension messaging server started at ${this.pipePath}.`); |
| 72 | |
| 73 | if (this.serverInstance) { |
| 74 | this.serverInstance.removeListener("error", errorCallback); |
| 75 | this.serverInstance.on("error", this.recoverServer.bind(this, null, null)); |
| 76 | } |
| 77 | done(void 0); |
| 78 | }; |
| 79 | |
| 80 | this.serverInstance = new WebSocketServer({port: <any>this.pipePath}); |
| 81 | this.api = new rpc.Server(this.serverInstance).api(); |
| 82 | this.serverInstance.on("listening", launchCallback.bind(this, resolve)); |
| 83 | this.serverInstance.on("error", errorCallback); |
| 84 | |
| 85 | this.setupApiHandlers(); |
| 86 | } |
| 87 | |
| 88 | private setupApiHandlers(): void { |
| 89 | let methods: any = {}; |
| 90 | methods.stopMonitoringLogCat = this.stopMonitoringLogCat.bind(this); |
| 91 | methods.getPackagerPort = this.getPackagerPort.bind(this); |
| 92 | methods.sendTelemetry = this.sendTelemetry.bind(this); |
| 93 | methods.openFileAtLocation = this.openFileAtLocation.bind(this); |
| 94 | methods.showInformationMessage = this.showInformationMessage.bind(this); |
| 95 | methods.launch = this.launch.bind(this); |
| 96 | methods.showDevMenu = this.showDevMenu.bind(this); |
| 97 | methods.reloadApp = this.reloadApp.bind(this); |
| 98 | |
| 99 | this.api.Extension.expose(methods); |
| 100 | } |
| 101 | |
| 102 | private showDevMenu(deviceId?: string) { |
| 103 | this.api.Debugger.emitShowDevMenu(deviceId); |
| 104 | } |
| 105 | |
| 106 | private reloadApp(deviceId?: string) { |
| 107 | this.api.Debugger.emitReloadApp(deviceId); |
| 108 | } |
| 109 | |
| 110 | /** |
| 111 | * Recovers the server in case the named socket we use already exists, but no other instance of VSCode is active. |
| 112 | */ |
| 113 | private recoverServer(resolve: (value: void) => {} , reject: (reason: any) => {}, error: any): void { |
| 114 | let errorHandler = (e: any) => { |
| 115 | /* The named socket is not used. */ |
| 116 | if (e.code === "ECONNREFUSED") { |
| 117 | new FileSystem().removePathRecursivelyAsync(this.pipePath) |
| 118 | .then(() => { |
| 119 | if (resolve && reject) { |
| 120 | return this._setup(resolve, reject); |
| 121 | } else { |
| 122 | return this.setup(); |
| 123 | } |
| 124 | }) |
| 125 | .done(); |
| 126 | } |
| 127 | }; |
| 128 | |
| 129 | /* The named socket already exists. */ |
| 130 | if (error.code === "EADDRINUSE") { |
| 131 | let clientSocket = new WebSocket(`ws+unix://${this.pipePath}`); |
| 132 | clientSocket.on("error", errorHandler); |
| 133 | clientSocket.on("open", function() { |
| 134 | clientSocket.close(); |
| 135 | }); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | /** |
| 140 | * Message handler for GET_PACKAGER_PORT. |
| 141 | */ |
| 142 | private getPackagerPort(projectFolder: string): number { |
| 143 | return SettingsHelper.getPackagerPort(projectFolder); |
| 144 | } |
| 145 | |
| 146 | /** |
| 147 | * Message handler for OPEN_FILE_AT_LOCATION |
| 148 | */ |
| 149 | private openFileAtLocation(openFileRequest: OpenFileRequest): Promise<void> { |
| 150 | const { filename, lineNumber } = openFileRequest; |
| 151 | return new Promise((resolve) => { |
| 152 | vscode.workspace.openTextDocument(vscode.Uri.file(filename)) |
| 153 | .then((document: vscode.TextDocument) => { |
| 154 | vscode.window.showTextDocument(document) |
| 155 | .then((editor: vscode.TextEditor) => { |
| 156 | let range = editor.document.lineAt(lineNumber - 1).range; |
| 157 | editor.selection = new vscode.Selection(range.start, range.end); |
| 158 | editor.revealRange(range, vscode.TextEditorRevealType.InCenter); |
| 159 | resolve(); |
| 160 | }); |
| 161 | }); |
| 162 | }); |
| 163 | } |
| 164 | |
| 165 | private stopMonitoringLogCat(): void { |
| 166 | if (this.logCatMonitor) { |
| 167 | this.logCatMonitor.dispose(); |
| 168 | this.logCatMonitor = null; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /** |
| 173 | * Sends telemetry |
| 174 | */ |
| 175 | private sendTelemetry(telemetryRequest: Telemetry.TelemetryRequest): void { |
| 176 | const { extensionId, extensionVersion, appInsightsKey, eventName, properties, measures } = telemetryRequest; |
| 177 | Telemetry.sendExtensionTelemetry(extensionId, extensionVersion, appInsightsKey, eventName, properties, measures); |
| 178 | } |
| 179 | |
| 180 | /** |
| 181 | * Message handler for SHOW_INFORMATION_MESSAGE |
| 182 | */ |
| 183 | private showInformationMessage(message: string): void { |
| 184 | vscode.window.showInformationMessage(message); |
| 185 | } |
| 186 | |
| 187 | private launch(request: any): Promise<any> { |
| 188 | let mobilePlatformOptions = requestSetup(request.arguments); |
| 189 | |
| 190 | // We add the parameter if it's defined (adapter crashes otherwise) |
| 191 | if (!isNullOrUndefined(request.arguments.logCatArguments)) { |
| 192 | mobilePlatformOptions.logCatArguments = [parseLogCatArguments(request.arguments.logCatArguments)]; |
| 193 | } |
| 194 | |
| 195 | if (!isNullOrUndefined(request.arguments.variant)) { |
| 196 | mobilePlatformOptions.variant = request.arguments.variant; |
| 197 | } |
| 198 | |
| 199 | if (!isNullOrUndefined(request.arguments.scheme)) { |
| 200 | mobilePlatformOptions.scheme = request.arguments.scheme; |
| 201 | } |
| 202 | |
| 203 | if (!isNullOrUndefined(request.arguments.productName)) { |
| 204 | mobilePlatformOptions.productName = request.arguments.productName; |
| 205 | } |
| 206 | |
| 207 | if (!isNullOrUndefined(request.arguments.launchActivity)) { |
| 208 | mobilePlatformOptions.debugLaunchActivity = request.arguments.launchActivity; |
| 209 | } |
| 210 | |
| 211 | if (request.arguments.type === "reactnativedirect") { |
| 212 | mobilePlatformOptions.isDirect = true; |
| 213 | } |
| 214 | |
| 215 | mobilePlatformOptions.packagerPort = SettingsHelper.getPackagerPort(request.arguments.cwd || request.arguments.program); |
| 216 | const platformDeps: MobilePlatformDeps = { |
| 217 | packager: this.reactNativePackager, |
| 218 | }; |
| 219 | const mobilePlatform = new PlatformResolver() |
| 220 | .resolveMobilePlatform(request.arguments.platform, mobilePlatformOptions, platformDeps); |
| 221 | return new Promise((resolve, reject) => { |
| 222 | let extProps: any = { |
| 223 | platform: { |
| 224 | value: request.arguments.platform, |
| 225 | isPii: false, |
| 226 | }, |
| 227 | }; |
| 228 | |
| 229 | if (mobilePlatformOptions.isDirect) { |
| 230 | extProps.isDirect = { |
| 231 | value: true, |
| 232 | isPii: false, |
| 233 | }; |
| 234 | } |
| 235 | |
| 236 | ReactNativeProjectHelper.getReactNativePackageVersionFromNodeModules(mobilePlatformOptions.projectRoot) |
| 237 | .then(version => { |
| 238 | mobilePlatformOptions.reactNativeVersion = version; |
| 239 | extProps = TelemetryHelper.addReactNativeVersionToEventProperties(version, extProps); |
| 240 | TelemetryHelper.generate("launch", extProps, (generator) => { |
| 241 | generator.step("checkPlatformCompatibility"); |
| 242 | TargetPlatformHelper.checkTargetPlatformSupport(mobilePlatformOptions.platform); |
| 243 | return mobilePlatform.beforeStartPackager() |
| 244 | .then(() => { |
| 245 | generator.step("startPackager"); |
| 246 | return mobilePlatform.startPackager(); |
| 247 | }) |
| 248 | .then(() => { |
| 249 | // We've seen that if we don't prewarm the bundle cache, the app fails on the first attempt to connect to the debugger logic |
| 250 | // and the user needs to Reload JS manually. We prewarm it to prevent that issue |
| 251 | generator.step("prewarmBundleCache"); |
| 252 | this.logger.info(localize("PrewarmingBundleCache", "Prewarming bundle cache. This may take a while ...")); |
| 253 | return mobilePlatform.prewarmBundleCache(); |
| 254 | }) |
| 255 | .then(() => { |
| 256 | generator.step("mobilePlatform.runApp").add("target", mobilePlatformOptions.target, false); |
| 257 | this.logger.info(localize("BuildingAndRunningApplication", "Building and running application.")); |
| 258 | return mobilePlatform.runApp(); |
| 259 | }) |
| 260 | .then(() => { |
| 261 | if (mobilePlatformOptions.isDirect) { |
| 262 | generator.step("mobilePlatform.enableDirectDebuggingMode"); |
| 263 | if (request.arguments.platform === "android") { |
| 264 | this.logger.info(localize("PrepareHermesDebugging", "Prepare Hermes debugging (experimental)")); |
| 265 | } |
| 266 | return mobilePlatform.disableJSDebuggingMode(); |
| 267 | } |
| 268 | generator.step("mobilePlatform.enableJSDebuggingMode"); |
| 269 | this.logger.info(localize("EnableJSDebugging", "Enable JS Debugging")); |
| 270 | return mobilePlatform.enableJSDebuggingMode(); |
| 271 | }) |
| 272 | .then(() => { |
| 273 | resolve(); |
| 274 | }) |
| 275 | .catch(error => { |
| 276 | generator.addError(error); |
| 277 | this.logger.error(error); |
| 278 | reject(error); |
| 279 | }); |
| 280 | }); |
| 281 | }) |
| 282 | .catch(error => { |
| 283 | TelemetryHelper.sendErrorEvent( |
| 284 | "ReactNativePackageIsNotInstalled", |
| 285 | ErrorHelper.getInternalError(InternalErrorCode.ReactNativePackageIsNotInstalled) |
| 286 | ); |
| 287 | this.logger.error(error); |
| 288 | reject(error); |
| 289 | }); |
| 290 | }); |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | /** |
| 295 | * Parses log cat arguments to a string |
| 296 | */ |
| 297 | function parseLogCatArguments(userProvidedLogCatArguments: any): string { |
| 298 | return Array.isArray(userProvidedLogCatArguments) |
| 299 | ? userProvidedLogCatArguments.join(" ") // If it's an array, we join the arguments |
| 300 | : userProvidedLogCatArguments; // If not, we leave it as-is |
| 301 | } |
| 302 | |
| 303 | function isNullOrUndefined(value: any): boolean { |
| 304 | return typeof value === "undefined" || value === null; |
| 305 | } |
| 306 | |
| 307 | function requestSetup(args: any): any { |
| 308 | const workspaceFolder: vscode.WorkspaceFolder = <vscode.WorkspaceFolder>vscode.workspace.getWorkspaceFolder(vscode.Uri.file(args.cwd || args.program)); |
| 309 | const projectRootPath = getProjectRoot(args); |
| 310 | let mobilePlatformOptions: any = { |
| 311 | workspaceRoot: workspaceFolder.uri.fsPath, |
| 312 | projectRoot: projectRootPath, |
| 313 | platform: args.platform, |
| 314 | env: args.env, |
| 315 | envFile: args.envFile, |
| 316 | target: args.target || "simulator", |
| 317 | }; |
| 318 | |
| 319 | CommandExecutor.ReactNativeCommand = SettingsHelper.getReactNativeGlobalCommandName(workspaceFolder.uri); |
| 320 | |
| 321 | if (!args.runArguments) { |
| 322 | let runArgs = SettingsHelper.getRunArgs(args.platform, args.target || "simulator", workspaceFolder.uri); |
| 323 | mobilePlatformOptions.runArguments = runArgs; |
| 324 | } else { |
| 325 | mobilePlatformOptions.runArguments = args.runArguments; |
| 326 | } |
| 327 | |
| 328 | return mobilePlatformOptions; |
| 329 | } |
| 330 | |
| 331 | function getProjectRoot(args: any): string { |
| 332 | return SettingsHelper.getReactNativeProjectRoot(args.cwd || args.program); |
| 333 | } |
| 334 | |