-
Notifications
You must be signed in to change notification settings - Fork 8
/
sizeTracker.mjs
92 lines (80 loc) · 2.1 KB
/
sizeTracker.mjs
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
import { readFileSync } from 'node:fs';
import { watch } from 'node:fs/promises';
import path from 'node:path';
import { styleText, parseArgs } from 'node:util';
import { compileSync } from './tasks/compile.js';
const ac = new AbortController();
const { signal } = ac;
// const initialSize = 10403;
function getSize() {
const { code } = compileSync();
return code.length;
}
function humanReadableSize(size) {
const absSize = Math.abs(size);
if (absSize > 1024) {
return `${(size / 1024).toFixed(2)} KB`;
} else if (absSize >= 1) {
return `${size} B`;
}
return '';
}
const originalSize = readFileSync('./dist/oc-client.min.js').length;
function getDiff(compareTo) {
const newSize = getSize();
const diff = newSize - compareTo;
const result = diff > 0 ? 'bigger' : diff < 0 ? 'smaller' : 'same';
const humanReadable = humanReadableSize(diff);
return { result, diff, humanReadable };
}
function getText(initial) {
const { result, humanReadable } = getDiff(originalSize);
let text = '';
if (result === 'same') {
text = 'No changes';
} else if (result === 'bigger') {
text = styleText('red', `Current size increased by ${humanReadable}`);
} else {
text = styleText('green', `Current size decreased by ${humanReadable}`);
}
if (initial) {
text += `\nTotal reduction: ${getDiff(initial).humanReadable}`;
}
return text;
}
async function program(options) {
if (options.watch) {
try {
const watcher = watch(path.join(process.cwd(), 'src/oc-client.js'), {
signal
});
for await (const event of watcher) {
if (event.eventType === 'change') {
const text = getText(options.initial);
console.clear();
console.log(text);
}
}
} catch (err) {
if (err.name === 'AbortError') return;
throw err;
}
} else {
console.log(getText());
}
}
const options = parseArgs({
args: process.argv.slice(2),
options: {
watch: {
type: 'boolean',
default: false,
short: 'w'
},
initial: {
type: 'string',
short: 'i'
}
}
});
program(options.values);