-
Notifications
You must be signed in to change notification settings - Fork 3
/
optimize.js
222 lines (184 loc) · 6.01 KB
/
optimize.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
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import guetzli from '@343dev/guetzli';
import execBuffer from 'exec-buffer';
import gifsicle from 'gifsicle';
import pLimit from 'p-limit';
import sharp from 'sharp';
import { optimize as svgoOptimize } from 'svgo';
import { calculateRatio } from './lib/calculate-ratio.js';
import { createProgressBarContainer } from './lib/create-progress-bar-container.js';
import { formatBytes } from './lib/format-bytes.js';
import { getPlural } from './lib/get-plural.js';
import { getRelativePath } from './lib/get-relative-path.js';
import {
LOG_TYPES,
log,
logProgress,
logProgressVerbose,
} from './lib/log.js';
import { optionsToArguments } from './lib/options-to-arguments.js';
import { parseImageMetadata } from './lib/parse-image-metadata.js';
import { programOptions } from './lib/program-options.js';
import { showTotal } from './lib/show-total.js';
export async function optimize({ filePaths, config }) {
const { isLossless } = programOptions;
const filePathsCount = filePaths.length;
if (filePathsCount <= 0) {
return;
}
log(`Optimizing ${filePathsCount} ${getPlural(filePathsCount, 'image', 'images')} (${isLossless ? 'lossless' : 'lossy'})...`);
const progressBarContainer = createProgressBarContainer(filePathsCount);
const progressBar = progressBarContainer.create(filePathsCount, 0);
const totalSize = { before: 0, after: 0 };
const cpuCount = os.cpus().length;
const tasksSimultaneousLimit = pLimit(cpuCount);
const guetzliTasksSimultaneousLimit = pLimit(1); // Guetzli uses a large amount of memory and a significant amount of CPU time. To reduce system load, we only allow one instance of guetzli to run at the same time.
await Promise.all(
filePaths.map(filePath => {
const extension = path.extname(filePath.input).toLowerCase();
const isJpeg = extension === '.jpg' || extension === '.jpeg';
const limit = isJpeg && isLossless
? guetzliTasksSimultaneousLimit
: tasksSimultaneousLimit;
return limit(() => processFile({
filePath,
config,
progressBarContainer,
progressBar,
totalSize,
isLossless,
}));
}),
);
progressBarContainer.update(); // Prevent logs lost. See: https://github.com/npkgz/cli-progress/issues/145#issuecomment-1859863159
progressBarContainer.stop();
showTotal(totalSize.before, totalSize.after);
}
async function processFile({
filePath,
config,
progressBarContainer,
progressBar,
totalSize,
isLossless,
}) {
try {
const fileBuffer = await fs.promises.readFile(filePath.input);
const processedFileBuffer = await processFileByFormat({ fileBuffer, config, isLossless });
const fileSize = fileBuffer.length;
const processedFileSize = processedFileBuffer.length;
totalSize.before = fileSize;
totalSize.after = Math.min(fileSize, processedFileSize);
const ratio = calculateRatio(fileSize, processedFileSize);
const isOptimized = ratio > 0;
const isChanged = !fileBuffer.equals(processedFileBuffer);
const isSvg = path.extname(filePath.input).toLowerCase() === '.svg';
if (!isOptimized && !(isChanged && isSvg)) {
logProgressVerbose(getRelativePath(filePath.input), {
description: `${(isChanged ? 'File size increased' : 'Nothing changed')}. Skipped`,
progressBarContainer,
});
return;
}
await fs.promises.mkdir(path.dirname(filePath.output), { recursive: true });
await fs.promises.writeFile(filePath.output, processedFileBuffer);
const before = formatBytes(fileSize);
const after = formatBytes(processedFileSize);
logProgress(getRelativePath(filePath.input), {
type: isOptimized ? LOG_TYPES.SUCCESS : LOG_TYPES.WARNING,
description: `${before} → ${after}. Ratio: ${ratio}%`,
progressBarContainer,
});
} catch (error) {
if (error.message) {
logProgress(getRelativePath(filePath.input), {
type: LOG_TYPES.ERROR,
description: (error.message || '').trim(),
progressBarContainer,
});
} else {
progressBarContainer.log(error);
}
} finally {
progressBar.increment();
}
}
async function processFileByFormat({ fileBuffer, config, isLossless }) {
const imageMetadata = await parseImageMetadata(fileBuffer);
if (!imageMetadata.format) {
throw new Error('Unknown file format');
}
switch (imageMetadata.format) {
case 'jpeg': {
return processJpeg({ fileBuffer, config, isLossless });
}
case 'png': {
return processPng({ fileBuffer, config, isLossless });
}
case 'gif': {
return processGif({ fileBuffer, config, isLossless });
}
case 'svg': {
return processSvg({ fileBuffer, config });
}
default: {
throw new Error(`Unsupported image format: "${imageMetadata.format}"`);
}
}
}
async function processJpeg({ fileBuffer, config, isLossless }) {
const sharpImage = sharp(fileBuffer)
.rotate(); // Rotate image using information from EXIF Orientation tag
if (isLossless) {
const inputBuffer = await sharpImage
.toColorspace('srgb') // Replace colorspace (guetzli works only with sRGB)
.jpeg({ quality: 100, optimizeCoding: false }) // Applying maximum quality to minimize losses during image processing with sharp
.toBuffer();
return execBuffer({
bin: guetzli,
args: [
...optionsToArguments({
options: config?.jpeg?.lossless || {},
}),
execBuffer.input,
execBuffer.output,
],
input: inputBuffer,
});
}
return sharpImage
.jpeg(config?.jpeg?.lossy || {})
.toBuffer();
}
function processPng({ fileBuffer, config, isLossless }) {
return sharp(fileBuffer)
.png(isLossless ? config?.png?.lossless : config?.png?.lossy || {})
.toBuffer();
}
function processGif({ fileBuffer, config, isLossless }) {
return execBuffer({
bin: gifsicle,
args: [
...optionsToArguments({
options: (isLossless ? config?.gif?.lossless : config?.gif?.lossy) || {},
concat: true,
}),
`--threads=${os.cpus().length}`,
'--no-warnings',
'--output',
execBuffer.output,
execBuffer.input,
],
input: fileBuffer,
});
}
function processSvg({ fileBuffer, config }) {
return Buffer.from(
svgoOptimize(
fileBuffer,
config.svg,
).data,
);
}