openvibers/openvibe.shared minify.js

minify.js

main 1.8 KB · 41 lines · javascript

1'use strict';
2/**
3 * openvibe-shared/minify — serve-time minification of the shared browser JS/CSS, cached by content
4 * hash. Sites have no build step by choice (plain files, content-hashed at serve time), so
5 * "minified" comes from the serve path (serve.js), not a bundler per site.
6 *
7 * const { minifyJs, minifyCss } = require('openvibe-shared/minify');
8 * const js = await minifyJs(src); // terser, names mangled, comments dropped
9 * const css = minifyCss(src); // clean-css (sync)
10 *
11 * Both fail open: a file the minifier cannot handle is returned unchanged, and serve.js falls back
12 * to the raw file on any error, so a minifier surprise can never 500 a page.
13 */
14const { minify: terserMinify } = require('terser');
15const CleanCSS = require('clean-css');
16
17// Level 1 only: it removes what is not needed inside each rule and never moves or merges rules, so the cascade's order
18// (and a later rule winning) cannot change (the orchestrator's review, 2026-11-10: level 2 restructures).
19const cleanCss = new CleanCSS({ level: { 1: { specialComments: 0 } } });
20
21/** Minify browser JS (terser, async). Input/output are strings. Throws on a parse error. */
22async function minifyJs(src) {
23 const out = await terserMinify(String(src), { compress: true, mangle: true, format: { comments: false } });
24 return out.code;
25}
26
27/** Minify browser CSS (clean-css, sync). Input/output are strings. */
28function minifyCss(src) {
29 return cleanCss.minify(String(src)).styles;
30}
31
32/** Minify by filename extension; anything else is returned unchanged. */
33async function minifyFile(name, data) {
34 const s = data.toString('utf8');
35 if (name.endsWith('.js')) return Buffer.from(await minifyJs(s));
36 if (name.endsWith('.css')) return Buffer.from(minifyCss(s));
37 return data;
38}
39
40module.exports = { minifyJs, minifyCss, minifyFile };
41