-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·259 lines (217 loc) · 6.69 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
module.exports.runCLI = async function runCLI() {
const chalk = require("chalk");
const ora = require("ora");
const spinner = ora(chalk.cyan("Initializing...")).start();
const webpack = require("webpack");
const stream = require("stream");
const inquirer = require("inquirer");
const formatWebpackMessages = require("react-dev-utils/formatWebpackMessages");
const child_process = require("child_process");
const { createServerWebpackConfig } = require("./server.webpack.config");
spinner.text = chalk.cyan("Creating compiler...");
const webpackConfig = createServerWebpackConfig();
const serverCompiler = createCompiler(webpackConfig);
const compilationPromise = waitForCompilation(serverCompiler);
let serverProcess;
let serverLogPaused = false;
let ui = new inquirer.ui.BottomBar();
const stdin = process.stdin;
const startServerProcess = () => {
serverProcess = child_process.fork("./build/index.js", {
stdio: "pipe",
execArgv: process.argv.slice(3),
env: {
...process.env,
NODE_ENV: "development"
}
});
serverProcess.stdout
.pipe(serverLogPauser())
.pipe(serverLogPrefixer())
.pipe(ui.log)
.pipe(process.stdout);
serverProcess.stderr
.pipe(serverLogPauser())
.pipe(serverLogPrefixer())
.pipe(ui.log)
.pipe(process.stderr);
serverProcess.on("disconnect", () => (serverProcess = undefined));
serverProcess.on("close", code => {
console.log("closed!");
ui.updateBottomBar(
`${
code && code > 0
? chalk.red(`! Exited with code ${code}...`)
: chalk.green(`✔ Exited cleanly`)
} ${chalk.gray("(any key to view menu)")}`
);
});
serverProcess.on("exit", code => {
// console.log("exit");
});
serverProcess.on("message", () => {
serverProcess.kill();
startServerProcess();
});
};
spinner.succeed(chalk.green("Compiler created"));
serverCompiler.watch({ "info-verbosity": "none" }, (error, stats) => {
if (!error && !stats.hasErrors()) {
if (serverProcess) {
serverProcess.send({});
} else {
startServerProcess();
ui.updateBottomBar(
`${chalk.green("✈ Running...")} ${chalk.gray(
"(any key to view menu)"
)}`
);
stdin.resume();
}
}
});
try {
await compilationPromise;
} catch (error) {}
ui.updateBottomBar(
`${chalk.green("✈ Running...")} ${chalk.gray("(any key to view menu)")}`
);
// without this, we would only get streams once enter is pressed
stdin.setRawMode(true);
// resume stdin in the parent process (node app won't quit all by itself
// unless an error or process.exit() happens)
stdin.resume();
// i don't want binary, do you?
stdin.setEncoding("utf8");
const prompt = inquirer.createPromptModule();
const onKeyPress = key => {
// ctrl-c ( end of text )
if (key === "\u0003") {
process.exit();
}
serverLogPaused = true;
ui.updateBottomBar("");
stdin.removeListener("data", onKeyPress);
prompt([
{
type: "list",
name: "action",
message: "What now?",
choices: ["Restart", "Show stdout"]
}
]).then(({ action }) => {
if (action === "Show stdout") {
serverLogPaused = false;
ui.updateBottomBar(
`${chalk.green("✈ Running...")} ${chalk.gray(
"(any key to view menu)"
)}`
);
stdin.resume();
stdin.on("data", onKeyPress);
} else if (action === "Restart") {
serverLogPaused = false;
if (serverProcess) {
spinner.text = "Killing process...";
spinner.start();
serverProcess.removeAllListeners("exit");
serverProcess.on("exit", () => {
spinner.succeed("Process killed");
startServerProcess();
ui.updateBottomBar(
`${chalk.green("✈ Running...")} ${chalk.gray(
"(any key to view menu)"
)}`
);
stdin.resume();
stdin.on("data", onKeyPress);
});
serverProcess.kill();
} else {
startServerProcess();
ui.updateBottomBar(
`${chalk.green("✈ Running...")} ${chalk.gray(
"(any key to view menu)"
)}`
);
stdin.resume();
stdin.on("data", onKeyPress);
}
}
});
};
// on any data into stdin
stdin.on("data", onKeyPress);
function createCompiler(config) {
let compiler;
try {
compiler = webpack(config);
} catch (err) {
console.log(chalk.red("Failed to compile."));
console.log();
console.log(err.message || err);
console.log();
process.exit(1);
}
let spinner;
compiler.hooks.watchRun.tap("start-log", () => {
serverLogPaused = true;
console.log();
spinner = ora(chalk.cyan("Compiling...")).start();
});
compiler.hooks.done.tap("finished-log", stats => {
const messages = formatWebpackMessages(stats.toJson({}, true));
const isSuccessful = !messages.errors.length && !messages.warnings.length;
if (isSuccessful) {
spinner.succeed(chalk.green("Compiled successfully!"));
console.log();
}
// If errors exist, only show errors.
if (messages.errors.length) {
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
spinner.fail(chalk.red("Failed to compile."));
console.log(messages.errors.join("\n\n"));
return;
}
// Show warnings if no errors were found.
if (messages.warnings.length) {
spinner.warn(chalk.orange("Compiled with warnings."));
console.log(messages.warnings.join("\n\n"));
}
serverLogPaused = false;
});
return compiler;
}
function waitForCompilation(compiler) {
return new Promise((resolve, reject) => {
compiler.hooks.done.tap("promise", stats =>
stats.hasErrors() ? reject(stats) : resolve(stats)
);
});
}
function serverLogPrefixer() {
return new stream.Transform({
transform(chunk, encoding, callback) {
const chunkString = chunk.toString();
if (chunkString.startsWith("[HMR]")) {
this.push(chunkString.replace(/\[HMR\]/g, chalk.cyan(["[HMR]"])));
} else {
this.push(`${chalk.blue("[SERVER]")}: ${chunk.toString()}`);
}
callback();
}
});
}
function serverLogPauser() {
return new stream.Transform({
transform(chunk, encoding, callback) {
if (!serverLogPaused) {
this.push(chunk);
}
callback();
}
});
}
};