microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
0.11.1

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/appWorker.ts

379lines · 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 Q from "q";
5import * as path from "path";
6import * as WebSocket from "ws";
7import { EventEmitter } from "events";
8import { ensurePackagerRunning } from "../common/packagerStatus";
9import {ErrorHelper} from "../common/error/errorHelper";
10import { logger } from "vscode-chrome-debug-core";
11import {ExecutionsLimiter} from "../common/executionsLimiter";
12import { FileSystem as NodeFileSystem} from "../common/node/fileSystem";
13import { ForkedAppWorker } from "./forkedAppWorker";
14import { ScriptImporter } from "./scriptImporter";
15import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper";
16import * as nls from "vscode-nls";
17import { InternalErrorCode } from "../common/error/internalErrorCode";
18const localize = nls.loadMessageBundle();
19
20export interface RNAppMessage {
21 method: string;
22 url?: string;
23 // These objects have also other properties but that we don't currently use
24}
25
26export interface IDebuggeeWorker {
27 start(): Q.Promise<any>;
28 stop(): void;
29 postMessage(message: RNAppMessage): void;
30}
31
32function printDebuggingError(error: Error, reason: any) {
33 const nestedError = ErrorHelper.getNestedError(error, InternalErrorCode.DebuggingWontWorkReloadJSAndReconnect, reason);
34
35 logger.error(nestedError.message);
36}
37
38 /** This class will create a SandboxedAppWorker that will run the RN App logic, and then create a socket
39 * and send the RN App messages to the SandboxedAppWorker. The only RN App message that this class handles
40 * is the prepareJSRuntime, which we reply to the RN App that the sandbox was created successfully.
41 * When the socket closes, we'll create a new SandboxedAppWorker and a new socket pair and discard the old ones.
42 */
43
44export class MultipleLifetimesAppWorker extends EventEmitter {
45 public static WORKER_BOOTSTRAP = `
46// Initialize some variables before react-native code would access them
47var onmessage=null, self=global;
48// Cache Node's original require as __debug__.require
49global.__debug__={require: require};
50// Prevent leaking process.versions from debugger process to
51// worker because pure React Native doesn't do that and some packages as js-md5 rely on this behavior
52Object.defineProperty(process, "versions", {
53 value: undefined
54});
55
56function getNativeModules() {
57 var NativeModules;
58 try {
59 // This approach is for old RN versions
60 NativeModules = global.require('NativeModules');
61 } catch (err) {
62 // ignore error and try another way for more recent RN versions
63 try {
64 var nativeModuleId;
65 var modules = global.__r.getModules();
66 var ids = Object.keys(modules);
67 for (var i = 0; i < ids.length; i++) {
68 if (modules[ids[i]].verboseName) {
69 var packagePath = new String(modules[ids[i]].verboseName);
70 if (packagePath.indexOf("react-native/Libraries/BatchedBridge/NativeModules.js") > 0) {
71 nativeModuleId = parseInt(ids[i], 10);
72 break;
73 }
74 }
75 }
76 if (nativeModuleId) {
77 NativeModules = global.__r(nativeModuleId);
78 }
79 }
80 catch (err) {
81 // suppress errors
82 }
83 }
84 return NativeModules;
85}
86
87// Originally, this was made for iOS only
88var vscodeHandlers = {
89 'vscode_reloadApp': function () {
90 var NativeModules = getNativeModules();
91 if (NativeModules) {
92 NativeModules.DevMenu.reload();
93 }
94 },
95 'vscode_showDevMenu': function () {
96 var NativeModules = getNativeModules();
97 if (NativeModules) {
98 NativeModules.DevMenu.show();
99 }
100 }
101};
102
103process.on("message", function (message) {
104 if (message.data && vscodeHandlers[message.data.method]) {
105 vscodeHandlers[message.data.method]();
106 } else if(onmessage) {
107 onmessage(message);
108 }
109});
110
111var postMessage = function(message){
112 process.send(message);
113};
114
115if (!self.postMessage) {
116 self.postMessage = postMessage;
117}
118
119var importScripts = (function(){
120 var fs=require('fs'), vm=require('vm');
121 return function(scriptUrl){
122 var scriptCode = fs.readFileSync(scriptUrl, "utf8");
123 vm.runInThisContext(scriptCode, {filename: scriptUrl});
124 };
125})();`;
126
127 public static CONSOLE_TRACE_PATCH = `// Worker is ran as nodejs process, so console.trace() writes to stderr and it leads to error in native app
128// To avoid this console.trace() is overridden to print stacktrace via console.log()
129// Please, see Node JS implementation: https://github.com/nodejs/node/blob/master/lib/internal/console/constructor.js
130console.trace = (function() {
131 return function() {
132 try {
133 var err = {
134 name: 'Trace',
135 message: require('util').format.apply(null, arguments)
136 };
137 // Node uses 10, but usually it's not enough for RN app trace
138 Error.stackTraceLimit = 30;
139 Error.captureStackTrace(err, console.trace);
140 console.log(err.stack);
141 } catch (e) {
142 console.error(e);
143 }
144 };
145})();`;
146
147 public static PROCESS_TO_STRING_PATCH = `// As worker is ran in node, it breaks broadcast-channels package approach of identifying if it’s ran in node:
148// https://github.com/pubkey/broadcast-channel/blob/master/src/util.js#L64
149// To avoid it if process.toString() is called if will return empty string instead of [object process].
150var nativeObjectToString = Object.prototype.toString;
151Object.prototype.toString = function() {
152 if (this === process) {
153 return '';
154 } else {
155 return nativeObjectToString.call(this);
156 }
157}
158`;
159
160 public static WORKER_DONE = `// Notify debugger that we're done with loading
161// and started listening for IPC messages
162postMessage({workerLoaded:true});`;
163
164 public static FETCH_STUB = `(function(self) {
165 'use strict';
166
167 if (self.fetch) {
168 return
169 }
170
171 self.fetch = fetch;
172
173 function fetch(url) {
174 return new Promise((resolve, reject) => {
175 var data = require("fs").readFileSync(url, 'utf8');
176 resolve(
177 {
178 text: function () {
179 return data;
180 }
181 });
182 });
183 }
184 })(global);`;
185
186 private packagerAddress: string;
187 private packagerPort: number;
188 private sourcesStoragePath: string;
189 private projectRootPath: string;
190 private packagerRemoteRoot?: string;
191 private packagerLocalRoot?: string;
192 private debuggerWorkerUrlPath?: string;
193 private socketToApp: WebSocket;
194 private singleLifetimeWorker: IDebuggeeWorker | null;
195 private webSocketConstructor: (url: string) => WebSocket;
196
197 private executionLimiter = new ExecutionsLimiter();
198 private nodeFileSystem = new NodeFileSystem();
199 private scriptImporter: ScriptImporter;
200
201 constructor(
202 attachRequestArguments: any,
203 sourcesStoragePath: string,
204 projectRootPath: string,
205 {
206 webSocketConstructor = (url: string) => new WebSocket(url),
207 } = {}) {
208 super();
209 this.packagerAddress = attachRequestArguments.address || "localhost";
210 this.packagerPort = attachRequestArguments.port;
211 this.packagerRemoteRoot = attachRequestArguments.remoteRoot;
212 this.packagerLocalRoot = attachRequestArguments.localRoot;
213 this.debuggerWorkerUrlPath = attachRequestArguments.debuggerWorkerUrlPath;
214 this.sourcesStoragePath = sourcesStoragePath;
215 this.projectRootPath = projectRootPath;
216 if (!this.sourcesStoragePath)
217 throw ErrorHelper.getInternalError(InternalErrorCode.SourcesStoragePathIsNullOrEmpty);
218 this.webSocketConstructor = webSocketConstructor;
219 this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot);
220 }
221
222 public start(retryAttempt: boolean = false): Q.Promise<any> {
223 const errPackagerNotRunning = ErrorHelper.getInternalError(InternalErrorCode.CannotAttachToPackagerCheckPackagerRunningOnPort, this.packagerPort);
224
225 return ensurePackagerRunning(this.packagerAddress, this.packagerPort, errPackagerNotRunning)
226 .then(() => {
227 // Don't fetch debugger worker on socket disconnect
228 return retryAttempt ? Q.resolve<void>(void 0) :
229 this.downloadAndPatchDebuggerWorker();
230 })
231 .then(() => this.createSocketToApp(retryAttempt));
232 }
233
234 public stop() {
235 if (this.socketToApp) {
236 this.socketToApp.removeAllListeners();
237 this.socketToApp.close();
238 }
239
240 if (this.singleLifetimeWorker) {
241 this.singleLifetimeWorker.stop();
242 }
243 }
244
245 public downloadAndPatchDebuggerWorker(): Q.Promise<void> {
246 let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME);
247 return this.scriptImporter.downloadDebuggerWorker(this.sourcesStoragePath, this.projectRootPath, this.debuggerWorkerUrlPath)
248 .then(() => this.nodeFileSystem.readFile(scriptToRunPath, "utf8"))
249 .then((workerContent: string) => {
250 const isHaulProject = ReactNativeProjectHelper.isHaulProject(this.projectRootPath);
251 // Add our customizations to debugger worker to get it working smoothly
252 // in Node env and polyfill WebWorkers API over Node's IPC.
253 const modifiedDebuggeeContent = [
254 MultipleLifetimesAppWorker.WORKER_BOOTSTRAP,
255 MultipleLifetimesAppWorker.CONSOLE_TRACE_PATCH,
256 MultipleLifetimesAppWorker.PROCESS_TO_STRING_PATCH,
257 isHaulProject ? MultipleLifetimesAppWorker.FETCH_STUB : null,
258 workerContent,
259 MultipleLifetimesAppWorker.WORKER_DONE,
260 ].join("\n");
261 return this.nodeFileSystem.writeFile(scriptToRunPath, modifiedDebuggeeContent);
262 });
263 }
264
265 private startNewWorkerLifetime(): Q.Promise<void> {
266 this.singleLifetimeWorker = new ForkedAppWorker(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.projectRootPath,
267 (message) => {
268 this.sendMessageToApp(message);
269 },
270 this.packagerRemoteRoot, this.packagerLocalRoot);
271 logger.verbose("A new app worker lifetime was created.");
272 return this.singleLifetimeWorker.start()
273 .then(startedEvent => {
274 this.emit("connected", startedEvent);
275 });
276 }
277
278 private createSocketToApp(retryAttempt: boolean = false): Q.Promise<void> {
279 let deferred = Q.defer<void>();
280 this.socketToApp = this.webSocketConstructor(this.debuggerProxyUrl());
281 this.socketToApp.on("open", () => {
282 this.onSocketOpened();
283 });
284 this.socketToApp.on("close",
285 () => {
286 this.executionLimiter.execute("onSocketClose.msg", /*limitInSeconds*/ 10, () => {
287 /*
288 * It is not the best idea to compare with the message, but this is the only thing React Native gives that is unique when
289 * it closes the socket because it already has a connection to a debugger.
290 * https://github.com/facebook/react-native/blob/588f01e9982775f0699c7bfd56623d4ed3949810/local-cli/server/util/webSocketProxy.js#L38
291 */
292 let msgKey = "_closeMessage";
293 if (this.socketToApp[msgKey] === "Another debugger is already connected") {
294 deferred.reject(ErrorHelper.getInternalError(InternalErrorCode.AnotherDebuggerConnectedToPackager));
295 }
296 logger.log(localize("DisconnectedFromThePackagerToReactNative", "Disconnected from the Proxy (Packager) to the React Native application. Retrying reconnection soon..."));
297 });
298 setTimeout(() => {
299 this.start(true /* retryAttempt */);
300 }, 100);
301 });
302 this.socketToApp.on("message",
303 (message: any) => this.onMessage(message));
304 this.socketToApp.on("error",
305 (error: Error) => {
306 if (retryAttempt) {
307 printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.ReconnectionToPackagerFailedCheckForErrorsOrRestartReactNative), error);
308 }
309
310 deferred.reject(error);
311 });
312
313 // In an attempt to catch failures in starting the packager on first attempt,
314 // wait for 300 ms before resolving the promise
315 Q.delay(300).done(() => deferred.resolve(void 0));
316 return deferred.promise;
317 }
318
319 private debuggerProxyUrl() {
320 return `ws://${this.packagerAddress}:${this.packagerPort}/debugger-proxy?role=debugger&name=vscode`;
321 }
322
323 private onSocketOpened() {
324 this.executionLimiter.execute("onSocketOpened.msg", /*limitInSeconds*/ 10, () =>
325 logger.log(localize("EstablishedConnectionWithPackagerToReactNativeApp", "Established a connection with the Proxy (Packager) to the React Native application")));
326 }
327
328 private killWorker() {
329 if (!this.singleLifetimeWorker) return;
330 this.singleLifetimeWorker.stop();
331 this.singleLifetimeWorker = null;
332 }
333
334 private onMessage(message: string) {
335 try {
336 logger.verbose("From RN APP: " + message);
337 let object = <RNAppMessage>JSON.parse(message);
338 if (object.method === "prepareJSRuntime") {
339 // In RN 0.40 Android runtime doesn't seem to be sending "$disconnected" event
340 // when user reloads an app, hence we need to try to kill it here either.
341 this.killWorker();
342 // The MultipleLifetimesAppWorker will handle prepareJSRuntime aka create new lifetime
343 this.gotPrepareJSRuntime(object);
344 } else if (object.method === "$disconnected") {
345 // We need to shutdown the current app worker, and create a new lifetime
346 this.killWorker();
347 } else if (object.method) {
348 // All the other messages are handled by the single lifetime worker
349 if (this.singleLifetimeWorker) {
350 this.singleLifetimeWorker.postMessage(object);
351 }
352 } else {
353 // Message doesn't have a method. Ignore it. This is an info message instead of warn because it's normal and expected
354 logger.verbose(`The react-native app sent a message without specifying a method: ${message}`);
355 }
356 } catch (exception) {
357 printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToProcessMessageFromReactNativeApp, message), exception);
358 }
359 }
360
361 private gotPrepareJSRuntime(message: any): void {
362 // Create the sandbox, and replay that we finished processing the message
363 this.startNewWorkerLifetime().done(() => {
364 this.sendMessageToApp({ replyID: parseInt(message.id, 10) });
365 }, error => printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToPrepareJSRuntimeEnvironment, message), error));
366 }
367
368 private sendMessageToApp(message: any): void {
369 let stringified: string = "";
370 try {
371 stringified = JSON.stringify(message);
372 logger.verbose(`To RN APP: ${stringified}`);
373 this.socketToApp.send(stringified);
374 } catch (exception) {
375 let messageToShow = stringified || ("" + message); // Try to show the stringified version, but show the toString if unavailable
376 printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToSendMessageToTheReactNativeApp, messageToShow), exception);
377 }
378 }
379}
380