microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
fb6c0d0507b286c72b88078fd6d7bc0ff2fa682d

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/common/packager.ts

164lines · 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 public start(outputChannel?: OutputChannel): Q.Promise<void> {
40 this.isRunning().done(running => {
41 if (!running) {
42 return this.monkeyPatchOpnForRNPackager()
43 .then(() => {
44 let args = ["--port", Packager.PORT];
45 let childEnvForDebugging = Object.assign({}, process.env, { REACT_DEBUGGER: "echo A debugger is not needed: " });
46
47 Log.logMessage("Starting Packager", outputChannel);
48 // The packager will continue running while we debug the application, so we can"t
49 // wait for this command to finish
50
51 let spawnOptions = { env: childEnvForDebugging };
52
53 new CommandExecutor(this.projectPath).spawnReactCommand("start", args, spawnOptions, outputChannel).then((packagerProcess) => {
54 this.packagerProcess = packagerProcess;
55 });
56 }).done();
57 }
58 });
59
60 return this.awaitStart().then(() => {
61 Log.logMessage("Packager started.", outputChannel);
62 if (this.sourcesStoragePath) {
63 return this.downloadDebuggerWorker().then(() => {
64 Log.logMessage("Downloaded debuggerWorker.js (Logic to run the React Native app) from the Packager.");
65 });
66 }
67 });
68 }
69
70 public stop(outputChannel?: OutputChannel): void {
71 Log.logMessage("Stopping Packager", outputChannel);
72
73 if (this.packagerProcess) {
74 this.packagerProcess.kill();
75 this.packagerProcess = null;
76 Log.logMessage("Packager stopped", outputChannel);
77 } else {
78 Log.logMessage("Packager not found", outputChannel);
79 }
80 }
81
82 public prewarmBundleCache(platform: string) {
83 let bundleURL = `http://${Packager.HOST}/index.${platform}.bundle`;
84 Log.logInternalMessage(LogLevel.Info, "About to get: " + bundleURL);
85 return new Request().request(bundleURL, true).then(() => {
86 Log.logMessage("The Bundle Cache was prewarmed.");
87 }).catch(() => {
88 // The attempt to prefetch the bundle failed.
89 // This may be because the bundle is not index.* so we shouldn't treat this as fatal.
90 });
91 }
92
93 private isRunning(): Q.Promise<boolean> {
94 let statusURL = `http://${Packager.HOST}/status`;
95
96 return new Request().request(statusURL)
97 .then((body: string) => {
98 return body === "packager-status:running";
99 },
100 (error: any) => {
101 return false;
102 });
103 }
104
105 private awaitStart(retryCount = 30, delay = 2000): Q.Promise<boolean> {
106 let pu: PromiseUtil = new PromiseUtil();
107 return pu.retryAsync(() => this.isRunning(), (running) => running, retryCount, delay, "Could not start the packager.");
108 }
109
110 private downloadDebuggerWorker(): Q.Promise<void> {
111 let debuggerWorkerURL = `http://${Packager.HOST}/${Packager.DEBUGGER_WORKER_FILENAME}`;
112 let debuggerWorkerLocalPath = path.join(this.sourcesStoragePath, Packager.DEBUGGER_WORKER_FILENAME);
113 Log.logInternalMessage(LogLevel.Info, "About to download: " + debuggerWorkerURL + " to: " + debuggerWorkerLocalPath);
114 return new Request().request(debuggerWorkerURL, true).then((body: string) => {
115 return new Node.FileSystem().writeFile(debuggerWorkerLocalPath, body);
116 });
117 }
118
119 private findOpnPackage(): Q.Promise<string> {
120 try {
121 let flatDependencyPackagePath = path.resolve(this.projectPath, Packager.NODE_MODULES_FODLER_NAME,
122 Packager.OPN_PACKAGE_NAME, Packager.OPN_PACKAGE_MAIN_FILENAME);
123
124 let nestedDependencyPackagePath = path.resolve(this.projectPath, Packager.NODE_MODULES_FODLER_NAME,
125 Packager.REACT_NATIVE_PACKAGE_NAME, Packager.NODE_MODULES_FODLER_NAME, Packager.OPN_PACKAGE_NAME, Packager.OPN_PACKAGE_MAIN_FILENAME);
126
127 let fsHelper = new Node.FileSystem();
128
129 // Attempt to find the 'opn' package directly under the project's node_modules folder (node4 +)
130 // Else, attempt to find the package within the dependent node_modules of react-native package
131 let possiblePaths = [flatDependencyPackagePath, nestedDependencyPackagePath];
132 return Q.any(possiblePaths.map(path =>
133 fsHelper.exists(path).then(exists =>
134 exists
135 ? Q.resolve(path)
136 : Q.reject<string>("opn package location not found"))));
137 } catch (err) {
138 console.error("The package \'opn\' was not found." + err);
139 }
140 }
141
142 private monkeyPatchOpnForRNPackager(): Q.Promise<void> {
143 let opnPackage: Package;
144 let destnFilePath: string;
145
146 // Finds the 'opn' package
147 return this.findOpnPackage()
148 .then((opnIndexFilePath) => {
149 destnFilePath = opnIndexFilePath;
150 // Read the package's "package.json"
151 opnPackage = new Package(path.resolve(path.dirname(destnFilePath)));
152 return opnPackage.parsePackageInformation();
153 }).then((packageJson) => {
154 if (packageJson.main !== Packager.JS_INJECTOR_FILENAME) {
155 // Copy over the patched 'opn' main file
156 return new Node.FileSystem().copyFile(Packager.JS_INJECTOR_FILEPATH, path.resolve(path.dirname(destnFilePath), Packager.JS_INJECTOR_FILENAME))
157 .then(() => {
158 // Write/over-write the "main" attribute with the new file
159 return opnPackage.setMainFile(Packager.JS_INJECTOR_FILENAME);
160 });
161 }
162 });
163 }
164}
165