-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.asset.js
More file actions
71 lines (59 loc) · 1.75 KB
/
util.asset.js
File metadata and controls
71 lines (59 loc) · 1.75 KB
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
const { execSync } = require('node:child_process');
const { mkdir } = require('node:fs/promises');
const path = require('node:path');
const MAX_IMAGE_SIZE = 512;
module.exports = function asset(waw) {
run(waw).catch((error) => {
console.error(error.message);
process.exitCode = 1;
});
};
async function run(waw) {
const [, imageUrl, destination] = waw.argv;
if (!imageUrl || !destination) {
throw new Error('Usage: waw asset <image-url> <output-path>');
}
const url = new URL(imageUrl);
const sharp = loadSharp();
const outputPath = resolveOutputPath(waw.projectPath, destination);
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Image download failed with status ${response.status} ${response.statusText}.`);
}
const sourceBuffer = Buffer.from(await response.arrayBuffer());
await mkdir(path.dirname(outputPath), { recursive: true });
await sharp(sourceBuffer)
.resize({
width: MAX_IMAGE_SIZE,
height: MAX_IMAGE_SIZE,
fit: 'inside',
withoutEnlargement: true,
})
.webp()
.toFile(outputPath);
console.log(`Saved ${outputPath}`);
}
function resolveOutputPath(projectPath, destination) {
const requestedPath = path.resolve(projectPath, destination);
return requestedPath.toLowerCase().endsWith('.webp')
? requestedPath
: `${requestedPath}.webp`;
}
function loadSharp() {
try {
return require('sharp');
} catch (localError) {
try {
const globalModulesPath = execSync('npm root -g', {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
}).trim();
return require(path.join(globalModulesPath, 'sharp'));
} catch (globalError) {
throw new Error(
'Unable to load sharp. Install it locally or globally before running this command.',
{ cause: globalError },
);
}
}
}