/
compile-swc.ts
189 lines (160 loc) · 5.4 KB
/
compile-swc.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
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
import { ExecutorContext, logger } from '@nrwl/devkit';
import { cacheDir } from '@nrwl/workspace/src/utilities/cache-directory';
import { exec, execSync } from 'child_process';
import { createAsyncIterable } from '../create-async-iterable/create-async-iteratable';
import { NormalizedSwcExecutorOptions, SwcCliOptions } from '../schema';
import { printDiagnostics } from '../typescript/print-diagnostics';
import { runTypeCheck, TypeCheckOptions } from '../typescript/run-type-check';
function getSwcCmd(
{ swcrcPath, srcPath, destPath }: SwcCliOptions,
watch = false
) {
let swcCmd = `npx swc ${srcPath} -d ${destPath} --no-swcrc --config-file=${swcrcPath}`;
return watch ? swcCmd.concat(' --watch') : swcCmd;
}
function getTypeCheckOptions(normalizedOptions: NormalizedSwcExecutorOptions) {
const { projectRoot, watch, tsConfig, root, outputPath } = normalizedOptions;
const typeCheckOptions: TypeCheckOptions = {
mode: 'emitDeclarationOnly',
tsConfigPath: tsConfig,
outDir: outputPath,
workspaceRoot: root,
rootDir: projectRoot,
};
if (watch) {
typeCheckOptions.incremental = true;
typeCheckOptions.cacheDir = cacheDir;
}
return typeCheckOptions;
}
export async function compileSwc(
context: ExecutorContext,
normalizedOptions: NormalizedSwcExecutorOptions,
postCompilationCallback: () => Promise<void>
) {
logger.log(`Compiling with SWC for ${context.projectName}...`);
const swcCmdLog = execSync(getSwcCmd(normalizedOptions.swcCliOptions), {
cwd: normalizedOptions.swcCliOptions.swcCwd,
}).toString();
logger.log(swcCmdLog.replace(/\n/, ''));
const isCompileSuccess = swcCmdLog.includes('Successfully compiled');
await postCompilationCallback();
if (normalizedOptions.skipTypeCheck) {
return { success: isCompileSuccess };
}
const { errors, warnings } = await runTypeCheck(
getTypeCheckOptions(normalizedOptions)
);
const hasErrors = errors.length > 0;
const hasWarnings = warnings.length > 0;
if (hasErrors || hasWarnings) {
await printDiagnostics(errors, warnings);
}
return { success: !hasErrors && isCompileSuccess };
}
export async function* compileSwcWatch(
context: ExecutorContext,
normalizedOptions: NormalizedSwcExecutorOptions,
postCompilationCallback: () => Promise<void>
) {
const getResult = (success: boolean) => ({
success,
outfile: normalizedOptions.mainOutputPath,
});
let typeCheckOptions: TypeCheckOptions;
let initialPostCompile = true;
return yield* createAsyncIterable<{ success: boolean; outfile: string }>(
async ({ next, done }) => {
let processOnExit: () => void;
let stdoutOnData: () => void;
let stderrOnData: () => void;
let watcherOnExit: () => void;
const swcWatcher = exec(
getSwcCmd(normalizedOptions.swcCliOptions, true),
{ cwd: normalizedOptions.swcCliOptions.swcCwd }
);
processOnExit = () => {
swcWatcher.kill();
done();
process.off('SIGINT', processOnExit);
process.off('SIGTERM', processOnExit);
process.off('exit', processOnExit);
};
stdoutOnData = async (data?: string) => {
process.stdout.write(data);
if (!data.startsWith('Watching')) {
const swcStatus = data.includes('Successfully');
if (initialPostCompile) {
await postCompilationCallback();
initialPostCompile = false;
}
if (normalizedOptions.skipTypeCheck) {
next(getResult(swcStatus));
return;
}
if (!typeCheckOptions) {
typeCheckOptions = getTypeCheckOptions(normalizedOptions);
}
const delayed = delay(5000);
next(
getResult(
await Promise.race([
delayed
.start()
.then(() => ({ tscStatus: false, type: 'timeout' })),
runTypeCheck(typeCheckOptions).then(({ errors, warnings }) => {
const hasErrors = errors.length > 0;
if (hasErrors) {
printDiagnostics(errors, warnings);
}
return {
tscStatus: !hasErrors,
type: 'tsc',
};
}),
]).then(({ type, tscStatus }) => {
if (type === 'tsc') {
delayed.cancel();
return tscStatus && swcStatus;
}
return swcStatus;
})
)
);
}
};
stderrOnData = (err?: any) => {
process.stderr.write(err);
next(getResult(false));
};
watcherOnExit = () => {
done();
swcWatcher.off('exit', watcherOnExit);
};
swcWatcher.stdout.on('data', stdoutOnData);
swcWatcher.stderr.on('data', stderrOnData);
process.on('SIGINT', processOnExit);
process.on('SIGTERM', processOnExit);
process.on('exit', processOnExit);
swcWatcher.on('exit', watcherOnExit);
}
);
}
function delay(ms: number): { start: () => Promise<void>; cancel: () => void } {
let timerId: ReturnType<typeof setTimeout> = undefined;
return {
start() {
return new Promise<void>((resolve) => {
timerId = setTimeout(() => {
resolve();
}, ms);
});
},
cancel() {
if (timerId) {
clearTimeout(timerId);
timerId = undefined;
}
},
};
}