-
Notifications
You must be signed in to change notification settings - Fork 1
/
compiler.ts
70 lines (60 loc) · 1.8 KB
/
compiler.ts
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
import spawn from 'cross-spawn';
import type { ChildProcess } from 'child_process';
const RELAY = 'relay-compiler';
const COMPILING = 'compiling';
const FAILED = 'compilation failed';
export interface IRelayCompiler {
runOnce(): void;
watch(callback?: () => void): void;
stop(): void;
hasError: boolean;
error: Error;
}
export class RelayCompiler implements IRelayCompiler {
private subprocess?: ChildProcess;
private errorMessage: string = '';
constructor(private args: string[]) {}
get hasError() {
return this.errorMessage.length > 0;
}
get error() {
return new Error(this.errorMessage);
}
runOnce() {
this.errorMessage = '';
const subprocess = spawn.sync(RELAY, this.args);
if (subprocess.stdout?.byteLength > 0) {
console.log(`${subprocess.stdout}`);
}
if (subprocess.stderr?.byteLength > 0) {
this.errorMessage += subprocess.stderr.toString('utf-8');
}
}
// In the watch mode, we have to parse output
// to detect compiler's state
watch(callback?: () => void) {
if (!this.subprocess) {
// Start relay-compiler in watch mode
this.subprocess = spawn(RELAY, [...this.args, '--watch']);
this.subprocess?.stderr?.setEncoding("utf-8");
// Clear errors during compilation
this.subprocess?.stdout?.on('data', chunk => {
if (String(chunk).toLowerCase().includes(COMPILING)) {
this.errorMessage = '';
}
});
// Collect errors from stderr (added in v13.0.2)
this.subprocess?.stderr?.on('data', chunk => {
this.errorMessage += chunk;
// Do something if compilation failed
if (this.errorMessage.toLowerCase().includes(FAILED)) {
callback?.();
}
});
}
}
stop() {
this.subprocess?.kill();
this.subprocess = undefined;
}
}