image-optimizer-node 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +224 -2
- package/action.yml +257 -0
- package/dist/cli.cjs +3158 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +3131 -0
- package/dist/index.cjs +2902 -0
- package/dist/index.d.cts +414 -0
- package/dist/index.d.ts +414 -0
- package/dist/index.js +2810 -0
- package/docs/AI/SKILL.md +73 -0
- package/package.json +83 -4
- package/schemas/imgopt.config.schema.json +236 -0
- package/templates/workflows/optimize-images.yml +64 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,3131 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import fsSync2 from "fs";
|
|
5
|
+
import path14 from "path";
|
|
6
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
7
|
+
import { Command } from "commander";
|
|
8
|
+
import pc from "picocolors";
|
|
9
|
+
|
|
10
|
+
// src/cli-manager/downloader.ts
|
|
11
|
+
import { execFile } from "child_process";
|
|
12
|
+
import crypto2 from "crypto";
|
|
13
|
+
import fs2 from "fs/promises";
|
|
14
|
+
import path3 from "path";
|
|
15
|
+
import { promisify } from "util";
|
|
16
|
+
import AdmZip from "adm-zip";
|
|
17
|
+
import * as tar from "tar";
|
|
18
|
+
|
|
19
|
+
// src/constants.ts
|
|
20
|
+
var DEFAULT_CONFIG_FILENAME = "imgopt.config.json";
|
|
21
|
+
var CONFIG_FILENAMES = [
|
|
22
|
+
"imgopt.config.json",
|
|
23
|
+
".imgoptrc.json"
|
|
24
|
+
];
|
|
25
|
+
var DEFAULT_CLI_REPO = "xzsean666/Image-Optimizer-Cli";
|
|
26
|
+
var DEFAULT_CLI_VERSION = "latest";
|
|
27
|
+
var DEFAULT_BACKUP_DIR = ".imgopt/originals";
|
|
28
|
+
var DEFAULT_MANIFEST_PATH = ".imgopt/manifest.json";
|
|
29
|
+
var DEFAULT_INCLUDE_GLOBS = ["**/*.{png,jpg,jpeg,webp,avif,gif}"];
|
|
30
|
+
var DEFAULT_EXCLUDE_GLOBS = [
|
|
31
|
+
"**/favicon*.*",
|
|
32
|
+
"**/apple-touch-icon*.*"
|
|
33
|
+
];
|
|
34
|
+
var SUPPORTED_IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
35
|
+
".png",
|
|
36
|
+
".jpg",
|
|
37
|
+
".jpeg",
|
|
38
|
+
".webp",
|
|
39
|
+
".avif",
|
|
40
|
+
".gif"
|
|
41
|
+
]);
|
|
42
|
+
var IGNORED_DIR_NAMES = /* @__PURE__ */ new Set([
|
|
43
|
+
"node_modules",
|
|
44
|
+
".git",
|
|
45
|
+
".hg",
|
|
46
|
+
".svn",
|
|
47
|
+
".imgopt",
|
|
48
|
+
"dist",
|
|
49
|
+
"build",
|
|
50
|
+
"out",
|
|
51
|
+
".next",
|
|
52
|
+
".nuxt",
|
|
53
|
+
".output",
|
|
54
|
+
".svelte-kit",
|
|
55
|
+
".astro",
|
|
56
|
+
".vitepress",
|
|
57
|
+
"coverage",
|
|
58
|
+
"target",
|
|
59
|
+
".cache"
|
|
60
|
+
]);
|
|
61
|
+
var DEFAULT_CLI_CONFIG = {
|
|
62
|
+
repo: DEFAULT_CLI_REPO,
|
|
63
|
+
version: DEFAULT_CLI_VERSION,
|
|
64
|
+
autoDownload: true,
|
|
65
|
+
autoUpdate: false
|
|
66
|
+
};
|
|
67
|
+
var DEFAULT_BACKUP_CONFIG = {
|
|
68
|
+
enabled: true,
|
|
69
|
+
dir: DEFAULT_BACKUP_DIR,
|
|
70
|
+
strategy: "preserve-first"
|
|
71
|
+
};
|
|
72
|
+
var DEFAULT_OPTIMIZATION_OPTIONS = {
|
|
73
|
+
preset: "balanced",
|
|
74
|
+
quality: 0.95,
|
|
75
|
+
effort: 5,
|
|
76
|
+
format: "preserve",
|
|
77
|
+
preserveMetadata: false,
|
|
78
|
+
preserveIcc: false,
|
|
79
|
+
convertToSrgb: true,
|
|
80
|
+
minBytes: 1024,
|
|
81
|
+
minSavingsPercent: 1,
|
|
82
|
+
removeSourceOnFormatChange: true
|
|
83
|
+
};
|
|
84
|
+
var DEFAULT_SCHEMA_REF = "https://raw.githubusercontent.com/xzsean666/image-optimizer-node/main/schemas/imgopt.config.schema.json";
|
|
85
|
+
function createDefaultConfig(targets) {
|
|
86
|
+
return {
|
|
87
|
+
$schema: DEFAULT_SCHEMA_REF,
|
|
88
|
+
version: 1,
|
|
89
|
+
cli: { ...DEFAULT_CLI_CONFIG },
|
|
90
|
+
targets,
|
|
91
|
+
backup: { ...DEFAULT_BACKUP_CONFIG },
|
|
92
|
+
manifest: DEFAULT_MANIFEST_PATH,
|
|
93
|
+
optimization: { ...DEFAULT_OPTIMIZATION_OPTIONS },
|
|
94
|
+
rules: []
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
var CANDIDATE_ASSET_DIRS = [
|
|
98
|
+
{ dir: "src/assets", stacks: ["vite", "vue", "react", "svelte", "astro", "angular", "general"] },
|
|
99
|
+
{ dir: "src/images", stacks: ["vite", "vue", "react", "general"] },
|
|
100
|
+
{ dir: "src/img", stacks: ["vite", "vue", "react", "general"] },
|
|
101
|
+
{ dir: "public", stacks: ["next", "nuxt", "vite", "astro", "svelte", "react", "vue", "general"] },
|
|
102
|
+
{ dir: "public/images", stacks: ["next", "nuxt", "general"] },
|
|
103
|
+
{ dir: "static", stacks: ["svelte", "docusaurus", "hugo", "hexo", "general"] },
|
|
104
|
+
{ dir: "static/img", stacks: ["docusaurus", "hugo", "general"] },
|
|
105
|
+
{ dir: "assets", stacks: ["react-native", "flutter", "electron", "general"] },
|
|
106
|
+
{ dir: "assets/images", stacks: ["react-native", "flutter", "general"] },
|
|
107
|
+
{ dir: "app/assets", stacks: ["remix", "rails", "general"] },
|
|
108
|
+
{ dir: "docs/public", stacks: ["vitepress", "docs"] },
|
|
109
|
+
{ dir: "docs/images", stacks: ["docs", "general"] },
|
|
110
|
+
{ dir: "docs/assets", stacks: ["docs", "general"] },
|
|
111
|
+
{ dir: "content/images", stacks: ["docs", "hugo", "astro", "general"] },
|
|
112
|
+
{ dir: "resources/images", stacks: ["electron", "general"] },
|
|
113
|
+
{ dir: "images", stacks: ["general"] },
|
|
114
|
+
{ dir: "img", stacks: ["general"] },
|
|
115
|
+
{ dir: "media", stacks: ["general"] }
|
|
116
|
+
];
|
|
117
|
+
var LATEST_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
118
|
+
|
|
119
|
+
// src/utils/fs.ts
|
|
120
|
+
import crypto from "crypto";
|
|
121
|
+
import fs from "fs/promises";
|
|
122
|
+
import path from "path";
|
|
123
|
+
async function fileExists(targetPath) {
|
|
124
|
+
try {
|
|
125
|
+
await fs.access(targetPath);
|
|
126
|
+
return true;
|
|
127
|
+
} catch {
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
async function isDirectory(targetPath) {
|
|
132
|
+
try {
|
|
133
|
+
const stat = await fs.stat(targetPath);
|
|
134
|
+
return stat.isDirectory();
|
|
135
|
+
} catch {
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
async function isFile(targetPath) {
|
|
140
|
+
try {
|
|
141
|
+
const stat = await fs.stat(targetPath);
|
|
142
|
+
return stat.isFile();
|
|
143
|
+
} catch {
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async function atomicWriteFile(filePath, data) {
|
|
148
|
+
const dir = path.dirname(filePath);
|
|
149
|
+
await fs.mkdir(dir, { recursive: true });
|
|
150
|
+
const tempPath = path.join(
|
|
151
|
+
dir,
|
|
152
|
+
`.tmp-${path.basename(filePath)}-${process.pid}-${crypto.randomUUID()}`
|
|
153
|
+
);
|
|
154
|
+
try {
|
|
155
|
+
await fs.writeFile(tempPath, data);
|
|
156
|
+
await fs.rename(tempPath, filePath);
|
|
157
|
+
} catch (err) {
|
|
158
|
+
await fs.rm(tempPath, { force: true }).catch(() => {
|
|
159
|
+
});
|
|
160
|
+
throw err;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
async function atomicCopyFile(srcPath, destPath) {
|
|
164
|
+
const dir = path.dirname(destPath);
|
|
165
|
+
await fs.mkdir(dir, { recursive: true });
|
|
166
|
+
const tempPath = path.join(
|
|
167
|
+
dir,
|
|
168
|
+
`.tmp-${path.basename(destPath)}-${process.pid}-${crypto.randomUUID()}`
|
|
169
|
+
);
|
|
170
|
+
try {
|
|
171
|
+
await fs.copyFile(srcPath, tempPath);
|
|
172
|
+
await fs.rename(tempPath, destPath);
|
|
173
|
+
} catch (err) {
|
|
174
|
+
await fs.rm(tempPath, { force: true }).catch(() => {
|
|
175
|
+
});
|
|
176
|
+
throw err;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
async function writeJsonAtomic(filePath, value) {
|
|
180
|
+
await atomicWriteFile(filePath, `${JSON.stringify(value, null, 2)}
|
|
181
|
+
`);
|
|
182
|
+
}
|
|
183
|
+
async function readJsonFile(filePath) {
|
|
184
|
+
const raw = await fs.readFile(filePath, "utf8");
|
|
185
|
+
return JSON.parse(raw);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// src/utils/path.ts
|
|
189
|
+
import os from "os";
|
|
190
|
+
import path2 from "path";
|
|
191
|
+
function toPosixPath(inputPath) {
|
|
192
|
+
return inputPath.split(path2.sep).join("/");
|
|
193
|
+
}
|
|
194
|
+
function normalizeRelativePosix(rootDir, targetPath) {
|
|
195
|
+
const resolvedRoot = path2.resolve(rootDir);
|
|
196
|
+
const resolvedTarget = path2.resolve(rootDir, targetPath);
|
|
197
|
+
const rel = path2.relative(resolvedRoot, resolvedTarget);
|
|
198
|
+
if (rel === ".." || rel.startsWith(`..${path2.sep}`) || path2.isAbsolute(rel)) {
|
|
199
|
+
throw new Error(
|
|
200
|
+
`Path "${targetPath}" escapes project root "${resolvedRoot}"`
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
return toPosixPath(rel);
|
|
204
|
+
}
|
|
205
|
+
function resolveInsideRoot(rootDir, relPath) {
|
|
206
|
+
const resolvedRoot = path2.resolve(rootDir);
|
|
207
|
+
const resolvedTarget = path2.resolve(resolvedRoot, relPath);
|
|
208
|
+
const rel = path2.relative(resolvedRoot, resolvedTarget);
|
|
209
|
+
if (rel === ".." || rel.startsWith(`..${path2.sep}`) || path2.isAbsolute(rel)) {
|
|
210
|
+
throw new Error(
|
|
211
|
+
`Path "${relPath}" escapes project root "${resolvedRoot}"`
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
return resolvedTarget;
|
|
215
|
+
}
|
|
216
|
+
function expandHome(inputPath) {
|
|
217
|
+
if (inputPath === "~") {
|
|
218
|
+
return os.homedir();
|
|
219
|
+
}
|
|
220
|
+
if (inputPath.startsWith("~/") || inputPath.startsWith("~\\")) {
|
|
221
|
+
return path2.join(os.homedir(), inputPath.slice(2));
|
|
222
|
+
}
|
|
223
|
+
return inputPath;
|
|
224
|
+
}
|
|
225
|
+
function getDefaultCliCacheDir() {
|
|
226
|
+
if (process.env.IMGOPT_CACHE_DIR) {
|
|
227
|
+
return path2.resolve(expandHome(process.env.IMGOPT_CACHE_DIR));
|
|
228
|
+
}
|
|
229
|
+
if (process.env.XDG_CACHE_HOME) {
|
|
230
|
+
return path2.join(expandHome(process.env.XDG_CACHE_HOME), "imgopt-node", "bin");
|
|
231
|
+
}
|
|
232
|
+
if (process.platform === "win32" && process.env.LOCALAPPDATA) {
|
|
233
|
+
return path2.join(process.env.LOCALAPPDATA, "imgopt-node", "Cache", "bin");
|
|
234
|
+
}
|
|
235
|
+
return path2.join(os.homedir(), ".cache", "imgopt-node", "bin");
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// src/utils/http.ts
|
|
239
|
+
import http from "http";
|
|
240
|
+
import https from "https";
|
|
241
|
+
import tls from "tls";
|
|
242
|
+
function isHttpProxyUrl(val) {
|
|
243
|
+
if (!val) return void 0;
|
|
244
|
+
return /^https?:\/\//i.test(val.trim()) ? val.trim() : void 0;
|
|
245
|
+
}
|
|
246
|
+
function isBypassedByNoProxy(hostname) {
|
|
247
|
+
const lower = hostname.toLowerCase();
|
|
248
|
+
if (lower === "127.0.0.1" || lower === "localhost" || lower === "::1" || lower === "[::1]") {
|
|
249
|
+
return true;
|
|
250
|
+
}
|
|
251
|
+
const noProxyRaw = process.env.NO_PROXY || process.env.no_proxy;
|
|
252
|
+
if (!noProxyRaw) return false;
|
|
253
|
+
const entries = noProxyRaw.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
|
|
254
|
+
for (const entry of entries) {
|
|
255
|
+
if (entry === "*") return true;
|
|
256
|
+
const clean = entry.replace(/^\./, "");
|
|
257
|
+
if (lower === clean || lower.endsWith(`.${clean}`)) {
|
|
258
|
+
return true;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return false;
|
|
262
|
+
}
|
|
263
|
+
function resolveProxyUrl(targetUrl) {
|
|
264
|
+
if (isBypassedByNoProxy(targetUrl.hostname)) {
|
|
265
|
+
return null;
|
|
266
|
+
}
|
|
267
|
+
const allProxy = isHttpProxyUrl(process.env.ALL_PROXY || process.env.all_proxy);
|
|
268
|
+
const raw = targetUrl.protocol === "https:" ? isHttpProxyUrl(process.env.HTTPS_PROXY || process.env.https_proxy) || allProxy : isHttpProxyUrl(process.env.HTTP_PROXY || process.env.http_proxy) || allProxy;
|
|
269
|
+
if (!raw) return null;
|
|
270
|
+
try {
|
|
271
|
+
return new URL(raw);
|
|
272
|
+
} catch {
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
function buildProxyAuthHeader(proxyUrl) {
|
|
277
|
+
if (!proxyUrl.username && !proxyUrl.password) return void 0;
|
|
278
|
+
const creds = `${decodeURIComponent(proxyUrl.username)}:${decodeURIComponent(proxyUrl.password)}`;
|
|
279
|
+
return `Basic ${Buffer.from(creds).toString("base64")}`;
|
|
280
|
+
}
|
|
281
|
+
function makeResponse(status, rawHeaders, body) {
|
|
282
|
+
return {
|
|
283
|
+
ok: status >= 200 && status < 300,
|
|
284
|
+
status,
|
|
285
|
+
headers: {
|
|
286
|
+
get(name) {
|
|
287
|
+
const val = rawHeaders[name.toLowerCase()];
|
|
288
|
+
if (val === void 0) return null;
|
|
289
|
+
return Array.isArray(val) ? val.join(", ") : val;
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
async arrayBuffer() {
|
|
293
|
+
return body.buffer.slice(
|
|
294
|
+
body.byteOffset,
|
|
295
|
+
body.byteOffset + body.byteLength
|
|
296
|
+
);
|
|
297
|
+
},
|
|
298
|
+
async json() {
|
|
299
|
+
return JSON.parse(body.toString("utf8"));
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
function singleRequest(targetUrl, method, headers) {
|
|
304
|
+
return new Promise((resolve, reject) => {
|
|
305
|
+
const proxyUrl = resolveProxyUrl(targetUrl);
|
|
306
|
+
const isHttps = targetUrl.protocol === "https:";
|
|
307
|
+
const targetPort = Number(targetUrl.port) || (isHttps ? 443 : 80);
|
|
308
|
+
const handleIncoming = (res) => {
|
|
309
|
+
const chunks = [];
|
|
310
|
+
res.on("data", (chunk) => chunks.push(chunk));
|
|
311
|
+
res.on("error", reject);
|
|
312
|
+
res.on("end", () => {
|
|
313
|
+
resolve(
|
|
314
|
+
makeResponse(
|
|
315
|
+
res.statusCode ?? 0,
|
|
316
|
+
res.headers,
|
|
317
|
+
Buffer.concat(chunks)
|
|
318
|
+
)
|
|
319
|
+
);
|
|
320
|
+
});
|
|
321
|
+
};
|
|
322
|
+
if (!proxyUrl) {
|
|
323
|
+
const transport = isHttps ? https : http;
|
|
324
|
+
const req = transport.request(
|
|
325
|
+
targetUrl,
|
|
326
|
+
{ method, headers },
|
|
327
|
+
handleIncoming
|
|
328
|
+
);
|
|
329
|
+
req.setTimeout(3e4, () => {
|
|
330
|
+
req.destroy(new Error(`Request timed out: ${targetUrl.href}`));
|
|
331
|
+
});
|
|
332
|
+
req.on("error", reject);
|
|
333
|
+
req.end();
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
const proxyPort = Number(proxyUrl.port) || (proxyUrl.protocol === "https:" ? 443 : 80);
|
|
337
|
+
const proxyAuth = buildProxyAuthHeader(proxyUrl);
|
|
338
|
+
if (!isHttps) {
|
|
339
|
+
const proxyHeaders = {
|
|
340
|
+
...headers,
|
|
341
|
+
Host: targetUrl.host
|
|
342
|
+
};
|
|
343
|
+
if (proxyAuth) {
|
|
344
|
+
proxyHeaders["Proxy-Authorization"] = proxyAuth;
|
|
345
|
+
}
|
|
346
|
+
const proxyTransport2 = proxyUrl.protocol === "https:" ? https : http;
|
|
347
|
+
const req = proxyTransport2.request(
|
|
348
|
+
{
|
|
349
|
+
hostname: proxyUrl.hostname,
|
|
350
|
+
port: proxyPort,
|
|
351
|
+
method,
|
|
352
|
+
path: targetUrl.href,
|
|
353
|
+
headers: proxyHeaders
|
|
354
|
+
},
|
|
355
|
+
handleIncoming
|
|
356
|
+
);
|
|
357
|
+
req.setTimeout(3e4, () => {
|
|
358
|
+
req.destroy(new Error(`Proxy request timed out: ${targetUrl.href}`));
|
|
359
|
+
});
|
|
360
|
+
req.on("error", reject);
|
|
361
|
+
req.end();
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
const connectHeaders = {
|
|
365
|
+
Host: `${targetUrl.hostname}:${targetPort}`
|
|
366
|
+
};
|
|
367
|
+
if (proxyAuth) {
|
|
368
|
+
connectHeaders["Proxy-Authorization"] = proxyAuth;
|
|
369
|
+
}
|
|
370
|
+
const proxyTransport = proxyUrl.protocol === "https:" ? https : http;
|
|
371
|
+
const connectReq = proxyTransport.request({
|
|
372
|
+
hostname: proxyUrl.hostname,
|
|
373
|
+
port: proxyPort,
|
|
374
|
+
method: "CONNECT",
|
|
375
|
+
path: `${targetUrl.hostname}:${targetPort}`,
|
|
376
|
+
headers: connectHeaders
|
|
377
|
+
});
|
|
378
|
+
connectReq.setTimeout(3e4, () => {
|
|
379
|
+
connectReq.destroy(
|
|
380
|
+
new Error(`Proxy CONNECT timed out for ${targetUrl.host}`)
|
|
381
|
+
);
|
|
382
|
+
});
|
|
383
|
+
connectReq.on("error", reject);
|
|
384
|
+
connectReq.on("connect", (connectRes, socket, head) => {
|
|
385
|
+
if (connectRes.statusCode !== 200) {
|
|
386
|
+
socket.destroy();
|
|
387
|
+
reject(
|
|
388
|
+
new Error(
|
|
389
|
+
`Proxy CONNECT failed with HTTP ${connectRes.statusCode ?? 0} for ${targetUrl.host}`
|
|
390
|
+
)
|
|
391
|
+
);
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
if (head && head.length > 0) {
|
|
395
|
+
socket.unshift(head);
|
|
396
|
+
}
|
|
397
|
+
const agent = new https.Agent({ keepAlive: false });
|
|
398
|
+
agent.createConnection = () => tls.connect({
|
|
399
|
+
socket,
|
|
400
|
+
servername: targetUrl.hostname
|
|
401
|
+
});
|
|
402
|
+
const req = https.request(
|
|
403
|
+
{
|
|
404
|
+
hostname: targetUrl.hostname,
|
|
405
|
+
port: targetPort,
|
|
406
|
+
path: `${targetUrl.pathname}${targetUrl.search}`,
|
|
407
|
+
method,
|
|
408
|
+
headers,
|
|
409
|
+
agent
|
|
410
|
+
},
|
|
411
|
+
handleIncoming
|
|
412
|
+
);
|
|
413
|
+
req.setTimeout(3e4, () => {
|
|
414
|
+
req.destroy(new Error(`Request timed out: ${targetUrl.href}`));
|
|
415
|
+
});
|
|
416
|
+
req.on("error", reject);
|
|
417
|
+
req.end();
|
|
418
|
+
});
|
|
419
|
+
connectReq.end();
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
async function proxyFetch(url, init = {}) {
|
|
423
|
+
const method = (init.method ?? "GET").toUpperCase();
|
|
424
|
+
const redirectMode = init.redirect ?? "follow";
|
|
425
|
+
const maxRedirects = init.maxRedirects ?? 10;
|
|
426
|
+
let currentUrl = new URL(url);
|
|
427
|
+
let currentHeaders = { ...init.headers ?? {} };
|
|
428
|
+
for (let hop = 0; hop <= maxRedirects; hop += 1) {
|
|
429
|
+
const res = await singleRequest(currentUrl, method, currentHeaders);
|
|
430
|
+
const isRedirect = res.status === 301 || res.status === 302 || res.status === 303 || res.status === 307 || res.status === 308;
|
|
431
|
+
if (!isRedirect || redirectMode === "manual") {
|
|
432
|
+
return res;
|
|
433
|
+
}
|
|
434
|
+
const location = res.headers.get("location");
|
|
435
|
+
if (!location) {
|
|
436
|
+
return res;
|
|
437
|
+
}
|
|
438
|
+
const nextUrl = new URL(location, currentUrl);
|
|
439
|
+
if (nextUrl.origin !== currentUrl.origin) {
|
|
440
|
+
delete currentHeaders.Authorization;
|
|
441
|
+
delete currentHeaders.authorization;
|
|
442
|
+
}
|
|
443
|
+
currentUrl = nextUrl;
|
|
444
|
+
}
|
|
445
|
+
throw new Error(`Exceeded maximum redirects (${maxRedirects}) for ${url}`);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// src/cli-manager/platform.ts
|
|
449
|
+
function resolveReleaseAsset(platform = process.platform, arch = process.arch) {
|
|
450
|
+
if (platform === "linux" && arch === "x64") {
|
|
451
|
+
return {
|
|
452
|
+
platformKey: "linux-x86_64",
|
|
453
|
+
assetName: "imgopt-linux-x86_64.tar.gz",
|
|
454
|
+
checksumAssetName: "imgopt-linux-x86_64.tar.gz.sha256",
|
|
455
|
+
archiveType: "tar.gz",
|
|
456
|
+
binaryName: "imgopt"
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
if (platform === "linux" && arch === "arm64") {
|
|
460
|
+
return {
|
|
461
|
+
platformKey: "linux-aarch64",
|
|
462
|
+
assetName: "imgopt-linux-aarch64.tar.gz",
|
|
463
|
+
checksumAssetName: "imgopt-linux-aarch64.tar.gz.sha256",
|
|
464
|
+
archiveType: "tar.gz",
|
|
465
|
+
binaryName: "imgopt"
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
if (platform === "darwin" && arch === "x64") {
|
|
469
|
+
return {
|
|
470
|
+
platformKey: "macos-x86_64",
|
|
471
|
+
assetName: "imgopt-macos-x86_64.tar.gz",
|
|
472
|
+
checksumAssetName: "imgopt-macos-x86_64.tar.gz.sha256",
|
|
473
|
+
archiveType: "tar.gz",
|
|
474
|
+
binaryName: "imgopt"
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
if (platform === "darwin" && arch === "arm64") {
|
|
478
|
+
return {
|
|
479
|
+
platformKey: "macos-aarch64",
|
|
480
|
+
assetName: "imgopt-macos-aarch64.tar.gz",
|
|
481
|
+
checksumAssetName: "imgopt-macos-aarch64.tar.gz.sha256",
|
|
482
|
+
archiveType: "tar.gz",
|
|
483
|
+
binaryName: "imgopt"
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
if (platform === "win32" && arch === "x64") {
|
|
487
|
+
return {
|
|
488
|
+
platformKey: "windows-x86_64",
|
|
489
|
+
assetName: "imgopt-windows-x86_64.zip",
|
|
490
|
+
checksumAssetName: "imgopt-windows-x86_64.zip.sha256",
|
|
491
|
+
archiveType: "zip",
|
|
492
|
+
binaryName: "imgopt.exe"
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
throw new Error(
|
|
496
|
+
`Unsupported platform/arch "${platform}/${arch}" for prebuilt imgopt binaries. Set IMGOPT_BIN to a locally compiled imgopt binary.`
|
|
497
|
+
);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// src/cli-manager/downloader.ts
|
|
501
|
+
var execFileAsync = promisify(execFile);
|
|
502
|
+
function getAuthHeaders() {
|
|
503
|
+
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
|
504
|
+
const headers = {
|
|
505
|
+
"User-Agent": "image-optimizer-node",
|
|
506
|
+
Accept: "application/vnd.github+json"
|
|
507
|
+
};
|
|
508
|
+
if (token) {
|
|
509
|
+
headers.Authorization = `Bearer ${token}`;
|
|
510
|
+
}
|
|
511
|
+
return headers;
|
|
512
|
+
}
|
|
513
|
+
function resolveCacheDir(cliConfig) {
|
|
514
|
+
if (cliConfig?.cacheDir) {
|
|
515
|
+
return path3.resolve(expandHome(cliConfig.cacheDir));
|
|
516
|
+
}
|
|
517
|
+
return getDefaultCliCacheDir();
|
|
518
|
+
}
|
|
519
|
+
async function probeBinaryVersion(binPath) {
|
|
520
|
+
const { stdout, stderr } = await execFileAsync(binPath, ["--version"], {
|
|
521
|
+
timeout: 1e4
|
|
522
|
+
});
|
|
523
|
+
const text = `${stdout}
|
|
524
|
+
${stderr}`.trim();
|
|
525
|
+
const match = text.match(/(\d+\.\d+\.\d+(?:[-+][\w.]+)?)/);
|
|
526
|
+
return match ? `v${match[1]}` : text || "unknown";
|
|
527
|
+
}
|
|
528
|
+
async function findBinaryOnPath(binaryName) {
|
|
529
|
+
const pathEnv = process.env.PATH ?? "";
|
|
530
|
+
const dirs = pathEnv.split(path3.delimiter).filter(Boolean);
|
|
531
|
+
for (const dir of dirs) {
|
|
532
|
+
const candidate = path3.join(dir, binaryName);
|
|
533
|
+
if (await isFile(candidate)) {
|
|
534
|
+
return candidate;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
return null;
|
|
538
|
+
}
|
|
539
|
+
async function fetchLatestReleaseTag(repo) {
|
|
540
|
+
const redirectUrl = `https://github.com/${repo}/releases/latest`;
|
|
541
|
+
try {
|
|
542
|
+
const res = await proxyFetch(redirectUrl, {
|
|
543
|
+
method: "HEAD",
|
|
544
|
+
redirect: "manual",
|
|
545
|
+
headers: { "User-Agent": "image-optimizer-node" }
|
|
546
|
+
});
|
|
547
|
+
const location = res.headers.get("location");
|
|
548
|
+
if (location) {
|
|
549
|
+
const match = location.match(/\/releases\/tag\/([^/?#]+)/);
|
|
550
|
+
if (match?.[1]) {
|
|
551
|
+
return match[1];
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
} catch {
|
|
555
|
+
}
|
|
556
|
+
const apiUrl = `https://api.github.com/repos/${repo}/releases/latest`;
|
|
557
|
+
const apiRes = await proxyFetch(apiUrl, { headers: getAuthHeaders() });
|
|
558
|
+
if (!apiRes.ok) {
|
|
559
|
+
throw new Error(
|
|
560
|
+
`Failed to query latest release for ${repo} (HTTP ${apiRes.status})`
|
|
561
|
+
);
|
|
562
|
+
}
|
|
563
|
+
const data = await apiRes.json();
|
|
564
|
+
if (!data.tag_name) {
|
|
565
|
+
throw new Error(`No tag_name found in latest release response for ${repo}`);
|
|
566
|
+
}
|
|
567
|
+
return data.tag_name;
|
|
568
|
+
}
|
|
569
|
+
async function listCachedVersions(cacheDir) {
|
|
570
|
+
try {
|
|
571
|
+
const entries = await fs2.readdir(cacheDir, { withFileTypes: true });
|
|
572
|
+
const spec = resolveReleaseAsset();
|
|
573
|
+
const versions = [];
|
|
574
|
+
for (const entry of entries) {
|
|
575
|
+
if (!entry.isDirectory()) continue;
|
|
576
|
+
const binCandidate = path3.join(cacheDir, entry.name, spec.binaryName);
|
|
577
|
+
if (await isFile(binCandidate)) {
|
|
578
|
+
versions.push(entry.name);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return versions.sort();
|
|
582
|
+
} catch {
|
|
583
|
+
return [];
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
function parseSha256Text(text) {
|
|
587
|
+
const match = text.match(/\b([a-fA-F0-9]{64})\b/);
|
|
588
|
+
if (!match?.[1]) {
|
|
589
|
+
throw new Error(`Unable to parse SHA-256 checksum from: ${text.trim()}`);
|
|
590
|
+
}
|
|
591
|
+
return match[1].toLowerCase();
|
|
592
|
+
}
|
|
593
|
+
async function downloadBuffer(url) {
|
|
594
|
+
const res = await proxyFetch(url, {
|
|
595
|
+
redirect: "follow",
|
|
596
|
+
headers: { "User-Agent": "image-optimizer-node" }
|
|
597
|
+
});
|
|
598
|
+
if (!res.ok) {
|
|
599
|
+
throw new Error(`Download failed from ${url} (HTTP ${res.status})`);
|
|
600
|
+
}
|
|
601
|
+
const ab = await res.arrayBuffer();
|
|
602
|
+
return Buffer.from(ab);
|
|
603
|
+
}
|
|
604
|
+
async function findExtractedBinary(rootDir, binaryName, depth = 0) {
|
|
605
|
+
if (depth > 3) return null;
|
|
606
|
+
const entries = await fs2.readdir(rootDir, { withFileTypes: true });
|
|
607
|
+
for (const entry of entries) {
|
|
608
|
+
const full = path3.join(rootDir, entry.name);
|
|
609
|
+
if (entry.isFile() && entry.name === binaryName) {
|
|
610
|
+
return full;
|
|
611
|
+
}
|
|
612
|
+
if (entry.isDirectory()) {
|
|
613
|
+
const nested = await findExtractedBinary(full, binaryName, depth + 1);
|
|
614
|
+
if (nested) return nested;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
return null;
|
|
618
|
+
}
|
|
619
|
+
async function downloadCliRelease(options) {
|
|
620
|
+
const repo = options.repo ?? DEFAULT_CLI_REPO;
|
|
621
|
+
const cacheDir = options.cacheDir ?? getDefaultCliCacheDir();
|
|
622
|
+
const assetSpec = resolveReleaseAsset();
|
|
623
|
+
const requestedVersion = options.version ?? "latest";
|
|
624
|
+
const resolvedTag = requestedVersion === "latest" ? await fetchLatestReleaseTag(repo) : requestedVersion.startsWith("v") ? requestedVersion : `v${requestedVersion}`;
|
|
625
|
+
const versionDir = path3.join(cacheDir, resolvedTag);
|
|
626
|
+
const targetBinPath = path3.join(versionDir, assetSpec.binaryName);
|
|
627
|
+
if (!options.force && await isFile(targetBinPath)) {
|
|
628
|
+
const actualVer = await probeBinaryVersion(targetBinPath);
|
|
629
|
+
if (requestedVersion === "latest") {
|
|
630
|
+
await writeJsonAtomic(path3.join(cacheDir, "latest-meta.json"), {
|
|
631
|
+
repo,
|
|
632
|
+
tag: resolvedTag,
|
|
633
|
+
checkedAt: Date.now()
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
return {
|
|
637
|
+
binPath: targetBinPath,
|
|
638
|
+
tag: resolvedTag,
|
|
639
|
+
version: actualVer,
|
|
640
|
+
source: "cache",
|
|
641
|
+
cacheDir
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
const baseUrl = (options.downloadBaseUrl ?? process.env.IMGOPT_DOWNLOAD_BASE_URL ?? `https://github.com/${repo}/releases/download`).replace(/\/+$/, "");
|
|
645
|
+
const archiveUrl = `${baseUrl}/${resolvedTag}/${assetSpec.assetName}`;
|
|
646
|
+
const checksumUrl = `${baseUrl}/${resolvedTag}/${assetSpec.checksumAssetName}`;
|
|
647
|
+
const [archiveBytes, checksumBytes] = await Promise.all([
|
|
648
|
+
downloadBuffer(archiveUrl),
|
|
649
|
+
downloadBuffer(checksumUrl)
|
|
650
|
+
]);
|
|
651
|
+
const expectedHash = parseSha256Text(checksumBytes.toString("utf8"));
|
|
652
|
+
const actualHash = crypto2.createHash("sha256").update(archiveBytes).digest("hex");
|
|
653
|
+
if (actualHash !== expectedHash) {
|
|
654
|
+
throw new Error(
|
|
655
|
+
`SHA-256 verification failed for ${assetSpec.assetName}: expected ${expectedHash}, got ${actualHash}`
|
|
656
|
+
);
|
|
657
|
+
}
|
|
658
|
+
const tempExtractDir = path3.join(
|
|
659
|
+
cacheDir,
|
|
660
|
+
`.tmp-extract-${resolvedTag}-${process.pid}-${crypto2.randomUUID()}`
|
|
661
|
+
);
|
|
662
|
+
await fs2.mkdir(tempExtractDir, { recursive: true });
|
|
663
|
+
await fs2.mkdir(versionDir, { recursive: true });
|
|
664
|
+
try {
|
|
665
|
+
if (assetSpec.archiveType === "tar.gz") {
|
|
666
|
+
const archivePath = path3.join(tempExtractDir, assetSpec.assetName);
|
|
667
|
+
await fs2.writeFile(archivePath, archiveBytes);
|
|
668
|
+
await tar.x({
|
|
669
|
+
file: archivePath,
|
|
670
|
+
cwd: tempExtractDir
|
|
671
|
+
});
|
|
672
|
+
} else {
|
|
673
|
+
const zip = new AdmZip(archiveBytes);
|
|
674
|
+
zip.extractAllTo(tempExtractDir, true);
|
|
675
|
+
}
|
|
676
|
+
const extractedBin = await findExtractedBinary(
|
|
677
|
+
tempExtractDir,
|
|
678
|
+
assetSpec.binaryName
|
|
679
|
+
);
|
|
680
|
+
if (!extractedBin) {
|
|
681
|
+
throw new Error(
|
|
682
|
+
`Archive ${assetSpec.assetName} did not contain expected binary "${assetSpec.binaryName}"`
|
|
683
|
+
);
|
|
684
|
+
}
|
|
685
|
+
const tempTargetBin = `${targetBinPath}.tmp-${process.pid}`;
|
|
686
|
+
await fs2.copyFile(extractedBin, tempTargetBin);
|
|
687
|
+
if (process.platform !== "win32") {
|
|
688
|
+
await fs2.chmod(tempTargetBin, 493);
|
|
689
|
+
}
|
|
690
|
+
await fs2.rename(tempTargetBin, targetBinPath);
|
|
691
|
+
} finally {
|
|
692
|
+
await fs2.rm(tempExtractDir, { recursive: true, force: true }).catch(() => {
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
const verifiedVersion = await probeBinaryVersion(targetBinPath);
|
|
696
|
+
if (requestedVersion === "latest") {
|
|
697
|
+
await writeJsonAtomic(path3.join(cacheDir, "latest-meta.json"), {
|
|
698
|
+
repo,
|
|
699
|
+
tag: resolvedTag,
|
|
700
|
+
checkedAt: Date.now()
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
return {
|
|
704
|
+
binPath: targetBinPath,
|
|
705
|
+
tag: resolvedTag,
|
|
706
|
+
version: verifiedVersion,
|
|
707
|
+
source: "downloaded",
|
|
708
|
+
cacheDir
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
async function ensureCli(options = {}) {
|
|
712
|
+
const cliConfig = {
|
|
713
|
+
repo: options.cliConfig?.repo ?? DEFAULT_CLI_REPO,
|
|
714
|
+
version: options.versionOverride ?? options.cliConfig?.version ?? "latest",
|
|
715
|
+
autoDownload: options.cliConfig?.autoDownload ?? true,
|
|
716
|
+
autoUpdate: options.cliConfig?.autoUpdate ?? false,
|
|
717
|
+
cacheDir: options.cliConfig?.cacheDir,
|
|
718
|
+
binPath: options.cliConfig?.binPath,
|
|
719
|
+
downloadBaseUrl: options.cliConfig?.downloadBaseUrl
|
|
720
|
+
};
|
|
721
|
+
const cacheDir = resolveCacheDir(cliConfig);
|
|
722
|
+
const assetSpec = resolveReleaseAsset();
|
|
723
|
+
if (!options.forceUpdate && process.env.IMGOPT_BIN) {
|
|
724
|
+
const envBin = path3.resolve(expandHome(process.env.IMGOPT_BIN));
|
|
725
|
+
if (!await isFile(envBin)) {
|
|
726
|
+
throw new Error(`IMGOPT_BIN points to a missing file: ${envBin}`);
|
|
727
|
+
}
|
|
728
|
+
const version = await probeBinaryVersion(envBin);
|
|
729
|
+
return { binPath: envBin, tag: version, version, source: "env", cacheDir };
|
|
730
|
+
}
|
|
731
|
+
if (!options.forceUpdate && cliConfig.binPath) {
|
|
732
|
+
const cfgBin = path3.resolve(expandHome(cliConfig.binPath));
|
|
733
|
+
if (!await isFile(cfgBin)) {
|
|
734
|
+
throw new Error(`cli.binPath points to a missing file: ${cfgBin}`);
|
|
735
|
+
}
|
|
736
|
+
const version = await probeBinaryVersion(cfgBin);
|
|
737
|
+
return { binPath: cfgBin, tag: version, version, source: "config", cacheDir };
|
|
738
|
+
}
|
|
739
|
+
const shouldCheckRemote = options.forceUpdate || cliConfig.version === "latest" && cliConfig.autoUpdate;
|
|
740
|
+
if (cliConfig.version !== "latest") {
|
|
741
|
+
const tag = cliConfig.version.startsWith("v") ? cliConfig.version : `v${cliConfig.version}`;
|
|
742
|
+
const cachedPath = path3.join(cacheDir, tag, assetSpec.binaryName);
|
|
743
|
+
if (!options.forceUpdate && await isFile(cachedPath)) {
|
|
744
|
+
const version = await probeBinaryVersion(cachedPath);
|
|
745
|
+
return { binPath: cachedPath, tag, version, source: "cache", cacheDir };
|
|
746
|
+
}
|
|
747
|
+
if (cliConfig.autoDownload) {
|
|
748
|
+
return downloadCliRelease({
|
|
749
|
+
repo: cliConfig.repo,
|
|
750
|
+
version: tag,
|
|
751
|
+
cacheDir,
|
|
752
|
+
downloadBaseUrl: cliConfig.downloadBaseUrl,
|
|
753
|
+
force: options.forceUpdate
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
} else {
|
|
757
|
+
const metaPath = path3.join(cacheDir, "latest-meta.json");
|
|
758
|
+
if (!shouldCheckRemote && await fileExists(metaPath)) {
|
|
759
|
+
try {
|
|
760
|
+
const meta = await readJsonFile(metaPath);
|
|
761
|
+
if (meta.repo === cliConfig.repo && Date.now() - meta.checkedAt < LATEST_CACHE_TTL_MS) {
|
|
762
|
+
const cachedPath = path3.join(
|
|
763
|
+
cacheDir,
|
|
764
|
+
meta.tag,
|
|
765
|
+
assetSpec.binaryName
|
|
766
|
+
);
|
|
767
|
+
if (await isFile(cachedPath)) {
|
|
768
|
+
const version = await probeBinaryVersion(cachedPath);
|
|
769
|
+
return {
|
|
770
|
+
binPath: cachedPath,
|
|
771
|
+
tag: meta.tag,
|
|
772
|
+
version,
|
|
773
|
+
source: "cache",
|
|
774
|
+
cacheDir
|
|
775
|
+
};
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
} catch {
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
if (cliConfig.autoDownload || options.forceUpdate) {
|
|
782
|
+
try {
|
|
783
|
+
return await downloadCliRelease({
|
|
784
|
+
repo: cliConfig.repo,
|
|
785
|
+
version: "latest",
|
|
786
|
+
cacheDir,
|
|
787
|
+
downloadBaseUrl: cliConfig.downloadBaseUrl,
|
|
788
|
+
force: options.forceUpdate
|
|
789
|
+
});
|
|
790
|
+
} catch (err) {
|
|
791
|
+
const cachedVersions = await listCachedVersions(cacheDir);
|
|
792
|
+
const latestCached = cachedVersions[cachedVersions.length - 1];
|
|
793
|
+
if (latestCached && !options.forceUpdate) {
|
|
794
|
+
const fallbackBin = path3.join(
|
|
795
|
+
cacheDir,
|
|
796
|
+
latestCached,
|
|
797
|
+
assetSpec.binaryName
|
|
798
|
+
);
|
|
799
|
+
const version = await probeBinaryVersion(fallbackBin);
|
|
800
|
+
return {
|
|
801
|
+
binPath: fallbackBin,
|
|
802
|
+
tag: latestCached,
|
|
803
|
+
version,
|
|
804
|
+
source: "cache",
|
|
805
|
+
cacheDir
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
throw err;
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
const pathBin = await findBinaryOnPath(assetSpec.binaryName);
|
|
813
|
+
if (pathBin) {
|
|
814
|
+
const version = await probeBinaryVersion(pathBin);
|
|
815
|
+
return { binPath: pathBin, tag: version, version, source: "path", cacheDir };
|
|
816
|
+
}
|
|
817
|
+
throw new Error(
|
|
818
|
+
`Unable to locate ${assetSpec.binaryName}. Run "imgopt-node cli update" or enable cli.autoDownload.`
|
|
819
|
+
);
|
|
820
|
+
}
|
|
821
|
+
async function getCliStatus(cliConfig, checkRemote = true) {
|
|
822
|
+
const repo = cliConfig?.repo ?? DEFAULT_CLI_REPO;
|
|
823
|
+
const configuredVersion = cliConfig?.version ?? "latest";
|
|
824
|
+
const cacheDir = resolveCacheDir(cliConfig);
|
|
825
|
+
const cachedVersions = await listCachedVersions(cacheDir);
|
|
826
|
+
const assetSpec = resolveReleaseAsset();
|
|
827
|
+
let resolvedBinPath = null;
|
|
828
|
+
let installedTag = null;
|
|
829
|
+
let installedVersion = null;
|
|
830
|
+
let source = "missing";
|
|
831
|
+
if (process.env.IMGOPT_BIN && await isFile(process.env.IMGOPT_BIN)) {
|
|
832
|
+
resolvedBinPath = path3.resolve(process.env.IMGOPT_BIN);
|
|
833
|
+
installedVersion = await probeBinaryVersion(resolvedBinPath);
|
|
834
|
+
installedTag = installedVersion;
|
|
835
|
+
source = "env";
|
|
836
|
+
} else if (cliConfig?.binPath && await isFile(cliConfig.binPath)) {
|
|
837
|
+
resolvedBinPath = path3.resolve(expandHome(cliConfig.binPath));
|
|
838
|
+
installedVersion = await probeBinaryVersion(resolvedBinPath);
|
|
839
|
+
installedTag = installedVersion;
|
|
840
|
+
source = "config";
|
|
841
|
+
} else if (cachedVersions.length > 0) {
|
|
842
|
+
const picked = configuredVersion !== "latest" && cachedVersions.includes(
|
|
843
|
+
configuredVersion.startsWith("v") ? configuredVersion : `v${configuredVersion}`
|
|
844
|
+
) ? configuredVersion.startsWith("v") ? configuredVersion : `v${configuredVersion}` : cachedVersions[cachedVersions.length - 1];
|
|
845
|
+
resolvedBinPath = path3.join(cacheDir, picked, assetSpec.binaryName);
|
|
846
|
+
installedVersion = await probeBinaryVersion(resolvedBinPath);
|
|
847
|
+
installedTag = picked;
|
|
848
|
+
source = "cache";
|
|
849
|
+
} else {
|
|
850
|
+
const pathBin = await findBinaryOnPath(assetSpec.binaryName);
|
|
851
|
+
if (pathBin) {
|
|
852
|
+
resolvedBinPath = pathBin;
|
|
853
|
+
installedVersion = await probeBinaryVersion(pathBin);
|
|
854
|
+
installedTag = installedVersion;
|
|
855
|
+
source = "path";
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
let latestRemoteVersion = null;
|
|
859
|
+
if (checkRemote) {
|
|
860
|
+
try {
|
|
861
|
+
latestRemoteVersion = await fetchLatestReleaseTag(repo);
|
|
862
|
+
} catch {
|
|
863
|
+
latestRemoteVersion = null;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
const comparedInstalled = installedTag ?? installedVersion;
|
|
867
|
+
const updateAvailable = Boolean(
|
|
868
|
+
latestRemoteVersion && comparedInstalled && latestRemoteVersion !== comparedInstalled
|
|
869
|
+
);
|
|
870
|
+
return {
|
|
871
|
+
repo,
|
|
872
|
+
configuredVersion,
|
|
873
|
+
resolvedBinPath,
|
|
874
|
+
installedTag,
|
|
875
|
+
installedVersion,
|
|
876
|
+
source,
|
|
877
|
+
latestRemoteVersion,
|
|
878
|
+
updateAvailable,
|
|
879
|
+
cacheDir,
|
|
880
|
+
cachedVersions
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
// src/config/loader.ts
|
|
885
|
+
import crypto3 from "crypto";
|
|
886
|
+
import path4 from "path";
|
|
887
|
+
import picomatch from "picomatch";
|
|
888
|
+
var VALID_PRESETS = /* @__PURE__ */ new Set(["balanced", "maximum", "aggressive"]);
|
|
889
|
+
var VALID_FORMATS = /* @__PURE__ */ new Set([
|
|
890
|
+
"preserve",
|
|
891
|
+
"webp",
|
|
892
|
+
"avif",
|
|
893
|
+
"auto",
|
|
894
|
+
"jpeg",
|
|
895
|
+
"png",
|
|
896
|
+
"gif",
|
|
897
|
+
"force-webp",
|
|
898
|
+
"force-avif"
|
|
899
|
+
]);
|
|
900
|
+
var VALID_RESIZE_MODES = /* @__PURE__ */ new Set([
|
|
901
|
+
"scale-down",
|
|
902
|
+
"contain",
|
|
903
|
+
"cover",
|
|
904
|
+
"exact"
|
|
905
|
+
]);
|
|
906
|
+
var VALID_BACKUP_STRATEGIES = /* @__PURE__ */ new Set([
|
|
907
|
+
"preserve-first",
|
|
908
|
+
"keep-initial"
|
|
909
|
+
]);
|
|
910
|
+
async function findConfigPath(projectRoot, explicitPath) {
|
|
911
|
+
if (explicitPath) {
|
|
912
|
+
const resolved = path4.resolve(projectRoot, explicitPath);
|
|
913
|
+
if (!await fileExists(resolved)) {
|
|
914
|
+
throw new Error(`Configuration file not found: ${resolved}`);
|
|
915
|
+
}
|
|
916
|
+
return resolved;
|
|
917
|
+
}
|
|
918
|
+
for (const candidate of CONFIG_FILENAMES) {
|
|
919
|
+
const resolved = path4.join(projectRoot, candidate);
|
|
920
|
+
if (await fileExists(resolved)) {
|
|
921
|
+
return resolved;
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
throw new Error(
|
|
925
|
+
`No configuration file found in ${projectRoot} (expected ${DEFAULT_CONFIG_FILENAME}). Run "imgopt-node init" first.`
|
|
926
|
+
);
|
|
927
|
+
}
|
|
928
|
+
function validateOptimizationFields(opt, label) {
|
|
929
|
+
if (opt.preset !== void 0 && !VALID_PRESETS.has(opt.preset)) {
|
|
930
|
+
throw new Error(
|
|
931
|
+
`Invalid ${label}.preset "${String(opt.preset)}"; expected balanced | maximum | aggressive`
|
|
932
|
+
);
|
|
933
|
+
}
|
|
934
|
+
if (opt.quality !== void 0 && (typeof opt.quality !== "number" || !Number.isFinite(opt.quality) || opt.quality < 0 || opt.quality > 1)) {
|
|
935
|
+
throw new Error(
|
|
936
|
+
`Invalid ${label}.quality "${String(opt.quality)}"; expected a number between 0.0 and 1.0`
|
|
937
|
+
);
|
|
938
|
+
}
|
|
939
|
+
if (opt.effort !== void 0 && (typeof opt.effort !== "number" || !Number.isInteger(opt.effort) || opt.effort < 1 || opt.effort > 6)) {
|
|
940
|
+
throw new Error(
|
|
941
|
+
`Invalid ${label}.effort "${String(opt.effort)}"; expected an integer between 1 and 6`
|
|
942
|
+
);
|
|
943
|
+
}
|
|
944
|
+
if (opt.format !== void 0 && !VALID_FORMATS.has(opt.format)) {
|
|
945
|
+
throw new Error(
|
|
946
|
+
`Invalid ${label}.format "${String(opt.format)}"; unsupported format policy`
|
|
947
|
+
);
|
|
948
|
+
}
|
|
949
|
+
if (opt.resize !== void 0) {
|
|
950
|
+
const { maxWidth, maxHeight, mode } = opt.resize;
|
|
951
|
+
if (maxWidth !== void 0 && (!Number.isInteger(maxWidth) || maxWidth <= 0)) {
|
|
952
|
+
throw new Error(
|
|
953
|
+
`Invalid ${label}.resize.maxWidth "${String(maxWidth)}"; expected positive integer`
|
|
954
|
+
);
|
|
955
|
+
}
|
|
956
|
+
if (maxHeight !== void 0 && (!Number.isInteger(maxHeight) || maxHeight <= 0)) {
|
|
957
|
+
throw new Error(
|
|
958
|
+
`Invalid ${label}.resize.maxHeight "${String(maxHeight)}"; expected positive integer`
|
|
959
|
+
);
|
|
960
|
+
}
|
|
961
|
+
if (mode !== void 0 && !VALID_RESIZE_MODES.has(mode)) {
|
|
962
|
+
throw new Error(
|
|
963
|
+
`Invalid ${label}.resize.mode "${String(mode)}"; expected scale-down | contain | cover | exact`
|
|
964
|
+
);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
if (opt.minBytes !== void 0 && (typeof opt.minBytes !== "number" || opt.minBytes < 0)) {
|
|
968
|
+
throw new Error(
|
|
969
|
+
`Invalid ${label}.minBytes "${String(opt.minBytes)}"; expected >= 0`
|
|
970
|
+
);
|
|
971
|
+
}
|
|
972
|
+
if (opt.minSavingsPercent !== void 0 && (typeof opt.minSavingsPercent !== "number" || opt.minSavingsPercent < 0 || opt.minSavingsPercent > 100)) {
|
|
973
|
+
throw new Error(
|
|
974
|
+
`Invalid ${label}.minSavingsPercent "${String(opt.minSavingsPercent)}"; expected 0..100`
|
|
975
|
+
);
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
function normalizeConfig(raw, projectRoot) {
|
|
979
|
+
if (!raw || typeof raw !== "object") {
|
|
980
|
+
throw new Error("Configuration must be a JSON object");
|
|
981
|
+
}
|
|
982
|
+
if (raw.version !== void 0 && raw.version !== 1) {
|
|
983
|
+
throw new Error(`Unsupported configuration version: ${String(raw.version)}`);
|
|
984
|
+
}
|
|
985
|
+
if (!Array.isArray(raw.targets) || raw.targets.length === 0) {
|
|
986
|
+
throw new Error(
|
|
987
|
+
'Configuration must include at least one directory in "targets"'
|
|
988
|
+
);
|
|
989
|
+
}
|
|
990
|
+
const normalizedTargets = raw.targets.map((target, index) => {
|
|
991
|
+
if (!target || typeof target.dir !== "string" || !target.dir.trim()) {
|
|
992
|
+
throw new Error(`targets[${index}].dir must be a non-empty string`);
|
|
993
|
+
}
|
|
994
|
+
const relDir = normalizeRelativePosix(projectRoot, target.dir.trim());
|
|
995
|
+
return {
|
|
996
|
+
dir: relDir || ".",
|
|
997
|
+
include: Array.isArray(target.include) && target.include.length > 0 ? target.include : [...DEFAULT_INCLUDE_GLOBS],
|
|
998
|
+
exclude: Array.isArray(target.exclude) ? target.exclude : [...DEFAULT_EXCLUDE_GLOBS]
|
|
999
|
+
};
|
|
1000
|
+
});
|
|
1001
|
+
const backupRaw = raw.backup ?? {};
|
|
1002
|
+
const backupDirRaw = backupRaw.dir !== void 0 ? backupRaw.dir.trim() : DEFAULT_BACKUP_CONFIG.dir;
|
|
1003
|
+
if (!backupDirRaw) {
|
|
1004
|
+
throw new Error("backup.dir must not be empty");
|
|
1005
|
+
}
|
|
1006
|
+
const normalizedBackupDir = normalizeRelativePosix(projectRoot, backupDirRaw);
|
|
1007
|
+
if (!normalizedBackupDir || normalizedBackupDir === ".") {
|
|
1008
|
+
throw new Error("backup.dir must not be the project root directory");
|
|
1009
|
+
}
|
|
1010
|
+
const backupStrategy = backupRaw.strategy ?? DEFAULT_BACKUP_CONFIG.strategy;
|
|
1011
|
+
if (!VALID_BACKUP_STRATEGIES.has(backupStrategy)) {
|
|
1012
|
+
throw new Error(
|
|
1013
|
+
`Invalid backup.strategy "${String(backupStrategy)}"; expected preserve-first | keep-initial`
|
|
1014
|
+
);
|
|
1015
|
+
}
|
|
1016
|
+
const manifestRaw = raw.manifest !== void 0 ? raw.manifest.trim() : DEFAULT_MANIFEST_PATH;
|
|
1017
|
+
if (!manifestRaw) {
|
|
1018
|
+
throw new Error("manifest path must not be empty");
|
|
1019
|
+
}
|
|
1020
|
+
const normalizedManifest = normalizeRelativePosix(projectRoot, manifestRaw);
|
|
1021
|
+
const userOpt = raw.optimization;
|
|
1022
|
+
if (userOpt) {
|
|
1023
|
+
validateOptimizationFields(userOpt, "optimization");
|
|
1024
|
+
}
|
|
1025
|
+
let optimization;
|
|
1026
|
+
if (!userOpt) {
|
|
1027
|
+
optimization = { ...DEFAULT_OPTIMIZATION_OPTIONS };
|
|
1028
|
+
} else {
|
|
1029
|
+
optimization = {
|
|
1030
|
+
preset: userOpt.preset ?? DEFAULT_OPTIMIZATION_OPTIONS.preset,
|
|
1031
|
+
quality: userOpt.quality !== void 0 ? userOpt.quality : userOpt.preset && userOpt.preset !== "balanced" ? void 0 : DEFAULT_OPTIMIZATION_OPTIONS.quality,
|
|
1032
|
+
effort: userOpt.effort !== void 0 ? userOpt.effort : userOpt.preset && userOpt.preset !== "balanced" ? void 0 : DEFAULT_OPTIMIZATION_OPTIONS.effort,
|
|
1033
|
+
format: userOpt.format ?? DEFAULT_OPTIMIZATION_OPTIONS.format,
|
|
1034
|
+
preserveMetadata: userOpt.preserveMetadata ?? DEFAULT_OPTIMIZATION_OPTIONS.preserveMetadata,
|
|
1035
|
+
preserveIcc: userOpt.preserveIcc ?? DEFAULT_OPTIMIZATION_OPTIONS.preserveIcc,
|
|
1036
|
+
convertToSrgb: userOpt.convertToSrgb ?? DEFAULT_OPTIMIZATION_OPTIONS.convertToSrgb,
|
|
1037
|
+
resize: userOpt.resize ? {
|
|
1038
|
+
maxWidth: userOpt.resize.maxWidth,
|
|
1039
|
+
maxHeight: userOpt.resize.maxHeight,
|
|
1040
|
+
mode: userOpt.resize.mode ?? "scale-down"
|
|
1041
|
+
} : void 0,
|
|
1042
|
+
concurrency: userOpt.concurrency,
|
|
1043
|
+
minBytes: userOpt.minBytes ?? DEFAULT_OPTIMIZATION_OPTIONS.minBytes,
|
|
1044
|
+
minSavingsPercent: userOpt.minSavingsPercent ?? DEFAULT_OPTIMIZATION_OPTIONS.minSavingsPercent,
|
|
1045
|
+
removeSourceOnFormatChange: userOpt.removeSourceOnFormatChange ?? DEFAULT_OPTIMIZATION_OPTIONS.removeSourceOnFormatChange
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
const rules = Array.isArray(raw.rules) ? raw.rules.map((rule, idx) => {
|
|
1049
|
+
if (!rule || typeof rule.match !== "string" && !Array.isArray(rule.match) || !rule.optimization) {
|
|
1050
|
+
throw new Error(`rules[${idx}] must define "match" and "optimization"`);
|
|
1051
|
+
}
|
|
1052
|
+
validateOptimizationFields(rule.optimization, `rules[${idx}].optimization`);
|
|
1053
|
+
return rule;
|
|
1054
|
+
}) : [];
|
|
1055
|
+
return {
|
|
1056
|
+
$schema: raw.$schema,
|
|
1057
|
+
version: 1,
|
|
1058
|
+
cli: {
|
|
1059
|
+
...DEFAULT_CLI_CONFIG,
|
|
1060
|
+
...raw.cli ?? {}
|
|
1061
|
+
},
|
|
1062
|
+
targets: normalizedTargets,
|
|
1063
|
+
backup: {
|
|
1064
|
+
enabled: backupRaw.enabled ?? DEFAULT_BACKUP_CONFIG.enabled,
|
|
1065
|
+
dir: normalizedBackupDir,
|
|
1066
|
+
strategy: backupStrategy
|
|
1067
|
+
},
|
|
1068
|
+
manifest: normalizedManifest,
|
|
1069
|
+
optimization,
|
|
1070
|
+
rules,
|
|
1071
|
+
budgets: raw.budgets
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
async function loadConfig(projectRoot = process.cwd(), explicitConfigPath) {
|
|
1075
|
+
const resolvedRoot = path4.resolve(projectRoot);
|
|
1076
|
+
const configPath = await findConfigPath(resolvedRoot, explicitConfigPath);
|
|
1077
|
+
const raw = await readJsonFile(configPath);
|
|
1078
|
+
const config = normalizeConfig(raw, resolvedRoot);
|
|
1079
|
+
return {
|
|
1080
|
+
configPath,
|
|
1081
|
+
projectRoot: resolvedRoot,
|
|
1082
|
+
config
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
async function saveConfig(configPath, config) {
|
|
1086
|
+
await writeJsonAtomic(configPath, config);
|
|
1087
|
+
}
|
|
1088
|
+
function resolveEffectiveOptimization(config, relPosixPath) {
|
|
1089
|
+
const normalizedPath = toPosixPath(relPosixPath).replace(/^\.\//, "");
|
|
1090
|
+
let effective = {
|
|
1091
|
+
...config.optimization,
|
|
1092
|
+
resize: config.optimization.resize ? { ...config.optimization.resize } : void 0
|
|
1093
|
+
};
|
|
1094
|
+
for (const rule of config.rules) {
|
|
1095
|
+
const patterns = Array.isArray(rule.match) ? rule.match : [rule.match];
|
|
1096
|
+
const isMatch = picomatch.isMatch(normalizedPath, patterns, {
|
|
1097
|
+
dot: true,
|
|
1098
|
+
nocase: true
|
|
1099
|
+
});
|
|
1100
|
+
if (!isMatch) continue;
|
|
1101
|
+
const patch = rule.optimization;
|
|
1102
|
+
const presetChanged = patch.preset !== void 0 && patch.preset !== effective.preset;
|
|
1103
|
+
effective = {
|
|
1104
|
+
...effective,
|
|
1105
|
+
...patch,
|
|
1106
|
+
quality: patch.quality !== void 0 ? patch.quality : presetChanged ? void 0 : effective.quality,
|
|
1107
|
+
effort: patch.effort !== void 0 ? patch.effort : presetChanged ? void 0 : effective.effort,
|
|
1108
|
+
resize: patch.resize ? {
|
|
1109
|
+
...effective.resize ?? {},
|
|
1110
|
+
...patch.resize,
|
|
1111
|
+
mode: patch.resize.mode ?? effective.resize?.mode ?? "scale-down"
|
|
1112
|
+
} : effective.resize
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
return effective;
|
|
1116
|
+
}
|
|
1117
|
+
function computeOptimizationConfigHash(opt) {
|
|
1118
|
+
const canonical = {
|
|
1119
|
+
preset: opt.preset,
|
|
1120
|
+
quality: opt.quality ?? null,
|
|
1121
|
+
effort: opt.effort ?? null,
|
|
1122
|
+
format: opt.format,
|
|
1123
|
+
preserveMetadata: opt.preserveMetadata,
|
|
1124
|
+
preserveIcc: opt.preserveIcc,
|
|
1125
|
+
convertToSrgb: opt.convertToSrgb,
|
|
1126
|
+
resize: opt.resize ? {
|
|
1127
|
+
maxWidth: opt.resize.maxWidth ?? null,
|
|
1128
|
+
maxHeight: opt.resize.maxHeight ?? null,
|
|
1129
|
+
mode: opt.resize.mode ?? "scale-down"
|
|
1130
|
+
} : null,
|
|
1131
|
+
minBytes: opt.minBytes,
|
|
1132
|
+
minSavingsPercent: opt.minSavingsPercent,
|
|
1133
|
+
removeSourceOnFormatChange: opt.removeSourceOnFormatChange
|
|
1134
|
+
};
|
|
1135
|
+
return crypto3.createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// src/core/backup.ts
|
|
1139
|
+
import fs4 from "fs/promises";
|
|
1140
|
+
import path5 from "path";
|
|
1141
|
+
|
|
1142
|
+
// src/core/hash.ts
|
|
1143
|
+
import crypto4 from "crypto";
|
|
1144
|
+
import fs3 from "fs";
|
|
1145
|
+
async function sha256File(filePath) {
|
|
1146
|
+
return new Promise((resolve, reject) => {
|
|
1147
|
+
const hash = crypto4.createHash("sha256");
|
|
1148
|
+
const stream = fs3.createReadStream(filePath);
|
|
1149
|
+
stream.on("data", (chunk) => hash.update(chunk));
|
|
1150
|
+
stream.on("error", reject);
|
|
1151
|
+
stream.on("end", () => resolve(hash.digest("hex")));
|
|
1152
|
+
});
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
// src/core/backup.ts
|
|
1156
|
+
function getBackupRelPath(backupDir, sourceRelPath) {
|
|
1157
|
+
const cleanDir = toPosixPath(backupDir).replace(/\/+$/, "");
|
|
1158
|
+
const cleanRel = toPosixPath(sourceRelPath).replace(/^\/+/, "");
|
|
1159
|
+
return `${cleanDir}/${cleanRel}`;
|
|
1160
|
+
}
|
|
1161
|
+
async function ensureOriginalBackup(options) {
|
|
1162
|
+
const {
|
|
1163
|
+
projectRoot,
|
|
1164
|
+
backupConfig,
|
|
1165
|
+
sourceRelPath,
|
|
1166
|
+
sourceAbsPath,
|
|
1167
|
+
isNewSourceVersion
|
|
1168
|
+
} = options;
|
|
1169
|
+
if (!backupConfig.enabled) {
|
|
1170
|
+
return void 0;
|
|
1171
|
+
}
|
|
1172
|
+
const backupRelPath = getBackupRelPath(backupConfig.dir, sourceRelPath);
|
|
1173
|
+
const backupAbsPath = resolveInsideRoot(projectRoot, backupRelPath);
|
|
1174
|
+
const exists = await fileExists(backupAbsPath);
|
|
1175
|
+
if (!exists) {
|
|
1176
|
+
await atomicCopyFile(sourceAbsPath, backupAbsPath);
|
|
1177
|
+
return backupRelPath;
|
|
1178
|
+
}
|
|
1179
|
+
if (backupConfig.strategy === "preserve-first" && isNewSourceVersion) {
|
|
1180
|
+
await atomicCopyFile(sourceAbsPath, backupAbsPath);
|
|
1181
|
+
}
|
|
1182
|
+
return backupRelPath;
|
|
1183
|
+
}
|
|
1184
|
+
async function hasValidBackup(options) {
|
|
1185
|
+
if (!options.backupRelPath) {
|
|
1186
|
+
return { exists: false };
|
|
1187
|
+
}
|
|
1188
|
+
const absPath = resolveInsideRoot(options.projectRoot, options.backupRelPath);
|
|
1189
|
+
if (!await isFile(absPath)) {
|
|
1190
|
+
return { exists: false };
|
|
1191
|
+
}
|
|
1192
|
+
if (options.expectedSha256) {
|
|
1193
|
+
const actual = await sha256File(absPath);
|
|
1194
|
+
if (actual !== options.expectedSha256) {
|
|
1195
|
+
return { exists: false };
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
return { exists: true, absPath };
|
|
1199
|
+
}
|
|
1200
|
+
async function listBackupFiles(projectRoot, backupDir) {
|
|
1201
|
+
const backupRootAbs = resolveInsideRoot(projectRoot, backupDir);
|
|
1202
|
+
const results = [];
|
|
1203
|
+
async function walk(current) {
|
|
1204
|
+
let entries;
|
|
1205
|
+
try {
|
|
1206
|
+
entries = await fs4.readdir(current, { withFileTypes: true });
|
|
1207
|
+
} catch {
|
|
1208
|
+
return;
|
|
1209
|
+
}
|
|
1210
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
1211
|
+
for (const entry of entries) {
|
|
1212
|
+
if (entry.isSymbolicLink()) continue;
|
|
1213
|
+
const absPath = path5.join(current, entry.name);
|
|
1214
|
+
if (entry.isDirectory()) {
|
|
1215
|
+
await walk(absPath);
|
|
1216
|
+
} else if (entry.isFile()) {
|
|
1217
|
+
const sourceRelPath = toPosixPath(path5.relative(backupRootAbs, absPath));
|
|
1218
|
+
const backupRelPath = getBackupRelPath(backupDir, sourceRelPath);
|
|
1219
|
+
results.push({ backupRelPath, sourceRelPath, absPath });
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
await walk(backupRootAbs);
|
|
1224
|
+
return results;
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
// src/core/manifest.ts
|
|
1228
|
+
import path6 from "path";
|
|
1229
|
+
function createEmptyManifest() {
|
|
1230
|
+
return {
|
|
1231
|
+
version: 1,
|
|
1232
|
+
entries: {}
|
|
1233
|
+
};
|
|
1234
|
+
}
|
|
1235
|
+
async function loadManifest(projectRoot, manifestRelPath) {
|
|
1236
|
+
const absPath = resolveInsideRoot(projectRoot, manifestRelPath);
|
|
1237
|
+
if (!await fileExists(absPath)) {
|
|
1238
|
+
return createEmptyManifest();
|
|
1239
|
+
}
|
|
1240
|
+
const parsed = await readJsonFile(absPath);
|
|
1241
|
+
if (!parsed || typeof parsed !== "object" || parsed.version !== 1 || !parsed.entries) {
|
|
1242
|
+
throw new Error(`Invalid manifest schema in ${absPath}`);
|
|
1243
|
+
}
|
|
1244
|
+
return parsed;
|
|
1245
|
+
}
|
|
1246
|
+
async function saveManifest(projectRoot, manifestRelPath, manifest) {
|
|
1247
|
+
const absPath = resolveInsideRoot(projectRoot, manifestRelPath);
|
|
1248
|
+
const sortedEntries = {};
|
|
1249
|
+
for (const key of Object.keys(manifest.entries).sort()) {
|
|
1250
|
+
sortedEntries[key] = manifest.entries[key];
|
|
1251
|
+
}
|
|
1252
|
+
const ordered = {
|
|
1253
|
+
version: 1,
|
|
1254
|
+
entries: sortedEntries
|
|
1255
|
+
};
|
|
1256
|
+
await writeJsonAtomic(absPath, ordered);
|
|
1257
|
+
return path6.relative(projectRoot, absPath);
|
|
1258
|
+
}
|
|
1259
|
+
function buildManifestIndex(manifest) {
|
|
1260
|
+
const bySourcePath = /* @__PURE__ */ new Map();
|
|
1261
|
+
const byOutputPath = /* @__PURE__ */ new Map();
|
|
1262
|
+
for (const entry of Object.values(manifest.entries)) {
|
|
1263
|
+
bySourcePath.set(entry.sourcePath, entry);
|
|
1264
|
+
byOutputPath.set(entry.outputPath, entry);
|
|
1265
|
+
}
|
|
1266
|
+
return { bySourcePath, byOutputPath };
|
|
1267
|
+
}
|
|
1268
|
+
function findEntryForDiskPath(index, relPath) {
|
|
1269
|
+
return index.bySourcePath.get(relPath) ?? index.byOutputPath.get(relPath);
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
// src/core/scanner.ts
|
|
1273
|
+
import fs5 from "fs/promises";
|
|
1274
|
+
import path7 from "path";
|
|
1275
|
+
import picomatch2 from "picomatch";
|
|
1276
|
+
function isSameOrInside(candidatePosix, parentPosix) {
|
|
1277
|
+
const cleanParent = parentPosix.replace(/\/+$/, "");
|
|
1278
|
+
if (!cleanParent || cleanParent === ".") return false;
|
|
1279
|
+
return candidatePosix === cleanParent || candidatePosix.startsWith(`${cleanParent}/`);
|
|
1280
|
+
}
|
|
1281
|
+
async function scanProjectImages(projectRoot, config, onlyRelPaths) {
|
|
1282
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1283
|
+
const backupDirPosix = toPosixPath(config.backup.dir).replace(/^\.\//, "");
|
|
1284
|
+
const manifestPosix = toPosixPath(config.manifest).replace(/^\.\//, "");
|
|
1285
|
+
for (const target of config.targets) {
|
|
1286
|
+
const targetDirAbs = resolveInsideRoot(projectRoot, target.dir);
|
|
1287
|
+
if (!await isDirectory(targetDirAbs)) {
|
|
1288
|
+
continue;
|
|
1289
|
+
}
|
|
1290
|
+
const includePatterns = target.include && target.include.length > 0 ? target.include : DEFAULT_INCLUDE_GLOBS;
|
|
1291
|
+
const excludePatterns = target.exclude !== void 0 ? target.exclude : DEFAULT_EXCLUDE_GLOBS;
|
|
1292
|
+
const isIncluded = picomatch2(includePatterns, { dot: false, nocase: true });
|
|
1293
|
+
const isExcluded = excludePatterns.length > 0 ? picomatch2(excludePatterns, { dot: true, nocase: true }) : () => false;
|
|
1294
|
+
async function walk(currentAbs) {
|
|
1295
|
+
let entries;
|
|
1296
|
+
try {
|
|
1297
|
+
entries = await fs5.readdir(currentAbs, { withFileTypes: true });
|
|
1298
|
+
} catch {
|
|
1299
|
+
return;
|
|
1300
|
+
}
|
|
1301
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
1302
|
+
for (const entry of entries) {
|
|
1303
|
+
if (entry.isSymbolicLink()) continue;
|
|
1304
|
+
if (entry.name.startsWith(".") || IGNORED_DIR_NAMES.has(entry.name)) {
|
|
1305
|
+
continue;
|
|
1306
|
+
}
|
|
1307
|
+
const absPath = path7.join(currentAbs, entry.name);
|
|
1308
|
+
const relToProject = toPosixPath(path7.relative(projectRoot, absPath));
|
|
1309
|
+
if (isSameOrInside(relToProject, backupDirPosix) || relToProject === manifestPosix) {
|
|
1310
|
+
continue;
|
|
1311
|
+
}
|
|
1312
|
+
if (entry.isDirectory()) {
|
|
1313
|
+
await walk(absPath);
|
|
1314
|
+
continue;
|
|
1315
|
+
}
|
|
1316
|
+
if (!entry.isFile()) continue;
|
|
1317
|
+
const ext = path7.extname(entry.name).toLowerCase();
|
|
1318
|
+
if (!SUPPORTED_IMAGE_EXTENSIONS.has(ext)) {
|
|
1319
|
+
continue;
|
|
1320
|
+
}
|
|
1321
|
+
const relToTarget = toPosixPath(path7.relative(targetDirAbs, absPath));
|
|
1322
|
+
if (!isIncluded(relToTarget) || isExcluded(relToTarget)) {
|
|
1323
|
+
continue;
|
|
1324
|
+
}
|
|
1325
|
+
if (onlyRelPaths && !onlyRelPaths.has(relToProject)) {
|
|
1326
|
+
continue;
|
|
1327
|
+
}
|
|
1328
|
+
if (!seen.has(relToProject)) {
|
|
1329
|
+
const stat = await fs5.stat(absPath);
|
|
1330
|
+
seen.set(relToProject, {
|
|
1331
|
+
relPath: relToProject,
|
|
1332
|
+
absPath,
|
|
1333
|
+
byteSize: stat.size,
|
|
1334
|
+
targetDir: target.dir
|
|
1335
|
+
});
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
await walk(targetDirAbs);
|
|
1340
|
+
}
|
|
1341
|
+
return [...seen.values()].sort((a, b) => a.relPath.localeCompare(b.relPath));
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
// src/commands/optimize.ts
|
|
1345
|
+
import fs7 from "fs/promises";
|
|
1346
|
+
import path9 from "path";
|
|
1347
|
+
|
|
1348
|
+
// src/core/git.ts
|
|
1349
|
+
import { execFile as execFile2 } from "child_process";
|
|
1350
|
+
import { promisify as promisify2 } from "util";
|
|
1351
|
+
var execFileAsync2 = promisify2(execFile2);
|
|
1352
|
+
async function isGitRepo(projectRoot) {
|
|
1353
|
+
try {
|
|
1354
|
+
await execFileAsync2("git", ["rev-parse", "--is-inside-work-tree"], {
|
|
1355
|
+
cwd: projectRoot
|
|
1356
|
+
});
|
|
1357
|
+
return true;
|
|
1358
|
+
} catch {
|
|
1359
|
+
return false;
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
async function getStagedImagePaths(projectRoot) {
|
|
1363
|
+
const { stdout } = await execFileAsync2(
|
|
1364
|
+
"git",
|
|
1365
|
+
["diff", "--cached", "--name-only", "--diff-filter=ACM", "-z"],
|
|
1366
|
+
{ cwd: projectRoot }
|
|
1367
|
+
);
|
|
1368
|
+
const files = stdout.split("\0").map((p) => p.trim()).filter(Boolean).map((p) => toPosixPath(p));
|
|
1369
|
+
return new Set(files);
|
|
1370
|
+
}
|
|
1371
|
+
async function gitAddFiles(projectRoot, relPaths) {
|
|
1372
|
+
if (relPaths.length === 0) return;
|
|
1373
|
+
const nonIgnored = [];
|
|
1374
|
+
for (const rel of relPaths) {
|
|
1375
|
+
try {
|
|
1376
|
+
await execFileAsync2("git", ["check-ignore", "-q", rel], {
|
|
1377
|
+
cwd: projectRoot
|
|
1378
|
+
});
|
|
1379
|
+
} catch {
|
|
1380
|
+
nonIgnored.push(rel);
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
if (nonIgnored.length > 0) {
|
|
1384
|
+
await execFileAsync2("git", ["add", "--", ...nonIgnored], {
|
|
1385
|
+
cwd: projectRoot
|
|
1386
|
+
});
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
// src/core/runner.ts
|
|
1391
|
+
import { execFile as execFile3 } from "child_process";
|
|
1392
|
+
import crypto5 from "crypto";
|
|
1393
|
+
import fs6 from "fs/promises";
|
|
1394
|
+
import os2 from "os";
|
|
1395
|
+
import path8 from "path";
|
|
1396
|
+
import { promisify as promisify3 } from "util";
|
|
1397
|
+
var execFileAsync3 = promisify3(execFile3);
|
|
1398
|
+
function buildOptimizeCliArgs(inputDir, outputDir, reportJsonPath, opt) {
|
|
1399
|
+
const args = [
|
|
1400
|
+
"optimize",
|
|
1401
|
+
inputDir,
|
|
1402
|
+
"--output",
|
|
1403
|
+
outputDir,
|
|
1404
|
+
"--format",
|
|
1405
|
+
opt.format,
|
|
1406
|
+
"--preset",
|
|
1407
|
+
opt.preset,
|
|
1408
|
+
"--json",
|
|
1409
|
+
reportJsonPath,
|
|
1410
|
+
"--quiet"
|
|
1411
|
+
];
|
|
1412
|
+
if (opt.quality !== void 0) {
|
|
1413
|
+
args.push("--quality", String(opt.quality));
|
|
1414
|
+
}
|
|
1415
|
+
if (opt.effort !== void 0) {
|
|
1416
|
+
args.push("--effort", String(opt.effort));
|
|
1417
|
+
}
|
|
1418
|
+
if (opt.preserveMetadata) {
|
|
1419
|
+
args.push("--preserve-metadata");
|
|
1420
|
+
} else if (opt.preserveIcc) {
|
|
1421
|
+
args.push("--preserve-icc");
|
|
1422
|
+
}
|
|
1423
|
+
if (!opt.convertToSrgb) {
|
|
1424
|
+
args.push("--no-srgb-convert");
|
|
1425
|
+
}
|
|
1426
|
+
if (opt.resize) {
|
|
1427
|
+
if (opt.resize.maxWidth !== void 0) {
|
|
1428
|
+
args.push("--resize-width", String(opt.resize.maxWidth));
|
|
1429
|
+
}
|
|
1430
|
+
if (opt.resize.maxHeight !== void 0) {
|
|
1431
|
+
args.push("--resize-height", String(opt.resize.maxHeight));
|
|
1432
|
+
}
|
|
1433
|
+
if (opt.resize.mode) {
|
|
1434
|
+
args.push("--resize-mode", opt.resize.mode);
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
if (opt.concurrency !== void 0) {
|
|
1438
|
+
args.push("--concurrency", String(opt.concurrency));
|
|
1439
|
+
}
|
|
1440
|
+
return args;
|
|
1441
|
+
}
|
|
1442
|
+
function formatToExtension(format, fallbackExt) {
|
|
1443
|
+
switch (format.toLowerCase()) {
|
|
1444
|
+
case "jpeg":
|
|
1445
|
+
case "jpg":
|
|
1446
|
+
return ".jpg";
|
|
1447
|
+
case "png":
|
|
1448
|
+
return ".png";
|
|
1449
|
+
case "webp":
|
|
1450
|
+
return ".webp";
|
|
1451
|
+
case "avif":
|
|
1452
|
+
return ".avif";
|
|
1453
|
+
case "gif":
|
|
1454
|
+
return ".gif";
|
|
1455
|
+
default:
|
|
1456
|
+
return fallbackExt;
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
function extensionToCanonicalFormat(ext) {
|
|
1460
|
+
const lower = ext.toLowerCase();
|
|
1461
|
+
if (lower === ".jpg" || lower === ".jpeg") return "jpeg";
|
|
1462
|
+
if (lower === ".png") return "png";
|
|
1463
|
+
if (lower === ".webp") return "webp";
|
|
1464
|
+
if (lower === ".avif") return "avif";
|
|
1465
|
+
if (lower === ".gif") return "gif";
|
|
1466
|
+
return lower.replace(/^\./, "");
|
|
1467
|
+
}
|
|
1468
|
+
function partitionCollisionSafeBatches(tasks, formatPolicy) {
|
|
1469
|
+
if (formatPolicy === "preserve") {
|
|
1470
|
+
return tasks.length > 0 ? [tasks] : [];
|
|
1471
|
+
}
|
|
1472
|
+
const batches = [];
|
|
1473
|
+
const usedStemsPerBatch = [];
|
|
1474
|
+
for (const task of tasks) {
|
|
1475
|
+
const parsed = path8.posix.parse(task.relPath);
|
|
1476
|
+
const stemKey = `${parsed.dir}/${parsed.name}`.toLowerCase();
|
|
1477
|
+
let placed = false;
|
|
1478
|
+
for (let i = 0; i < batches.length; i += 1) {
|
|
1479
|
+
if (!usedStemsPerBatch[i].has(stemKey)) {
|
|
1480
|
+
usedStemsPerBatch[i].add(stemKey);
|
|
1481
|
+
batches[i].push(task);
|
|
1482
|
+
placed = true;
|
|
1483
|
+
break;
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
if (!placed) {
|
|
1487
|
+
batches.push([task]);
|
|
1488
|
+
usedStemsPerBatch.push(/* @__PURE__ */ new Set([stemKey]));
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
return batches;
|
|
1492
|
+
}
|
|
1493
|
+
async function runImgoptBatch(options) {
|
|
1494
|
+
const batches = partitionCollisionSafeBatches(
|
|
1495
|
+
options.tasks,
|
|
1496
|
+
options.optimization.format
|
|
1497
|
+
);
|
|
1498
|
+
for (const batch of batches) {
|
|
1499
|
+
const workDir = await fs6.mkdtemp(
|
|
1500
|
+
path8.join(os2.tmpdir(), `imgopt-node-${crypto5.randomUUID().slice(0, 8)}-`)
|
|
1501
|
+
);
|
|
1502
|
+
const inputDir = path8.join(workDir, "in");
|
|
1503
|
+
const outputDir = path8.join(workDir, "out");
|
|
1504
|
+
const reportPath = path8.join(workDir, "report.json");
|
|
1505
|
+
try {
|
|
1506
|
+
await fs6.mkdir(inputDir, { recursive: true });
|
|
1507
|
+
await fs6.mkdir(outputDir, { recursive: true });
|
|
1508
|
+
const stagedMap = /* @__PURE__ */ new Map();
|
|
1509
|
+
for (const task of batch) {
|
|
1510
|
+
const stagedIn = path8.join(inputDir, task.relPath);
|
|
1511
|
+
await fs6.mkdir(path8.dirname(stagedIn), { recursive: true });
|
|
1512
|
+
await fs6.copyFile(task.sourceFileToOptimize, stagedIn);
|
|
1513
|
+
stagedMap.set(toPosixPath(path8.resolve(stagedIn)), task);
|
|
1514
|
+
}
|
|
1515
|
+
const cliArgs = buildOptimizeCliArgs(
|
|
1516
|
+
inputDir,
|
|
1517
|
+
outputDir,
|
|
1518
|
+
reportPath,
|
|
1519
|
+
options.optimization
|
|
1520
|
+
);
|
|
1521
|
+
let cliError = null;
|
|
1522
|
+
try {
|
|
1523
|
+
await execFileAsync3(options.binPath, cliArgs, {
|
|
1524
|
+
maxBuffer: 20 * 1024 * 1024
|
|
1525
|
+
});
|
|
1526
|
+
} catch (err) {
|
|
1527
|
+
cliError = err instanceof Error ? err : new Error(String(err));
|
|
1528
|
+
}
|
|
1529
|
+
let parsedReport = null;
|
|
1530
|
+
try {
|
|
1531
|
+
const raw = await fs6.readFile(reportPath, "utf8");
|
|
1532
|
+
parsedReport = JSON.parse(raw);
|
|
1533
|
+
} catch {
|
|
1534
|
+
parsedReport = null;
|
|
1535
|
+
}
|
|
1536
|
+
if (!parsedReport) {
|
|
1537
|
+
throw cliError ?? new Error("imgopt did not produce a readable JSON report");
|
|
1538
|
+
}
|
|
1539
|
+
const outcomes = [];
|
|
1540
|
+
const resolvedInputDir = toPosixPath(path8.resolve(inputDir));
|
|
1541
|
+
for (const item of parsedReport.items) {
|
|
1542
|
+
const resolvedItemPath = toPosixPath(path8.resolve(item.path));
|
|
1543
|
+
const task = stagedMap.get(resolvedItemPath) ?? (() => {
|
|
1544
|
+
const relFromIn = toPosixPath(
|
|
1545
|
+
path8.relative(resolvedInputDir, resolvedItemPath)
|
|
1546
|
+
);
|
|
1547
|
+
return batch.find((b) => b.relPath === relFromIn);
|
|
1548
|
+
})();
|
|
1549
|
+
if (!task) continue;
|
|
1550
|
+
if (item.status === "failed" || !item.format) {
|
|
1551
|
+
outcomes.push({
|
|
1552
|
+
relPath: task.relPath,
|
|
1553
|
+
projectOutputRelPath: task.relPath,
|
|
1554
|
+
stagedOutputPath: "",
|
|
1555
|
+
format: item.format ?? "unknown",
|
|
1556
|
+
originalBytes: item.source_bytes,
|
|
1557
|
+
optimizedBytes: item.source_bytes,
|
|
1558
|
+
error: item.error ?? "Optimization failed"
|
|
1559
|
+
});
|
|
1560
|
+
continue;
|
|
1561
|
+
}
|
|
1562
|
+
const origParsed = path8.posix.parse(task.relPath);
|
|
1563
|
+
const imgoptExt = formatToExtension(item.format, origParsed.ext);
|
|
1564
|
+
const relStagedOut = path8.posix.join(
|
|
1565
|
+
origParsed.dir,
|
|
1566
|
+
`${origParsed.name}${imgoptExt}`
|
|
1567
|
+
);
|
|
1568
|
+
const stagedOutAbs = path8.join(outputDir, relStagedOut);
|
|
1569
|
+
const sameFormatAsSource = extensionToCanonicalFormat(origParsed.ext) === item.format.toLowerCase();
|
|
1570
|
+
const projectOutputRelPath = options.optimization.format === "preserve" || sameFormatAsSource ? task.relPath : relStagedOut;
|
|
1571
|
+
outcomes.push({
|
|
1572
|
+
relPath: task.relPath,
|
|
1573
|
+
projectOutputRelPath,
|
|
1574
|
+
stagedOutputPath: stagedOutAbs,
|
|
1575
|
+
format: item.format,
|
|
1576
|
+
originalBytes: item.source_bytes,
|
|
1577
|
+
optimizedBytes: item.optimized_bytes ?? item.source_bytes,
|
|
1578
|
+
qualityScore: item.quality_score
|
|
1579
|
+
});
|
|
1580
|
+
}
|
|
1581
|
+
await options.onEachStagedResult(outcomes);
|
|
1582
|
+
} finally {
|
|
1583
|
+
await fs6.rm(workDir, { recursive: true, force: true }).catch(() => {
|
|
1584
|
+
});
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
async function inspectImagesWithImgopt(binPath, absPaths) {
|
|
1589
|
+
const resultMap = /* @__PURE__ */ new Map();
|
|
1590
|
+
for (const absPath of absPaths) {
|
|
1591
|
+
try {
|
|
1592
|
+
const { stdout } = await execFileAsync3(
|
|
1593
|
+
binPath,
|
|
1594
|
+
["inspect", absPath, "--json"],
|
|
1595
|
+
{ maxBuffer: 5 * 1024 * 1024 }
|
|
1596
|
+
);
|
|
1597
|
+
const parsed = JSON.parse(stdout);
|
|
1598
|
+
if (Array.isArray(parsed)) {
|
|
1599
|
+
for (const entry of parsed) {
|
|
1600
|
+
if (entry?.path) {
|
|
1601
|
+
resultMap.set(path8.resolve(entry.path), entry);
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
} else if (parsed?.path) {
|
|
1605
|
+
resultMap.set(path8.resolve(parsed.path), parsed);
|
|
1606
|
+
}
|
|
1607
|
+
} catch {
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
return resultMap;
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
// src/utils/format.ts
|
|
1614
|
+
function formatBytes(bytes) {
|
|
1615
|
+
if (!Number.isFinite(bytes) || bytes < 0) return "0 B";
|
|
1616
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
1617
|
+
const units = ["KB", "MB", "GB", "TB"];
|
|
1618
|
+
let value = bytes / 1024;
|
|
1619
|
+
let unitIdx = 0;
|
|
1620
|
+
while (value >= 1024 && unitIdx < units.length - 1) {
|
|
1621
|
+
value /= 1024;
|
|
1622
|
+
unitIdx += 1;
|
|
1623
|
+
}
|
|
1624
|
+
return `${value.toFixed(value >= 100 ? 0 : value >= 10 ? 1 : 2)} ${units[unitIdx]}`;
|
|
1625
|
+
}
|
|
1626
|
+
function formatPercent(ratio) {
|
|
1627
|
+
return `${ratio.toFixed(1)}%`;
|
|
1628
|
+
}
|
|
1629
|
+
function computeSavings(originalBytes, optimizedBytes) {
|
|
1630
|
+
const savedBytes = Math.max(0, originalBytes - optimizedBytes);
|
|
1631
|
+
const savedPercent = originalBytes > 0 ? savedBytes / originalBytes * 100 : 0;
|
|
1632
|
+
return { savedBytes, savedPercent };
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
// src/commands/optimize.ts
|
|
1636
|
+
async function optimizeProject(options = {}) {
|
|
1637
|
+
const startMs = Date.now();
|
|
1638
|
+
const dryRun = Boolean(options.dryRun);
|
|
1639
|
+
const { projectRoot, config } = await loadConfig(
|
|
1640
|
+
options.projectRoot,
|
|
1641
|
+
options.configPath
|
|
1642
|
+
);
|
|
1643
|
+
let stagedFilter;
|
|
1644
|
+
if (options.staged) {
|
|
1645
|
+
if (!await isGitRepo(projectRoot)) {
|
|
1646
|
+
throw new Error("--staged requires running inside a Git repository");
|
|
1647
|
+
}
|
|
1648
|
+
stagedFilter = await getStagedImagePaths(projectRoot);
|
|
1649
|
+
if (stagedFilter.size === 0) {
|
|
1650
|
+
return {
|
|
1651
|
+
summary: {
|
|
1652
|
+
totalScanned: 0,
|
|
1653
|
+
optimized: 0,
|
|
1654
|
+
reoptimizedFromBackup: 0,
|
|
1655
|
+
skippedCached: 0,
|
|
1656
|
+
skippedSmall: 0,
|
|
1657
|
+
skippedNoSavings: 0,
|
|
1658
|
+
skippedConfigChangedNoBackup: 0,
|
|
1659
|
+
failed: 0,
|
|
1660
|
+
originalBytes: 0,
|
|
1661
|
+
optimizedBytes: 0,
|
|
1662
|
+
savedBytes: 0,
|
|
1663
|
+
savedPercent: 0,
|
|
1664
|
+
elapsedMs: Date.now() - startMs,
|
|
1665
|
+
dryRun,
|
|
1666
|
+
cliVersion: config.cli.version
|
|
1667
|
+
},
|
|
1668
|
+
items: [],
|
|
1669
|
+
budgetWarnings: []
|
|
1670
|
+
};
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
const scannedFiles = await scanProjectImages(
|
|
1674
|
+
projectRoot,
|
|
1675
|
+
config,
|
|
1676
|
+
stagedFilter
|
|
1677
|
+
);
|
|
1678
|
+
const cliInfo = await ensureCli({
|
|
1679
|
+
cliConfig: config.cli,
|
|
1680
|
+
forceUpdate: options.updateCli,
|
|
1681
|
+
versionOverride: options.cliVersion
|
|
1682
|
+
});
|
|
1683
|
+
if (scannedFiles.length === 0) {
|
|
1684
|
+
return {
|
|
1685
|
+
summary: {
|
|
1686
|
+
totalScanned: 0,
|
|
1687
|
+
optimized: 0,
|
|
1688
|
+
reoptimizedFromBackup: 0,
|
|
1689
|
+
skippedCached: 0,
|
|
1690
|
+
skippedSmall: 0,
|
|
1691
|
+
skippedNoSavings: 0,
|
|
1692
|
+
skippedConfigChangedNoBackup: 0,
|
|
1693
|
+
failed: 0,
|
|
1694
|
+
originalBytes: 0,
|
|
1695
|
+
optimizedBytes: 0,
|
|
1696
|
+
savedBytes: 0,
|
|
1697
|
+
savedPercent: 0,
|
|
1698
|
+
elapsedMs: Date.now() - startMs,
|
|
1699
|
+
dryRun,
|
|
1700
|
+
cliVersion: cliInfo.tag
|
|
1701
|
+
},
|
|
1702
|
+
items: [],
|
|
1703
|
+
budgetWarnings: []
|
|
1704
|
+
};
|
|
1705
|
+
}
|
|
1706
|
+
const manifest = await loadManifest(projectRoot, config.manifest);
|
|
1707
|
+
const index = buildManifestIndex(manifest);
|
|
1708
|
+
const results = [];
|
|
1709
|
+
const pendingByConfigHash = /* @__PURE__ */ new Map();
|
|
1710
|
+
const finalDiskPathsForBudget = [];
|
|
1711
|
+
let manifestDirty = false;
|
|
1712
|
+
const filesToStage = [];
|
|
1713
|
+
for (const file of scannedFiles) {
|
|
1714
|
+
const diskSha256 = await sha256File(file.absPath);
|
|
1715
|
+
const existingEntry = findEntryForDiskPath(index, file.relPath);
|
|
1716
|
+
const effectiveOpt = resolveEffectiveOptimization(config, file.relPath);
|
|
1717
|
+
if (options.concurrency !== void 0) {
|
|
1718
|
+
effectiveOpt.concurrency = options.concurrency;
|
|
1719
|
+
}
|
|
1720
|
+
const configHash = computeOptimizationConfigHash(effectiveOpt);
|
|
1721
|
+
if (existingEntry && existingEntry.optimizedSha256 === diskSha256) {
|
|
1722
|
+
if (!options.force && existingEntry.configHash === configHash) {
|
|
1723
|
+
results.push({
|
|
1724
|
+
sourcePath: existingEntry.sourcePath,
|
|
1725
|
+
outputPath: existingEntry.outputPath,
|
|
1726
|
+
status: "skipped-cached",
|
|
1727
|
+
originalBytes: existingEntry.originalBytes,
|
|
1728
|
+
optimizedBytes: file.byteSize,
|
|
1729
|
+
savedBytes: Math.max(0, existingEntry.originalBytes - file.byteSize),
|
|
1730
|
+
savedPercent: existingEntry.originalBytes > 0 ? (existingEntry.originalBytes - file.byteSize) / existingEntry.originalBytes * 100 : 0,
|
|
1731
|
+
format: existingEntry.format,
|
|
1732
|
+
qualityScore: existingEntry.qualityScore,
|
|
1733
|
+
backupPath: existingEntry.backupPath
|
|
1734
|
+
});
|
|
1735
|
+
finalDiskPathsForBudget.push(file.absPath);
|
|
1736
|
+
continue;
|
|
1737
|
+
}
|
|
1738
|
+
const backupRel = existingEntry.backupPath ?? getBackupRelPath(config.backup.dir, existingEntry.sourcePath);
|
|
1739
|
+
const backupCheck = await hasValidBackup({
|
|
1740
|
+
projectRoot,
|
|
1741
|
+
backupRelPath: config.backup.enabled ? backupRel : void 0,
|
|
1742
|
+
expectedSha256: existingEntry.originalSha256
|
|
1743
|
+
});
|
|
1744
|
+
if (backupCheck.exists && backupCheck.absPath) {
|
|
1745
|
+
const backupStat = await fs7.stat(backupCheck.absPath);
|
|
1746
|
+
const group2 = pendingByConfigHash.get(configHash) ?? {
|
|
1747
|
+
opt: effectiveOpt,
|
|
1748
|
+
tasks: []
|
|
1749
|
+
};
|
|
1750
|
+
group2.tasks.push({
|
|
1751
|
+
scanned: file,
|
|
1752
|
+
diskSha256,
|
|
1753
|
+
effectiveOpt,
|
|
1754
|
+
configHash,
|
|
1755
|
+
existingEntry,
|
|
1756
|
+
sourceFileToOptimize: backupCheck.absPath,
|
|
1757
|
+
isReoptimizeFromBackup: true,
|
|
1758
|
+
originalSha256: existingEntry.originalSha256,
|
|
1759
|
+
originalBytes: backupStat.size,
|
|
1760
|
+
canonicalSourcePath: existingEntry.sourcePath
|
|
1761
|
+
});
|
|
1762
|
+
pendingByConfigHash.set(configHash, group2);
|
|
1763
|
+
continue;
|
|
1764
|
+
}
|
|
1765
|
+
if (!options.force && !options.reprocessOnConfigChange) {
|
|
1766
|
+
results.push({
|
|
1767
|
+
sourcePath: existingEntry.sourcePath,
|
|
1768
|
+
outputPath: existingEntry.outputPath,
|
|
1769
|
+
status: "skipped-config-changed-no-backup",
|
|
1770
|
+
originalBytes: existingEntry.originalBytes,
|
|
1771
|
+
optimizedBytes: file.byteSize,
|
|
1772
|
+
savedBytes: Math.max(0, existingEntry.originalBytes - file.byteSize),
|
|
1773
|
+
savedPercent: 0,
|
|
1774
|
+
format: existingEntry.format,
|
|
1775
|
+
qualityScore: existingEntry.qualityScore,
|
|
1776
|
+
backupPath: existingEntry.backupPath
|
|
1777
|
+
});
|
|
1778
|
+
finalDiskPathsForBudget.push(file.absPath);
|
|
1779
|
+
continue;
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
if (file.byteSize < effectiveOpt.minBytes && !options.force) {
|
|
1783
|
+
results.push({
|
|
1784
|
+
sourcePath: file.relPath,
|
|
1785
|
+
outputPath: file.relPath,
|
|
1786
|
+
status: "skipped-small",
|
|
1787
|
+
originalBytes: file.byteSize,
|
|
1788
|
+
optimizedBytes: file.byteSize,
|
|
1789
|
+
savedBytes: 0,
|
|
1790
|
+
savedPercent: 0
|
|
1791
|
+
});
|
|
1792
|
+
finalDiskPathsForBudget.push(file.absPath);
|
|
1793
|
+
continue;
|
|
1794
|
+
}
|
|
1795
|
+
const group = pendingByConfigHash.get(configHash) ?? {
|
|
1796
|
+
opt: effectiveOpt,
|
|
1797
|
+
tasks: []
|
|
1798
|
+
};
|
|
1799
|
+
group.tasks.push({
|
|
1800
|
+
scanned: file,
|
|
1801
|
+
diskSha256,
|
|
1802
|
+
effectiveOpt,
|
|
1803
|
+
configHash,
|
|
1804
|
+
existingEntry,
|
|
1805
|
+
sourceFileToOptimize: file.absPath,
|
|
1806
|
+
isReoptimizeFromBackup: false,
|
|
1807
|
+
originalSha256: diskSha256,
|
|
1808
|
+
originalBytes: file.byteSize,
|
|
1809
|
+
canonicalSourcePath: file.relPath
|
|
1810
|
+
});
|
|
1811
|
+
pendingByConfigHash.set(configHash, group);
|
|
1812
|
+
}
|
|
1813
|
+
for (const [, group] of pendingByConfigHash) {
|
|
1814
|
+
const taskByRel = /* @__PURE__ */ new Map();
|
|
1815
|
+
const batchTasks = group.tasks.map((task) => {
|
|
1816
|
+
const batchRelPath = task.isReoptimizeFromBackup ? task.canonicalSourcePath : task.scanned.relPath;
|
|
1817
|
+
taskByRel.set(batchRelPath, task);
|
|
1818
|
+
return {
|
|
1819
|
+
relPath: batchRelPath,
|
|
1820
|
+
sourceFileToOptimize: task.sourceFileToOptimize
|
|
1821
|
+
};
|
|
1822
|
+
});
|
|
1823
|
+
await runImgoptBatch({
|
|
1824
|
+
binPath: cliInfo.binPath,
|
|
1825
|
+
tasks: batchTasks,
|
|
1826
|
+
optimization: group.opt,
|
|
1827
|
+
onEachStagedResult: async (outcomes) => {
|
|
1828
|
+
for (const outcome of outcomes) {
|
|
1829
|
+
const task = taskByRel.get(outcome.relPath);
|
|
1830
|
+
if (!task) continue;
|
|
1831
|
+
if (outcome.error || !outcome.stagedOutputPath) {
|
|
1832
|
+
results.push({
|
|
1833
|
+
sourcePath: task.canonicalSourcePath,
|
|
1834
|
+
outputPath: task.scanned.relPath,
|
|
1835
|
+
status: "failed",
|
|
1836
|
+
originalBytes: task.originalBytes,
|
|
1837
|
+
optimizedBytes: task.scanned.byteSize,
|
|
1838
|
+
savedBytes: 0,
|
|
1839
|
+
savedPercent: 0,
|
|
1840
|
+
error: outcome.error ?? "Unknown optimization error"
|
|
1841
|
+
});
|
|
1842
|
+
continue;
|
|
1843
|
+
}
|
|
1844
|
+
const stagedStat = await fs7.stat(outcome.stagedOutputPath);
|
|
1845
|
+
const optimizedBytes = stagedStat.size;
|
|
1846
|
+
const formatChanged = outcome.projectOutputRelPath !== task.scanned.relPath;
|
|
1847
|
+
const { savedBytes: savedBytes2, savedPercent: savedPercent2 } = computeSavings(
|
|
1848
|
+
task.originalBytes,
|
|
1849
|
+
optimizedBytes
|
|
1850
|
+
);
|
|
1851
|
+
const shouldRejectSmallSavings = !task.isReoptimizeFromBackup && !formatChanged && (optimizedBytes >= task.scanned.byteSize || savedPercent2 < task.effectiveOpt.minSavingsPercent);
|
|
1852
|
+
if (shouldRejectSmallSavings) {
|
|
1853
|
+
if (!dryRun) {
|
|
1854
|
+
manifest.entries[task.canonicalSourcePath] = {
|
|
1855
|
+
sourcePath: task.canonicalSourcePath,
|
|
1856
|
+
outputPath: task.scanned.relPath,
|
|
1857
|
+
originalSha256: task.originalSha256,
|
|
1858
|
+
optimizedSha256: task.diskSha256,
|
|
1859
|
+
configHash: task.configHash,
|
|
1860
|
+
originalBytes: task.originalBytes,
|
|
1861
|
+
optimizedBytes: task.scanned.byteSize,
|
|
1862
|
+
format: outcome.format,
|
|
1863
|
+
qualityScore: outcome.qualityScore,
|
|
1864
|
+
backupPath: task.existingEntry?.backupPath,
|
|
1865
|
+
status: "unchanged",
|
|
1866
|
+
cliVersion: cliInfo.tag,
|
|
1867
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1868
|
+
};
|
|
1869
|
+
manifestDirty = true;
|
|
1870
|
+
}
|
|
1871
|
+
results.push({
|
|
1872
|
+
sourcePath: task.canonicalSourcePath,
|
|
1873
|
+
outputPath: task.scanned.relPath,
|
|
1874
|
+
status: "skipped-no-savings",
|
|
1875
|
+
originalBytes: task.originalBytes,
|
|
1876
|
+
optimizedBytes: task.scanned.byteSize,
|
|
1877
|
+
savedBytes: 0,
|
|
1878
|
+
savedPercent: 0,
|
|
1879
|
+
format: outcome.format,
|
|
1880
|
+
qualityScore: outcome.qualityScore
|
|
1881
|
+
});
|
|
1882
|
+
finalDiskPathsForBudget.push(task.scanned.absPath);
|
|
1883
|
+
continue;
|
|
1884
|
+
}
|
|
1885
|
+
const destRelPath = outcome.projectOutputRelPath;
|
|
1886
|
+
const destAbsPath = resolveInsideRoot(projectRoot, destRelPath);
|
|
1887
|
+
let backupRelPath = task.existingEntry?.backupPath;
|
|
1888
|
+
if (!dryRun) {
|
|
1889
|
+
if (config.backup.enabled && !task.isReoptimizeFromBackup) {
|
|
1890
|
+
backupRelPath = await ensureOriginalBackup({
|
|
1891
|
+
projectRoot,
|
|
1892
|
+
backupConfig: config.backup,
|
|
1893
|
+
sourceRelPath: task.canonicalSourcePath,
|
|
1894
|
+
sourceAbsPath: task.scanned.absPath,
|
|
1895
|
+
isNewSourceVersion: true
|
|
1896
|
+
});
|
|
1897
|
+
if (backupRelPath) {
|
|
1898
|
+
filesToStage.push(backupRelPath);
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1901
|
+
await atomicCopyFile(outcome.stagedOutputPath, destAbsPath);
|
|
1902
|
+
if (formatChanged && task.effectiveOpt.removeSourceOnFormatChange && task.scanned.absPath !== destAbsPath) {
|
|
1903
|
+
await fs7.rm(task.scanned.absPath, { force: true });
|
|
1904
|
+
filesToStage.push(task.scanned.relPath);
|
|
1905
|
+
}
|
|
1906
|
+
const optimizedSha256 = await sha256File(destAbsPath);
|
|
1907
|
+
if (task.existingEntry && task.existingEntry.sourcePath !== task.canonicalSourcePath) {
|
|
1908
|
+
delete manifest.entries[task.existingEntry.sourcePath];
|
|
1909
|
+
}
|
|
1910
|
+
manifest.entries[task.canonicalSourcePath] = {
|
|
1911
|
+
sourcePath: task.canonicalSourcePath,
|
|
1912
|
+
outputPath: destRelPath,
|
|
1913
|
+
originalSha256: task.originalSha256,
|
|
1914
|
+
optimizedSha256,
|
|
1915
|
+
configHash: task.configHash,
|
|
1916
|
+
originalBytes: task.originalBytes,
|
|
1917
|
+
optimizedBytes,
|
|
1918
|
+
format: outcome.format,
|
|
1919
|
+
qualityScore: outcome.qualityScore,
|
|
1920
|
+
backupPath: backupRelPath,
|
|
1921
|
+
status: "optimized",
|
|
1922
|
+
cliVersion: cliInfo.tag,
|
|
1923
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1924
|
+
};
|
|
1925
|
+
manifestDirty = true;
|
|
1926
|
+
filesToStage.push(destRelPath);
|
|
1927
|
+
finalDiskPathsForBudget.push(destAbsPath);
|
|
1928
|
+
}
|
|
1929
|
+
results.push({
|
|
1930
|
+
sourcePath: task.canonicalSourcePath,
|
|
1931
|
+
outputPath: destRelPath,
|
|
1932
|
+
status: task.isReoptimizeFromBackup ? "reoptimized-from-backup" : "optimized",
|
|
1933
|
+
originalBytes: task.originalBytes,
|
|
1934
|
+
optimizedBytes,
|
|
1935
|
+
savedBytes: savedBytes2,
|
|
1936
|
+
savedPercent: savedPercent2,
|
|
1937
|
+
format: outcome.format,
|
|
1938
|
+
qualityScore: outcome.qualityScore,
|
|
1939
|
+
backupPath: backupRelPath
|
|
1940
|
+
});
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
});
|
|
1944
|
+
}
|
|
1945
|
+
if (manifestDirty && !dryRun) {
|
|
1946
|
+
await saveManifest(projectRoot, config.manifest, manifest);
|
|
1947
|
+
filesToStage.push(config.manifest);
|
|
1948
|
+
}
|
|
1949
|
+
if (options.staged && !dryRun && filesToStage.length > 0) {
|
|
1950
|
+
await gitAddFiles(projectRoot, [...new Set(filesToStage)]);
|
|
1951
|
+
}
|
|
1952
|
+
const budgetWarnings = await evaluateBudgets(
|
|
1953
|
+
config,
|
|
1954
|
+
cliInfo.binPath,
|
|
1955
|
+
projectRoot,
|
|
1956
|
+
dryRun ? [] : finalDiskPathsForBudget,
|
|
1957
|
+
results
|
|
1958
|
+
);
|
|
1959
|
+
results.sort((a, b) => a.sourcePath.localeCompare(b.sourcePath));
|
|
1960
|
+
let optimized = 0;
|
|
1961
|
+
let reoptimizedFromBackup = 0;
|
|
1962
|
+
let skippedCached = 0;
|
|
1963
|
+
let skippedSmall = 0;
|
|
1964
|
+
let skippedNoSavings = 0;
|
|
1965
|
+
let skippedConfigChangedNoBackup = 0;
|
|
1966
|
+
let failed = 0;
|
|
1967
|
+
let totalOriginalBytes = 0;
|
|
1968
|
+
let totalOptimizedBytes = 0;
|
|
1969
|
+
for (const item of results) {
|
|
1970
|
+
totalOriginalBytes += item.originalBytes;
|
|
1971
|
+
totalOptimizedBytes += item.optimizedBytes;
|
|
1972
|
+
switch (item.status) {
|
|
1973
|
+
case "optimized":
|
|
1974
|
+
optimized += 1;
|
|
1975
|
+
break;
|
|
1976
|
+
case "reoptimized-from-backup":
|
|
1977
|
+
reoptimizedFromBackup += 1;
|
|
1978
|
+
break;
|
|
1979
|
+
case "skipped-cached":
|
|
1980
|
+
skippedCached += 1;
|
|
1981
|
+
break;
|
|
1982
|
+
case "skipped-small":
|
|
1983
|
+
skippedSmall += 1;
|
|
1984
|
+
break;
|
|
1985
|
+
case "skipped-no-savings":
|
|
1986
|
+
skippedNoSavings += 1;
|
|
1987
|
+
break;
|
|
1988
|
+
case "skipped-config-changed-no-backup":
|
|
1989
|
+
skippedConfigChangedNoBackup += 1;
|
|
1990
|
+
break;
|
|
1991
|
+
case "failed":
|
|
1992
|
+
failed += 1;
|
|
1993
|
+
break;
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
const { savedBytes, savedPercent } = computeSavings(
|
|
1997
|
+
totalOriginalBytes,
|
|
1998
|
+
totalOptimizedBytes
|
|
1999
|
+
);
|
|
2000
|
+
return {
|
|
2001
|
+
summary: {
|
|
2002
|
+
totalScanned: scannedFiles.length,
|
|
2003
|
+
optimized,
|
|
2004
|
+
reoptimizedFromBackup,
|
|
2005
|
+
skippedCached,
|
|
2006
|
+
skippedSmall,
|
|
2007
|
+
skippedNoSavings,
|
|
2008
|
+
skippedConfigChangedNoBackup,
|
|
2009
|
+
failed,
|
|
2010
|
+
originalBytes: totalOriginalBytes,
|
|
2011
|
+
optimizedBytes: totalOptimizedBytes,
|
|
2012
|
+
savedBytes,
|
|
2013
|
+
savedPercent,
|
|
2014
|
+
elapsedMs: Date.now() - startMs,
|
|
2015
|
+
dryRun,
|
|
2016
|
+
cliVersion: cliInfo.tag
|
|
2017
|
+
},
|
|
2018
|
+
items: results,
|
|
2019
|
+
budgetWarnings
|
|
2020
|
+
};
|
|
2021
|
+
}
|
|
2022
|
+
async function evaluateBudgets(config, binPath, projectRoot, diskAbsPaths, results) {
|
|
2023
|
+
const budgets = config.budgets;
|
|
2024
|
+
if (!budgets) return [];
|
|
2025
|
+
const violations = [];
|
|
2026
|
+
if (budgets.maxFileSizeKb !== void 0) {
|
|
2027
|
+
const limitBytes = budgets.maxFileSizeKb * 1024;
|
|
2028
|
+
if (results) {
|
|
2029
|
+
for (const item of results) {
|
|
2030
|
+
if (item.status !== "failed" && item.optimizedBytes > limitBytes) {
|
|
2031
|
+
violations.push({
|
|
2032
|
+
path: item.outputPath,
|
|
2033
|
+
rule: "maxFileSizeKb",
|
|
2034
|
+
actual: Number((item.optimizedBytes / 1024).toFixed(1)),
|
|
2035
|
+
limit: budgets.maxFileSizeKb
|
|
2036
|
+
});
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
} else {
|
|
2040
|
+
for (const absPath of diskAbsPaths) {
|
|
2041
|
+
try {
|
|
2042
|
+
const stat = await fs7.stat(absPath);
|
|
2043
|
+
if (stat.size > limitBytes) {
|
|
2044
|
+
violations.push({
|
|
2045
|
+
path: path9.relative(projectRoot, absPath).split(path9.sep).join("/"),
|
|
2046
|
+
rule: "maxFileSizeKb",
|
|
2047
|
+
actual: Number((stat.size / 1024).toFixed(1)),
|
|
2048
|
+
limit: budgets.maxFileSizeKb
|
|
2049
|
+
});
|
|
2050
|
+
}
|
|
2051
|
+
} catch {
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
}
|
|
2056
|
+
if (binPath && (budgets.maxWidth !== void 0 || budgets.maxHeight !== void 0) && diskAbsPaths.length > 0) {
|
|
2057
|
+
const inspected = await inspectImagesWithImgopt(binPath, diskAbsPaths);
|
|
2058
|
+
for (const [absPath, info] of inspected) {
|
|
2059
|
+
const rel = path9.relative(projectRoot, absPath).split(path9.sep).join("/");
|
|
2060
|
+
if (budgets.maxWidth !== void 0 && info.dimensions && info.dimensions.width > budgets.maxWidth) {
|
|
2061
|
+
violations.push({
|
|
2062
|
+
path: rel,
|
|
2063
|
+
rule: "maxWidth",
|
|
2064
|
+
actual: info.dimensions.width,
|
|
2065
|
+
limit: budgets.maxWidth
|
|
2066
|
+
});
|
|
2067
|
+
}
|
|
2068
|
+
if (budgets.maxHeight !== void 0 && info.dimensions && info.dimensions.height > budgets.maxHeight) {
|
|
2069
|
+
violations.push({
|
|
2070
|
+
path: rel,
|
|
2071
|
+
rule: "maxHeight",
|
|
2072
|
+
actual: info.dimensions.height,
|
|
2073
|
+
limit: budgets.maxHeight
|
|
2074
|
+
});
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
return violations;
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
// src/commands/check.ts
|
|
2082
|
+
async function checkProject(options = {}) {
|
|
2083
|
+
const { projectRoot, config } = await loadConfig(
|
|
2084
|
+
options.projectRoot,
|
|
2085
|
+
options.configPath
|
|
2086
|
+
);
|
|
2087
|
+
const scanned = await scanProjectImages(projectRoot, config);
|
|
2088
|
+
const manifest = await loadManifest(projectRoot, config.manifest);
|
|
2089
|
+
const index = buildManifestIndex(manifest);
|
|
2090
|
+
const pending = [];
|
|
2091
|
+
let upToDate = 0;
|
|
2092
|
+
for (const file of scanned) {
|
|
2093
|
+
const effectiveOpt = resolveEffectiveOptimization(config, file.relPath);
|
|
2094
|
+
if (file.byteSize < effectiveOpt.minBytes) {
|
|
2095
|
+
upToDate += 1;
|
|
2096
|
+
continue;
|
|
2097
|
+
}
|
|
2098
|
+
const diskSha = await sha256File(file.absPath);
|
|
2099
|
+
const entry = findEntryForDiskPath(index, file.relPath);
|
|
2100
|
+
const configHash = computeOptimizationConfigHash(effectiveOpt);
|
|
2101
|
+
if (entry && entry.optimizedSha256 === diskSha) {
|
|
2102
|
+
if (entry.configHash === configHash) {
|
|
2103
|
+
upToDate += 1;
|
|
2104
|
+
continue;
|
|
2105
|
+
}
|
|
2106
|
+
const backupCheck = await hasValidBackup({
|
|
2107
|
+
projectRoot,
|
|
2108
|
+
backupRelPath: config.backup.enabled ? entry.backupPath ?? getBackupRelPath(config.backup.dir, entry.sourcePath) : void 0,
|
|
2109
|
+
expectedSha256: entry.originalSha256
|
|
2110
|
+
});
|
|
2111
|
+
if (backupCheck.exists) {
|
|
2112
|
+
pending.push({
|
|
2113
|
+
path: file.relPath,
|
|
2114
|
+
reason: "config-changed-with-backup",
|
|
2115
|
+
bytes: file.byteSize
|
|
2116
|
+
});
|
|
2117
|
+
} else {
|
|
2118
|
+
upToDate += 1;
|
|
2119
|
+
}
|
|
2120
|
+
continue;
|
|
2121
|
+
}
|
|
2122
|
+
pending.push({
|
|
2123
|
+
path: file.relPath,
|
|
2124
|
+
reason: "new-or-modified",
|
|
2125
|
+
bytes: file.byteSize
|
|
2126
|
+
});
|
|
2127
|
+
}
|
|
2128
|
+
let binPath = null;
|
|
2129
|
+
const needsDimensionInspect = Boolean(
|
|
2130
|
+
config.budgets && (config.budgets.maxWidth !== void 0 || config.budgets.maxHeight !== void 0)
|
|
2131
|
+
);
|
|
2132
|
+
if (needsDimensionInspect || options.checkDimensions) {
|
|
2133
|
+
try {
|
|
2134
|
+
const cliInfo = await ensureCli({ cliConfig: config.cli });
|
|
2135
|
+
binPath = cliInfo.binPath;
|
|
2136
|
+
} catch {
|
|
2137
|
+
binPath = null;
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
const budgetViolations = await evaluateBudgets(
|
|
2141
|
+
config,
|
|
2142
|
+
binPath,
|
|
2143
|
+
projectRoot,
|
|
2144
|
+
scanned.map((s) => s.absPath)
|
|
2145
|
+
);
|
|
2146
|
+
return {
|
|
2147
|
+
ok: pending.length === 0 && budgetViolations.length === 0,
|
|
2148
|
+
totalScanned: scanned.length,
|
|
2149
|
+
upToDate,
|
|
2150
|
+
pending,
|
|
2151
|
+
budgetViolations
|
|
2152
|
+
};
|
|
2153
|
+
}
|
|
2154
|
+
|
|
2155
|
+
// src/commands/clean.ts
|
|
2156
|
+
import fs8 from "fs/promises";
|
|
2157
|
+
import path10 from "path";
|
|
2158
|
+
async function cleanProject(options = {}) {
|
|
2159
|
+
const { projectRoot, config } = await loadConfig(
|
|
2160
|
+
options.projectRoot,
|
|
2161
|
+
options.configPath
|
|
2162
|
+
);
|
|
2163
|
+
const dryRun = Boolean(options.dryRun);
|
|
2164
|
+
const manifest = await loadManifest(projectRoot, config.manifest);
|
|
2165
|
+
const backups = await listBackupFiles(projectRoot, config.backup.dir);
|
|
2166
|
+
const removedBackups = [];
|
|
2167
|
+
const removedManifestEntries = [];
|
|
2168
|
+
const removedCacheVersions = [];
|
|
2169
|
+
let reclaimedBytes = 0;
|
|
2170
|
+
for (const backup of backups) {
|
|
2171
|
+
const sourceAbs = resolveInsideRoot(projectRoot, backup.sourceRelPath);
|
|
2172
|
+
const entry = manifest.entries[backup.sourceRelPath];
|
|
2173
|
+
const outputExists = entry ? await fileExists(resolveInsideRoot(projectRoot, entry.outputPath)) : false;
|
|
2174
|
+
const sourceExists = await fileExists(sourceAbs);
|
|
2175
|
+
if (!sourceExists && !outputExists) {
|
|
2176
|
+
const stat = await fs8.stat(backup.absPath);
|
|
2177
|
+
reclaimedBytes += stat.size;
|
|
2178
|
+
removedBackups.push(backup.backupRelPath);
|
|
2179
|
+
if (!dryRun) {
|
|
2180
|
+
await fs8.rm(backup.absPath, { force: true });
|
|
2181
|
+
}
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
let manifestDirty = false;
|
|
2185
|
+
for (const [key, entry] of Object.entries(manifest.entries)) {
|
|
2186
|
+
const sourceExists = await fileExists(
|
|
2187
|
+
resolveInsideRoot(projectRoot, entry.sourcePath)
|
|
2188
|
+
);
|
|
2189
|
+
const outputExists = await fileExists(
|
|
2190
|
+
resolveInsideRoot(projectRoot, entry.outputPath)
|
|
2191
|
+
);
|
|
2192
|
+
if (!sourceExists && !outputExists) {
|
|
2193
|
+
removedManifestEntries.push(key);
|
|
2194
|
+
if (!dryRun) {
|
|
2195
|
+
delete manifest.entries[key];
|
|
2196
|
+
manifestDirty = true;
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
if (manifestDirty && !dryRun) {
|
|
2201
|
+
await saveManifest(projectRoot, config.manifest, manifest);
|
|
2202
|
+
}
|
|
2203
|
+
if (options.cache) {
|
|
2204
|
+
const cacheDir = resolveCacheDir(config.cli);
|
|
2205
|
+
const cachedVersions = await listCachedVersions(cacheDir);
|
|
2206
|
+
const status = await getCliStatus(config.cli, false);
|
|
2207
|
+
const keepVersion = status.installedTag ?? status.installedVersion;
|
|
2208
|
+
for (const ver of cachedVersions) {
|
|
2209
|
+
if (keepVersion && ver === keepVersion) continue;
|
|
2210
|
+
const verDir = path10.join(cacheDir, ver);
|
|
2211
|
+
removedCacheVersions.push(ver);
|
|
2212
|
+
if (!dryRun) {
|
|
2213
|
+
await fs8.rm(verDir, { recursive: true, force: true });
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
}
|
|
2217
|
+
return {
|
|
2218
|
+
dryRun,
|
|
2219
|
+
removedBackups,
|
|
2220
|
+
removedManifestEntries,
|
|
2221
|
+
removedCacheVersions,
|
|
2222
|
+
reclaimedBytes
|
|
2223
|
+
};
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
// src/commands/doctor.ts
|
|
2227
|
+
import fs9 from "fs/promises";
|
|
2228
|
+
import path11 from "path";
|
|
2229
|
+
async function doctorProject(options = {}) {
|
|
2230
|
+
const checks = [];
|
|
2231
|
+
const projectRoot = path11.resolve(options.projectRoot ?? process.cwd());
|
|
2232
|
+
let loaded;
|
|
2233
|
+
try {
|
|
2234
|
+
loaded = await loadConfig(projectRoot, options.configPath);
|
|
2235
|
+
checks.push({
|
|
2236
|
+
name: "config",
|
|
2237
|
+
status: "ok",
|
|
2238
|
+
message: `Valid config loaded from ${path11.relative(projectRoot, loaded.configPath) || loaded.configPath}`
|
|
2239
|
+
});
|
|
2240
|
+
} catch (err) {
|
|
2241
|
+
checks.push({
|
|
2242
|
+
name: "config",
|
|
2243
|
+
status: "error",
|
|
2244
|
+
message: err instanceof Error ? err.message : String(err)
|
|
2245
|
+
});
|
|
2246
|
+
return { ok: false, checks };
|
|
2247
|
+
}
|
|
2248
|
+
const { config } = loaded;
|
|
2249
|
+
let existingTargetCount = 0;
|
|
2250
|
+
for (const target of config.targets) {
|
|
2251
|
+
const abs = resolveInsideRoot(projectRoot, target.dir);
|
|
2252
|
+
if (await isDirectory(abs)) {
|
|
2253
|
+
existingTargetCount += 1;
|
|
2254
|
+
} else {
|
|
2255
|
+
checks.push({
|
|
2256
|
+
name: `target:${target.dir}`,
|
|
2257
|
+
status: "warn",
|
|
2258
|
+
message: `Target directory "${target.dir}" does not exist on disk`
|
|
2259
|
+
});
|
|
2260
|
+
}
|
|
2261
|
+
}
|
|
2262
|
+
if (existingTargetCount > 0) {
|
|
2263
|
+
checks.push({
|
|
2264
|
+
name: "targets",
|
|
2265
|
+
status: "ok",
|
|
2266
|
+
message: `${existingTargetCount}/${config.targets.length} target directory(ies) present`
|
|
2267
|
+
});
|
|
2268
|
+
}
|
|
2269
|
+
const cliStatus = await getCliStatus(config.cli, options.checkRemote ?? true);
|
|
2270
|
+
if (cliStatus.resolvedBinPath && cliStatus.installedVersion) {
|
|
2271
|
+
const displayTag = cliStatus.installedTag ?? cliStatus.installedVersion;
|
|
2272
|
+
if (cliStatus.updateAvailable && cliStatus.latestRemoteVersion) {
|
|
2273
|
+
checks.push({
|
|
2274
|
+
name: "cli-binary",
|
|
2275
|
+
status: "warn",
|
|
2276
|
+
message: `Installed imgopt ${displayTag} (${cliStatus.source}); newer release ${cliStatus.latestRemoteVersion} available`
|
|
2277
|
+
});
|
|
2278
|
+
} else {
|
|
2279
|
+
checks.push({
|
|
2280
|
+
name: "cli-binary",
|
|
2281
|
+
status: "ok",
|
|
2282
|
+
message: `imgopt ${displayTag} ready (${cliStatus.source}: ${cliStatus.resolvedBinPath})`
|
|
2283
|
+
});
|
|
2284
|
+
}
|
|
2285
|
+
} else {
|
|
2286
|
+
checks.push({
|
|
2287
|
+
name: "cli-binary",
|
|
2288
|
+
status: config.cli.autoDownload ? "warn" : "error",
|
|
2289
|
+
message: config.cli.autoDownload ? `imgopt not downloaded yet; will auto-download ${cliStatus.configuredVersion} on first optimize run` : "imgopt binary not found and cli.autoDownload is false"
|
|
2290
|
+
});
|
|
2291
|
+
}
|
|
2292
|
+
try {
|
|
2293
|
+
const manifest = await loadManifest(projectRoot, config.manifest);
|
|
2294
|
+
const entryCount = Object.keys(manifest.entries).length;
|
|
2295
|
+
checks.push({
|
|
2296
|
+
name: "manifest",
|
|
2297
|
+
status: "ok",
|
|
2298
|
+
message: `Manifest valid (${entryCount} tracked asset(s))`
|
|
2299
|
+
});
|
|
2300
|
+
if (config.backup.enabled) {
|
|
2301
|
+
const backups = await listBackupFiles(projectRoot, config.backup.dir);
|
|
2302
|
+
let orphanCount = 0;
|
|
2303
|
+
for (const b of backups) {
|
|
2304
|
+
const entry = manifest.entries[b.sourceRelPath];
|
|
2305
|
+
const srcExists = await fileExists(
|
|
2306
|
+
resolveInsideRoot(projectRoot, b.sourceRelPath)
|
|
2307
|
+
);
|
|
2308
|
+
const outExists = entry ? await fileExists(resolveInsideRoot(projectRoot, entry.outputPath)) : false;
|
|
2309
|
+
if (!srcExists && !outExists) orphanCount += 1;
|
|
2310
|
+
}
|
|
2311
|
+
if (orphanCount > 0) {
|
|
2312
|
+
checks.push({
|
|
2313
|
+
name: "backups",
|
|
2314
|
+
status: "warn",
|
|
2315
|
+
message: `${backups.length} backup(s) in ${config.backup.dir}; ${orphanCount} orphan(s) can be cleaned via "imgopt-node clean"`
|
|
2316
|
+
});
|
|
2317
|
+
} else {
|
|
2318
|
+
checks.push({
|
|
2319
|
+
name: "backups",
|
|
2320
|
+
status: "ok",
|
|
2321
|
+
message: `Originals backup enabled (${config.backup.dir}, ${backups.length} file(s))`
|
|
2322
|
+
});
|
|
2323
|
+
}
|
|
2324
|
+
} else {
|
|
2325
|
+
checks.push({
|
|
2326
|
+
name: "backups",
|
|
2327
|
+
status: "warn",
|
|
2328
|
+
message: "Original image backup is disabled (backup.enabled = false)"
|
|
2329
|
+
});
|
|
2330
|
+
}
|
|
2331
|
+
} catch (err) {
|
|
2332
|
+
checks.push({
|
|
2333
|
+
name: "manifest",
|
|
2334
|
+
status: "error",
|
|
2335
|
+
message: err instanceof Error ? err.message : String(err)
|
|
2336
|
+
});
|
|
2337
|
+
}
|
|
2338
|
+
const gitignorePath = path11.join(projectRoot, ".gitignore");
|
|
2339
|
+
if (await fileExists(gitignorePath)) {
|
|
2340
|
+
const content = await fs9.readFile(gitignorePath, "utf8");
|
|
2341
|
+
const dirNorm = config.backup.dir.replace(/\/+$/, "");
|
|
2342
|
+
const ignored = content.includes(dirNorm) || content.includes(".imgopt/");
|
|
2343
|
+
checks.push({
|
|
2344
|
+
name: "gitignore",
|
|
2345
|
+
status: "ok",
|
|
2346
|
+
message: ignored ? `Backup directory (${dirNorm}) is listed in .gitignore` : `Backup directory (${dirNorm}) is tracked by Git (team-shared backups)`
|
|
2347
|
+
});
|
|
2348
|
+
}
|
|
2349
|
+
return {
|
|
2350
|
+
ok: checks.every((c) => c.status !== "error"),
|
|
2351
|
+
checks
|
|
2352
|
+
};
|
|
2353
|
+
}
|
|
2354
|
+
|
|
2355
|
+
// src/commands/init.ts
|
|
2356
|
+
import fs11 from "fs/promises";
|
|
2357
|
+
import path13 from "path";
|
|
2358
|
+
import { fileURLToPath } from "url";
|
|
2359
|
+
|
|
2360
|
+
// src/config/detector.ts
|
|
2361
|
+
import fs10 from "fs/promises";
|
|
2362
|
+
import path12 from "path";
|
|
2363
|
+
async function countImagesInDir(dirPath, maxDepth = 6) {
|
|
2364
|
+
let count = 0;
|
|
2365
|
+
async function walk(current, depth) {
|
|
2366
|
+
if (depth > maxDepth) return;
|
|
2367
|
+
let entries;
|
|
2368
|
+
try {
|
|
2369
|
+
entries = await fs10.readdir(current, { withFileTypes: true });
|
|
2370
|
+
} catch {
|
|
2371
|
+
return;
|
|
2372
|
+
}
|
|
2373
|
+
for (const entry of entries) {
|
|
2374
|
+
if (entry.name.startsWith(".") || IGNORED_DIR_NAMES.has(entry.name)) {
|
|
2375
|
+
continue;
|
|
2376
|
+
}
|
|
2377
|
+
const fullPath = path12.join(current, entry.name);
|
|
2378
|
+
if (entry.isDirectory()) {
|
|
2379
|
+
await walk(fullPath, depth + 1);
|
|
2380
|
+
} else if (entry.isFile()) {
|
|
2381
|
+
const ext = path12.extname(entry.name).toLowerCase();
|
|
2382
|
+
if (SUPPORTED_IMAGE_EXTENSIONS.has(ext)) {
|
|
2383
|
+
count += 1;
|
|
2384
|
+
}
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
await walk(dirPath, 0);
|
|
2389
|
+
return count;
|
|
2390
|
+
}
|
|
2391
|
+
async function detectStacks(projectRoot) {
|
|
2392
|
+
const stacks = /* @__PURE__ */ new Set();
|
|
2393
|
+
let isMonorepo = false;
|
|
2394
|
+
const workspaceRoots = [];
|
|
2395
|
+
const pkgPath = path12.join(projectRoot, "package.json");
|
|
2396
|
+
if (await fileExists(pkgPath)) {
|
|
2397
|
+
try {
|
|
2398
|
+
const pkg = await readJsonFile(pkgPath);
|
|
2399
|
+
const deps = {
|
|
2400
|
+
...pkg.dependencies ?? {},
|
|
2401
|
+
...pkg.devDependencies ?? {}
|
|
2402
|
+
};
|
|
2403
|
+
if ("next" in deps) stacks.add("next");
|
|
2404
|
+
if ("nuxt" in deps) stacks.add("nuxt");
|
|
2405
|
+
if ("vite" in deps) stacks.add("vite");
|
|
2406
|
+
if ("astro" in deps) stacks.add("astro");
|
|
2407
|
+
if ("vitepress" in deps) stacks.add("vitepress");
|
|
2408
|
+
if ("@docusaurus/core" in deps) stacks.add("docusaurus");
|
|
2409
|
+
if ("@remix-run/react" in deps || "react-router" in deps) stacks.add("remix");
|
|
2410
|
+
if ("svelte" in deps || "@sveltejs/kit" in deps) stacks.add("svelte");
|
|
2411
|
+
if ("vue" in deps) stacks.add("vue");
|
|
2412
|
+
if ("react" in deps) stacks.add("react");
|
|
2413
|
+
if ("react-native" in deps || "expo" in deps) stacks.add("react-native");
|
|
2414
|
+
if ("electron" in deps) stacks.add("electron");
|
|
2415
|
+
if ("@tauri-apps/api" in deps) stacks.add("tauri");
|
|
2416
|
+
if (pkg.workspaces) {
|
|
2417
|
+
isMonorepo = true;
|
|
2418
|
+
const patterns = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces.packages ?? [];
|
|
2419
|
+
for (const p of patterns) {
|
|
2420
|
+
if (typeof p === "string") workspaceRoots.push(p);
|
|
2421
|
+
}
|
|
2422
|
+
}
|
|
2423
|
+
} catch {
|
|
2424
|
+
}
|
|
2425
|
+
}
|
|
2426
|
+
if (await fileExists(path12.join(projectRoot, "pnpm-workspace.yaml"))) {
|
|
2427
|
+
isMonorepo = true;
|
|
2428
|
+
workspaceRoots.push("apps/*", "packages/*");
|
|
2429
|
+
}
|
|
2430
|
+
if (await fileExists(path12.join(projectRoot, "pubspec.yaml"))) {
|
|
2431
|
+
stacks.add("flutter");
|
|
2432
|
+
}
|
|
2433
|
+
if (await fileExists(path12.join(projectRoot, "docs")) || await fileExists(path12.join(projectRoot, "mkdocs.yml"))) {
|
|
2434
|
+
stacks.add("docs");
|
|
2435
|
+
}
|
|
2436
|
+
if (stacks.size === 0) {
|
|
2437
|
+
stacks.add("general");
|
|
2438
|
+
}
|
|
2439
|
+
return {
|
|
2440
|
+
stacks: [...stacks],
|
|
2441
|
+
isMonorepo,
|
|
2442
|
+
workspaceRoots
|
|
2443
|
+
};
|
|
2444
|
+
}
|
|
2445
|
+
async function expandWorkspaceParents(projectRoot, patterns) {
|
|
2446
|
+
const bases = /* @__PURE__ */ new Set();
|
|
2447
|
+
const defaultGlobs = patterns.length > 0 ? patterns : ["apps/*", "packages/*"];
|
|
2448
|
+
for (const rawPattern of defaultGlobs) {
|
|
2449
|
+
const clean = rawPattern.replace(/\/\*+$/, "").replace(/^\.\//, "");
|
|
2450
|
+
if (!clean || clean.includes("*") || clean.startsWith("!")) continue;
|
|
2451
|
+
const baseAbs = path12.join(projectRoot, clean);
|
|
2452
|
+
if (!await isDirectory(baseAbs)) continue;
|
|
2453
|
+
try {
|
|
2454
|
+
const entries = await fs10.readdir(baseAbs, { withFileTypes: true });
|
|
2455
|
+
for (const entry of entries) {
|
|
2456
|
+
if (entry.isDirectory() && !entry.name.startsWith(".")) {
|
|
2457
|
+
bases.add(toPosixPath(path12.join(clean, entry.name)));
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
} catch {
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
return [...bases].sort();
|
|
2464
|
+
}
|
|
2465
|
+
function isNestedUnder(child, parent) {
|
|
2466
|
+
if (child === parent) return true;
|
|
2467
|
+
if (parent === ".") return true;
|
|
2468
|
+
return child.startsWith(`${parent}/`);
|
|
2469
|
+
}
|
|
2470
|
+
async function detectProject(projectRoot = process.cwd(), customDirs = []) {
|
|
2471
|
+
const resolvedRoot = path12.resolve(projectRoot);
|
|
2472
|
+
const { stacks, isMonorepo, workspaceRoots } = await detectStacks(resolvedRoot);
|
|
2473
|
+
const discovered = /* @__PURE__ */ new Map();
|
|
2474
|
+
for (const rawDir of customDirs) {
|
|
2475
|
+
const clean = toPosixPath(rawDir.trim()).replace(/^\.\//, "").replace(/\/+$/, "");
|
|
2476
|
+
if (!clean) continue;
|
|
2477
|
+
const abs = path12.join(resolvedRoot, clean);
|
|
2478
|
+
const exists = await isDirectory(abs);
|
|
2479
|
+
const imageCount = exists ? await countImagesInDir(abs) : 0;
|
|
2480
|
+
discovered.set(clean, {
|
|
2481
|
+
dir: clean,
|
|
2482
|
+
imageCount,
|
|
2483
|
+
source: "custom"
|
|
2484
|
+
});
|
|
2485
|
+
}
|
|
2486
|
+
for (const candidate of CANDIDATE_ASSET_DIRS) {
|
|
2487
|
+
const abs = path12.join(resolvedRoot, candidate.dir);
|
|
2488
|
+
if (!await isDirectory(abs)) continue;
|
|
2489
|
+
const imageCount = await countImagesInDir(abs);
|
|
2490
|
+
if (imageCount === 0 && customDirs.length === 0) {
|
|
2491
|
+
const isPrimaryRoot = candidate.dir === "src/assets" || candidate.dir === "public" || candidate.dir === "assets" || candidate.dir === "static";
|
|
2492
|
+
if (!isPrimaryRoot) continue;
|
|
2493
|
+
}
|
|
2494
|
+
if (!discovered.has(candidate.dir)) {
|
|
2495
|
+
discovered.set(candidate.dir, {
|
|
2496
|
+
dir: candidate.dir,
|
|
2497
|
+
imageCount,
|
|
2498
|
+
source: "standard"
|
|
2499
|
+
});
|
|
2500
|
+
}
|
|
2501
|
+
}
|
|
2502
|
+
if (isMonorepo) {
|
|
2503
|
+
const wsDirs = await expandWorkspaceParents(resolvedRoot, workspaceRoots);
|
|
2504
|
+
const subCandidates = ["src/assets", "public", "static", "assets"];
|
|
2505
|
+
for (const ws of wsDirs) {
|
|
2506
|
+
for (const sub of subCandidates) {
|
|
2507
|
+
const rel = `${ws}/${sub}`;
|
|
2508
|
+
const abs = path12.join(resolvedRoot, rel);
|
|
2509
|
+
if (!await isDirectory(abs)) continue;
|
|
2510
|
+
const imageCount = await countImagesInDir(abs);
|
|
2511
|
+
if (imageCount > 0 && !discovered.has(rel)) {
|
|
2512
|
+
discovered.set(rel, {
|
|
2513
|
+
dir: rel,
|
|
2514
|
+
imageCount,
|
|
2515
|
+
source: "monorepo"
|
|
2516
|
+
});
|
|
2517
|
+
}
|
|
2518
|
+
}
|
|
2519
|
+
}
|
|
2520
|
+
}
|
|
2521
|
+
const sortedAll = [...discovered.values()].sort(
|
|
2522
|
+
(a, b) => a.dir.localeCompare(b.dir)
|
|
2523
|
+
);
|
|
2524
|
+
const deduplicated = [];
|
|
2525
|
+
for (const item of sortedAll) {
|
|
2526
|
+
const shadowedByParent = deduplicated.some(
|
|
2527
|
+
(parent) => item.source !== "custom" && isNestedUnder(item.dir, parent.dir)
|
|
2528
|
+
);
|
|
2529
|
+
if (!shadowedByParent) {
|
|
2530
|
+
deduplicated.push(item);
|
|
2531
|
+
}
|
|
2532
|
+
}
|
|
2533
|
+
const suggestedTargets = deduplicated.length > 0 ? deduplicated.map((d) => ({
|
|
2534
|
+
dir: d.dir,
|
|
2535
|
+
include: [...DEFAULT_INCLUDE_GLOBS],
|
|
2536
|
+
exclude: [...DEFAULT_EXCLUDE_GLOBS]
|
|
2537
|
+
})) : [
|
|
2538
|
+
{
|
|
2539
|
+
dir: "assets",
|
|
2540
|
+
include: [...DEFAULT_INCLUDE_GLOBS],
|
|
2541
|
+
exclude: [...DEFAULT_EXCLUDE_GLOBS]
|
|
2542
|
+
}
|
|
2543
|
+
];
|
|
2544
|
+
return {
|
|
2545
|
+
projectRoot: resolvedRoot,
|
|
2546
|
+
stacks,
|
|
2547
|
+
isMonorepo,
|
|
2548
|
+
detectedDirs: deduplicated,
|
|
2549
|
+
suggestedTargets
|
|
2550
|
+
};
|
|
2551
|
+
}
|
|
2552
|
+
|
|
2553
|
+
// src/commands/init.ts
|
|
2554
|
+
import fsSync from "fs";
|
|
2555
|
+
function getPackageRoot() {
|
|
2556
|
+
let dir = path13.dirname(fileURLToPath(import.meta.url));
|
|
2557
|
+
for (let i = 0; i < 6; i += 1) {
|
|
2558
|
+
const pkgPath = path13.join(dir, "package.json");
|
|
2559
|
+
if (fsSync.existsSync(pkgPath)) {
|
|
2560
|
+
return dir;
|
|
2561
|
+
}
|
|
2562
|
+
const parent = path13.dirname(dir);
|
|
2563
|
+
if (parent === dir) break;
|
|
2564
|
+
dir = parent;
|
|
2565
|
+
}
|
|
2566
|
+
return path13.resolve(path13.dirname(fileURLToPath(import.meta.url)), "..", "..");
|
|
2567
|
+
}
|
|
2568
|
+
async function ensureGitignoreLines(projectRoot, linesToEnsure) {
|
|
2569
|
+
const gitignorePath = path13.join(projectRoot, ".gitignore");
|
|
2570
|
+
let content = "";
|
|
2571
|
+
if (await fileExists(gitignorePath)) {
|
|
2572
|
+
content = await fs11.readFile(gitignorePath, "utf8");
|
|
2573
|
+
}
|
|
2574
|
+
const existingLines = new Set(
|
|
2575
|
+
content.split(/\r?\n/).map((line) => line.trim())
|
|
2576
|
+
);
|
|
2577
|
+
const missing = linesToEnsure.filter((line) => !existingLines.has(line));
|
|
2578
|
+
if (missing.length === 0) {
|
|
2579
|
+
return false;
|
|
2580
|
+
}
|
|
2581
|
+
const suffix = (content.length > 0 && !content.endsWith("\n") ? "\n" : "") + `
|
|
2582
|
+
# image-optimizer-node
|
|
2583
|
+
${missing.join("\n")}
|
|
2584
|
+
`;
|
|
2585
|
+
await atomicWriteFile(gitignorePath, content + suffix);
|
|
2586
|
+
return true;
|
|
2587
|
+
}
|
|
2588
|
+
async function initProject(options = {}) {
|
|
2589
|
+
const projectRoot = path13.resolve(options.projectRoot ?? process.cwd());
|
|
2590
|
+
const configPath = path13.resolve(
|
|
2591
|
+
projectRoot,
|
|
2592
|
+
options.configPath ?? DEFAULT_CONFIG_FILENAME
|
|
2593
|
+
);
|
|
2594
|
+
if (!options.force && await fileExists(configPath)) {
|
|
2595
|
+
throw new Error(
|
|
2596
|
+
`Configuration already exists at ${configPath}. Pass --force to overwrite.`
|
|
2597
|
+
);
|
|
2598
|
+
}
|
|
2599
|
+
const detection = await detectProject(projectRoot, options.dirs ?? []);
|
|
2600
|
+
const config = createDefaultConfig(detection.suggestedTargets);
|
|
2601
|
+
if (options.cliVersion) {
|
|
2602
|
+
config.cli.version = options.cliVersion;
|
|
2603
|
+
}
|
|
2604
|
+
if (options.backup !== void 0) {
|
|
2605
|
+
config.backup.enabled = options.backup;
|
|
2606
|
+
}
|
|
2607
|
+
if (options.backupDir) {
|
|
2608
|
+
config.backup.dir = options.backupDir;
|
|
2609
|
+
}
|
|
2610
|
+
if (options.preset) {
|
|
2611
|
+
config.optimization.preset = options.preset;
|
|
2612
|
+
if (options.preset !== "balanced") {
|
|
2613
|
+
if (options.quality === void 0) {
|
|
2614
|
+
delete config.optimization.quality;
|
|
2615
|
+
}
|
|
2616
|
+
if (options.effort === void 0) {
|
|
2617
|
+
delete config.optimization.effort;
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
}
|
|
2621
|
+
if (options.quality !== void 0) {
|
|
2622
|
+
config.optimization.quality = options.quality;
|
|
2623
|
+
}
|
|
2624
|
+
if (options.effort !== void 0) {
|
|
2625
|
+
config.optimization.effort = options.effort;
|
|
2626
|
+
}
|
|
2627
|
+
if (options.format) {
|
|
2628
|
+
config.optimization.format = options.format;
|
|
2629
|
+
}
|
|
2630
|
+
if (options.template === "web") {
|
|
2631
|
+
config.optimization.resize = {
|
|
2632
|
+
maxWidth: 2560,
|
|
2633
|
+
maxHeight: 2560,
|
|
2634
|
+
mode: "scale-down"
|
|
2635
|
+
};
|
|
2636
|
+
}
|
|
2637
|
+
await saveConfig(configPath, config);
|
|
2638
|
+
let ciWorkflowPath;
|
|
2639
|
+
if (options.ci) {
|
|
2640
|
+
const templatePath = path13.join(
|
|
2641
|
+
getPackageRoot(),
|
|
2642
|
+
"templates",
|
|
2643
|
+
"workflows",
|
|
2644
|
+
"optimize-images.yml"
|
|
2645
|
+
);
|
|
2646
|
+
const workflowDest = path13.join(
|
|
2647
|
+
projectRoot,
|
|
2648
|
+
".github",
|
|
2649
|
+
"workflows",
|
|
2650
|
+
"optimize-images.yml"
|
|
2651
|
+
);
|
|
2652
|
+
if (options.force || !await fileExists(workflowDest)) {
|
|
2653
|
+
const templateContent = await fs11.readFile(templatePath, "utf8");
|
|
2654
|
+
await atomicWriteFile(workflowDest, templateContent);
|
|
2655
|
+
}
|
|
2656
|
+
ciWorkflowPath = path13.relative(projectRoot, workflowDest);
|
|
2657
|
+
}
|
|
2658
|
+
let gitignoreUpdated = false;
|
|
2659
|
+
if (options.gitignore) {
|
|
2660
|
+
const backupEntry = `${(config.backup.dir || DEFAULT_BACKUP_DIR).replace(/\/+$/, "")}/`;
|
|
2661
|
+
gitignoreUpdated = await ensureGitignoreLines(projectRoot, [backupEntry]);
|
|
2662
|
+
}
|
|
2663
|
+
return {
|
|
2664
|
+
configPath,
|
|
2665
|
+
config,
|
|
2666
|
+
stacks: detection.stacks,
|
|
2667
|
+
detectedDirs: detection.detectedDirs,
|
|
2668
|
+
ciWorkflowPath,
|
|
2669
|
+
gitignoreUpdated
|
|
2670
|
+
};
|
|
2671
|
+
}
|
|
2672
|
+
|
|
2673
|
+
// src/commands/inspect.ts
|
|
2674
|
+
async function inspectProject(options = {}) {
|
|
2675
|
+
const { projectRoot, config } = await loadConfig(
|
|
2676
|
+
options.projectRoot,
|
|
2677
|
+
options.configPath
|
|
2678
|
+
);
|
|
2679
|
+
const cliInfo = await ensureCli({ cliConfig: config.cli });
|
|
2680
|
+
let pathsToInspect;
|
|
2681
|
+
if (options.targetPath) {
|
|
2682
|
+
pathsToInspect = [resolveInsideRoot(projectRoot, options.targetPath)];
|
|
2683
|
+
} else {
|
|
2684
|
+
const scanned = await scanProjectImages(projectRoot, config);
|
|
2685
|
+
pathsToInspect = scanned.map((s) => s.absPath);
|
|
2686
|
+
}
|
|
2687
|
+
const inspected = await inspectImagesWithImgopt(
|
|
2688
|
+
cliInfo.binPath,
|
|
2689
|
+
pathsToInspect
|
|
2690
|
+
);
|
|
2691
|
+
return [...inspected.values()];
|
|
2692
|
+
}
|
|
2693
|
+
|
|
2694
|
+
// src/commands/restore.ts
|
|
2695
|
+
import fs12 from "fs/promises";
|
|
2696
|
+
import picomatch3 from "picomatch";
|
|
2697
|
+
async function restoreOriginals(options = {}) {
|
|
2698
|
+
const { projectRoot, config } = await loadConfig(
|
|
2699
|
+
options.projectRoot,
|
|
2700
|
+
options.configPath
|
|
2701
|
+
);
|
|
2702
|
+
const dryRun = Boolean(options.dryRun);
|
|
2703
|
+
const patterns = (options.patterns ?? []).map(
|
|
2704
|
+
(p) => toPosixPath(p.trim()).replace(/^\.\//, "")
|
|
2705
|
+
);
|
|
2706
|
+
if (!options.all && patterns.length === 0) {
|
|
2707
|
+
throw new Error(
|
|
2708
|
+
"Specify file path/glob patterns to restore, or pass --all to restore all backed-up originals."
|
|
2709
|
+
);
|
|
2710
|
+
}
|
|
2711
|
+
const manifest = await loadManifest(projectRoot, config.manifest);
|
|
2712
|
+
const backupFiles = await listBackupFiles(projectRoot, config.backup.dir);
|
|
2713
|
+
const candidateSourcePaths = /* @__PURE__ */ new Set([
|
|
2714
|
+
...Object.keys(manifest.entries),
|
|
2715
|
+
...backupFiles.map((b) => b.sourceRelPath)
|
|
2716
|
+
]);
|
|
2717
|
+
const matcher = patterns.length > 0 ? picomatch3(patterns, { dot: true, nocase: true }) : () => true;
|
|
2718
|
+
const items = [];
|
|
2719
|
+
let manifestDirty = false;
|
|
2720
|
+
for (const sourcePath of [...candidateSourcePaths].sort()) {
|
|
2721
|
+
if (!options.all && !matcher(sourcePath)) {
|
|
2722
|
+
continue;
|
|
2723
|
+
}
|
|
2724
|
+
const entry = manifest.entries[sourcePath];
|
|
2725
|
+
const backupRelPath = entry?.backupPath ?? getBackupRelPath(config.backup.dir, sourcePath);
|
|
2726
|
+
const backupAbsPath = resolveInsideRoot(projectRoot, backupRelPath);
|
|
2727
|
+
if (!await isFile(backupAbsPath)) {
|
|
2728
|
+
items.push({
|
|
2729
|
+
sourcePath,
|
|
2730
|
+
backupPath: backupRelPath,
|
|
2731
|
+
restoredBytes: 0,
|
|
2732
|
+
status: "missing-backup"
|
|
2733
|
+
});
|
|
2734
|
+
continue;
|
|
2735
|
+
}
|
|
2736
|
+
const backupStat = await fs12.stat(backupAbsPath);
|
|
2737
|
+
const destAbsPath = resolveInsideRoot(projectRoot, sourcePath);
|
|
2738
|
+
let removedOutputPath;
|
|
2739
|
+
if (entry && entry.outputPath !== sourcePath) {
|
|
2740
|
+
const convertedAbsPath = resolveInsideRoot(projectRoot, entry.outputPath);
|
|
2741
|
+
if (await fileExists(convertedAbsPath)) {
|
|
2742
|
+
removedOutputPath = entry.outputPath;
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2745
|
+
if (!dryRun) {
|
|
2746
|
+
await atomicCopyFile(backupAbsPath, destAbsPath);
|
|
2747
|
+
if (removedOutputPath) {
|
|
2748
|
+
await fs12.rm(resolveInsideRoot(projectRoot, removedOutputPath), {
|
|
2749
|
+
force: true
|
|
2750
|
+
});
|
|
2751
|
+
}
|
|
2752
|
+
if (options.deleteBackup) {
|
|
2753
|
+
await fs12.rm(backupAbsPath, { force: true });
|
|
2754
|
+
}
|
|
2755
|
+
if (entry) {
|
|
2756
|
+
delete manifest.entries[sourcePath];
|
|
2757
|
+
manifestDirty = true;
|
|
2758
|
+
}
|
|
2759
|
+
}
|
|
2760
|
+
items.push({
|
|
2761
|
+
sourcePath,
|
|
2762
|
+
backupPath: backupRelPath,
|
|
2763
|
+
removedOutputPath,
|
|
2764
|
+
restoredBytes: backupStat.size,
|
|
2765
|
+
status: "restored"
|
|
2766
|
+
});
|
|
2767
|
+
}
|
|
2768
|
+
if (manifestDirty && !dryRun) {
|
|
2769
|
+
await saveManifest(projectRoot, config.manifest, manifest);
|
|
2770
|
+
}
|
|
2771
|
+
return {
|
|
2772
|
+
dryRun,
|
|
2773
|
+
restoredCount: items.filter((i) => i.status === "restored").length,
|
|
2774
|
+
missingCount: items.filter((i) => i.status === "missing-backup").length,
|
|
2775
|
+
items
|
|
2776
|
+
};
|
|
2777
|
+
}
|
|
2778
|
+
|
|
2779
|
+
// src/cli.ts
|
|
2780
|
+
function readPackageVersion() {
|
|
2781
|
+
let dir = path14.dirname(fileURLToPath2(import.meta.url));
|
|
2782
|
+
for (let i = 0; i < 6; i += 1) {
|
|
2783
|
+
const pkgPath = path14.join(dir, "package.json");
|
|
2784
|
+
if (fsSync2.existsSync(pkgPath)) {
|
|
2785
|
+
try {
|
|
2786
|
+
const parsed = JSON.parse(fsSync2.readFileSync(pkgPath, "utf8"));
|
|
2787
|
+
if (parsed.version) return parsed.version;
|
|
2788
|
+
} catch {
|
|
2789
|
+
break;
|
|
2790
|
+
}
|
|
2791
|
+
}
|
|
2792
|
+
const parent = path14.dirname(dir);
|
|
2793
|
+
if (parent === dir) break;
|
|
2794
|
+
dir = parent;
|
|
2795
|
+
}
|
|
2796
|
+
return "0.1.0";
|
|
2797
|
+
}
|
|
2798
|
+
async function tryLoadCliConfig(configPath) {
|
|
2799
|
+
try {
|
|
2800
|
+
const loaded = await loadConfig(process.cwd(), configPath);
|
|
2801
|
+
return loaded.config.cli;
|
|
2802
|
+
} catch {
|
|
2803
|
+
return void 0;
|
|
2804
|
+
}
|
|
2805
|
+
}
|
|
2806
|
+
var program = new Command();
|
|
2807
|
+
program.name("imgopt-node").description(
|
|
2808
|
+
"Node.js asset optimizer powered by imgopt with auto-init config, idempotent incremental manifest, original backup/restore, and GitHub Action CLI management"
|
|
2809
|
+
).version(readPackageVersion());
|
|
2810
|
+
program.command("init").description(
|
|
2811
|
+
"Auto-detect project image directories (assets, public, static, docs, etc.) and generate imgopt.config.json"
|
|
2812
|
+
).option("-c, --config <path>", "Output config file path", "imgopt.config.json").option("-d, --dir <dirs...>", "Explicit asset directories to include").option(
|
|
2813
|
+
"--template <name>",
|
|
2814
|
+
"Preset template (general | web)",
|
|
2815
|
+
"general"
|
|
2816
|
+
).option("--no-backup", "Disable original image backups in generated config").option(
|
|
2817
|
+
"--backup-dir <dir>",
|
|
2818
|
+
"Directory for preserving original images",
|
|
2819
|
+
".imgopt/originals"
|
|
2820
|
+
).option("--cli-version <tag>", "Target imgopt CLI release tag", "latest").option(
|
|
2821
|
+
"--preset <preset>",
|
|
2822
|
+
"Default optimization preset (balanced | maximum | aggressive)"
|
|
2823
|
+
).option("--quality <number>", "Target SSIM quality (0.0 - 1.0)", parseFloat).option(
|
|
2824
|
+
"--effort <number>",
|
|
2825
|
+
"Encoder effort (1 - 6)",
|
|
2826
|
+
(v) => parseInt(v, 10)
|
|
2827
|
+
).option("--format <policy>", "Default output format policy", "preserve").option("--ci", "Generate .github/workflows/optimize-images.yml workflow").option("--gitignore", "Add backup directory to .gitignore").option("-f, --force", "Overwrite existing configuration file").option("--json", "Output result as JSON").action(async (opts) => {
|
|
2828
|
+
const result = await initProject({
|
|
2829
|
+
configPath: opts.config,
|
|
2830
|
+
dirs: opts.dir,
|
|
2831
|
+
template: opts.template === "web" ? "web" : "general",
|
|
2832
|
+
backup: opts.backup,
|
|
2833
|
+
backupDir: opts.backupDir,
|
|
2834
|
+
cliVersion: opts.cliVersion,
|
|
2835
|
+
preset: opts.preset,
|
|
2836
|
+
quality: opts.quality,
|
|
2837
|
+
effort: opts.effort,
|
|
2838
|
+
format: opts.format,
|
|
2839
|
+
ci: Boolean(opts.ci),
|
|
2840
|
+
gitignore: Boolean(opts.gitignore),
|
|
2841
|
+
force: Boolean(opts.force)
|
|
2842
|
+
});
|
|
2843
|
+
if (opts.json) {
|
|
2844
|
+
console.log(JSON.stringify(result, null, 2));
|
|
2845
|
+
return;
|
|
2846
|
+
}
|
|
2847
|
+
console.log(pc.green("\u2714 Initialized imgopt-node configuration"));
|
|
2848
|
+
console.log(` Config: ${result.configPath}`);
|
|
2849
|
+
console.log(` Stacks: ${result.stacks.join(", ")}`);
|
|
2850
|
+
console.log(
|
|
2851
|
+
` Targets: ${result.config.targets.map((t) => t.dir).join(", ")}`
|
|
2852
|
+
);
|
|
2853
|
+
if (result.detectedDirs.length > 0) {
|
|
2854
|
+
for (const d of result.detectedDirs) {
|
|
2855
|
+
console.log(
|
|
2856
|
+
` - ${d.dir} (${d.imageCount} image(s), ${d.source})`
|
|
2857
|
+
);
|
|
2858
|
+
}
|
|
2859
|
+
}
|
|
2860
|
+
console.log(
|
|
2861
|
+
` Backup: ${result.config.backup.enabled ? `enabled -> ${result.config.backup.dir}` : "disabled"}`
|
|
2862
|
+
);
|
|
2863
|
+
console.log(` Manifest: ${result.config.manifest}`);
|
|
2864
|
+
if (result.ciWorkflowPath) {
|
|
2865
|
+
console.log(` Workflow: ${result.ciWorkflowPath}`);
|
|
2866
|
+
}
|
|
2867
|
+
if (result.gitignoreUpdated) {
|
|
2868
|
+
console.log(" Updated: .gitignore");
|
|
2869
|
+
}
|
|
2870
|
+
console.log(
|
|
2871
|
+
pc.cyan("\nNext step: run `imgopt-node optimize` to optimize your images.")
|
|
2872
|
+
);
|
|
2873
|
+
});
|
|
2874
|
+
program.command("optimize").alias("opt").description(
|
|
2875
|
+
"Incrementally optimize configured image targets without reprocessing unchanged images"
|
|
2876
|
+
).option("-c, --config <path>", "Path to imgopt.config.json").option("--dry-run", "Preview optimizations without writing files").option("--staged", "Only optimize Git-staged image files and re-stage results").option("--force", "Reprocess files even if cached or below minBytes").option(
|
|
2877
|
+
"--reprocess-on-config-change",
|
|
2878
|
+
"Allow reprocessing already-optimized images when config changed and no backup exists"
|
|
2879
|
+
).option("--update-cli", "Check and download latest imgopt CLI before running").option("--cli-version <tag>", "Override target imgopt CLI release version").option(
|
|
2880
|
+
"--concurrency <n>",
|
|
2881
|
+
"Worker concurrency override",
|
|
2882
|
+
(v) => parseInt(v, 10)
|
|
2883
|
+
).option(
|
|
2884
|
+
"--fail-on-budget",
|
|
2885
|
+
"Exit with non-zero status if any budget warning occurs"
|
|
2886
|
+
).option("--json", "Output machine-readable JSON report").option("-q, --quiet", "Suppress per-file output").action(async (opts) => {
|
|
2887
|
+
const report = await optimizeProject({
|
|
2888
|
+
configPath: opts.config,
|
|
2889
|
+
dryRun: Boolean(opts.dryRun),
|
|
2890
|
+
staged: Boolean(opts.staged),
|
|
2891
|
+
force: Boolean(opts.force),
|
|
2892
|
+
reprocessOnConfigChange: Boolean(opts.reprocessOnConfigChange),
|
|
2893
|
+
updateCli: Boolean(opts.updateCli),
|
|
2894
|
+
cliVersion: opts.cliVersion,
|
|
2895
|
+
concurrency: opts.concurrency
|
|
2896
|
+
});
|
|
2897
|
+
if (opts.json) {
|
|
2898
|
+
console.log(JSON.stringify(report, null, 2));
|
|
2899
|
+
} else {
|
|
2900
|
+
if (!opts.quiet) {
|
|
2901
|
+
for (const item of report.items) {
|
|
2902
|
+
if (item.status === "optimized" || item.status === "reoptimized-from-backup") {
|
|
2903
|
+
const tag = item.status === "reoptimized-from-backup" ? pc.magenta("[reoptimized]") : pc.green("[optimized]");
|
|
2904
|
+
const arrow = item.sourcePath !== item.outputPath ? `${item.sourcePath} -> ${item.outputPath}` : item.outputPath;
|
|
2905
|
+
console.log(
|
|
2906
|
+
`${tag} ${arrow} (${formatBytes(item.originalBytes)} -> ${formatBytes(item.optimizedBytes)}, -${formatPercent(item.savedPercent)}${item.qualityScore !== void 0 ? `, SSIM ${item.qualityScore.toFixed(4)}` : ""})`
|
|
2907
|
+
);
|
|
2908
|
+
} else if (item.status === "failed") {
|
|
2909
|
+
console.error(
|
|
2910
|
+
`${pc.red("[failed]")} ${item.sourcePath}: ${item.error ?? "error"}`
|
|
2911
|
+
);
|
|
2912
|
+
} else if (item.status === "skipped-config-changed-no-backup") {
|
|
2913
|
+
console.log(
|
|
2914
|
+
`${pc.yellow("[skipped:no-backup]")} ${item.outputPath} (config changed; no original backup to avoid lossy re-encoding)`
|
|
2915
|
+
);
|
|
2916
|
+
}
|
|
2917
|
+
}
|
|
2918
|
+
}
|
|
2919
|
+
const s = report.summary;
|
|
2920
|
+
console.log(
|
|
2921
|
+
`
|
|
2922
|
+
${s.dryRun ? pc.yellow("Dry-run summary") : pc.bold("Summary")} (imgopt ${s.cliVersion}):`
|
|
2923
|
+
);
|
|
2924
|
+
console.log(` Scanned: ${s.totalScanned}`);
|
|
2925
|
+
console.log(
|
|
2926
|
+
` Optimized: ${s.optimized}${s.reoptimizedFromBackup > 0 ? ` (+${s.reoptimizedFromBackup} from backup)` : ""}`
|
|
2927
|
+
);
|
|
2928
|
+
console.log(
|
|
2929
|
+
` Skipped: ${s.skippedCached} cached, ${s.skippedSmall} small, ${s.skippedNoSavings} no-savings${s.skippedConfigChangedNoBackup > 0 ? `, ${s.skippedConfigChangedNoBackup} no-backup` : ""}`
|
|
2930
|
+
);
|
|
2931
|
+
if (s.failed > 0) {
|
|
2932
|
+
console.log(pc.red(` Failed: ${s.failed}`));
|
|
2933
|
+
}
|
|
2934
|
+
console.log(
|
|
2935
|
+
` Total size: ${formatBytes(s.originalBytes)} -> ${formatBytes(s.optimizedBytes)} (saved ${formatBytes(s.savedBytes)}, ${formatPercent(s.savedPercent)})`
|
|
2936
|
+
);
|
|
2937
|
+
console.log(` Elapsed: ${s.elapsedMs} ms`);
|
|
2938
|
+
if (report.budgetWarnings.length > 0) {
|
|
2939
|
+
console.log(pc.yellow("\nBudget warnings:"));
|
|
2940
|
+
for (const w of report.budgetWarnings) {
|
|
2941
|
+
console.log(
|
|
2942
|
+
` - ${w.path}: ${w.rule} = ${w.actual} (limit ${w.limit})`
|
|
2943
|
+
);
|
|
2944
|
+
}
|
|
2945
|
+
}
|
|
2946
|
+
}
|
|
2947
|
+
if (report.summary.failed > 0 || opts.failOnBudget && report.budgetWarnings.length > 0) {
|
|
2948
|
+
process.exitCode = 1;
|
|
2949
|
+
}
|
|
2950
|
+
});
|
|
2951
|
+
program.command("check").description(
|
|
2952
|
+
"Verify all target images are already optimized and comply with configured size/dimension budgets (ideal for CI)"
|
|
2953
|
+
).option("-c, --config <path>", "Path to imgopt.config.json").option("--json", "Output check result as JSON").action(async (opts) => {
|
|
2954
|
+
const result = await checkProject({ configPath: opts.config });
|
|
2955
|
+
if (opts.json) {
|
|
2956
|
+
console.log(JSON.stringify(result, null, 2));
|
|
2957
|
+
} else {
|
|
2958
|
+
console.log(
|
|
2959
|
+
result.ok ? pc.green(`\u2714 All ${result.upToDate} image(s) are up-to-date and within budgets.`) : pc.red(`\u2716 Optimization check failed:`)
|
|
2960
|
+
);
|
|
2961
|
+
if (result.pending.length > 0) {
|
|
2962
|
+
console.log(
|
|
2963
|
+
pc.yellow(`
|
|
2964
|
+
Pending optimization (${result.pending.length}):`)
|
|
2965
|
+
);
|
|
2966
|
+
for (const item of result.pending) {
|
|
2967
|
+
console.log(
|
|
2968
|
+
` - ${item.path} (${formatBytes(item.bytes)}, ${item.reason})`
|
|
2969
|
+
);
|
|
2970
|
+
}
|
|
2971
|
+
}
|
|
2972
|
+
if (result.budgetViolations.length > 0) {
|
|
2973
|
+
console.log(
|
|
2974
|
+
pc.red(`
|
|
2975
|
+
Budget violations (${result.budgetViolations.length}):`)
|
|
2976
|
+
);
|
|
2977
|
+
for (const v of result.budgetViolations) {
|
|
2978
|
+
console.log(` - ${v.path}: ${v.rule} = ${v.actual} (limit ${v.limit})`);
|
|
2979
|
+
}
|
|
2980
|
+
}
|
|
2981
|
+
}
|
|
2982
|
+
if (!result.ok) {
|
|
2983
|
+
process.exitCode = 1;
|
|
2984
|
+
}
|
|
2985
|
+
});
|
|
2986
|
+
program.command("restore [patterns...]").description("Restore original unoptimized images from backup directory").option("-c, --config <path>", "Path to imgopt.config.json").option("--all", "Restore all backed-up originals").option("--dry-run", "Preview restore without modifying files").option("--delete-backup", "Remove backup file after restoring").option("--json", "Output JSON result").action(async (patterns, opts) => {
|
|
2987
|
+
const result = await restoreOriginals({
|
|
2988
|
+
configPath: opts.config,
|
|
2989
|
+
patterns,
|
|
2990
|
+
all: Boolean(opts.all),
|
|
2991
|
+
dryRun: Boolean(opts.dryRun),
|
|
2992
|
+
deleteBackup: Boolean(opts.deleteBackup)
|
|
2993
|
+
});
|
|
2994
|
+
if (opts.json) {
|
|
2995
|
+
console.log(JSON.stringify(result, null, 2));
|
|
2996
|
+
} else {
|
|
2997
|
+
for (const item of result.items) {
|
|
2998
|
+
if (item.status === "restored") {
|
|
2999
|
+
console.log(
|
|
3000
|
+
`${pc.green("[restored]")} ${item.sourcePath} (${formatBytes(item.restoredBytes)})${item.removedOutputPath ? ` [removed ${item.removedOutputPath}]` : ""}`
|
|
3001
|
+
);
|
|
3002
|
+
} else if (item.status === "missing-backup") {
|
|
3003
|
+
console.log(
|
|
3004
|
+
`${pc.yellow("[missing-backup]")} ${item.sourcePath} (${item.backupPath})`
|
|
3005
|
+
);
|
|
3006
|
+
}
|
|
3007
|
+
}
|
|
3008
|
+
console.log(
|
|
3009
|
+
`
|
|
3010
|
+
${result.dryRun ? "Dry-run: " : ""}Restored ${result.restoredCount} file(s), ${result.missingCount} missing backup(s).`
|
|
3011
|
+
);
|
|
3012
|
+
}
|
|
3013
|
+
if (result.missingCount > 0) {
|
|
3014
|
+
process.exitCode = 1;
|
|
3015
|
+
}
|
|
3016
|
+
});
|
|
3017
|
+
program.command("clean").description(
|
|
3018
|
+
"Remove orphan original backups and stale manifest entries for deleted project files"
|
|
3019
|
+
).option("-c, --config <path>", "Path to imgopt.config.json").option("--cache", "Also remove older cached imgopt CLI binary versions").option("--dry-run", "Preview cleanup without deleting anything").option("--json", "Output JSON result").action(async (opts) => {
|
|
3020
|
+
const result = await cleanProject({
|
|
3021
|
+
configPath: opts.config,
|
|
3022
|
+
dryRun: Boolean(opts.dryRun),
|
|
3023
|
+
cache: Boolean(opts.cache)
|
|
3024
|
+
});
|
|
3025
|
+
if (opts.json) {
|
|
3026
|
+
console.log(JSON.stringify(result, null, 2));
|
|
3027
|
+
return;
|
|
3028
|
+
}
|
|
3029
|
+
console.log(
|
|
3030
|
+
`${result.dryRun ? "Dry-run cleanup:" : "Cleanup complete:"}`
|
|
3031
|
+
);
|
|
3032
|
+
console.log(
|
|
3033
|
+
` Orphan backups removed: ${result.removedBackups.length} (${formatBytes(result.reclaimedBytes)})`
|
|
3034
|
+
);
|
|
3035
|
+
console.log(
|
|
3036
|
+
` Stale manifest entries: ${result.removedManifestEntries.length}`
|
|
3037
|
+
);
|
|
3038
|
+
if (opts.cache) {
|
|
3039
|
+
console.log(
|
|
3040
|
+
` Old CLI caches removed: ${result.removedCacheVersions.length}`
|
|
3041
|
+
);
|
|
3042
|
+
}
|
|
3043
|
+
});
|
|
3044
|
+
program.command("inspect [path]").description("Inspect image dimensions, format, channels, and metadata").option("-c, --config <path>", "Path to imgopt.config.json").option("--json", "Output JSON array").action(async (targetPath, opts) => {
|
|
3045
|
+
const entries = await inspectProject({
|
|
3046
|
+
configPath: opts.config,
|
|
3047
|
+
targetPath
|
|
3048
|
+
});
|
|
3049
|
+
if (opts.json) {
|
|
3050
|
+
console.log(JSON.stringify(entries, null, 2));
|
|
3051
|
+
return;
|
|
3052
|
+
}
|
|
3053
|
+
for (const item of entries) {
|
|
3054
|
+
if (item.error) {
|
|
3055
|
+
console.log(`${pc.red("[error]")} ${item.path}: ${item.error}`);
|
|
3056
|
+
} else {
|
|
3057
|
+
const dims = item.dimensions ? `${item.dimensions.width}x${item.dimensions.height}` : "unknown";
|
|
3058
|
+
console.log(
|
|
3059
|
+
`${pc.cyan(item.path)}: ${item.format ?? "unknown"}, ${dims}, ${formatBytes(item.byte_size ?? 0)}`
|
|
3060
|
+
);
|
|
3061
|
+
}
|
|
3062
|
+
}
|
|
3063
|
+
});
|
|
3064
|
+
program.command("doctor").description("Diagnose configuration, imgopt CLI binary, backups, and manifest health").option("-c, --config <path>", "Path to imgopt.config.json").option("--offline", "Skip checking remote GitHub release version").option("--json", "Output JSON report").action(async (opts) => {
|
|
3065
|
+
const report = await doctorProject({
|
|
3066
|
+
configPath: opts.config,
|
|
3067
|
+
checkRemote: !opts.offline
|
|
3068
|
+
});
|
|
3069
|
+
if (opts.json) {
|
|
3070
|
+
console.log(JSON.stringify(report, null, 2));
|
|
3071
|
+
} else {
|
|
3072
|
+
for (const check of report.checks) {
|
|
3073
|
+
const icon = check.status === "ok" ? pc.green("\u2714") : check.status === "warn" ? pc.yellow("!") : pc.red("\u2716");
|
|
3074
|
+
console.log(`${icon} [${check.name}] ${check.message}`);
|
|
3075
|
+
}
|
|
3076
|
+
}
|
|
3077
|
+
if (!report.ok) {
|
|
3078
|
+
process.exitCode = 1;
|
|
3079
|
+
}
|
|
3080
|
+
});
|
|
3081
|
+
var cliCmd = program.command("cli").description("Manage and download the underlying imgopt CLI binary");
|
|
3082
|
+
cliCmd.command("status").description("Show resolved imgopt binary, cached versions, and latest release").option("-c, --config <path>", "Path to imgopt.config.json").option("--offline", "Skip querying GitHub Releases").option("--json", "Output JSON").action(async (opts) => {
|
|
3083
|
+
const cliConfig = await tryLoadCliConfig(opts.config);
|
|
3084
|
+
const status = await getCliStatus(cliConfig, !opts.offline);
|
|
3085
|
+
if (opts.json) {
|
|
3086
|
+
console.log(JSON.stringify(status, null, 2));
|
|
3087
|
+
return;
|
|
3088
|
+
}
|
|
3089
|
+
console.log(`Repo: ${status.repo}`);
|
|
3090
|
+
console.log(`Configured: ${status.configuredVersion}`);
|
|
3091
|
+
console.log(
|
|
3092
|
+
`Installed: ${status.installedTag ?? status.installedVersion ?? "none"} (${status.source})`
|
|
3093
|
+
);
|
|
3094
|
+
console.log(`Binary path: ${status.resolvedBinPath ?? "-"}`);
|
|
3095
|
+
console.log(`Latest remote: ${status.latestRemoteVersion ?? "unknown"}`);
|
|
3096
|
+
console.log(
|
|
3097
|
+
`Update available: ${status.updateAvailable ? pc.yellow("yes") : "no"}`
|
|
3098
|
+
);
|
|
3099
|
+
console.log(`Cache dir: ${status.cacheDir}`);
|
|
3100
|
+
console.log(
|
|
3101
|
+
`Cached versions: ${status.cachedVersions.length > 0 ? status.cachedVersions.join(", ") : "none"}`
|
|
3102
|
+
);
|
|
3103
|
+
});
|
|
3104
|
+
cliCmd.command("update").alias("download").description("Download latest (or specific tag) imgopt CLI binary from GitHub Releases").option("-c, --config <path>", "Path to imgopt.config.json").option("-v, --cli-version <tag>", "Release tag to download (e.g. latest or v0.1.2)").option("-f, --force", "Force re-download even if version is already cached").option("--json", "Output JSON").action(async (opts) => {
|
|
3105
|
+
const cliConfig = await tryLoadCliConfig(opts.config);
|
|
3106
|
+
const info = await downloadCliRelease({
|
|
3107
|
+
repo: cliConfig?.repo,
|
|
3108
|
+
version: opts.cliVersion ?? cliConfig?.version ?? "latest",
|
|
3109
|
+
cacheDir: cliConfig?.cacheDir,
|
|
3110
|
+
downloadBaseUrl: cliConfig?.downloadBaseUrl,
|
|
3111
|
+
force: Boolean(opts.force)
|
|
3112
|
+
});
|
|
3113
|
+
if (opts.json) {
|
|
3114
|
+
console.log(JSON.stringify(info, null, 2));
|
|
3115
|
+
return;
|
|
3116
|
+
}
|
|
3117
|
+
console.log(
|
|
3118
|
+
`${pc.green("\u2714 imgopt ready:")} ${info.tag} (binary ${info.version}, ${info.source})`
|
|
3119
|
+
);
|
|
3120
|
+
console.log(` Path: ${info.binPath}`);
|
|
3121
|
+
});
|
|
3122
|
+
cliCmd.command("path").description("Ensure imgopt binary is available and print its executable path").option("-c, --config <path>", "Path to imgopt.config.json").action(async (opts) => {
|
|
3123
|
+
const cliConfig = await tryLoadCliConfig(opts.config);
|
|
3124
|
+
const info = await ensureCli({ cliConfig });
|
|
3125
|
+
console.log(info.binPath);
|
|
3126
|
+
});
|
|
3127
|
+
program.parseAsync(process.argv).catch((err) => {
|
|
3128
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3129
|
+
console.error(pc.red(`Error: ${msg}`));
|
|
3130
|
+
process.exit(1);
|
|
3131
|
+
});
|