microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
0.13.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/appWorker.ts

381lines · 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 // Add a 'debugger;' statement to stop code execution
124 // to wait for the sourcemaps to be processed by the debug adapter
125 vm.runInThisContext('debugger;' + scriptCode, {filename: scriptUrl});
126 };
127})();`;
128
129 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
130// To avoid this console.trace() is overridden to print stacktrace via console.log()
131// Please, see Node JS implementation: https://github.com/nodejs/node/blob/master/lib/internal/console/constructor.js
132console.trace = (function() {
133 return function() {
134 try {
135 var err = {
136 name: 'Trace',
137 message: require('util').format.apply(null, arguments)
138 };
139 // Node uses 10, but usually it's not enough for RN app trace
140 Error.stackTraceLimit = 30;
141 Error.captureStackTrace(err, console.trace);
142 console.log(err.stack);
143 } catch (e) {
144 console.error(e);
145 }
146 };
147})();`;
148
149 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:
150// https://github.com/pubkey/broadcast-channel/blob/master/src/util.js#L64
151// To avoid it if process.toString() is called if will return empty string instead of [object process].
152var nativeObjectToString = Object.prototype.toString;
153Object.prototype.toString = function() {
154 if (this === process) {
155 return '';
156 } else {
157 return nativeObjectToString.call(this);
158 }
159};
160`;
161
162 public static WORKER_DONE = `// Notify debugger that we're done with loading
163// and started listening for IPC messages
164postMessage({workerLoaded:true});`;
165
166 public static FETCH_STUB = `(function(self) {
167 'use strict';
168
169 if (self.fetch) {
170 return
171 }
172
173 self.fetch = fetch;
174
175 function fetch(url) {
176 return new Promise((resolve, reject) => {
177 var data = require("fs").readFileSync(url, 'utf8');
178 resolve(
179 {
180 text: function () {
181 return data;
182 }
183 });
184 });
185 }
186 })(global);`;
187
188 private packagerAddress: string;
189 private packagerPort: number;
190 private sourcesStoragePath: string;
191 private projectRootPath: string;
192 private packagerRemoteRoot?: string;
193 private packagerLocalRoot?: string;
194 private debuggerWorkerUrlPath?: string;
195 private socketToApp: WebSocket;
196 private singleLifetimeWorker: IDebuggeeWorker | null;
197 private webSocketConstructor: (url: string) => WebSocket;
198
199 private executionLimiter = new ExecutionsLimiter();
200 private nodeFileSystem = new NodeFileSystem();
201 private scriptImporter: ScriptImporter;
202
203 constructor(
204 attachRequestArguments: any,
205 sourcesStoragePath: string,
206 projectRootPath: string,
207 {
208 webSocketConstructor = (url: string) => new WebSocket(url),
209 } = {}) {
210 super();
211 this.packagerAddress = attachRequestArguments.address || "localhost";
212 this.packagerPort = attachRequestArguments.port;
213 this.packagerRemoteRoot = attachRequestArguments.remoteRoot;
214 this.packagerLocalRoot = attachRequestArguments.localRoot;
215 this.debuggerWorkerUrlPath = attachRequestArguments.debuggerWorkerUrlPath;
216 this.sourcesStoragePath = sourcesStoragePath;
217 this.projectRootPath = projectRootPath;
218 if (!this.sourcesStoragePath)
219 throw ErrorHelper.getInternalError(InternalErrorCode.SourcesStoragePathIsNullOrEmpty);
220 this.webSocketConstructor = webSocketConstructor;
221 this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot);
222 }
223
224 public start(retryAttempt: boolean = false): Q.Promise<any> {
225 const errPackagerNotRunning = ErrorHelper.getInternalError(InternalErrorCode.CannotAttachToPackagerCheckPackagerRunningOnPort, this.packagerPort);
226
227 return ensurePackagerRunning(this.packagerAddress, this.packagerPort, errPackagerNotRunning)
228 .then(() => {
229 // Don't fetch debugger worker on socket disconnect
230 return retryAttempt ? Q.resolve<void>(void 0) :
231 this.downloadAndPatchDebuggerWorker();
232 })
233 .then(() => this.createSocketToApp(retryAttempt));
234 }
235
236 public stop() {
237 if (this.socketToApp) {
238 this.socketToApp.removeAllListeners();
239 this.socketToApp.close();
240 }
241
242 if (this.singleLifetimeWorker) {
243 this.singleLifetimeWorker.stop();
244 }
245 }
246
247 public downloadAndPatchDebuggerWorker(): Q.Promise<void> {
248 let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME);
249 return this.scriptImporter.downloadDebuggerWorker(this.sourcesStoragePath, this.projectRootPath, this.debuggerWorkerUrlPath)
250 .then(() => this.nodeFileSystem.readFile(scriptToRunPath, "utf8"))
251 .then((workerContent: string) => {
252 const isHaulProject = ReactNativeProjectHelper.isHaulProject(this.projectRootPath);
253 // Add our customizations to debugger worker to get it working smoothly
254 // in Node env and polyfill WebWorkers API over Node's IPC.
255 const modifiedDebuggeeContent = [
256 MultipleLifetimesAppWorker.WORKER_BOOTSTRAP,
257 MultipleLifetimesAppWorker.CONSOLE_TRACE_PATCH,
258 MultipleLifetimesAppWorker.PROCESS_TO_STRING_PATCH,
259 isHaulProject ? MultipleLifetimesAppWorker.FETCH_STUB : null,
260 workerContent,
261 MultipleLifetimesAppWorker.WORKER_DONE,
262 ].join("\n");
263 return this.nodeFileSystem.writeFile(scriptToRunPath, modifiedDebuggeeContent);
264 });
265 }
266
267 private startNewWorkerLifetime(): Q.Promise<void> {
268 this.singleLifetimeWorker = new ForkedAppWorker(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.projectRootPath,
269 (message) => {
270 this.sendMessageToApp(message);
271 },
272 this.packagerRemoteRoot, this.packagerLocalRoot);
273 logger.verbose("A new app worker lifetime was created.");
274 return this.singleLifetimeWorker.start()
275 .then(startedEvent => {
276 this.emit("connected", startedEvent);
277 });
278 }
279
280 private createSocketToApp(retryAttempt: boolean = false): Q.Promise<void> {
281 let deferred = Q.defer<void>();
282 this.socketToApp = this.webSocketConstructor(this.debuggerProxyUrl());
283 this.socketToApp.on("open", () => {
284 this.onSocketOpened();
285 });
286 this.socketToApp.on("close",
287 () => {
288 this.executionLimiter.execute("onSocketClose.msg", /*limitInSeconds*/ 10, () => {
289 /*
290 * It is not the best idea to compare with the message, but this is the only thing React Native gives that is unique when
291 * it closes the socket because it already has a connection to a debugger.
292 * https://github.com/facebook/react-native/blob/588f01e9982775f0699c7bfd56623d4ed3949810/local-cli/server/util/webSocketProxy.js#L38
293 */
294 let msgKey = "_closeMessage";
295 if (this.socketToApp[msgKey] === "Another debugger is already connected") {
296 deferred.reject(ErrorHelper.getInternalError(InternalErrorCode.AnotherDebuggerConnectedToPackager));
297 }
298 logger.log(localize("DisconnectedFromThePackagerToReactNative", "Disconnected from the Proxy (Packager) to the React Native application. Retrying reconnection soon..."));
299 });
300 setTimeout(() => {
301 this.start(true /* retryAttempt */);
302 }, 100);
303 });
304 this.socketToApp.on("message",
305 (message: any) => this.onMessage(message));
306 this.socketToApp.on("error",
307 (error: Error) => {
308 if (retryAttempt) {
309 printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.ReconnectionToPackagerFailedCheckForErrorsOrRestartReactNative), error);
310 }
311
312 deferred.reject(error);
313 });
314
315 // In an attempt to catch failures in starting the packager on first attempt,
316 // wait for 300 ms before resolving the promise
317 Q.delay(300).done(() => deferred.resolve(void 0));
318 return deferred.promise;
319 }
320
321 private debuggerProxyUrl() {
322 return `ws://${this.packagerAddress}:${this.packagerPort}/debugger-proxy?role=debugger&name=vscode`;
323 }
324
325 private onSocketOpened() {
326 this.executionLimiter.execute("onSocketOpened.msg", /*limitInSeconds*/ 10, () =>
327 logger.log(localize("EstablishedConnectionWithPackagerToReactNativeApp", "Established a connection with the Proxy (Packager) to the React Native application")));
328 }
329
330 private killWorker() {
331 if (!this.singleLifetimeWorker) return;
332 this.singleLifetimeWorker.stop();
333 this.singleLifetimeWorker = null;
334 }
335
336 private onMessage(message: string) {
337 try {
338 logger.verbose("From RN APP: " + message);
339 let object = <RNAppMessage>JSON.parse(message);
340 if (object.method === "prepareJSRuntime") {
341 // In RN 0.40 Android runtime doesn't seem to be sending "$disconnected" event
342 // when user reloads an app, hence we need to try to kill it here either.
343 this.killWorker();
344 // The MultipleLifetimesAppWorker will handle prepareJSRuntime aka create new lifetime
345 this.gotPrepareJSRuntime(object);
346 } else if (object.method === "$disconnected") {
347 // We need to shutdown the current app worker, and create a new lifetime
348 this.killWorker();
349 } else if (object.method) {
350 // All the other messages are handled by the single lifetime worker
351 if (this.singleLifetimeWorker) {
352 this.singleLifetimeWorker.postMessage(object);
353 }
354 } else {
355 // Message doesn't have a method. Ignore it. This is an info message instead of warn because it's normal and expected
356 logger.verbose(`The react-native app sent a message without specifying a method: ${message}`);
357 }
358 } catch (exception) {
359 printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToProcessMessageFromReactNativeApp, message), exception);
360 }
361 }
362
363 private gotPrepareJSRuntime(message: any): void {
364 // Create the sandbox, and replay that we finished processing the message
365 this.startNewWorkerLifetime().done(() => {
366 this.sendMessageToApp({ replyID: parseInt(message.id, 10) });
367 }, error => printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToPrepareJSRuntimeEnvironment, message), error));
368 }
369
370 private sendMessageToApp(message: any): void {
371 let stringified: string = "";
372 try {
373 stringified = JSON.stringify(message);
374 logger.verbose(`To RN APP: ${stringified}`);
375 this.socketToApp.send(stringified);
376 } catch (exception) {
377 let messageToShow = stringified || ("" + message); // Try to show the stringified version, but show the toString if unavailable
378 printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToSendMessageToTheReactNativeApp, messageToShow), exception);
379 }
380 }
381}
382