microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
cc70057d4beada1315f86cbbf3246d5c065b9eda

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/forkedAppWorker.ts

102lines · 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 child_process from "child_process";
7import {ScriptImporter} from "./scriptImporter";
8
9import { Log } from "../common/log/log";
10import { LogLevel } from "../common/log/logHelper";
11import { ErrorHelper } from "../common/error/errorHelper";
12import { IDebuggeeWorker, RNAppMessage } from "./appWorker";
13
14function printDebuggingError(message: string, reason: any) {
15 Log.logWarning(ErrorHelper.getNestedWarning(reason, `${message}. Debugging won't work: Try reloading the JS from inside the app, or Reconnect the VS Code debugger`));
16}
17
18/** This class will run the RN App logic inside a forked Node process. The framework to run the logic is provided by the file
19 * debuggerWorker.js (designed to run on a WebWorker). We add a couple of tweaks (mostly to polyfill WebWorker API) to that
20 * file and load it inside of a process.
21 * On this side we listen to IPC messages and either respond to them or redirect them to packager via MultipleLifetimeAppWorker's
22 * instance. We also intercept packager's signal to load the bundle's code and mutate the message with path to file we've downloaded
23 * to let importScripts function take this file.
24 */
25export class ForkedAppWorker implements IDebuggeeWorker {
26
27 private scriptImporter: ScriptImporter;
28 private debuggeeProcess: child_process.ChildProcess = null;
29 /** A deferred that we use to make sure that worker has been loaded completely defore start sending IPC messages */
30 private workerLoaded = Q.defer<void>();
31
32 constructor(
33 private packagerPort: number,
34 private sourcesStoragePath: string,
35 private postReplyToApp: (message: any) => void
36 ) {
37 this.scriptImporter = new ScriptImporter(packagerPort, sourcesStoragePath);
38 }
39
40 public stop() {
41 if (this.debuggeeProcess) {
42 Log.logInternalMessage(LogLevel.Info, `About to kill debuggee with pid ${this.debuggeeProcess.pid}`);
43 this.debuggeeProcess.kill();
44 this.debuggeeProcess = null;
45 }
46 }
47
48 public start(): Q.Promise<number> {
49 let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME);
50 const port = Math.round(Math.random() * 40000 + 3000);
51
52 // Note that we set --debug-brk flag to pause the process on the first line - this is
53 // required for debug adapter to set the breakpoints BEFORE the debuggee has started.
54 // The adapter will continue execution once it's done with breakpoints.
55 const nodeArgs = [`--inspect=${port}`, "--debug-brk", scriptToRunPath];
56 // Start child Node process in debugging mode
57 this.debuggeeProcess = child_process.spawn("node", nodeArgs, {
58 stdio: ["pipe", "pipe", "pipe", "ipc"],
59 })
60 .on("message", (message: any) => {
61 // 'workerLoaded' is a special message that indicates that worker is done with loading.
62 // We need to wait for it before doing any IPC because process.send doesn't seems to care
63 // about whether the messahe has been received or not and the first messages are often get
64 // discarded by spawned process
65 if (message && message.workerLoaded) {
66 this.workerLoaded.resolve(void 0);
67 return;
68 }
69
70 this.postReplyToApp(message);
71 })
72 .on("error", (error: Error) => {
73 Log.logWarning(error);
74 });
75
76 // Resolve with port debugger server is listening on
77 // This will be sent to subscribers of MLAppWorker in "connected" event
78 Log.logInternalMessage(LogLevel.Info,
79 `Spawned debuggee process with pid ${this.debuggeeProcess.pid} listening to ${port}`);
80
81 return Q.resolve(port);
82 }
83
84 public postMessage(rnMessage: RNAppMessage): void {
85 // Before sending messages, make sure that the worker is loaded
86 this.workerLoaded.promise
87 .then(() => {
88 if (rnMessage.method !== "executeApplicationScript") return Q.resolve(rnMessage);
89
90 // When packager asks worker to load bundle we download that bundle and
91 // then set url field to point to that downloaded bundle, so the worker
92 // will take our modified bundle
93 Log.logInternalMessage(LogLevel.Info, "Packager requested runtime to load script from " + rnMessage.url);
94 return this.scriptImporter.downloadAppScript(rnMessage.url)
95 .then(downloadedScript => {
96 return Object.assign({}, rnMessage, { url: downloadedScript.filepath });
97 });
98 })
99 .done((message: RNAppMessage) => this.debuggeeProcess.send({ data: message }),
100 reason => printDebuggingError(`Couldn't import script at <${rnMessage.url}>`, reason));
101 }
102}
103