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