microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
10873e115f85fec54e69c69e094d16414ba24972

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/common/packager.ts

171lines · 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 {ChildProcess} from "child_process";
5import {CommandExecutor} from "./commandExecutor";
6import {Log, LogLevel} from "./log";
7import {Node} from "./node/node";
8import {OutputChannel} from "vscode";
9import {Package} from "./node/package";
10import {PromiseUtil} from "./node/promise";
11import {Request} from "./node/request";
12
13import * as Q from "q";
14import * as path from "path";
15
16export class Packager {
17 // TODO: Make the port configurable via a launch argument
18 public static PORT = "8081";
19 public static HOST = `localhost:${Packager.PORT}`;
20 public static DEBUGGER_WORKER_FILE_BASENAME = "debuggerWorker";
21 public static DEBUGGER_WORKER_FILENAME = Packager.DEBUGGER_WORKER_FILE_BASENAME + ".js";
22
23 private projectPath: string;
24 private packagerProcess: ChildProcess;
25 private sourcesStoragePath: string;
26
27 private static JS_INJECTOR_FILENAME = "opn-main.js";
28 private static JS_INJECTOR_FILEPATH = path.resolve(path.dirname(path.dirname(__dirname)), "js-patched", Packager.JS_INJECTOR_FILENAME);
29 private static NODE_MODULES_FODLER_NAME = "node_modules";
30 private static OPN_PACKAGE_NAME = "opn";
31 private static REACT_NATIVE_PACKAGE_NAME = "react-native";
32 private static OPN_PACKAGE_MAIN_FILENAME = "index.js";
33
34 constructor(projectPath: string, sourcesStoragePath?: string) {
35 this.projectPath = projectPath;
36 this.sourcesStoragePath = sourcesStoragePath;
37 }
38
39
40 public start(outputChannel?: OutputChannel): Q.Promise<void> {
41 let executedStartPackagerCmd = false;
42 return this.isRunning()
43 .then(running => {
44 if (!running) {
45 return this.monkeyPatchOpnForRNPackager()
46 .then(() => {
47 let args = ["--port", Packager.PORT];
48 let childEnvForDebugging = Object.assign({}, process.env, { REACT_DEBUGGER: "echo A debugger is not needed: " });
49
50 Log.logMessage("Starting Packager", outputChannel);
51 // The packager will continue running while we debug the application, so we can"t
52 // wait for this command to finish
53
54 let spawnOptions = { env: childEnvForDebugging };
55
56 // TODO - PROMISE: We need to consume the result of this spawn
57 new CommandExecutor(this.projectPath).spawnReactPackager(args, spawnOptions, outputChannel).then((packagerProcess) => {
58 this.packagerProcess = packagerProcess;
59 executedStartPackagerCmd = true;
60 });
61 });
62 }
63 })
64 .then(() =>
65 this.awaitStart())
66 .then(() => {
67 if (executedStartPackagerCmd) {
68 Log.logMessage("Packager started.", outputChannel);
69 } else {
70 Log.logMessage("Packager is already running.", outputChannel);
71 if (!outputChannel) {
72 Log.logMessage("Warning: Debugging is not supported if the React Native Packager is not started within VS Code. If debugging fails, please kill other active React Native packager processes and retry.", outputChannel);
73 }
74 }
75
76 if (this.sourcesStoragePath) {
77 return this.downloadDebuggerWorker().then(() => {
78 Log.logMessage("Downloaded debuggerWorker.js (Logic to run the React Native app) from the Packager.");
79 });
80 }
81 });
82 }
83
84 public stop(outputChannel?: OutputChannel): Q.Promise<void> {
85 return new CommandExecutor(this.projectPath).killReactPackager(this.packagerProcess, outputChannel).then(() =>
86 this.packagerProcess = null);
87 }
88
89 public prewarmBundleCache(platform: string) {
90 let bundleURL = `http://${Packager.HOST}/index.${platform}.bundle`;
91 Log.logInternalMessage(LogLevel.Info, "About to get: " + bundleURL);
92 return new Request().request(bundleURL, true).then(() => {
93 Log.logMessage("The Bundle Cache was prewarmed.");
94 }).catch(() => {
95 // The attempt to prefetch the bundle failed.
96 // This may be because the bundle is not index.* so we shouldn't treat this as fatal.
97 });
98 }
99
100 private isRunning(): Q.Promise<boolean> {
101 let statusURL = `http://${Packager.HOST}/status`;
102
103 return new Request().request(statusURL)
104 .then((body: string) => {
105 return body === "packager-status:running";
106 },
107 (error: any) => {
108 return false;
109 });
110 }
111
112 private awaitStart(retryCount = 30, delay = 2000): Q.Promise<boolean> {
113 let pu: PromiseUtil = new PromiseUtil();
114 return pu.retryAsync(() => this.isRunning(), (running) => running, retryCount, delay, "Could not start the packager.");
115 }
116
117 private downloadDebuggerWorker(): Q.Promise<void> {
118 let debuggerWorkerURL = `http://${Packager.HOST}/${Packager.DEBUGGER_WORKER_FILENAME}`;
119 let debuggerWorkerLocalPath = path.join(this.sourcesStoragePath, Packager.DEBUGGER_WORKER_FILENAME);
120 Log.logInternalMessage(LogLevel.Info, "About to download: " + debuggerWorkerURL + " to: " + debuggerWorkerLocalPath);
121 return new Request().request(debuggerWorkerURL, true).then((body: string) => {
122 return new Node.FileSystem().writeFile(debuggerWorkerLocalPath, body);
123 });
124 }
125
126 private findOpnPackage(): Q.Promise<string> {
127 try {
128 let flatDependencyPackagePath = path.resolve(this.projectPath, Packager.NODE_MODULES_FODLER_NAME,
129 Packager.OPN_PACKAGE_NAME, Packager.OPN_PACKAGE_MAIN_FILENAME);
130
131 let nestedDependencyPackagePath = path.resolve(this.projectPath, Packager.NODE_MODULES_FODLER_NAME,
132 Packager.REACT_NATIVE_PACKAGE_NAME, Packager.NODE_MODULES_FODLER_NAME, Packager.OPN_PACKAGE_NAME, Packager.OPN_PACKAGE_MAIN_FILENAME);
133
134 let fsHelper = new Node.FileSystem();
135
136 // Attempt to find the 'opn' package directly under the project's node_modules folder (node4 +)
137 // Else, attempt to find the package within the dependent node_modules of react-native package
138 let possiblePaths = [flatDependencyPackagePath, nestedDependencyPackagePath];
139 return Q.any(possiblePaths.map(path =>
140 fsHelper.exists(path).then(exists =>
141 exists
142 ? Q.resolve(path)
143 : Q.reject<string>("opn package location not found"))));
144 } catch (err) {
145 console.error("The package \'opn\' was not found." + err);
146 }
147 }
148
149 private monkeyPatchOpnForRNPackager(): Q.Promise<void> {
150 let opnPackage: Package;
151 let destnFilePath: string;
152
153 // Finds the 'opn' package
154 return this.findOpnPackage()
155 .then((opnIndexFilePath) => {
156 destnFilePath = opnIndexFilePath;
157 // Read the package's "package.json"
158 opnPackage = new Package(path.resolve(path.dirname(destnFilePath)));
159 return opnPackage.parsePackageInformation();
160 }).then((packageJson) => {
161 if (packageJson.main !== Packager.JS_INJECTOR_FILENAME) {
162 // Copy over the patched 'opn' main file
163 return new Node.FileSystem().copyFile(Packager.JS_INJECTOR_FILEPATH, path.resolve(path.dirname(destnFilePath), Packager.JS_INJECTOR_FILENAME))
164 .then(() => {
165 // Write/over-write the "main" attribute with the new file
166 return opnPackage.setMainFile(Packager.JS_INJECTOR_FILENAME);
167 });
168 }
169 });
170 }
171}
172