/
stdin.ts
39 lines (35 loc) · 897 Bytes
/
stdin.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
import process from 'node:process';
import type { Plugin } from '../../src/rollup/types';
export const stdinName = '-';
let stdinResult: Promise<string> | null = null;
export function stdinPlugin(arg: unknown): Plugin {
const suffix = typeof arg == 'string' && arg.length ? '.' + arg : '';
return {
load(id) {
if (id === stdinName || id.startsWith(stdinName + '.')) {
return stdinResult || (stdinResult = readStdin());
}
},
name: 'stdin',
resolveId(id) {
if (id === stdinName) {
return id + suffix;
}
}
};
}
function readStdin(): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
process.stdin.setEncoding('utf8');
process.stdin
.on('data', chunk => chunks.push(chunk))
.on('end', () => {
const result = chunks.join('');
resolve(result);
})
.on('error', err => {
reject(err);
});
});
}