microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
07775e4c95418b5d690c9d68e596b5ff4095d590

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/appWorker.ts

335lines · 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 vm from "vm";
5import * as Q from "q";
6import * as path from "path";
7import * as WebSocket from "ws";
8import {ScriptImporter} from "./scriptImporter";
9import {Packager} from "../common/packager";
10import {ErrorHelper} from "../common/error/errorHelper";
11import {Log} from "../common/log/log";
12import {LogLevel} from "../common/log/logHelper";
13import {FileSystem} from "../common/node/fileSystem";
14import {ExecutionsLimiter} from "../common/executionsLimiter";
15
16import Module = require("module");
17
18// This file is a replacement of: https://github.com/facebook/react-native/blob/8d397b4cbc05ad801cfafb421cee39bcfe89711d/local-cli/server/util/debugger.html for Node.JS
19interface DebuggerWorkerSandbox {
20 __debug__: {
21 // To support simulating native functionality when debugging,
22 // we expose a node require function to the app
23 require: (id: string) => any;
24 };
25 __filename: string;
26 __dirname: string;
27 self: DebuggerWorkerSandbox;
28 console: typeof console;
29 require: (id: string) => any;
30 importScripts: (url: string) => void;
31 postMessage: (object: any) => void;
32 onmessage: (object: RNAppMessage) => void;
33 postMessageArgument: RNAppMessage; // We use this argument to pass messages to the worker
34}
35
36interface RNAppMessage {
37 method: string;
38 // These objects have also other properties but that we don't currently use
39}
40
41function printDebuggingError(message: string, reason: any) {
42 Log.logWarning(ErrorHelper.getNestedWarning(reason, `${message}. Debugging won't work: Try reloading the JS from inside the app, or Reconnect the VS Code debugger`));
43}
44
45export class SandboxedAppWorker {
46 /** This class will run the RN App logic inside a sandbox. The framework to run the logic is provided by the file
47 * debuggerWorker.js (designed to run on a WebWorker). We load that file inside a sandbox, and then we use the
48 * PROCESS_MESSAGE_INSIDE_SANDBOX script to execute the logic to respond to a message inside the sandbox.
49 * The code inside the debuggerWorker.js will call the global function postMessage to send a reply back to the app,
50 * so we define our custom function there, so we can handle the message. We also provide our own importScript function
51 * to download any script used by debuggerWorker.js
52 */
53 private packagerPort: number;
54 private sourcesStoragePath: string;
55 private debugAdapterPort: number;
56 private postReplyToApp: (message: any) => void;
57
58 private sandbox: DebuggerWorkerSandbox;
59 private sandboxContext: vm.Context;
60 private scriptToReceiveMessageInSandbox: vm.Script;
61
62 private pendingScriptImport = Q(void 0);
63
64 private nodeFileSystem: FileSystem;
65 private scriptImporter: ScriptImporter;
66
67 private static PROCESS_MESSAGE_INSIDE_SANDBOX = "onmessage({ data: postMessageArgument });";
68
69 constructor(packagerPort: number, sourcesStoragePath: string, debugAdapterPort: number, postReplyToApp: (message: any) => void, {
70 nodeFileSystem = new FileSystem(),
71 scriptImporter = new ScriptImporter(packagerPort, sourcesStoragePath),
72 } = {}) {
73 this.packagerPort = packagerPort;
74 this.sourcesStoragePath = sourcesStoragePath;
75 this.debugAdapterPort = debugAdapterPort;
76 this.postReplyToApp = postReplyToApp;
77 this.scriptToReceiveMessageInSandbox = new vm.Script(SandboxedAppWorker.PROCESS_MESSAGE_INSIDE_SANDBOX);
78
79 this.nodeFileSystem = nodeFileSystem;
80 this.scriptImporter = scriptImporter;
81 }
82
83 public start(): Q.Promise<void> {
84
85 // This is a temporary fix for https://github.com/Microsoft/vscode-react-native/issues/340
86 // We need to disable lazy loading for regeneratorRuntime module to avoid infinite recursion
87 let definePropertyInterceptor = "(" + function () {
88 let definePropOriginal = Object.defineProperty;
89 Object.defineProperty = function (object: any, name: string, desc: any) {
90 if (name !== "regeneratorRuntime") {
91 // Behave as usual - as of now we only interested in workaround for regeneratorRuntime
92 return definePropOriginal(object, name, desc);
93 }
94
95 // Patch property descriptor - use static property rather than dynamic
96 // getter to disable react's lazy-loading for regenerator
97 return definePropOriginal(object, name, {
98 enumerable: desc.enumerable,
99 writable: desc.writable,
100 value: desc.get ? desc.get() : desc.value,
101 });
102 };
103 }.toString() + ")()";
104
105 let scriptToRunPath = require.resolve(path.join(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILE_BASENAME));
106 this.initializeSandboxAndContext(scriptToRunPath);
107
108 return Q.when()
109 .then(() => this.runInSandbox("definePropertyInterceptor.js", definePropertyInterceptor))
110 .then(() => this.readFileContents(scriptToRunPath))
111 .then((fileContents: string) =>
112 // On a debugger worker the onmessage variable already exist. We need to declare it before the
113 // javascript file can assign it. We do it in the first line without a new line to not break
114 // the debugging experience of debugging debuggerWorker.js itself (as part of the extension)
115 this.runInSandbox(scriptToRunPath, "var onmessage = null; " + fileContents));
116 }
117
118 public postMessage(object: RNAppMessage): void {
119 this.sandbox.postMessageArgument = object;
120 this.scriptToReceiveMessageInSandbox.runInContext(this.sandboxContext);
121 }
122
123 private initializeSandboxAndContext(scriptToRunPath: string): void {
124 let scriptToRunModule = new Module(scriptToRunPath);
125 scriptToRunModule.paths = Module._nodeModulePaths(path.dirname(scriptToRunPath));
126 // In order for __debug_.require("aNonInternalPackage") to work, we need to initialize where
127 // node searches for packages. We invoke the same method that node does:
128 // https://github.com/nodejs/node/blob/de1dc0ae2eb52842b5c5c974090123a64c3a594c/lib/module.js#L452
129
130 this.sandbox = {
131 __debug__: {
132 require: (filePath: string) => scriptToRunModule.require(filePath),
133 },
134 __filename: scriptToRunPath,
135 __dirname: path.dirname(scriptToRunPath),
136 self: null,
137 console: console,
138 require: (filePath: string) => scriptToRunModule.require(filePath), // Give the sandbox access to require("<filePath>");
139 importScripts: (url: string) => this.importScripts(url), // Import script like using <script/>
140 postMessage: (object: any) => this.gotResponseFromDebuggerWorker(object), // Post message back to the UI thread
141 onmessage: null,
142 postMessageArgument: null,
143 };
144 this.sandbox.self = this.sandbox;
145
146 this.sandboxContext = vm.createContext(this.sandbox);
147 }
148
149 private runInSandbox(filename: string, fileContents?: string): Q.Promise<void> {
150 let fileContentsPromise = fileContents
151 ? Q(fileContents)
152 : this.readFileContents(filename);
153
154 return fileContentsPromise.then(contents => {
155 vm.runInContext(contents, this.sandboxContext, filename);
156 });
157 }
158
159 private readFileContents(filename: string) {
160 return this.nodeFileSystem.readFile(filename).then(contents => contents.toString());
161 }
162
163 private importScripts(url: string): void {
164 /* The debuggerWorker.js executes this code:
165 importScripts(message.url);
166 sendReply();
167
168 In the original code importScripts is a sync call. In our code it's async, so we need to mess with sendReply() so we won't
169 actually send the reply back to the application until after importScripts has finished executing. We use
170 this.pendingScriptImport to make the gotResponseFromDebuggerWorker() method hold the reply back, until've finished importing
171 and running the script */
172 let defer = Q.defer<{}>();
173 this.pendingScriptImport = defer.promise;
174
175 // The next line converts to any due to the incorrect typing on node.d.ts of vm.runInThisContext
176 this.scriptImporter.downloadAppScript(url, this.debugAdapterPort)
177 .then(downloadedScript =>
178 this.runInSandbox(downloadedScript.filepath, downloadedScript.contents))
179 .done(() => {
180 // Now we let the reply to the app proceed
181 defer.resolve({});
182 }, reason => {
183 printDebuggingError(`Couldn't import script at <${url}>`, reason);
184 });
185 }
186
187 private gotResponseFromDebuggerWorker(object: any): void {
188 // We might need to hold the response until a script is imported. See comments on this.importScripts()
189 this.pendingScriptImport.done(() =>
190 this.postReplyToApp(object), reason => {
191 printDebuggingError("Unexpected internal error while processing a message from the RN App.", reason);
192 });
193 }
194}
195
196export class MultipleLifetimesAppWorker {
197 /** This class will create a SandboxedAppWorker that will run the RN App logic, and then create a socket
198 * and send the RN App messages to the SandboxedAppWorker. The only RN App message that this class handles
199 * is the prepareJSRuntime, which we reply to the RN App that the sandbox was created successfully.
200 * When the socket closes, we'll create a new SandboxedAppWorker and a new socket pair and discard the old ones.
201 */
202 private packagerPort: number;
203 private sourcesStoragePath: string;
204 private debugAdapterPort: number;
205 private socketToApp: WebSocket;
206 private singleLifetimeWorker: SandboxedAppWorker;
207
208 private sandboxedAppConstructor: (storagePath: string, adapterPort: number, messageFunction: (message: any) => void) => SandboxedAppWorker;
209 private webSocketConstructor: (url: string) => WebSocket;
210
211 private executionLimiter = new ExecutionsLimiter();
212
213 constructor(packagerPort: number, sourcesStoragePath: string, debugAdapterPort: number, {
214 sandboxedAppConstructor = (path: string, port: number, messageFunc: (message: any) => void) =>
215 new SandboxedAppWorker(packagerPort, path, port, messageFunc),
216 webSocketConstructor = (url: string) => new WebSocket(url),
217 } = {}) {
218 this.packagerPort = packagerPort;
219 this.sourcesStoragePath = sourcesStoragePath;
220 this.debugAdapterPort = debugAdapterPort;
221 console.assert(!!this.sourcesStoragePath, "The sourcesStoragePath argument was null or empty");
222
223 this.sandboxedAppConstructor = sandboxedAppConstructor;
224 this.webSocketConstructor = webSocketConstructor;
225 }
226
227 public start(warnOnFailure: boolean = false): Q.Promise<any> {
228 return Packager.isPackagerRunning(Packager.getHostForPort(this.packagerPort))
229 .then(running => {
230 if (running) {
231 return this.createSocketToApp(warnOnFailure);
232 }
233 throw new Error(`Cannot attach to packager. Are you sure there is a packager and it is running in the port ${this.packagerPort}? If your packager is configured to run in another port make sure to add that to the setting.json.`);
234 });
235 }
236
237 private startNewWorkerLifetime(): Q.Promise<void> {
238 this.singleLifetimeWorker = this.sandboxedAppConstructor(this.sourcesStoragePath, this.debugAdapterPort, (message) => {
239 this.sendMessageToApp(message);
240 });
241 Log.logInternalMessage(LogLevel.Info, "A new app worker lifetime was created.");
242 return this.singleLifetimeWorker.start();
243 }
244
245 private createSocketToApp(warnOnFailure: boolean = false): Q.Promise<void> {
246 let deferred = Q.defer<void>();
247 this.socketToApp = this.webSocketConstructor(this.debuggerProxyUrl());
248 this.socketToApp.on("open", () => {
249 this.onSocketOpened();
250 });
251 this.socketToApp.on("close",
252 () => {
253 this.executionLimiter.execute("onSocketClose.msg", /*limitInSeconds*/ 10, () => {
254 /*
255 * It is not the best idea to compare with the message, but this is the only thing React Native gives that is unique when
256 * it closes the socket because it already has a connection to a debugger.
257 * https://github.com/facebook/react-native/blob/588f01e9982775f0699c7bfd56623d4ed3949810/local-cli/server/util/webSocketProxy.js#L38
258 */
259 if (this.socketToApp._closeMessage === "Another debugger is already connected") {
260 deferred.reject(new RangeError("Another debugger is already connected to packager. Please close it before trying to debug with VSCode."));
261 }
262 Log.logMessage("Disconnected from the Proxy (Packager) to the React Native application. Retrying reconnection soon...");
263 });
264 setTimeout(() => {
265 this.start(true /* retryAttempt */);
266 }, 100);
267 });
268 this.socketToApp.on("message",
269 (message: any) => this.onMessage(message));
270 this.socketToApp.on("error",
271 (error: Error) => {
272 if (warnOnFailure) {
273 Log.logWarning(ErrorHelper.getNestedWarning(error,
274 "Reconnection to the proxy (Packager) failed. Please check the output window for Packager errors, if any. If failure persists, please restart the React Native debugger."));
275 }
276
277 deferred.reject(error);
278 });
279
280 // In an attempt to catch failures in starting the packager on first attempt,
281 // wait for 300 ms before resolving the promise
282 Q.delay(300).done(() => deferred.resolve(void 0));
283 return deferred.promise;
284 }
285
286 private debuggerProxyUrl() {
287 return `ws://${Packager.getHostForPort(this.packagerPort)}/debugger-proxy?role=debugger&name=vscode`;
288 }
289
290 private onSocketOpened() {
291 this.executionLimiter.execute("onSocketOpened.msg", /*limitInSeconds*/ 10, () =>
292 Log.logMessage("Established a connection with the Proxy (Packager) to the React Native application"));
293 }
294
295 private onMessage(message: string) {
296 try {
297 Log.logInternalMessage(LogLevel.Trace, "From RN APP: " + message);
298 let object = <RNAppMessage>JSON.parse(message);
299 if (object.method === "prepareJSRuntime") {
300 // The MultipleLifetimesAppWorker will handle prepareJSRuntime aka create new lifetime
301 this.gotPrepareJSRuntime(object);
302 } else if (object.method === "$disconnected") {
303 // We need to shutdown the current app worker, and create a new lifetime
304 this.singleLifetimeWorker = null;
305 } else if (object.method) {
306 // All the other messages are handled by the single lifetime worker
307 this.singleLifetimeWorker.postMessage(object);
308 } else {
309 // Message doesn't have a method. Ignore it. This is an info message instead of warn because it's normal and expected
310 Log.logInternalMessage(LogLevel.Info, "The react-native app sent a message without specifying a method: " + message);
311 }
312 } catch (exception) {
313 printDebuggingError(`Failed to process message from the React Native app. Message:\n${message}`, exception);
314 }
315 }
316
317 private gotPrepareJSRuntime(message: any): void {
318 // Create the sandbox, and replay that we finished processing the message
319 this.startNewWorkerLifetime().done(() => {
320 this.sendMessageToApp({ replyID: parseInt(message.id, 10) });
321 }, error => printDebuggingError(`Failed to prepare the JavaScript runtime environment. Message:\n${message}`, error));
322 }
323
324 private sendMessageToApp(message: any): void {
325 let stringified: string = null;
326 try {
327 stringified = JSON.stringify(message);
328 Log.logInternalMessage(LogLevel.Trace, "To RN APP: " + stringified);
329 this.socketToApp.send(stringified);
330 } catch (exception) {
331 let messageToShow = stringified || ("" + message); // Try to show the stringified version, but show the toString if unavailable
332 printDebuggingError(`Failed to send message to the React Native app. Message:\n${messageToShow}`, exception);
333 }
334 }
335}
336