2.7 KB84 lines
Blame
1/* eslint-disable no-console */
2import type { Metafile } from 'esbuild';
3import { readFile } from 'fs/promises';
4import { globby } from 'globby';
5import { markdownTable } from 'markdown-table';
6export const getSizes = (metafile: Metafile) => {
7 const { outputs } = metafile;
8 const sizes = Object.keys(outputs)
9 .filter((key) => key.endsWith('js') && !key.includes('chunk'))
10 .map((key) => {
11 const { bytes } = outputs[key];
12 return [key.replace('dist/', ''), bytes];
13 });
14 return sizes;
15};
16
17const readStats = async (path: string): Promise<Record<string, number>> => {
18 const files = await globby(path);
19 const contents = await Promise.all(files.map((file) => readFile(file, 'utf-8')));
20 const sizes = contents.flatMap((content) => getSizes(JSON.parse(content)));
21 return Object.fromEntries(sizes);
22};
23
24const formatBytes = (bytes: number): string => {
25 if (bytes == 0) {
26 return '0 Bytes';
27 }
28 bytes = Math.abs(bytes);
29 const base = 1024;
30 const decimals = 2;
31 const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
32 const i = Math.floor(Math.log(bytes) / Math.log(base));
33 return parseFloat((bytes / Math.pow(base, i)).toFixed(decimals)) + ' ' + sizes[i];
34};
35
36const formatSize = (bytes: number): string => {
37 const formatted = formatBytes(bytes);
38 if (formatted.includes('Bytes')) {
39 return formatted;
40 }
41 return `${formatBytes(bytes)} (${bytes} Bytes)`;
42};
43
44const percentageDifference = (oldValue: number, newValue: number): string => {
45 const difference = Math.abs(newValue - oldValue);
46 const avg = (newValue + oldValue) / 2;
47 const percentage = (difference / avg) * 100;
48 const roundedPercentage = percentage.toFixed(2); // Round to two decimal places
49 if (roundedPercentage === '0.00') {
50 return '0.00%';
51 }
52 const sign = newValue > oldValue ? '+' : '-';
53 return `${sign}${roundedPercentage}%`;
54};
55
56const main = async () => {
57 const oldStats = await readStats('./cypress/snapshots/stats/base/**/*.json');
58 const newStats = await readStats('./cypress/snapshots/stats/head/**/*.json');
59 const diff = Object.entries(newStats)
60 .filter(([, value]) => value > 2048)
61 .map(([key, value]) => {
62 const oldValue = oldStats[key];
63 const delta = value - oldValue;
64 const output = [
65 key,
66 formatSize(oldValue),
67 formatSize(value),
68 formatSize(delta),
69 percentageDifference(oldValue, value),
70 ];
71 return output;
72 })
73 .filter(([, , , delta]) => delta !== '0 Bytes');
74 if (diff.length === 0) {
75 console.log('No changes in bundle sizes');
76 return;
77 }
78 console.log(
79 markdownTable([['File', 'Previous Size', 'New Size', 'Difference', '% Change'], ...diff])
80 );
81};
82
83void main().catch((e) => console.error(e));
84