UNPKG

953 BJavaScriptView Raw
1import { basename } from 'path';
2import { green, red, yellow, white } from 'kleur';
3import gzipSize from 'gzip-size';
4import brotliSize from 'brotli-size';
5import prettyBytes from 'pretty-bytes';
6
7function getPadLeft(str, width, char = ' ') {
8 return char.repeat(width - str.length);
9}
10
11function formatSize(size, filename, type, raw) {
12 const pretty = raw ? `${size} B` : prettyBytes(size);
13 const color = size < 5000 ? green : size > 40000 ? red : yellow;
14 const indent = getPadLeft(pretty, type === 'br' ? 13 : 10);
15 return `${indent}${color(pretty)}: ${white(basename(filename))}.${type}`;
16}
17
18export async function getSizeInfo(code, filename, raw) {
19 raw = raw || code.length < 5000;
20
21 const [gzip, brotli] = await Promise.all([
22 gzipSize(code).catch(() => null),
23 brotliSize(code).catch(() => null),
24 ]);
25
26 let out = formatSize(gzip, filename, 'gz', raw);
27 if (brotli) {
28 out += '\n' + formatSize(brotli, filename, 'br', raw);
29 }
30
31 return out;
32}