microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
0.6.14

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/extension/extensionServer.ts

290lines · modeblame

0502b7a8dlebu10 years ago1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
710f8655digeff10 years ago4import * as Q from "q";
acf08bc2dlebu10 years ago5import * as vscode from "vscode";
6
7daed3fcArtem Egorov8 years ago7import {MessagingHelper}from "../common/extensionMessaging";
0a68f8dbArtem Egorov8 years ago8import {OutputChannelLogger} from "./log/OutputChannelLogger";
9import {Packager} from "../common/packager";
710f8655digeff10 years ago10import {LogCatMonitor} from "./android/logCatMonitor";
11import {FileSystem} from "../common/node/fileSystem";
df4bce40digeff10 years ago12import {SettingsHelper} from "./settingsHelper";
6e4d7a62Joshua Skelton10 years ago13import {Telemetry} from "../common/telemetry";
0a68f8dbArtem Egorov8 years ago14import {PlatformResolver} from "./platformResolver";
15import {TelemetryHelper} from "../common/telemetryHelper";
16import {TargetPlatformHelper} from "../common/targetPlatformHelper";
17import {MobilePlatformDeps} from "./generalMobilePlatform";
51a4641cArtem Egorov7 years ago18import {IRemoteExtension, OpenFileRequest} from "../common/remoteExtension";
7daed3fcArtem Egorov8 years ago19import * as rpc from "noice-json-rpc";
20import * as WebSocket from "ws";
21import WebSocketServer = WebSocket.Server;
0502b7a8dlebu10 years ago22
23export class ExtensionServer implements vscode.Disposable {
7daed3fcArtem Egorov8 years ago24public api: IRemoteExtension;
3118589cArtem Egorov8 years ago25public isDisposed: boolean = false;
7daed3fcArtem Egorov8 years ago26private serverInstance: WebSocketServer | null;
a822ac85dlebu10 years ago27private reactNativePackager: Packager;
8411fd8dDaniel Lebu10 years ago28private pipePath: string;
5c8365a6Artem Egorov8 years ago29private logCatMonitor: LogCatMonitor | null = null;
0a68f8dbArtem Egorov8 years ago30private logger: OutputChannelLogger = OutputChannelLogger.getMainChannel();
a822ac85dlebu10 years ago31
2e432a9eArtem Egorov8 years ago32public constructor(projectRootPath: string, reactNativePackager: Packager) {
7daed3fcArtem Egorov8 years ago33this.pipePath = MessagingHelper.getPath(projectRootPath);
a822ac85dlebu10 years ago34this.reactNativePackager = reactNativePackager;
35}
0502b7a8dlebu10 years ago36
37/**
38* Starts the server.
39*/
40public setup(): Q.Promise<void> {
3118589cArtem Egorov8 years ago41this.isDisposed = false;
0502b7a8dlebu10 years ago42
1950c5e9Artem Egorov8 years ago43return Q.Promise((resolve, reject) => {
44this._setup(resolve, reject);
45});
0502b7a8dlebu10 years ago46}
47
48/**
49* Stops the server.
50*/
51public dispose(): void {
3118589cArtem Egorov8 years ago52this.isDisposed = true;
0502b7a8dlebu10 years ago53if (this.serverInstance) {
54this.serverInstance.close();
acf08bc2dlebu10 years ago55this.serverInstance = null;
0502b7a8dlebu10 years ago56}
710f8655digeff10 years ago57
4edcda70Artem Egorov8 years ago58this.reactNativePackager.statusIndicator.dispose();
3118589cArtem Egorov8 years ago59this.reactNativePackager.stop(true);
c2bf3c4fdigeff10 years ago60this.stopMonitoringLogCat();
0502b7a8dlebu10 years ago61}
62
1950c5e9Artem Egorov8 years ago63private _setup(resolve: (val: void | Q.IPromise<void>) => void, reject: (reason: any) => void): void {
64const errorCallback = this.recoverServer.bind(this, resolve, reject);
65let launchCallback = (done: (val: void | Q.IPromise<void>) => void) => {
66this.logger.debug(`Extension messaging server started at ${this.pipePath}.`);
67
68if (this.serverInstance) {
69this.serverInstance.removeListener("error", errorCallback);
70this.serverInstance.on("error", this.recoverServer.bind(this, null, null));
71}
72done(void 0);
73};
74
75this.serverInstance = new WebSocketServer({port: <any>this.pipePath});
76this.api = new rpc.Server(this.serverInstance).api();
77this.serverInstance.on("listening", launchCallback.bind(this, resolve));
78this.serverInstance.on("error", errorCallback);
79
80this.setupApiHandlers();
81}
82
7daed3fcArtem Egorov8 years ago83private setupApiHandlers(): void {
84let methods: any = {};
85methods.stopMonitoringLogCat = this.stopMonitoringLogCat.bind(this);
86methods.getPackagerPort = this.getPackagerPort.bind(this);
87methods.sendTelemetry = this.sendTelemetry.bind(this);
88methods.openFileAtLocation = this.openFileAtLocation.bind(this);
89methods.showInformationMessage = this.showInformationMessage.bind(this);
90methods.launch = this.launch.bind(this);
91methods.showDevMenu = this.showDevMenu.bind(this);
92methods.reloadApp = this.reloadApp.bind(this);
93
94this.api.Extension.expose(methods);
5e651f3edigeff10 years ago95}
96
7daed3fcArtem Egorov8 years ago97private showDevMenu(deviceId?: string) {
98this.api.Debugger.emitShowDevMenu(deviceId);
514df4f4Patricio Beltran10 years ago99}
100
7daed3fcArtem Egorov8 years ago101private reloadApp(deviceId?: string) {
102this.api.Debugger.emitReloadApp(deviceId);
27710197Vladimir Kotikov8 years ago103}
0502b7a8dlebu10 years ago104
105/**
6b6eb911dlebu10 years ago106* Recovers the server in case the named socket we use already exists, but no other instance of VSCode is active.
0502b7a8dlebu10 years ago107*/
1950c5e9Artem Egorov8 years ago108private recoverServer(resolve: (value: void) => {} , reject: (reason: any) => {}, error: any): void {
6b6eb911dlebu10 years ago109let errorHandler = (e: any) => {
110/* The named socket is not used. */
111if (e.code === "ECONNREFUSED") {
8411fd8dDaniel Lebu10 years ago112new FileSystem().removePathRecursivelyAsync(this.pipePath)
6b6eb911dlebu10 years ago113.then(() => {
1950c5e9Artem Egorov8 years ago114if (resolve && reject) {
115return this._setup(resolve, reject);
116} else {
117return this.setup();
118}
6b6eb911dlebu10 years ago119})
120.done();
121}
122};
123
124/* The named socket already exists. */
125if (error.code === "EADDRINUSE") {
7daed3fcArtem Egorov8 years ago126let clientSocket = new WebSocket(`ws+unix://${this.pipePath}`);
6b6eb911dlebu10 years ago127clientSocket.on("error", errorHandler);
7daed3fcArtem Egorov8 years ago128clientSocket.on("open", function() {
129clientSocket.close();
6b6eb911dlebu10 years ago130});
0502b7a8dlebu10 years ago131}
132}
280c0746Patricio Beltran9 years ago133
7daed3fcArtem Egorov8 years ago134/**
135* Message handler for GET_PACKAGER_PORT.
136*/
2e432a9eArtem Egorov8 years ago137private getPackagerPort(program: string): number {
138return SettingsHelper.getPackagerPort(program);
7daed3fcArtem Egorov8 years ago139}
140
141/**
142* Message handler for OPEN_FILE_AT_LOCATION
143*/
51a4641cArtem Egorov7 years ago144private openFileAtLocation(openFileRequest: OpenFileRequest): Promise<void> {
145const { filename, lineNumber } = openFileRequest;
7daed3fcArtem Egorov8 years ago146return new Promise((resolve) => {
147vscode.workspace.openTextDocument(vscode.Uri.file(filename))
148.then((document: vscode.TextDocument) => {
149vscode.window.showTextDocument(document)
150.then((editor: vscode.TextEditor) => {
151let range = editor.document.lineAt(lineNumber - 1).range;
152editor.selection = new vscode.Selection(range.start, range.end);
153editor.revealRange(range, vscode.TextEditorRevealType.InCenter);
154resolve();
155});
156});
157});
158}
159
160private stopMonitoringLogCat(): void {
161if (this.logCatMonitor) {
162this.logCatMonitor.dispose();
163this.logCatMonitor = null;
164}
165}
166
167/**
168* Sends telemetry
169*/
51a4641cArtem Egorov7 years ago170private sendTelemetry(telemetryRequest: Telemetry.TelemetryRequest): void {
171const { extensionId, extensionVersion, appInsightsKey, eventName, properties, measures } = telemetryRequest;
7daed3fcArtem Egorov8 years ago172Telemetry.sendExtensionTelemetry(extensionId, extensionVersion, appInsightsKey, eventName, properties, measures);
173}
174
280c0746Patricio Beltran9 years ago175/**
176* Message handler for SHOW_INFORMATION_MESSAGE
177*/
7daed3fcArtem Egorov8 years ago178private showInformationMessage(message: string): void {
179vscode.window.showInformationMessage(message);
280c0746Patricio Beltran9 years ago180}
0a68f8dbArtem Egorov8 years ago181
7daed3fcArtem Egorov8 years ago182private launch(request: any): Promise<any> {
0a68f8dbArtem Egorov8 years ago183let mobilePlatformOptions = requestSetup(request.arguments);
184
185// We add the parameter if it's defined (adapter crashes otherwise)
186if (!isNullOrUndefined(request.arguments.logCatArguments)) {
187mobilePlatformOptions.logCatArguments = [parseLogCatArguments(request.arguments.logCatArguments)];
188}
189
190if (!isNullOrUndefined(request.arguments.variant)) {
191mobilePlatformOptions.variant = request.arguments.variant;
192}
193
194if (!isNullOrUndefined(request.arguments.scheme)) {
195mobilePlatformOptions.scheme = request.arguments.scheme;
196}
197
3e313f6fArtem Egorov7 years ago198if (!isNullOrUndefined(request.arguments.productName)) {
199mobilePlatformOptions.productName = request.arguments.productName;
200}
201
2e432a9eArtem Egorov8 years ago202mobilePlatformOptions.packagerPort = SettingsHelper.getPackagerPort(request.arguments.program);
0a68f8dbArtem Egorov8 years ago203const platformDeps: MobilePlatformDeps = {
204packager: this.reactNativePackager,
205};
206const mobilePlatform = new PlatformResolver()
207.resolveMobilePlatform(request.arguments.platform, mobilePlatformOptions, platformDeps);
7daed3fcArtem Egorov8 years ago208return new Promise((resolve, reject) => {
031832ffArtem Egorov8 years ago209const extProps = {
210platform: {
211value: request.arguments.platform,
212isPii: false,
213},
214};
215
216TelemetryHelper.generate("launch", extProps, (generator) => {
7daed3fcArtem Egorov8 years ago217generator.step("checkPlatformCompatibility");
218TargetPlatformHelper.checkTargetPlatformSupport(mobilePlatformOptions.platform);
4787ec09Artem Egorov8 years ago219return mobilePlatform.beforeStartPackager()
220.then(() => {
221generator.step("startPackager");
222return mobilePlatform.startPackager();
223})
7daed3fcArtem Egorov8 years ago224.then(() => {
225// 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
226// and the user needs to Reload JS manually. We prewarm it to prevent that issue
227generator.step("prewarmBundleCache");
228this.logger.info("Prewarming bundle cache. This may take a while ...");
229return mobilePlatform.prewarmBundleCache();
230})
231.then(() => {
88908964Artem Egorov8 years ago232generator.step("mobilePlatform.runApp").add("target", mobilePlatformOptions.target, false);
7daed3fcArtem Egorov8 years ago233this.logger.info("Building and running application.");
234return mobilePlatform.runApp();
235})
236.then(() => {
237generator.step("mobilePlatform.enableJSDebuggingMode");
e03193abArtem Egorov8 years ago238this.logger.info("Enable JS Debugging");
7daed3fcArtem Egorov8 years ago239return mobilePlatform.enableJSDebuggingMode();
240})
241.then(() => {
242resolve();
243})
244.catch(error => {
748105d9Artem Egorov8 years ago245this.logger.error(error);
7daed3fcArtem Egorov8 years ago246reject(error);
247});
248});
0a68f8dbArtem Egorov8 years ago249});
250}
251}
252
253/**
254* Parses log cat arguments to a string
255*/
256function parseLogCatArguments(userProvidedLogCatArguments: any): string {
257return Array.isArray(userProvidedLogCatArguments)
258? userProvidedLogCatArguments.join(" ") // If it's an array, we join the arguments
259: userProvidedLogCatArguments; // If not, we leave it as-is
260}
261
262function isNullOrUndefined(value: any): boolean {
263return typeof value === "undefined" || value === null;
264}
265
266function requestSetup(args: any): any {
2e432a9eArtem Egorov8 years ago267const workspaceFolder: vscode.WorkspaceFolder = <vscode.WorkspaceFolder>vscode.workspace.getWorkspaceFolder(vscode.Uri.file(args.program));
0a68f8dbArtem Egorov8 years ago268const projectRootPath = getProjectRoot(args);
269let mobilePlatformOptions: any = {
a41f5c68Artem Egorov8 years ago270workspaceRoot: workspaceFolder.uri.fsPath,
0a68f8dbArtem Egorov8 years ago271projectRoot: projectRootPath,
272platform: args.platform,
1174ee3dArtem Egorov8 years ago273env: args.env,
274envFile: args.envFile,
23d47878Artem Egorov8 years ago275target: args.target || "simulator",
0a68f8dbArtem Egorov8 years ago276};
277
278if (!args.runArguments) {
4529aa97Artem Egorov8 years ago279let runArgs = SettingsHelper.getRunArgs(args.platform, args.target || "simulator", workspaceFolder.uri);
0a68f8dbArtem Egorov8 years ago280mobilePlatformOptions.runArguments = runArgs;
a18a84baArtem Egorov8 years ago281} else {
282mobilePlatformOptions.runArguments = args.runArguments;
0a68f8dbArtem Egorov8 years ago283}
284
285return mobilePlatformOptions;
286}
287
288function getProjectRoot(args: any): string {
4edcda70Artem Egorov8 years ago289return SettingsHelper.getReactNativeProjectRoot(args.program);
0502b7a8dlebu10 years ago290}