-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
468 lines (465 loc) · 19.6 KB
/
index.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
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
import { S3Client, HeadObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
import { createFilter } from '@rollup/pluginutils';
import OSS from 'ali-oss';
import chalk from 'chalk';
import { fileTypeFromBuffer } from 'file-type';
import imageminjs from 'imagemin';
import imageminGifsicle from 'imagemin-gifsicle';
import imageminJpegtran from 'imagemin-jpegtran';
import imageminMozjpeg from 'imagemin-mozjpeg';
import imageminOptipng from 'imagemin-optipng';
import imageminPngquant from 'imagemin-pngquant';
import imageminSvgo from 'imagemin-svgo';
import imageminWebp from 'imagemin-webp';
import { defaultsDeep } from 'lodash-es';
import { createHash } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
import { readFile, mkdir, writeFile } from 'node:fs/promises';
import { join, basename, resolve, dirname, extname } from 'node:path';
import postcss from 'postcss';
import webpInCssPlugin from 'webp-in-css/plugin.js';
var name = "vite-plugin-imagemin-upload";
const getDefaultOptions = () => ({
mode: "production",
lossless: {
type: "public",
include: /\.(jpe?g|png|gif)$/i,
progressive: true,
interlaced: true,
gifsicle: true,
jpegtran: true,
optipng: true,
svgo: true,
webp: true,
},
lossy: {
type: "asset",
include: /\.(jpe?g|png|gif)$/i,
quality: 80,
progressive: true,
interlaced: true,
gifsicle: true,
mozjpeg: true,
pngquant: true,
svgo: true,
webp: true,
},
});
const urlRE = /^(https?:)?\/\/.+/i;
function isURL(url) {
return urlRE.test(url);
}
const postfixRE = /[?#].*$/s;
function cleanUrl(url) {
return url.replace(postfixRE, "");
}
function joinURL(base, ...paths) {
return paths.reduce((url, path) => {
if (!path)
return url;
return url.replace(/\/$/, "") + "/" + path.replace(/^\//, "");
}, base);
}
function createMD5(data) {
return createHash("md5").update(data).digest("hex");
}
function getPlugins(filename, options, compressionType) {
const plugins = [];
const opts = options[compressionType];
if (/\.svg$/i.test(filename) && opts?.svgo) {
plugins.push(imageminSvgo(defaultsDeep({}, opts.svgo)));
}
if (/\.gif$/i.test(filename) && opts?.gifsicle) {
plugins.push(imageminGifsicle(defaultsDeep({}, opts.gifsicle, {
optimizationLevel: 3,
interlaced: !!opts.interlaced,
})));
}
if (compressionType === "lossless") {
const losslessOptions = options.lossless;
if (/\.jpe?g$/i.test(filename) && losslessOptions?.jpegtran) {
plugins.push(imageminJpegtran(defaultsDeep({}, losslessOptions.jpegtran, {
progressive: !!losslessOptions.progressive,
})));
}
if (/\.png$/i.test(filename) && losslessOptions?.optipng) {
plugins.push(imageminOptipng(defaultsDeep({}, losslessOptions.optipng, {
optimizationLevel: 7,
interlaced: !!losslessOptions.interlaced,
})));
}
if (!noWebpAssets.has(filename) && losslessOptions?.webp) {
plugins.push(imageminWebp(defaultsDeep({}, losslessOptions.webp, {
lossless: 9,
})));
}
}
if (compressionType === "lossy") {
const lossyOptions = options.lossy;
if (/\.jpe?g$/i.test(filename) && lossyOptions?.mozjpeg) {
plugins.push(imageminMozjpeg(defaultsDeep({}, lossyOptions.mozjpeg, { progressive: !!lossyOptions.progressive }, lossyOptions.quality ? { quality: lossyOptions.quality } : {})));
}
if (/\.png$/i.test(filename) && lossyOptions?.pngquant) {
plugins.push(imageminPngquant(defaultsDeep({}, lossyOptions.pngquant, { speed: 1 }, lossyOptions.quality
? { quality: [lossyOptions.quality / 100, 1] }
: {})));
}
if (!noWebpAssets.has(filename) && lossyOptions?.webp) {
plugins.push(imageminWebp(defaultsDeep({}, lossyOptions.webp, { method: 6 }, lossyOptions.quality ? { quality: lossyOptions.quality } : {})));
}
}
return plugins;
}
const rootDir = process.cwd();
const cacheDir = join(rootDir, "node_modules/.cache", name);
const cacheImagesDir = join(cacheDir, "images");
const cacheCompressedFile = join(cacheDir, "compressed.json");
const cacheUploadedFile = join(cacheDir, "uploaded.json");
let compressed = [];
let uploaded = [];
async function compression(filename, buffer, options, compressionType) {
const md5 = createMD5(buffer);
const optionsStr = JSON.stringify(options);
const cache = compressed.find((file) => file.md5 === md5 &&
file.filename === filename &&
file.options === optionsStr &&
file.compressionType === compressionType);
if (cache) {
try {
return cache.files.map((file) => {
const path = join(cacheImagesDir, file.filename);
return {
filename: file.filename,
filebasename: file.filebasename,
buffer: readFileSync(path),
};
});
}
catch (error) { }
}
const cacheIndex = compressed.push({
md5,
filename,
options: optionsStr,
compressionType,
files: [],
}) - 1;
const filebasename = basename(filename);
const fileextname = extname(filename);
const size = buffer.byteLength;
const fileTypeResult = await fileTypeFromBuffer(buffer);
if (!fileTypeResult)
throw new Error(`Cannot retrieve the file type of ${filename}.`);
return await Promise.all(getPlugins(filename, options, compressionType).map(async (plugin) => {
const newBuffer = await imageminjs.buffer(buffer, {
plugins: [plugin],
});
const newSize = newBuffer.byteLength;
const newFileTypeResult = await fileTypeFromBuffer(newBuffer);
if (!newFileTypeResult)
throw new Error(`Cannot retrieve the file type of ${filename}.`);
const isOriginExt = fileTypeResult.ext === newFileTypeResult.ext;
const newFilename = filename.replace(/\.[^.]+$/g, isOriginExt ? fileextname : "." + newFileTypeResult.ext);
const newFilebasename = basename(newFilename);
console.log("\n[vite:imagemin-upload] " + filebasename, size, newFilebasename, size <= newSize ? chalk.red(newSize) : newSize);
if (size <= newSize) {
if (isOriginExt) {
console.log("\n[vite:imagemin-upload] " +
chalk.yellow(`${filebasename} still uses the original file.`));
}
else {
console.log("\n[vite:imagemin-upload] " +
chalk.red(`The volume of ${filebasename} has increased after being compressed into webp!`) +
"\n[vite:imagemin-upload] " +
chalk.yellow(`You can add the parameter ${chalk.red(`no-webp`)} at the end of the image path to prevent conversion to webp.`));
}
}
const cacheFilePath = join(cacheImagesDir, newFilename);
const cacheFileDir = dirname(cacheFilePath);
const cacheFile = size <= newSize && isOriginExt ? buffer : newBuffer;
if (!existsSync(cacheFileDir)) {
await mkdir(cacheFileDir, { recursive: true });
}
await writeFile(cacheFilePath, cacheFile);
compressed[cacheIndex].files.push({
filename: newFilename,
filebasename: newFilebasename,
});
return {
filename: newFilename,
filebasename: newFilebasename,
buffer: cacheFile,
};
}));
}
let s3Client;
let ossClient;
async function upload(filebasename, buffer, options) {
const md5 = createMD5(buffer);
const optionsStr = JSON.stringify(options);
if (uploaded.some((file) => file.md5 === md5 &&
file.filename === filebasename &&
file.options === optionsStr))
return;
if (options.s3) {
const opts = options.s3;
if (!s3Client) {
s3Client = new S3Client(opts.client);
}
const filename = joinURL(opts.dir, filebasename);
await s3Client
.send(new HeadObjectCommand({
...opts.head,
Key: filename,
}))
.catch(async (error) => {
if (error.name === "NotFound") {
await s3Client
.send(new PutObjectCommand({
...opts.put,
Key: filename,
Body: buffer,
}))
.then(() => {
uploaded.push({
md5,
filename: filebasename,
options: optionsStr,
});
console.log("\n[vite:imagemin-upload] " +
chalk.green(`${filebasename} has been successfully uploaded to S3.`));
})
.catch((error) => {
console.log("\n[vite:imagemin-upload] " +
chalk.red(`${filebasename} failed to upload to S3.`) +
"\n[vite:imagemin-upload] " +
chalk.red(error.message));
});
}
else {
console.log("\n[vite:imagemin-upload] " +
chalk.red(`Failed to query the existence of ${filebasename} from S3.`) +
"\n[vite:imagemin-upload] " +
chalk.red(error.message));
}
});
}
if (options.oss) {
const opts = options.oss;
if (!ossClient) {
ossClient = new OSS(opts.client);
}
const filename = joinURL(opts.dir, filebasename);
await ossClient.head(filename, opts.head).catch(async (error) => {
if (error.code === "NoSuchKey") {
await ossClient
.put(filename, buffer, opts.put)
.then(() => {
uploaded.push({
md5,
filename: filebasename,
options: optionsStr,
});
console.log("\n[vite:imagemin-upload] " +
chalk.green(`${filebasename} has been successfully uploaded to OSS.`));
})
.catch((error) => {
console.log("\n[vite:imagemin-upload] " +
chalk.red(`${filebasename} failed to upload to OSS.`) +
"\n[vite:imagemin-upload] " +
chalk.red(error.message));
});
}
else {
console.log("\n[vite:imagemin-upload] " +
chalk.red(`Failed to query the existence of ${filebasename} from OSS.`) +
"\n[vite:imagemin-upload] " +
chalk.red(error.message));
}
});
}
}
let outDir;
let publicDir;
const assets = {
lossless: new Set(),
lossy: new Set(),
};
const publicAssets = {
lossless: new Set(),
lossy: new Set(),
};
const noWebpAssets = new Set();
function imageminUpload(userOptions = {}) {
if (existsSync(cacheCompressedFile)) {
compressed = JSON.parse(readFileSync(cacheCompressedFile, "utf-8"));
}
if (existsSync(cacheUploadedFile)) {
uploaded = JSON.parse(readFileSync(cacheUploadedFile, "utf-8"));
}
const options = defaultsDeep({}, userOptions, getDefaultOptions());
if (options.s3?.baseURL && options.oss?.baseURL) {
throw new Error("When setting up S3 and OSS simultaneously, only one baseURL is allowed!");
}
const { baseURL, dir } = options.s3?.baseURL ? options.s3 : options.oss || {};
if (baseURL && !isURL(baseURL)) {
throw new Error(`The format of baseURL is incorrect.`);
}
const filter = {
lossless: createFilter(options.lossless?.include, options.lossless?.exclude),
lossy: createFilter(options.lossy?.include, options.lossy?.exclude),
};
let polyfill = false;
return {
name: "vite:imagemin-upload",
apply: "build",
config(config, { mode }) {
if (mode === options.mode) {
if (!config.experimental)
config.experimental = {};
const renderBuiltUrl = config.experimental.renderBuiltUrl;
config.experimental.renderBuiltUrl = function (filename, { type, hostId, hostType, ssr }) {
const filepath = cleanUrl(filename);
const compressionType = ["lossless", "lossy"].find((compressionType) => type === options[compressionType]?.type &&
filter[compressionType](filepath));
if (compressionType) {
const noWebp = /^['"]?[^#?]+\.(jpe?g|png|gif|svg)\?([^#]*&)?no-webp([&#].*)?['"]?$/i.test(filename);
if (noWebp)
noWebpAssets.add(filepath);
if (type === "public") {
publicAssets[compressionType].add(filepath);
return;
}
polyfill = true;
assets[compressionType].add(filepath);
let url = baseURL
? joinURL(baseURL, dir, basename(filename))
: filename;
if (options[compressionType]?.webp &&
!/\.webp$/.test(filepath) &&
!noWebp) {
return url.replace(/^([^#?]+\.)(jpe?g|png|gif|svg)(\?[^#]*)?(#.*)?$/i, (match, p1, p2, p3, p4) => {
if (hostType === "css") {
return `${p1}${p2}${p3?.length > 1 ? p3 + "&" : "?"}to-format=webp${p4 || ""}`;
}
return `${p1}webp${p3?.length > 1 ? p3 + "&" : "?"}from-format=${p2}${p4 || ""}`;
});
}
if (baseURL) {
return url;
}
}
if (renderBuiltUrl) {
return renderBuiltUrl(filename, {
type,
hostId,
hostType,
ssr,
});
}
};
}
},
configResolved(resolvedConfig) {
if (resolvedConfig.mode === options.mode) {
outDir = resolve(resolvedConfig.root, resolvedConfig.build.outDir);
publicDir = resolvedConfig.publicDir;
}
},
generateBundle: {
order: null,
async handler(outputOptions, bundle) {
for (const compressionType of ["lossless", "lossy"]) {
for (let filename of publicAssets[compressionType]) {
const buffer = await readFile(resolve(publicDir, filename));
const dir = resolve(outDir, dirname(filename));
try {
for (let { filebasename: newFilebasename, buffer: newBuffer, } of await compression(filename, buffer, options, compressionType)) {
if (!existsSync(dir)) {
await mkdir(dir, { recursive: true });
}
await writeFile(resolve(dir, newFilebasename), newBuffer);
}
}
catch (error) {
console.log("\n[vite:imagemin-upload] " +
chalk.red(`Compression of ${filename} failed.`) +
"\n[vite:imagemin-upload] " +
chalk.red(error.message));
}
}
}
if (!polyfill)
return;
const deleteFiles = [];
for (const [filename, file] of Object.entries(bundle)) {
if (file.type !== "asset")
continue;
if (/\.css$/.test(filename)) {
delete bundle[filename];
this.emitFile({
type: "asset",
fileName: filename,
source: postcss([
webpInCssPlugin({
check: (decl) => /^url\(['"]?[^#?]+\.(jpe?g|png|gif|svg)\?([^#]*&)?to-format=webp([&#].*)?['"]?\)$/i.test(decl.value),
}),
]).process(file.source).css,
});
continue;
}
for (const compressionType of ["lossless", "lossy"]) {
if (!assets[compressionType].has(filename)) {
continue;
}
if (!(file.source instanceof Uint8Array)) {
console.log("\n[vite:imagemin-upload] " +
chalk.red(`Compression of ${filename} failed.`) +
"\n[vite:imagemin-upload] " +
chalk.red(`${filename} is not a Uint8Array`));
}
const buffer = Buffer.from(file.source);
try {
const uploads = [];
for (let { filename: newFilename, filebasename: newFilebasename, buffer: newBuffer, } of await compression(filename, buffer, options, compressionType)) {
uploads.push(upload(newFilebasename, newBuffer, options));
if (filename === newFilename) {
delete bundle[filename];
if (baseURL)
deleteFiles.push(filename);
}
if (!baseURL) {
this.emitFile({
type: "asset",
fileName: newFilename,
source: newBuffer,
});
}
}
await Promise.all(uploads);
}
catch (error) {
console.log("\n[vite:imagemin-upload] " +
chalk.red(`Compression of ${filename} failed.`) +
"\n[vite:imagemin-upload] " +
chalk.red(error.message));
}
}
}
if (!existsSync(cacheDir)) {
await mkdir(cacheDir, { recursive: true });
}
await writeFile(cacheCompressedFile, JSON.stringify(compressed.filter(({ files }) => files.length), null, 2));
await writeFile(cacheUploadedFile, JSON.stringify(uploaded, null, 2));
for (const [, file] of Object.entries(bundle)) {
if (file.type !== "chunk")
continue;
deleteFiles.forEach((filename) => {
file.viteMetadata?.importedAssets.delete(cleanUrl(filename));
});
}
},
},
};
}
export { imageminUpload };