-
Notifications
You must be signed in to change notification settings - Fork 1
/
build.mjs
96 lines (83 loc) · 2.84 KB
/
build.mjs
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
import * as esbuild from 'esbuild'
import * as fs from "node:fs";
import * as chokidar from 'chokidar';
const tmpPath = 'build/arch-translator.js';
const outWSrcMapPath = 'build/arch-translator.srcmap.user.js';
const outPath = 'build/arch-translator.user.js';
const ctx = await esbuild.context({
entryPoints: ['src/index.ts'],
bundle: true,
outfile: tmpPath,
sourcemap: 'external',
loader: {
'.css': 'text' // TODO: Minify the CSS file
}
});
const NEW_LINE_ASCII = 0x0A;
function countNewLines(buffer) {
let count = 0;
for (let i = 0; i < buffer.length; ++i) {
if (buffer[i] === NEW_LINE_ASCII) {
count++;
}
}
return count;
}
async function build() {
try {
await ctx.rebuild();
} catch (e) {
console.error('Build failed');
console.error(e);
return;
}
console.log('Prepending userscript header');
const bundle = fs.readFileSync(tmpPath);
const header = fs.readFileSync('src/uscript-header.txt');
const noSrcMapHandle = fs.openSync(outPath, 'w');
fs.writeSync(noSrcMapHandle, header, 0, header.length, 0);
fs.writeSync(noSrcMapHandle, bundle, 0, bundle.length, header.length);
fs.closeSync(noSrcMapHandle);
const srcMap = JSON.parse(fs.readFileSync(tmpPath + '.map').toString());
let srcMapOffset = '';
for (let i = 0; i < countNewLines(header); ++i) {
srcMapOffset += ';'; // ; represents a newline in the mappings
}
srcMap['mappings'] = srcMapOffset + srcMap['mappings'];
const bundleHandle = fs.openSync(outWSrcMapPath, 'w');
fs.writeSync(bundleHandle, header, 0, header.length, 0);
fs.writeSync(bundleHandle, bundle, 0, bundle.length, header.length);
// inline the modified srcmap
const srcMapJsonB64 = Buffer.from(JSON.stringify(srcMap), 'utf8');
const srcMapString = '//# sourceMappingURL=data:application/json;base64,' + srcMapJsonB64.toString('base64');
const srcMapBuffer = Buffer.from(srcMapString, 'utf8');
fs.writeSync(bundleHandle, srcMapBuffer, 0, srcMapBuffer.length, header.length + bundle.length);
fs.closeSync(bundleHandle);
}
if (process.argv.length < 3) {
console.error("Usage: node build.mjs <build|watch>");
process.exit(1);
}
const verb = process.argv[2].toLowerCase();
switch (verb) {
case 'build':
build()
.then(() => {
ctx.dispose()
.then(() => {
console.log(`Build done. See ${outPath}`);
});
});
break;
case 'watch':
chokidar.watch('src').on('all', (event, path) => {
console.log(event, path);
build()
.then(() => {
console.log('build done');
});
});
break;
default:
throw new Error('Invalid verb: ' + verb);
}