This repository has been archived by the owner on Dec 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
240 lines (197 loc) · 6.17 KB
/
index.js
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
const fs = require('fs');
const path = require('path');
const { default: pQueue } = require('p-queue');
const { cosmiconfig } = require('cosmiconfig');
const chalk = require('chalk');
const zopfliAdapter = require('./zopfliAdapter');
const brotliAdapter = require('./brotliAdapter');
const zlib = require('zlib');
const { table, sortResults, formatResults } = require('./formatter');
const brotli = brotliAdapter();
const zopfli = zopfliAdapter();
const defaultOptions = {
test: '.',
compressOutput: false,
threshold: undefined,
concurrency: 2,
gzip: {
enabled: true,
numiterations: 15,
blocksplitting: true,
blocksplittinglast: false,
blocksplittingmax: 15,
zlib: false,
zlibLevel: zlib.constants.Z_BEST_COMPRESSION,
zlibMemLevel: zlib.constants.Z_BEST_COMPRESSION
},
brotli: {
enabled: true,
mode: 0,
quality: 11,
lgwin: 24,
enable_context_modeling: true
}
};
let output = [];
module.exports = bundler => {
bundler.on('bundled', async (bundle) => {
if (process.env.NODE_ENV === 'production') {
const start = new Date().getTime();
console.log(chalk.bold('\n🗜️ Compressing bundled files...\n'));
try {
const explorer = cosmiconfig('compress');
const { config: { gzip, brotli, test, threshold, compressOutput } } = (await explorer.search()) || { config: defaultOptions };
const fileTest = new RegExp(test);
let filesToCompress;
let input;
if (compressOutput === true) {
input = bundle.entryAsset.options.outDir;
filesToCompress = function* (dir) {
const files = fs.readdirSync(dir);
for (const file of files) {
const f = path.join(dir, file);
if (fs.statSync(f).isDirectory()) {
try {
yield* filesToCompress(f);
} catch (error) {
continue;
}
} else {
if (fileTest.test(f)) {
yield f;
}
}
}
}
} else {
input = bundle;
filesToCompress = function* (bundle) {
if (bundle.name && fileTest.test(bundle.name)) {
yield bundle.name
}
for (var child of bundle.childBundles) {
yield* filesToCompress(child)
}
}
}
const queue = new pQueue({ concurrency: defaultOptions.concurrency });
[...filesToCompress(input)].forEach(file => {
queue.add(() => gzipCompress(file, { ...defaultOptions.gzip, threshold, ...gzip }));
queue.add(() => brotliCompress(file, { ...defaultOptions.brotli, threshold, ...brotli }));
});
await queue.onIdle();
const end = new Date().getTime();
const formattedOutput = output.sort(sortResults).map(formatResults);
console.log(chalk.bold.green(`\n✨ Compressed in ${((end - start) / 1000).toFixed(2)}s.\n`));
table(formattedOutput);
} catch (err) {
console.error(chalk.bold.red('❌ Compression error:\n'), err);
}
}
});
function gzipCompress(file, config) {
if (!config.enabled) {
return Promise.resolve();
}
let stat;
try {
stat = fs.statSync(file);
} catch (err) {
return Promise.resolve();
}
const start = new Date().getTime();
if (!stat.isFile()) {
return Promise.resolve();
}
if (config.threshold && stat.size < config.threshold) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
fs.readFile(file, function (err, content) {
if (err) { return reject(err); }
if (config.zlib) {
zlib.gzip(content, { level: config.zlibLevel, memLevel: config.zlibMemLevel }, handleCompressedData.bind(this, resolve, reject));
} else {
zopfli.gzip(content, config, handleCompressedData.bind(this, resolve, reject));
}
});
});
function handleCompressedData(resolve, reject, err, compressedContent) {
if (err) { return reject(err); }
if (stat.size > compressedContent.length) {
const fileName = file + '.gz';
fs.writeFile(fileName, compressedContent, () => {
const end = new Date().getTime();
output.push({ size: compressedContent.length, file: fileName, time: end - start });
return resolve();
});
} else {
resolve();
}
}
}
function brotliCompress(file, config) {
if (!config.enabled) {
return Promise.resolve();
}
let stat;
try {
stat = fs.statSync(file);
} catch (err) {
return Promise.resolve();
}
const start = new Date().getTime();
if (!stat.isFile()) {
return Promise.resolve();
}
if (config.threshold && stat.size < config.threshold) {
return Promise.resolve();
}
if (brotli.isZlib) {
let brotliMode;
if (config.mode === 1) {
brotliMode = zlib.constants.BROTLI_MODE_TEXT;
}
else if (config.mode === 2) {
brotliMode = zlib.constants.BROTLI_MODE_FONT;
}
else {
brotliMode = zlib.constants.BROTLI_MODE_GENERIC;
}
config = {
params: {
[zlib.constants.BROTLI_PARAM_MODE]: brotliMode,
[zlib.constants.BROTLI_PARAM_QUALITY]: config.quality,
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: stat.size,
[zlib.constants.BROTLI_PARAM_LGWIN]: config.lgwin,
[zlib.constants.BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING]: (config.enable_context_modeling === false ? true : false)
}
};
if (config.lgblock) {
config.params[zlib.constants.BROTLI_PARAM_LGBLOCK] = config.lgblock;
}
if (config.nPostfix) {
config.params[zlib.constants.BROTLI_PARAM_NPOSTFIX] = config.nPostfix;
}
if (config.nDirect) {
config.params[zlib.constants.BROTLI_PARAM_NDIRECT] = config.nDirect;
}
}
return new Promise((resolve, reject) => {
fs.readFile(file, (err, content) => {
if (err) { return reject(err); }
const compressedContent = brotli.compress(content, config);
if (compressedContent !== null && stat.size > compressedContent.length) {
const fileName = file + '.br';
fs.writeFile(fileName, compressedContent, () => {
const end = new Date().getTime();
output.push({ size: compressedContent.length, file: fileName, time: end - start });
return resolve();
});
} else {
resolve();
}
});
});
}
};