-
Notifications
You must be signed in to change notification settings - Fork 1
/
build.ts
239 lines (217 loc) Β· 6.04 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/* eslint-disable no-bitwise, no-console */
import type { BuildArtifact, BunPlugin } from 'bun';
import * as csso from 'csso';
import * as xcss from 'ekscss';
import * as lightningcss from 'lightningcss';
import { PurgeCSS } from 'purgecss';
import * as terser from 'terser';
import { createManifest } from './manifest.config';
import xcssConfig from './xcss.config';
const mode = Bun.env.NODE_ENV;
const dev = mode === 'development';
let css = '';
// XXX: Temporary workaround to build CSS until Bun.build supports css loader
const extractCSS: BunPlugin = {
name: 'extract-css',
setup(build) {
build.onLoad({ filter: /\.css$/ }, async (args) => {
css += await Bun.file(args.path).text();
return { contents: '', loader: 'js' };
});
build.onLoad({ filter: /\.xcss$/ }, async (args) => {
const source = await Bun.file(args.path).text();
const compiled = xcss.compile(source, {
from: args.path,
globals: xcssConfig.globals,
plugins: xcssConfig.plugins,
});
for (const warning of compiled.warnings) {
console.error('XCSS:', warning.message);
if (warning.file) {
console.log(
` at ${[warning.file, warning.line, warning.column]
.filter(Boolean)
.join(':')}`,
);
}
}
css += compiled.css;
return { contents: '', loader: 'js' };
});
},
};
function makeHTML() {
return `
<!doctype html>
<meta charset=utf-8>
<meta name=google value=notranslate>
<link href=literata.woff2 rel=preload as=font type=font/woff2 crossorigin>
<link href=reader.css rel=stylesheet>
<script src=health.js defer></script>
<script src=reader.js defer></script>
`
.trim()
.replaceAll(/\n\s+/g, '\n'); // remove leading whitespace
}
async function minifyCSS(artifact: BuildArtifact) {
const js = await artifact.text();
const purged = await new PurgeCSS().purge({
content: [{ extension: '.js', raw: js }],
css: [{ raw: css }],
safelist: ['html', 'body'],
blocklist: [
// XXX: Remember to remove if actually using the element tag
'article',
'aside',
'blockquote',
'break',
'canvas',
'dd',
// 'disabled',
'dt',
'embed',
'figcaption',
'figure',
// 'footer',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'header',
'hgroup',
'hr',
'iframe',
'img',
'input',
'link',
'main',
'nav',
'ol',
'pre',
'section',
'select',
'source',
'svg',
'table',
'textarea',
'ul',
],
});
// TODO: Migrate to bun CSS handling (which is based on lightningcss).
const minified = lightningcss.transform({
filename: 'popup.css',
code: new TextEncoder().encode(purged[0].css),
minify: true,
targets: { chrome: 123 << 16 }, // matches manifest minimum_chrome_version
});
for (const warning of minified.warnings) {
console.error('CSS:', warning.message);
}
const minified2 = csso.minify(minified.code.toString(), {
filename: 'popup.css',
// forceMediaMerge: true, // somewhat unsafe
usage: {
blacklist: {
classes: [
'button', // #apply mapped to 'button'
'disabled', // not actually used (as class)
],
},
},
// debug: true,
});
await Bun.write('dist/reader.css', minified2.css);
}
async function minifyJS(artifact: BuildArtifact) {
let source = await artifact.text();
// Improve collapsing variables; terser doesn't do this so we do it manually.
source = source.replaceAll('const ', 'let ');
const result = await terser.minify(source, {
ecma: 2020,
module: true,
compress: {
reduce_funcs: false, // prevent functions being inlined
hoist_funs: true,
// XXX: Comment out to keep performance markers for debugging.
pure_funcs: ['performance.mark', 'performance.measure'],
passes: 3,
},
mangle: {
properties: {
regex: /^\$\$/,
},
},
});
await Bun.write(artifact.path, result.code!);
}
console.time('prebuild');
await Bun.$`rm -rf dist`;
await Bun.$`cp -r static dist`;
console.timeEnd('prebuild');
// Extension manifest
console.time('manifest');
const manifest = createManifest();
const release = manifest.version_name ?? manifest.version;
await Bun.write('dist/manifest.json', JSON.stringify(manifest));
console.timeEnd('manifest');
// Reader app HTML
console.time('html');
await Bun.write('dist/reader.html', makeHTML());
console.timeEnd('html');
// Reader app JS
console.time('build');
const out = await Bun.build({
entrypoints: ['src/reader.ts'],
outdir: 'dist',
target: 'browser',
define: {
'process.env.APP_RELEASE': JSON.stringify(release),
'process.env.NODE_ENV': JSON.stringify(mode),
},
loader: {
'.svg': 'text',
},
external: ['literata-ext.woff2', 'literata-italic.woff2', 'literata.woff2'],
plugins: [extractCSS],
// minify: !dev,
minify: {
whitespace: !dev,
identifiers: !dev,
// FIXME: Bun macros break if syntax minify is disabled (due to string
// interpolation and concatenation not being resolved).
syntax: true,
},
sourcemap: dev ? 'linked' : 'none',
});
console.timeEnd('build');
console.log(out);
// Health insights (exception monitoring)
console.time('build2');
const out2 = await Bun.build({
entrypoints: ['src/health.ts'],
outdir: 'dist',
target: 'browser',
// FIXME: Consider using iife once bun supports it.
// format: 'iife', // monitoring code must not mutate global state
define: {
'process.env.APP_RELEASE': JSON.stringify(release),
'process.env.NODE_ENV': JSON.stringify(mode),
},
minify: !dev,
sourcemap: dev ? 'linked' : 'none',
});
console.timeEnd('build2');
console.log(out2);
if (dev) {
await Bun.write('dist/reader.css', css);
} else {
console.time('minify:css');
await minifyCSS(out.outputs[0]);
console.timeEnd('minify:css');
console.time('minify:js');
await minifyJS(out.outputs[0]);
await minifyJS(out2.outputs[0]);
console.timeEnd('minify:js');
}