-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgulpfile.js
More file actions
386 lines (344 loc) · 10.1 KB
/
Copy pathgulpfile.js
File metadata and controls
386 lines (344 loc) · 10.1 KB
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
const fs = require('node:fs/promises');
const path = require('node:path');
const process = require('node:process');
const childProcess = require('node:child_process');
const { styleText } = require('node:util');
const sass = require('sass');
const CleanCSS = require('clean-css');
const vinylMap = require('vinyl-map');
const gulp = require('gulp');
const gulpif = require('gulp-if');
const gulpSass = require('gulp-sass')(sass);
const gulpNunjucks = require('gulp-nunjucks');
const gulpHtmlmin = require('gulp-htmlmin');
const rollup = require('rollup');
const { nodeResolve: rollupResolve } = require('@rollup/plugin-node-resolve');
const rollupCommon = require('@rollup/plugin-commonjs');
const rollupReplace = require('@rollup/plugin-replace');
const rollupTerser = require('@rollup/plugin-terser');
const liveServer = require('live-server');
const TOML = require('smol-toml');
const source = require('vinyl-source-stream');
const YAML = require('yaml');
const BUILD_FOLDER = 'build';
const IS_DEV_TASK =
process.argv.indexOf('dev') !== -1 || process.argv.indexOf('--dev') !== -1;
console.log(
styleText(
'green',
`--- ${IS_DEV_TASK ? 'Development Mode' : 'Production Mode'} ---`,
),
);
const buildConfig = {
cleancss: {
level: {
1: {
specialComments: '0',
},
2: {
all: false,
mergeMedia: true,
removeDuplicateMediaBlocks: true,
removeEmpty: true,
},
},
sourceMap: true,
sourceMapInlineSources: true,
},
htmlmin: {
collapseBooleanAttributes: true,
collapseInlineTagWhitespace: false,
collapseWhitespace: true,
decodeEntities: true,
minifyCSS: false,
minifyJS: true,
removeAttributeQuotes: true,
removeComments: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
sortAttributes: true,
sortClassName: true,
},
sass: {
outputStyle: IS_DEV_TASK ? 'expanded' : 'compressed',
},
terser: {
mangle: true,
compress: {
passes: 2,
},
format: {
comments: false,
},
},
};
const readFile = async (...paths) =>
await fs.readFile(path.join(__dirname, ...paths), 'utf8');
const readJSON = async (...paths) => {
const content = await readFile(...paths);
return JSON.parse(content);
};
const readTOML = async (...paths) => {
const content = await readFile(...paths);
return TOML.parse(content);
};
const readYAML = async (...paths) => {
const content = await readFile(...paths);
return YAML.parse(content);
};
const minifyCss = vinylMap((buffer) => {
return new CleanCSS(buildConfig.cleancss).minify(buffer.toString()).styles;
});
function copy() {
return gulp
.src(['src/fonts/*', 'src/public/*'], {
encoding: false, // Prevent image and font files from being re-encoded
})
.pipe(gulp.dest(BUILD_FOLDER));
}
function css() {
return gulp
.src('src/css/*.scss', { sourcemaps: true })
.pipe(gulpSass.sync(buildConfig.sass).on('error', gulpSass.logError))
.pipe(gulpif(!IS_DEV_TASK, minifyCss))
.pipe(gulp.dest(BUILD_FOLDER, { sourcemaps: '.' }));
}
async function html() {
const [config, packageJson, cargoToml, headCSS] =
/** @type {[any, typeof import('./package.json'), any, string]} */
await Promise.all([
readYAML('src', 'config.yaml'),
readJSON('package.json'),
readTOML('Cargo.toml'),
readFile(BUILD_FOLDER, 'head.css'),
]);
const { baseUrl, title, description, author, themeColor, jobs } = config;
return gulp
.src('src/*.html')
.pipe(
gulpNunjucks.compile({
OXVGUI_VERSION: packageJson.version,
OXVG_VERSION: cargoToml.package.version,
headCSS,
baseUrl,
title,
description,
author,
themeColor,
jobs,
}),
)
.pipe(gulpif(!IS_DEV_TASK, gulpHtmlmin(buildConfig.htmlmin)))
.pipe(gulp.dest(BUILD_FOLDER));
}
const rollupCaches = new Map();
async function jsEntry(entry, outputPath) {
/** @type {typeof import('./package.json')} */
const packageJson = await readJSON('package.json');
const name = path.basename(path.dirname(entry));
const bundle = await rollup.rollup({
cache: rollupCaches.get(entry),
input: `src/${entry}`,
plugins: [
rollupReplace({
preventAssignment: true,
OXVGUI_VERSION: JSON.stringify(packageJson.version),
}),
rollupResolve({ browser: true }),
rollupCommon({ include: /node_modules/ }),
// Don't use terser on development
IS_DEV_TASK
? ''
: rollupTerser(
name === 'page'
? {
...buildConfig.terser,
mangle: {
properties: {
regex: /^_/,
},
},
}
: buildConfig.terser,
),
],
});
rollupCaches.set(entry, bundle.cache);
await bundle.write({
sourcemap: true,
format: 'iife',
generatedCode: 'es2015',
file: path.join(BUILD_FOLDER, outputPath, `${name}.js`),
});
}
async function rust() {
await new Promise((resolve, reject) => {
const wasmPack = childProcess.spawn('wasm-pack', [
BUILD_FOLDER,
IS_DEV_TASK ? '--dev' : '--release',
'--target=web',
'--no-pack', // Don't create package.json
'--out-dir=src/rust/dist',
]);
wasmPack.stdout.pipe(process.stdout);
wasmPack.stderr.pipe(process.stderr);
wasmPack.on('error', (err) => {
const wrapErr = new Error(
`Failed to spawn '${err.path} ${err.spawnargs.join(' ')}' (${err.code})`,
);
wrapErr.cause = err;
reject(wrapErr);
});
wasmPack.on('close', (code) => {
if (code !== 0) {
reject(new Error(`The wasm-pack process exited with code ${code}`));
} else {
resolve();
}
});
});
return gulp
.src(['src/rust/dist/oxvg_wasm_bindings_bg.wasm'], {
encoding: false, // Prevent file from being re-encoded
})
.pipe(gulp.dest(BUILD_FOLDER));
}
async function manifest() {
const config = await readYAML('src', 'config.yaml');
const {
name,
longName,
description,
themeColor,
appBackgroundColor,
appDisplay,
appStartUrl,
appIcons,
} = config;
const stream = source('manifest.webmanifest');
stream.end(
JSON.stringify(
{
short_name: name,
name: longName,
description,
theme_color: themeColor,
background_color: appBackgroundColor,
display: appDisplay,
start_url: appStartUrl,
icons: appIcons,
},
undefined,
IS_DEV_TASK ? 2 : 0,
),
);
stream.pipe(gulp.dest(BUILD_FOLDER));
}
async function changelog() {
const changelog = await readYAML('src', 'changelog.yaml');
const stream = source('changelog.json');
stream.end(JSON.stringify(changelog, undefined, IS_DEV_TASK ? 2 : 0));
stream.pipe(gulp.dest(BUILD_FOLDER));
}
async function sitemap() {
const config = await readYAML('src', 'config.yaml');
const { baseUrl } = config;
// Allow reproducible builds by setting the sitemap's `lastmod` date
// based on the `SOURCE_DATE_EPOCH` env variable, if present.
// For more info, see: https://reproducible-builds.org/docs/source-date-epoch/
const epoch = Number(process.env.SOURCE_DATE_EPOCH);
const date = Number.isInteger(epoch) ? new Date(epoch * 1000) : new Date();
const lastmod = date.toISOString().split('T', 1)[0];
const stream = source('sitemap.xml');
stream.end(
[
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
' <url>',
` <loc>${baseUrl}</loc>`,
` <lastmod>${lastmod}</lastmod>`,
' <priority>1.00</priority>',
' </url>',
'</urlset>',
]
.map(IS_DEV_TASK ? (l) => l : (l) => l.trim())
.join(IS_DEV_TASK ? '\n' : ''),
);
stream.pipe(gulp.dest(BUILD_FOLDER));
}
async function robotsTxt() {
const config = await readYAML('src', 'config.yaml');
const { baseUrl } = config;
const stream = source('robots.txt');
stream.end(
[
'User-agent: *',
'Disallow: /cdn-cgi/',
'',
`Sitemap: ${baseUrl}sitemap.xml`,
].join('\n'),
);
stream.pipe(gulp.dest(BUILD_FOLDER));
}
function clean() {
return fs.rm(BUILD_FOLDER, { force: true, recursive: true });
}
function serve() {
liveServer.start({
root: BUILD_FOLDER,
host: 'localhost',
logLevel: 0,
open: false,
wait: 3000,
});
console.log(styleText('green', '---\nServing at http://localhost:8080\n---'));
}
// --- SETUP --- //
const cssAndHtml = gulp.series(css, html);
const jsOnlyOxvgWorker = jsEntry.bind(null, 'js/oxvg-worker/index.js', 'js/');
const jsExceptOxvgWorker = gulp.parallel(
jsEntry.bind(null, 'js/prism-worker/index.js', 'js/'),
jsEntry.bind(null, 'js/gzip-worker/index.js', 'js/'),
jsEntry.bind(null, 'js/sw/index.js', ''),
jsEntry.bind(null, 'js/page/index.js', 'js/'),
);
const js = gulp.parallel(jsOnlyOxvgWorker, jsExceptOxvgWorker);
const rustAndOxvgWorker = gulp.series(rust, jsOnlyOxvgWorker);
const build = gulp.parallel(
cssAndHtml,
rustAndOxvgWorker,
jsExceptOxvgWorker,
manifest,
changelog,
sitemap,
robotsTxt,
copy,
);
function watch() {
gulp.watch(['Cargo.toml'], gulp.parallel(html, rustAndOxvgWorker));
gulp.watch(['package.json'], gulp.parallel(html, js));
gulp.watch(['pnpm-lock.yaml'], build);
gulp.watch(
['src/config.yaml'],
gulp.parallel(html, manifest, sitemap, robotsTxt),
);
gulp.watch(['src/changelog.yaml'], changelog);
gulp.watch(['src/*.html', 'src/_partials/**/*.{html,svg}'], html);
gulp.watch(['src/css/**/*.scss'], cssAndHtml);
gulp.watch(['src/js/**/*.js'], js);
gulp.watch(['src/fonts/*', 'src/public/*'], copy);
gulp.watch(['src/rust/**/*.rs', 'Cargo.lock'], rustAndOxvgWorker);
}
exports.clean = clean;
exports.js = js;
exports.css = css;
exports.html = html;
exports.rust = rust;
exports.manifest = manifest;
exports.changelog = changelog;
exports.sitemap = sitemap;
exports['robots-txt'] = robotsTxt;
exports.copy = copy;
exports.build = gulp.series(clean, build);
exports.dev = gulp.series(clean, build, gulp.parallel(watch, serve));