-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
488 lines (410 loc) · 16.3 KB
/
index.js
File metadata and controls
488 lines (410 loc) · 16.3 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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
import * as fs from "fs";
import * as path from "path";
import {dirname} from "path";
import * as os from "os";
import {fork} from "child_process";
import {fileURLToPath} from 'url';
import {runZopfliGoCompression} from './zopfli-go-binary.js';
const VERSION = '4.0.0';
const DEFAULT_IGNORES = ['gz', 'br', 'zst', 'zip', 'png', 'jpeg', 'jpg', 'woff', 'woff2'];
const STYLE_CODES = {
blue: '\u001B[34m',
bold: '\u001B[1m',
green: '\u001B[32m',
red: '\u001B[31m',
reset: '\u001B[0m'
};
const ANSI_ENABLED = process.stdout.isTTY && process.env.NO_COLOR == null;
let parsedArgsCache;
function printHelp() {
console.log(`Usage: bread-compressor [options] <paths ...>
Options:
-V, --version Print the current version
-h, --help Show this help message
-s, --stats Show statistics
-a, --algorithm <items> Comma separated list of algorithms: brotli,gzip,zstd
-n, --no-default-ignores Do not add default glob ignores
-l, --limit <value> Number of concurrent tasks, defaults to CPU cores
--use-zopfli-go Use the zopfli-go gzip binary (downloads and caches a GitHub release binary on first use)
--zopfli-numiterations <value> Maximum LZ77 optimization iterations, default 15
--zopfli-blocksplittinglast <value> false, true, or both
--brotli-mode <value> 0 = generic, 1 = text, 2 = font
--brotli-quality <value> 0 - 11, default 11
--brotli-lgwin <value> Window size, default 22
--zstd-level <value> Zstandard compression level, default 3`);
}
function exitAfterOutput(output, code = 0) {
console.log(output);
process.exit(code);
}
function parseIntegerOption(name, value) {
const parsed = Number.parseInt(value, 10);
if (Number.isNaN(parsed)) {
throw new Error(`Invalid value for ${name}: ${value}`);
}
return parsed;
}
function takeOptionValue(argv, index, token) {
if (token.includes('=')) {
return {nextIndex: index, value: token.slice(token.indexOf('=') + 1)};
}
const value = argv[index + 1];
if (value == null) {
throw new Error(`Missing value for ${token}`);
}
return {nextIndex: index + 1, value};
}
function parseArgs() {
if (parsedArgsCache) {
return parsedArgsCache;
}
const argv = process.argv.slice(2);
const options = {
algorithm: null,
brotliLgwin: null,
brotliMode: null,
brotliQuality: null,
defaultIgnores: true,
limit: null,
stats: false,
useZopfliGo: false,
zopfliBlocksplittinglast: undefined,
zopfliNumiterations: null,
zstdLevel: null
};
const args = [];
for (let index = 0; index < argv.length; index += 1) {
const token = argv[index];
if (token === '--') {
args.push(...argv.slice(index + 1));
break;
}
if (token === '-h' || token === '--help') {
printHelp();
process.exit(0);
}
if (token === '-V' || token === '--version') {
exitAfterOutput(VERSION);
}
if (token === '-s' || token === '--stats') {
options.stats = true;
continue;
}
if (token === '-n' || token === '--no-default-ignores') {
options.defaultIgnores = false;
continue;
}
if (token === '--use-zopfli-go') {
options.useZopfliGo = true;
continue;
}
if (token === '-a' || token === '--algorithm' || token.startsWith('--algorithm=')) {
const optionValue = takeOptionValue(argv, index, token);
options.algorithm = optionValue.value.split(',').map(item => item.trim()).filter(Boolean);
index = optionValue.nextIndex;
continue;
}
if (token === '-l' || token === '--limit' || token.startsWith('--limit=')) {
const optionValue = takeOptionValue(argv, index, token);
options.limit = parseIntegerOption('--limit', optionValue.value);
index = optionValue.nextIndex;
continue;
}
if (token === '--zopfli-numiterations' || token.startsWith('--zopfli-numiterations=')) {
const optionValue = takeOptionValue(argv, index, token);
options.zopfliNumiterations = parseIntegerOption('--zopfli-numiterations', optionValue.value);
index = optionValue.nextIndex;
continue;
}
if (token === '--zopfli-blocksplittinglast' || token.startsWith('--zopfli-blocksplittinglast=')) {
const optionValue = takeOptionValue(argv, index, token);
options.zopfliBlocksplittinglast = optionValue.value;
index = optionValue.nextIndex;
continue;
}
if (token === '--brotli-mode' || token.startsWith('--brotli-mode=')) {
const optionValue = takeOptionValue(argv, index, token);
options.brotliMode = parseIntegerOption('--brotli-mode', optionValue.value);
index = optionValue.nextIndex;
continue;
}
if (token === '--brotli-quality' || token.startsWith('--brotli-quality=')) {
const optionValue = takeOptionValue(argv, index, token);
options.brotliQuality = parseIntegerOption('--brotli-quality', optionValue.value);
index = optionValue.nextIndex;
continue;
}
if (token === '--brotli-lgwin' || token.startsWith('--brotli-lgwin=')) {
const optionValue = takeOptionValue(argv, index, token);
options.brotliLgwin = parseIntegerOption('--brotli-lgwin', optionValue.value);
index = optionValue.nextIndex;
continue;
}
if (token === '--zstd-level' || token.startsWith('--zstd-level=')) {
const optionValue = takeOptionValue(argv, index, token);
options.zstdLevel = parseIntegerOption('--zstd-level', optionValue.value);
index = optionValue.nextIndex;
continue;
}
if (token.startsWith('-')) {
throw new Error(`Unknown option: ${token}`);
}
args.push(token);
}
parsedArgsCache = {args, options};
return parsedArgsCache;
}
function normalizeSlashes(value) {
return value.replace(/\\/g, '/').replace(/^\.\//, '');
}
function hasGlobToken(pattern) {
return /[*?]/.test(pattern);
}
function readAllFiles(targetPath) {
const absolutePath = path.resolve(targetPath);
if (!fs.existsSync(absolutePath)) {
return [];
}
const stat = fs.statSync(absolutePath);
if (stat.isFile()) {
return [absolutePath];
}
const files = [];
const directories = [absolutePath];
while (directories.length > 0) {
const currentDirectory = directories.pop();
for (const entry of fs.readdirSync(currentDirectory, {withFileTypes: true})) {
const entryPath = path.join(currentDirectory, entry.name);
if (entry.isDirectory()) {
directories.push(entryPath);
continue;
}
if (entry.isFile()) {
files.push(entryPath);
}
}
}
return files;
}
function resolveSearchBase(pattern) {
const normalizedPattern = normalizeSlashes(pattern.replace(/^!/, ''));
if (!hasGlobToken(normalizedPattern)) {
return path.resolve(normalizedPattern);
}
const baseSegments = [];
for (const segment of normalizedPattern.split('/')) {
if (segment === '**' || hasGlobToken(segment)) {
break;
}
baseSegments.push(segment);
}
return path.resolve(baseSegments.length > 0 ? baseSegments.join(path.sep) : '.');
}
function segmentMatches(patternSegment, pathSegment) {
const escaped = patternSegment.replace(/[|\\{}()[\]^$+.:]/g, '\\$&');
const regex = new RegExp(`^${escaped.replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]')}$`);
return regex.test(pathSegment);
}
function matchSegments(patternSegments, pathSegments) {
if (patternSegments.length === 0) {
return pathSegments.length === 0;
}
const [currentPattern, ...remainingPatterns] = patternSegments;
if (currentPattern === '**') {
if (remainingPatterns.length === 0) {
return true;
}
for (let index = 0; index <= pathSegments.length; index += 1) {
if (matchSegments(remainingPatterns, pathSegments.slice(index))) {
return true;
}
}
return false;
}
if (pathSegments.length === 0 || !segmentMatches(currentPattern, pathSegments[0])) {
return false;
}
return matchSegments(remainingPatterns, pathSegments.slice(1));
}
function matchesPattern(pattern, candidate) {
const rawPattern = pattern.replace(/^!/, '');
const normalizedPattern = normalizeSlashes(rawPattern);
const normalizedCandidate = normalizeSlashes(path.isAbsolute(rawPattern)
? path.resolve(candidate)
: path.relative(process.cwd(), candidate));
if (!normalizedPattern.includes('/')) {
return segmentMatches(normalizedPattern, path.posix.basename(normalizedCandidate));
}
return matchSegments(normalizedPattern.split('/'), normalizedCandidate.split('/'));
}
function expandPattern(pattern) {
const normalizedPattern = normalizeSlashes(pattern.replace(/^!/, ''));
if (!hasGlobToken(normalizedPattern)) {
return readAllFiles(normalizedPattern);
}
const basePath = resolveSearchBase(normalizedPattern);
return readAllFiles(basePath).filter(candidate => matchesPattern(normalizedPattern, candidate));
}
function addDefaultIgnores(args, options) {
if (!options.defaultIgnores) {
return args;
}
const globs = args.slice();
for (const ignore of DEFAULT_IGNORES) {
globs.push(`!*.${ignore}`);
globs.push(`!**/*.${ignore}`);
}
return globs;
}
function expandPaths(globs) {
const selectedPaths = new Set();
for (const glob of globs) {
if (glob.startsWith('!')) {
for (const filePath of Array.from(selectedPaths)) {
if (matchesPattern(glob, filePath)) {
selectedPaths.delete(filePath);
}
}
continue;
}
for (const filePath of expandPattern(glob)) {
selectedPaths.add(filePath);
}
}
return Array.from(selectedPaths).sort();
}
function createLimiter(maxConcurrency) {
const concurrency = Math.max(1, maxConcurrency);
const queue = [];
let activeCount = 0;
function runNext() {
if (activeCount >= concurrency || queue.length === 0) {
return;
}
activeCount += 1;
const {task, resolve, reject} = queue.shift();
Promise.resolve()
.then(task)
.then(result => {
activeCount -= 1;
resolve(result);
runNext();
})
.catch(error => {
activeCount -= 1;
reject(error);
runNext();
});
}
return task => new Promise((resolve, reject) => {
queue.push({task, resolve, reject});
runNext();
});
}
function styleText(text, ...styles) {
const stringValue = String(text);
if (!ANSI_ENABLED || styles.length === 0) {
return stringValue;
}
return `${styles.map(style => STYLE_CODES[style]).join('')}${stringValue}${STYLE_CODES.reset}`;
}
export async function compress(algorithm) {
const {args, options} = parseArgs();
if (args.length === 0) {
printHelp();
process.exit(0);
}
if (options.algorithm == null) {
options.algorithm = ['brotli', 'gzip'];
}
if (options.algorithm.indexOf(algorithm) === -1) {
return;
}
const globs = addDefaultIgnores(args, options);
const paths = expandPaths(globs);
const start = Date.now();
const limit = createLimiter(options.limit ? options.limit : os.cpus().length);
let results;
if (algorithm === 'brotli') {
const brotliOptions = {
mode: options.brotliMode != null ? options.brotliMode : 1,
quality: options.brotliQuality != null ? options.brotliQuality : 11,
lgwin: options.brotliLgwin != null ? options.brotliLgwin : 22
};
results = await Promise.all(paths.map(name => limit(() => {
return new Promise(function (resolve) {
const __dirname = dirname(fileURLToPath(import.meta.url));
const child = fork(path.resolve(__dirname, 'brotli-compress.js'));
child.on('message', msg => {
if (msg.ready) {
child.send({name: name, options: brotliOptions});
child.on('message', (message) => {
child.kill();
resolve(message);
});
}
});
});
})));
} else if (algorithm === 'zstd') {
const zstdOptions = {
level: options.zstdLevel != null ? options.zstdLevel : 3
};
results = await Promise.all(paths.map(name => limit(() => {
return new Promise(function (resolve) {
const __dirname = dirname(fileURLToPath(import.meta.url));
const child = fork(path.resolve(__dirname, 'zstd-compress.js'));
child.on('message', msg => {
if (msg.ready) {
child.send({name: name, options: zstdOptions});
child.on('message', (message) => {
child.kill();
resolve(message);
});
}
});
});
})));
} else {
if (options.useZopfliGo) {
results = await runZopfliGoCompression(paths, options);
} else {
const gzOptions = {
numiterations: options.zopfliNumiterations != null ? options.zopfliNumiterations : 15,
zopfliBlocksplittinglast: options.zopfliBlocksplittinglast,
};
results = await Promise.all(paths.map(name => limit(() => {
return new Promise(function (resolve) {
const __dirname = dirname(fileURLToPath(import.meta.url));
const child = fork(path.resolve(__dirname, 'gzip-compress.js'));
child.on('message', msg => {
if (msg.ready) {
child.send({name: name, options: gzOptions});
child.on('message', (message) => {
child.kill();
resolve(message);
});
}
});
});
})));
}
}
if (options.stats && results && results.length > 0) {
const elapsedTime = (Date.now() - start) / 1000;
const uncompressedSize = paths
.map(fs.statSync)
.map(stat => stat.size)
.reduce((prev, current) => prev + current);
const compressedSize = results.reduce((prev, current) => prev + current);
const ratio = (compressedSize * 100 / uncompressedSize).toFixed(2);
console.log(styleText(algorithm, 'bold', 'blue'));
console.log(`Number of Files : ${styleText(paths.length, 'bold')}`);
console.log(`Uncompressed : ${styleText(uncompressedSize.toLocaleString(), 'red', 'bold')} Bytes`);
console.log(`Compressed : ${styleText(compressedSize.toLocaleString(), 'green', 'bold')} Bytes`);
console.log(`Compression Ratio: ${styleText(`${ratio}%`, 'green', 'bold')}`);
console.log(`Compression Time : ${styleText(elapsedTime, 'bold')} s`);
console.log();
}
return results;
}