-
Notifications
You must be signed in to change notification settings - Fork 6
/
build.ts
executable file
·193 lines (177 loc) · 4.95 KB
/
build.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
190
191
192
193
#! node_modules/.bin/ts-node
import { fork, ChildProcess } from 'child_process'
import * as os from 'os'
import * as path from 'path'
import * as chokidar from 'chokidar'
import globby from 'globby'
import chalk from 'chalk'
const argv = parseArgv()
const PACKAGES_DIR = path.resolve(__dirname, 'packages')
const workers = createWorkers(Math.max(Math.min(os.cpus().length - 2, 8), 1))
function parseArgv() {
const hasFlag = (f: string) =>
process.argv.indexOf(`--${f}`) > -1 || process.argv.indexOf(`-${f[0]}`) > -1
return {
watch: hasFlag('watch'),
transpileOnly: hasFlag('transpile-only'),
}
}
const getSourceFiles = () =>
globby(
[
'**/*.ts',
'**/*.tsx',
'!**/examples/**/*',
'!**/node_modules/**/*',
'!**/__tests__/**/*',
'!**/test.ts',
'!**/test.tsx',
'!**/*.test.ts',
],
{
cwd: PACKAGES_DIR,
}
).then((files) => files.map((f) => path.resolve(__dirname, 'packages', f)))
function createWorkers(size: number) {
// tslint:disable no-console
console.info(chalk.cyan(`Forking ${size} worker processess`))
const workerFile = path.resolve(__dirname, './build.worker.ts')
const _workers: ChildProcess[] = []
let i = 0
while (i++ < size) _workers.push(fork(workerFile))
let numListeners = 0
return {
doWork(file: string) {
const worker = _workers[i++ % size]
const p = new Promise<{
file: string
hasErrors?: boolean
hasWarnings?: boolean
}>((resolve, reject) => {
worker.setMaxListeners(++numListeners)
worker.on('message', (message: any) => {
if (file === message.file) {
if (message.hasErrors) {
reject(message)
} else {
resolve(message)
console.log(chalk.dim(`Transpiled ${message.file}`))
}
}
})
})
worker.send({ file })
return p
},
cull(numToKeep: number) {
for (let j = numToKeep; j < size; j++) {
;(_workers.pop() as ChildProcess).kill()
}
size = numToKeep
},
destroy() {
_workers.forEach((w) => w.kill())
},
}
}
function pifyProc(proc: ChildProcess) {
return new Promise<{ code: number | null; output: string }>(
(resolve, reject) => {
let output = ''
if (proc.stdout) {
proc.stdout.on('data', (buf) => (output += buf.toString()))
}
proc.on('close', (code) => resolve({ code, output }))
proc.on('error', (err) => reject(err))
}
)
}
function startTypeChecker() {
// tslint:disable:no-console
const args: string[] = ['--pretty']
console.info(chalk.cyan('Forking type checker'))
if (argv.watch) args.push('--watch')
const proc = fork(
path.resolve(__dirname, 'node_modules/typescript/bin/tsc'),
args,
{ stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }
)
if (proc.stderr) proc.stderr.pipe(process.stderr)
proc.on('close', (code) => {
const color = code === 0 ? chalk.green : chalk.red
console.info(color(`\nType checker exited with code ${code}`))
})
return proc
}
async function build(files: string[]): Promise<number> {
const [typeCheckResults, transpileAndLintResults] = await Promise.all<any>([
argv.transpileOnly ? Promise.resolve() : pifyProc(startTypeChecker()),
Promise.all(files.map(workers.doWork)).then((results) => {
console.log(chalk.green('Transpilation completed without errors'))
workers.destroy()
return results
}),
// .catch((message) => {
// console.error('Error:', message)
// })
])
if (typeCheckResults && typeCheckResults.output) {
typeCheckResults.output
.split('\n')
.forEach((l: string) => console.error('[tsc]', l))
return 1
}
if (transpileAndLintResults.find((r: any) => !!r.hasErrors)) {
return 1
}
return 0
}
async function watch(files: string[]): Promise<number> {
if (!argv.transpileOnly) {
const proc = startTypeChecker()
if (proc.stdout) {
proc.stdout.on('data', (buf: Buffer) => {
const str = buf.toString().replace('\u001Bc', '')
str
.split('\n')
.filter((l) => l.length > 0)
.map((l) => console.log('[tsc]', l))
})
}
}
await Promise.all(files.map(workers.doWork))
console.log('Initial build complete, scaling back workers')
workers.cull(1)
console.log('Watching for changes...')
const watcher = chokidar.watch(files)
watcher.on('change', (p) => {
console.info('Change detected in', p)
workers.doWork(p).catch(() => {
/* noop */
})
})
return new Promise<number>(() => {
/* void */
})
}
async function main() {
const files = await getSourceFiles()
if (argv.watch) {
return await watch(files)
} else {
return await build(files)
}
}
main()
.catch((err) => {
// tslint:disable:no-console
if (err.message) console.error(err.message)
return 1
})
.then((code: number) => {
workers.destroy()
process.exit(code)
})
.catch(() => {
/* noop*/
})