summaryrefslogtreecommitdiff
path: root/scripts/cmd/prebuild.js
blob: bb8220eef16514968e38d28cea1a6a2a0b730d54 (plain) (blame)
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
import esbuild from 'esbuild';
import glob from 'tiny-glob';
import fs from 'fs';
import path from 'path';
import { pathToFileURL, fileURLToPath } from 'url';

function escapeTemplateLiterals(str) {
	return str.replace(/\`/g, '\\`').replace(/\$\{/g, '\\${');
}

export default async function prebuild(...args) {
	let buildToString = args.indexOf('--to-string');
	if (buildToString !== -1) {
		args.splice(buildToString, 1);
		buildToString = true;
	}
	let minify = true;
	let minifyIdx = args.indexOf('--no-minify');
	if (minifyIdx !== -1) {
		minify = false;
		args.splice(minifyIdx, 1);
	}

	let patterns = args;
	let entryPoints = [].concat(
		...(await Promise.all(
			patterns.map((pattern) => glob(pattern, { filesOnly: true, absolute: true }))
		))
	);

	function getPrebuildURL(entryfilepath) {
		const entryURL = pathToFileURL(entryfilepath);
		const basename = path.basename(entryfilepath);
		const ext = path.extname(entryfilepath);
		const name = basename.slice(0, basename.indexOf(ext));
		const outname = `${name}.prebuilt${ext}`;
		const outURL = new URL('./' + outname, entryURL);
		return outURL;
	}

	async function prebuildFile(filepath) {
		const tscode = await fs.promises.readFile(filepath, 'utf-8');
		const esbuildresult = await esbuild.transform(tscode, {
			loader: 'ts',
			minify,
		});
		const rootURL = new URL('../../', import.meta.url);
		const rel = path.relative(fileURLToPath(rootURL), filepath);
		const mod = `/**
 * This file is prebuilt from ${rel}
 * Do not edit this directly, but instead edit that file and rerun the prebuild
 * to generate this file.
 */

export default \`${escapeTemplateLiterals(esbuildresult.code.trim())}\`;`;
		const url = getPrebuildURL(filepath);
		await fs.promises.writeFile(url, mod, 'utf-8');
	}

	await Promise.all(entryPoints.map(prebuildFile));
}