epub-optimizer 0.0.0-stage → 3.16.0
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/LICENSE +21 -0
- package/README.md +1434 -2
- package/dist/src/batch.d.ts +34 -0
- package/dist/src/batch.js +137 -0
- package/dist/src/cli.d.ts +7 -0
- package/dist/src/cli.js +275 -0
- package/dist/src/index.d.ts +23 -0
- package/dist/src/index.js +24 -0
- package/dist/src/optimization.d.ts +7 -0
- package/dist/src/optimization.js +207 -0
- package/dist/src/pipeline.d.ts +2 -0
- package/dist/src/pipeline.js +48 -0
- package/dist/src/processors/archive-processor.d.ts +26 -0
- package/dist/src/processors/archive-processor.js +170 -0
- package/dist/src/processors/epub-processor.d.ts +17 -0
- package/dist/src/processors/epub-processor.js +133 -0
- package/dist/src/processors/font-characters.d.ts +2 -0
- package/dist/src/processors/font-characters.js +227 -0
- package/dist/src/processors/font-engine.d.ts +6 -0
- package/dist/src/processors/font-engine.js +101 -0
- package/dist/src/processors/font-limits.d.ts +3 -0
- package/dist/src/processors/font-limits.js +3 -0
- package/dist/src/processors/font-processor.d.ts +4 -0
- package/dist/src/processors/font-processor.js +121 -0
- package/dist/src/processors/font-runner.d.ts +8 -0
- package/dist/src/processors/font-runner.js +94 -0
- package/dist/src/processors/font-worker.d.ts +1 -0
- package/dist/src/processors/font-worker.js +12 -0
- package/dist/src/processors/html-processor.d.ts +22 -0
- package/dist/src/processors/html-processor.js +190 -0
- package/dist/src/processors/image-converter.d.ts +14 -0
- package/dist/src/processors/image-converter.js +481 -0
- package/dist/src/processors/image-processor.d.ts +24 -0
- package/dist/src/processors/image-processor.js +165 -0
- package/dist/src/processors/js-processor.d.ts +7 -0
- package/dist/src/processors/js-processor.js +59 -0
- package/dist/src/processors/lazy-img.d.ts +5 -0
- package/dist/src/processors/lazy-img.js +48 -0
- package/dist/src/processors/svg-optimizer.d.ts +5 -0
- package/dist/src/processors/svg-optimizer.js +49 -0
- package/dist/src/scripts/create-epub.d.ts +2 -0
- package/dist/src/scripts/create-epub.js +29 -0
- package/dist/src/scripts/fix/fix-span-tags.d.ts +2 -0
- package/dist/src/scripts/fix/fix-span-tags.js +36 -0
- package/dist/src/scripts/fix/fix-xml.d.ts +3 -0
- package/dist/src/scripts/fix/fix-xml.js +59 -0
- package/dist/src/scripts/fix/index.d.ts +5 -0
- package/dist/src/scripts/fix/index.js +20 -0
- package/dist/src/scripts/fix/remove-empty-styles.d.ts +10 -0
- package/dist/src/scripts/fix/remove-empty-styles.js +53 -0
- package/dist/src/scripts/fix/xhtml-files.d.ts +2 -0
- package/dist/src/scripts/fix/xhtml-files.js +34 -0
- package/dist/src/scripts/ops/add-chapter-sections-to-toc.d.ts +5 -0
- package/dist/src/scripts/ops/add-chapter-sections-to-toc.js +242 -0
- package/dist/src/scripts/ops/add-cover-image-property.d.ts +2 -0
- package/dist/src/scripts/ops/add-cover-image-property.js +27 -0
- package/dist/src/scripts/ops/ncx.d.ts +6 -0
- package/dist/src/scripts/ops/ncx.js +19 -0
- package/dist/src/scripts/ops/update-cover-linear.d.ts +11 -0
- package/dist/src/scripts/ops/update-cover-linear.js +45 -0
- package/dist/src/scripts/ops/update-structure.d.ts +5 -0
- package/dist/src/scripts/ops/update-structure.js +22 -0
- package/dist/src/scripts/ops/update-summary-page.d.ts +2 -0
- package/dist/src/scripts/ops/update-summary-page.js +53 -0
- package/dist/src/scripts/ops/update-toc-with-cover.d.ts +2 -0
- package/dist/src/scripts/ops/update-toc-with-cover.js +140 -0
- package/dist/src/scripts/utils.d.ts +53 -0
- package/dist/src/scripts/utils.js +92 -0
- package/dist/src/scripts/validate-epub.d.ts +12 -0
- package/dist/src/scripts/validate-epub.js +185 -0
- package/dist/src/storage.d.ts +30 -0
- package/dist/src/storage.js +286 -0
- package/dist/src/types.d.ts +51 -0
- package/dist/src/types.js +1 -0
- package/dist/src/utils/author-workflow-config.d.ts +17 -0
- package/dist/src/utils/author-workflow-config.js +95 -0
- package/dist/src/utils/buffered-process.d.ts +8 -0
- package/dist/src/utils/buffered-process.js +36 -0
- package/dist/src/utils/cli-config.d.ts +4 -0
- package/dist/src/utils/cli-config.js +84 -0
- package/dist/src/utils/config.d.ts +49 -0
- package/dist/src/utils/config.js +58 -0
- package/dist/src/utils/diagnostics.d.ts +11 -0
- package/dist/src/utils/diagnostics.js +38 -0
- package/dist/src/utils/epub-doctor.d.ts +78 -0
- package/dist/src/utils/epub-doctor.js +301 -0
- package/dist/src/utils/epub-features.d.ts +20 -0
- package/dist/src/utils/epub-features.js +105 -0
- package/dist/src/utils/epub-integrity.d.ts +25 -0
- package/dist/src/utils/epub-integrity.js +197 -0
- package/dist/src/utils/epub-text.d.ts +13 -0
- package/dist/src/utils/epub-text.js +106 -0
- package/dist/src/utils/epub-utils.d.ts +79 -0
- package/dist/src/utils/epub-utils.js +207 -0
- package/dist/src/utils/epubcheck-report.d.ts +35 -0
- package/dist/src/utils/epubcheck-report.js +68 -0
- package/dist/src/utils/file-size.d.ts +13 -0
- package/dist/src/utils/file-size.js +40 -0
- package/dist/src/utils/files.d.ts +14 -0
- package/dist/src/utils/files.js +39 -0
- package/dist/src/utils/html-report.d.ts +17 -0
- package/dist/src/utils/html-report.js +95 -0
- package/dist/src/utils/i18n.d.ts +5 -0
- package/dist/src/utils/i18n.js +9 -0
- package/dist/src/utils/output-transaction.d.ts +8 -0
- package/dist/src/utils/output-transaction.js +146 -0
- package/dist/src/utils/package-root.d.ts +2 -0
- package/dist/src/utils/package-root.js +15 -0
- package/dist/src/utils/path-safety.d.ts +2 -0
- package/dist/src/utils/path-safety.js +30 -0
- package/dist/src/utils/pipeline-options.d.ts +34 -0
- package/dist/src/utils/pipeline-options.js +49 -0
- package/dist/src/utils/png-animation.d.ts +7 -0
- package/dist/src/utils/png-animation.js +44 -0
- package/dist/src/utils/run-report.d.ts +49 -0
- package/dist/src/utils/run-report.js +71 -0
- package/dist/src/utils/temp-dir.d.ts +11 -0
- package/dist/src/utils/temp-dir.js +80 -0
- package/dist/src/utils/watch-lock.d.ts +8 -0
- package/dist/src/utils/watch-lock.js +100 -0
- package/dist/src/utils/watch-summary.d.ts +13 -0
- package/dist/src/utils/watch-summary.js +130 -0
- package/dist/src/utils/xhtml-structure.d.ts +7 -0
- package/dist/src/utils/xhtml-structure.js +53 -0
- package/dist/src/utils/xhtml.d.ts +27 -0
- package/dist/src/utils/xhtml.js +205 -0
- package/dist/src/utils/xml-dtd.d.ts +6 -0
- package/dist/src/utils/xml-dtd.js +133 -0
- package/dist/src/watch.d.ts +21 -0
- package/dist/src/watch.js +328 -0
- package/package.json +99 -3
- package/scripts/install-epubcheck.sh +44 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Args } from "./types.js";
|
|
2
|
+
import type { PipelineReport } from "./utils/run-report.js";
|
|
3
|
+
export interface BatchItem {
|
|
4
|
+
input: string;
|
|
5
|
+
output: string;
|
|
6
|
+
reportJson: string;
|
|
7
|
+
reportHtml?: string;
|
|
8
|
+
success: boolean;
|
|
9
|
+
outputPublished: boolean;
|
|
10
|
+
error?: string;
|
|
11
|
+
sizes?: PipelineReport["sizes"];
|
|
12
|
+
}
|
|
13
|
+
export interface BatchReport {
|
|
14
|
+
inputDirectory: string;
|
|
15
|
+
outputDirectory: string;
|
|
16
|
+
startedAt: string;
|
|
17
|
+
completedAt?: string;
|
|
18
|
+
success: boolean;
|
|
19
|
+
total: number;
|
|
20
|
+
succeeded: number;
|
|
21
|
+
failed: number;
|
|
22
|
+
books: BatchItem[];
|
|
23
|
+
}
|
|
24
|
+
interface BatchPlan {
|
|
25
|
+
inputDirectory: string;
|
|
26
|
+
outputDirectory: string;
|
|
27
|
+
reportJson: string;
|
|
28
|
+
reportHtml?: string;
|
|
29
|
+
books: Array<Omit<BatchItem, "success" | "outputPublished">>;
|
|
30
|
+
}
|
|
31
|
+
export declare function planBatch(args: Args): Promise<BatchPlan>;
|
|
32
|
+
export declare function renderBatchReport(report: BatchReport): string;
|
|
33
|
+
export declare function runBatch(args: Args): Promise<BatchReport>;
|
|
34
|
+
export {};
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import pLimit from "p-limit";
|
|
2
|
+
import { reportError, reportInfo } from "./utils/diagnostics.js";
|
|
3
|
+
import fs from "fs-extra";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { runOptimization } from "./optimization.js";
|
|
8
|
+
import { assertDistinctInputOutput, assertDistinctPathSet, assertSafeOutputTarget, } from "./utils/output-transaction.js";
|
|
9
|
+
import { escapeHtml, htmlDocument } from "./utils/html-report.js";
|
|
10
|
+
import { resolvePngBackground } from "./utils/pipeline-options.js";
|
|
11
|
+
export async function planBatch(args) {
|
|
12
|
+
resolvePngBackground(args);
|
|
13
|
+
if (!Number.isSafeInteger(args.jobs ?? 1) || (args.jobs ?? 1) < 1 || (args.jobs ?? 1) > 4)
|
|
14
|
+
throw new Error("Batch jobs must be an integer between 1 and 4.");
|
|
15
|
+
if (args.storage || args.applyStoragePlan)
|
|
16
|
+
throw new Error("Storage cannot be combined with batch optimization.");
|
|
17
|
+
if (!args.batch || !args.outputDir)
|
|
18
|
+
throw new Error("Batch processing requires --batch and --output-dir.");
|
|
19
|
+
if (args.watch)
|
|
20
|
+
throw new Error("Batch cannot be combined with watch mode.");
|
|
21
|
+
if (args.doctor || args.inspect)
|
|
22
|
+
throw new Error("Batch processing supports optimization only.");
|
|
23
|
+
const inputDirectory = path.resolve(args.batch), outputDirectory = path.resolve(args.outputDir);
|
|
24
|
+
if (!(await fs.lstat(inputDirectory)).isDirectory())
|
|
25
|
+
throw new Error("Batch input must be a real directory, not a symbolic link.");
|
|
26
|
+
assertDistinctInputOutput(inputDirectory, outputDirectory);
|
|
27
|
+
try {
|
|
28
|
+
if (!(await fs.lstat(outputDirectory)).isDirectory())
|
|
29
|
+
throw new Error("Batch output must be a real directory, not a symbolic link.");
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (error.code !== "ENOENT")
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
const entries = await fs.readdir(inputDirectory, { withFileTypes: true });
|
|
36
|
+
const inputs = [];
|
|
37
|
+
for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
|
|
38
|
+
if (!/\.epub$/i.test(entry.name))
|
|
39
|
+
continue;
|
|
40
|
+
if (entry.isSymbolicLink())
|
|
41
|
+
throw new Error(`Refusing symbolic-link batch input: ${entry.name}`);
|
|
42
|
+
if (entry.isFile())
|
|
43
|
+
inputs.push(path.join(inputDirectory, entry.name));
|
|
44
|
+
}
|
|
45
|
+
if (inputs.length === 0)
|
|
46
|
+
throw new Error("No regular EPUB files found in the batch input directory.");
|
|
47
|
+
const reportJson = path.resolve(args.reportJson ?? path.join(outputDirectory, "batch-report.json"));
|
|
48
|
+
const reportHtml = args.reportHtml ? path.resolve(args.reportHtml) : undefined;
|
|
49
|
+
const books = inputs.map((input) => {
|
|
50
|
+
const stem = path.basename(input, path.extname(input));
|
|
51
|
+
return {
|
|
52
|
+
input,
|
|
53
|
+
output: path.join(outputDirectory, `${stem}-optimized.epub`),
|
|
54
|
+
reportJson: path.join(outputDirectory, "reports", `${stem}.json`),
|
|
55
|
+
reportHtml: reportHtml ? path.join(outputDirectory, "reports", `${stem}.html`) : undefined,
|
|
56
|
+
};
|
|
57
|
+
});
|
|
58
|
+
const paths = [
|
|
59
|
+
...inputs,
|
|
60
|
+
reportJson,
|
|
61
|
+
...(reportHtml ? [reportHtml] : []),
|
|
62
|
+
...books.flatMap((book) => [
|
|
63
|
+
book.output,
|
|
64
|
+
book.reportJson,
|
|
65
|
+
...(book.reportHtml ? [book.reportHtml] : []),
|
|
66
|
+
]),
|
|
67
|
+
];
|
|
68
|
+
assertDistinctPathSet(paths);
|
|
69
|
+
// Validate the whole plan before creating directories, reports or outputs.
|
|
70
|
+
for (const target of paths.slice(inputs.length))
|
|
71
|
+
await assertSafeOutputTarget(target);
|
|
72
|
+
return { inputDirectory, outputDirectory, reportJson, reportHtml, books };
|
|
73
|
+
}
|
|
74
|
+
export function renderBatchReport(report) {
|
|
75
|
+
const e = escapeHtml;
|
|
76
|
+
return htmlDocument("EPUB batch report", `<header><p>EPUB Optimizer · batch</p><h1>Batch optimization report</h1><p>${e(report.inputDirectory)}</p></header><div class="cards"><div class="card">Books<strong>${report.total}</strong></div><div class="card">Completed<strong class="success">${report.succeeded}</strong></div><div class="card">Failed<strong class="failed">${report.failed}</strong></div></div><p>Started: ${e(report.startedAt)} · Completed: ${e(report.completedAt ?? "In progress")}</p><p>Output directory: <code>${e(report.outputDirectory)}</code></p><div class="table"><table><thead><tr><th>Book</th><th>Run result</th><th>Output published</th><th>Reduction</th><th>Diagnostic</th></tr></thead><tbody>${report.books.map((book) => `<tr><td>${e(path.basename(book.input))}</td><td class="${book.success ? "success" : "failed"}">${book.success ? "completed" : "failed"}</td><td>${book.outputPublished ? "yes" : "no"}</td><td>${book.sizes ? `${book.sizes.reductionPercent.toFixed(1)}%` : "—"}</td><td>${e(book.error ?? "—")}<br>JSON: <code>${e(book.reportJson)}</code>${book.reportHtml ? `<br>HTML: <code>${e(book.reportHtml)}</code>` : ""}</td></tr>`).join("")}</tbody></table></div><p>Books use bounded concurrency (one by default); rows retain input order. A failed run can still have published a validated output when a later cleanup or report operation failed; check the per-book report.</p>`);
|
|
77
|
+
}
|
|
78
|
+
export async function runBatch(args) {
|
|
79
|
+
const plan = await planBatch(args);
|
|
80
|
+
const report = {
|
|
81
|
+
inputDirectory: plan.inputDirectory,
|
|
82
|
+
outputDirectory: plan.outputDirectory,
|
|
83
|
+
startedAt: new Date().toISOString(),
|
|
84
|
+
success: false,
|
|
85
|
+
total: plan.books.length,
|
|
86
|
+
succeeded: 0,
|
|
87
|
+
failed: 0,
|
|
88
|
+
books: [],
|
|
89
|
+
};
|
|
90
|
+
await fs.ensureDir(plan.outputDirectory);
|
|
91
|
+
const limit = pLimit(args.jobs ?? 1);
|
|
92
|
+
report.books = await Promise.all(plan.books.map((book, index) => limit(async () => {
|
|
93
|
+
reportInfo(`\n=== Batch book ${index + 1}/${plan.books.length}: ${path.basename(book.input)} ===`);
|
|
94
|
+
const item = { ...book, success: false, outputPublished: false };
|
|
95
|
+
let detail;
|
|
96
|
+
try {
|
|
97
|
+
await runOptimization({
|
|
98
|
+
...args,
|
|
99
|
+
batch: undefined,
|
|
100
|
+
outputDir: undefined,
|
|
101
|
+
input: book.input,
|
|
102
|
+
output: book.output,
|
|
103
|
+
reportJson: book.reportJson,
|
|
104
|
+
reportHtml: book.reportHtml,
|
|
105
|
+
temp: path.join(os.tmpdir(), `epub-batch-${randomUUID()}`),
|
|
106
|
+
}, {
|
|
107
|
+
onReport: (current) => {
|
|
108
|
+
detail = current;
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
item.success = true;
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
item.error = error instanceof Error ? error.message : String(error);
|
|
115
|
+
reportError(`Batch book failed: ${path.basename(book.input)}: ${item.error}`);
|
|
116
|
+
}
|
|
117
|
+
// Use the in-memory report from this invocation, never a stale file or old output.
|
|
118
|
+
item.outputPublished =
|
|
119
|
+
detail?.steps.some((step) => step.name === "Publish validated EPUB" && step.status === "success") ?? false;
|
|
120
|
+
item.sizes = detail?.sizes;
|
|
121
|
+
if (item.success)
|
|
122
|
+
report.succeeded++;
|
|
123
|
+
else
|
|
124
|
+
report.failed++;
|
|
125
|
+
return item;
|
|
126
|
+
})));
|
|
127
|
+
report.completedAt = new Date().toISOString();
|
|
128
|
+
report.success = report.failed === 0;
|
|
129
|
+
await fs.ensureDir(path.dirname(plan.reportJson));
|
|
130
|
+
await fs.writeJson(plan.reportJson, report, { spaces: 2 });
|
|
131
|
+
if (plan.reportHtml) {
|
|
132
|
+
await fs.ensureDir(path.dirname(plan.reportHtml));
|
|
133
|
+
await fs.writeFile(plan.reportHtml, renderBatchReport(report), "utf8");
|
|
134
|
+
}
|
|
135
|
+
reportInfo(`Batch complete: ${report.succeeded}/${report.total} succeeded, ${report.failed} failed. Report: ${plan.reportJson}`);
|
|
136
|
+
return report;
|
|
137
|
+
}
|
package/dist/src/cli.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { readCliConfig, protectCliConfig } from "./utils/cli-config.js";
|
|
2
|
+
import yargs from "yargs/yargs";
|
|
3
|
+
import { hideBin } from "yargs/helpers";
|
|
4
|
+
import config from "./utils/config.js";
|
|
5
|
+
import fs from "fs-extra";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { randomUUID } from "node:crypto";
|
|
8
|
+
import { DEFAULT_FILE_CONCURRENCY } from "./utils/files.js";
|
|
9
|
+
import { applyPipelineOptions } from "./utils/pipeline-options.js";
|
|
10
|
+
import { findPackageRoot } from "./utils/package-root.js";
|
|
11
|
+
const packageJson = JSON.parse(fs.readFileSync(path.join(findPackageRoot(import.meta.url), "package.json"), "utf8"));
|
|
12
|
+
/**
|
|
13
|
+
* Parse command line arguments
|
|
14
|
+
* @returns Promise<Args> Parsed CLI options
|
|
15
|
+
*/
|
|
16
|
+
async function parseArguments() {
|
|
17
|
+
const parsed = await yargs(hideBin(process.argv))
|
|
18
|
+
.config("config", "Load explicit JSON configuration (CLI options take precedence)", readCliConfig)
|
|
19
|
+
.usage(`${packageJson.description}\n\nUsage: epub-optimizer [options]`)
|
|
20
|
+
.option("input", {
|
|
21
|
+
alias: "i",
|
|
22
|
+
describe: "Input EPUB file path",
|
|
23
|
+
type: "string",
|
|
24
|
+
default: config.inputEPUB,
|
|
25
|
+
})
|
|
26
|
+
.option("output", {
|
|
27
|
+
alias: "o",
|
|
28
|
+
describe: "Output EPUB file path",
|
|
29
|
+
type: "string",
|
|
30
|
+
default: config.outputEPUB,
|
|
31
|
+
})
|
|
32
|
+
.option("batch", {
|
|
33
|
+
describe: "Optimize regular EPUB files in this directory (non-recursive)",
|
|
34
|
+
type: "string",
|
|
35
|
+
})
|
|
36
|
+
.option("jobs", {
|
|
37
|
+
describe: "Concurrent batch books (1-4); each has its own image and Java memory use",
|
|
38
|
+
type: "number",
|
|
39
|
+
default: 1,
|
|
40
|
+
})
|
|
41
|
+
.option("storage", {
|
|
42
|
+
describe: "Inspect watcher output storage without deleting files",
|
|
43
|
+
type: "string",
|
|
44
|
+
})
|
|
45
|
+
.option("storage-plan", {
|
|
46
|
+
describe: "Save a new read-only storage purge preview",
|
|
47
|
+
type: "string",
|
|
48
|
+
})
|
|
49
|
+
.option("apply-storage-plan", {
|
|
50
|
+
describe: "Apply a saved and reverified storage plan",
|
|
51
|
+
type: "string",
|
|
52
|
+
})
|
|
53
|
+
.option("keep-revisions", {
|
|
54
|
+
describe: "Successful revisions retained per original (minimum 1)",
|
|
55
|
+
type: "number",
|
|
56
|
+
default: 2,
|
|
57
|
+
})
|
|
58
|
+
.option("watch", {
|
|
59
|
+
describe: "Continuously optimize stable EPUB files in this directory (non-recursive)",
|
|
60
|
+
type: "string",
|
|
61
|
+
})
|
|
62
|
+
.option("watch-settle-ms", {
|
|
63
|
+
describe: "Wait this long without file changes before processing a watched EPUB",
|
|
64
|
+
type: "number",
|
|
65
|
+
default: 3000,
|
|
66
|
+
})
|
|
67
|
+
.option("output-dir", {
|
|
68
|
+
describe: "Destination directory for batch/watch outputs and per-book reports",
|
|
69
|
+
type: "string",
|
|
70
|
+
})
|
|
71
|
+
.option("temp", {
|
|
72
|
+
alias: "t",
|
|
73
|
+
describe: "New temporary directory (must not already exist); unique by default",
|
|
74
|
+
type: "string",
|
|
75
|
+
default: () => `${config.tempDir}-${randomUUID()}`,
|
|
76
|
+
defaultDescription: "unique temp_epub-<id> directory",
|
|
77
|
+
})
|
|
78
|
+
.option("jpg-quality", {
|
|
79
|
+
describe: "JPEG compression quality (0-100)",
|
|
80
|
+
type: "number",
|
|
81
|
+
default: config.jpegOptions.quality,
|
|
82
|
+
})
|
|
83
|
+
.option("png-quality", {
|
|
84
|
+
describe: "PNG compression quality (0-1 scale, use decimal)",
|
|
85
|
+
type: "number",
|
|
86
|
+
default: config.pngOptions.quality,
|
|
87
|
+
})
|
|
88
|
+
.option("png-background", {
|
|
89
|
+
describe: "Flatten eligible transparent PNGs onto an opaque #RRGGBB color before JPEG conversion",
|
|
90
|
+
type: "string",
|
|
91
|
+
requiresArg: true,
|
|
92
|
+
})
|
|
93
|
+
.option("lang", {
|
|
94
|
+
describe: "UI language for labels (e.g. fr, en)",
|
|
95
|
+
type: "string",
|
|
96
|
+
default: config.lang,
|
|
97
|
+
})
|
|
98
|
+
.option("fonts", {
|
|
99
|
+
describe: "Enable conservative HarfBuzz font subsetting (optional)",
|
|
100
|
+
type: "boolean",
|
|
101
|
+
default: false,
|
|
102
|
+
})
|
|
103
|
+
.option("preset", {
|
|
104
|
+
describe: "Optimization preset",
|
|
105
|
+
choices: ["balanced", "lossless", "author"],
|
|
106
|
+
default: "balanced",
|
|
107
|
+
})
|
|
108
|
+
.option("repair", {
|
|
109
|
+
describe: "Apply potentially modifying XHTML repair passes",
|
|
110
|
+
type: "boolean",
|
|
111
|
+
default: false,
|
|
112
|
+
})
|
|
113
|
+
.option("author-workflow", {
|
|
114
|
+
describe: "Enable this project's complete author workflow (includes --repair)",
|
|
115
|
+
type: "boolean",
|
|
116
|
+
default: false,
|
|
117
|
+
})
|
|
118
|
+
.option("author-config", {
|
|
119
|
+
describe: "JSON overrides for the author workflow's summary, cover, and CSS class mapping",
|
|
120
|
+
type: "string",
|
|
121
|
+
})
|
|
122
|
+
.option("convert-png", {
|
|
123
|
+
describe: "Convert large opaque PNG files to JPEG when safe",
|
|
124
|
+
type: "boolean",
|
|
125
|
+
})
|
|
126
|
+
.option("lazy-loading", {
|
|
127
|
+
describe: 'Add loading="lazy" to XHTML images',
|
|
128
|
+
type: "boolean",
|
|
129
|
+
})
|
|
130
|
+
.option("max-image-dim", {
|
|
131
|
+
describe: "Maximum image width/height in pixels; 0 disables resizing",
|
|
132
|
+
type: "number",
|
|
133
|
+
})
|
|
134
|
+
.option("strict", {
|
|
135
|
+
describe: "Fail when a processing step emits warnings or errors",
|
|
136
|
+
type: "boolean",
|
|
137
|
+
default: false,
|
|
138
|
+
})
|
|
139
|
+
.option("validation-timeout", {
|
|
140
|
+
describe: "Maximum EPUBCheck runtime in milliseconds",
|
|
141
|
+
type: "number",
|
|
142
|
+
default: config.epubcheckTimeoutMs,
|
|
143
|
+
})
|
|
144
|
+
.option("image-concurrency", {
|
|
145
|
+
describe: "Concurrent image operations (1-64); lower values reduce memory use",
|
|
146
|
+
type: "number",
|
|
147
|
+
default: DEFAULT_FILE_CONCURRENCY,
|
|
148
|
+
})
|
|
149
|
+
.option("profile", {
|
|
150
|
+
describe: "Print execution time for each pipeline step",
|
|
151
|
+
type: "boolean",
|
|
152
|
+
default: false,
|
|
153
|
+
})
|
|
154
|
+
.option("report-json", {
|
|
155
|
+
describe: "Write a structured pipeline report to this JSON file",
|
|
156
|
+
type: "string",
|
|
157
|
+
})
|
|
158
|
+
.option("report-html", {
|
|
159
|
+
describe: "Write a standalone HTML optimization report",
|
|
160
|
+
type: "string",
|
|
161
|
+
})
|
|
162
|
+
.option("doctor", {
|
|
163
|
+
alias: "inspect",
|
|
164
|
+
describe: "Inspect an EPUB without optimizing or writing an output EPUB",
|
|
165
|
+
type: "boolean",
|
|
166
|
+
default: false,
|
|
167
|
+
})
|
|
168
|
+
.option("clean", {
|
|
169
|
+
describe: "Clean temporary files after processing",
|
|
170
|
+
type: "boolean",
|
|
171
|
+
default: false,
|
|
172
|
+
})
|
|
173
|
+
.example("pnpm optimize -i book.epub -o book-optimized.epub", "Basic optimization")
|
|
174
|
+
.example("pnpm optimize -i book.epub -o book-opt.epub --clean", "Optimize and clean temp files")
|
|
175
|
+
.example("pnpm optimize -i book.epub -o book-opt.epub --jpg-quality 85", "Higher JPEG quality")
|
|
176
|
+
.example("pnpm optimize -i book.epub -o book-opt.epub --png-quality 0.9", "Higher PNG quality")
|
|
177
|
+
.example("pnpm optimize -i book.epub -o book-opt.epub --fonts", "Enable font subsetting")
|
|
178
|
+
.example("pnpm optimize:lossless -i book.epub -o book-opt.epub", "Avoid lossy image changes")
|
|
179
|
+
.example("pnpm optimize:repair -i book.epub -o book-opt.epub", "Apply XHTML repair passes")
|
|
180
|
+
.example("pnpm optimize:author -i book.epub -o book-opt.epub", "Use the project author's complete Pages/manual-summary workflow")
|
|
181
|
+
.example("pnpm optimize:author -i book.epub -o book-opt.epub --author-config author-workflow.json", "Override the author workflow's summary, cover, and CSS class mapping")
|
|
182
|
+
.example("epub-optimizer -i input.epub -o output.epub --jpg-quality 85 --png-quality 0.8", "Custom image settings")
|
|
183
|
+
.example("epub-optimizer --doctor -i input.epub", "Inspect without modifying the EPUB")
|
|
184
|
+
.help()
|
|
185
|
+
.alias("help", "h")
|
|
186
|
+
.version(packageJson.version)
|
|
187
|
+
.alias("version", "v")
|
|
188
|
+
.strict()
|
|
189
|
+
.check((argv) => {
|
|
190
|
+
if (argv.config !== undefined && typeof argv.config !== "string")
|
|
191
|
+
throw new Error("Choose a single --config file.");
|
|
192
|
+
for (const key of ["storage", "storage-plan", "apply-storage-plan"]) {
|
|
193
|
+
if (argv[key] !== undefined && !argv[key]?.trim())
|
|
194
|
+
throw new Error(`--${key} requires a non-empty path.`);
|
|
195
|
+
}
|
|
196
|
+
if (typeof argv.config === "string")
|
|
197
|
+
protectCliConfig(argv.config, [argv.output, argv["report-json"], argv["report-html"]], argv["output-dir"]);
|
|
198
|
+
const explicit = hideBin(process.argv);
|
|
199
|
+
const configFile = typeof argv.config === "string" ? readCliConfig(argv.config) : {};
|
|
200
|
+
const hasExplicitPaths = explicit.some((value) => /^(--input|--output|--temp)(=|$)/.test(value) || /^-[iot]/.test(value)) || ["input", "output", "temp"].some((key) => key in configFile);
|
|
201
|
+
if (argv.storage || argv["apply-storage-plan"]) {
|
|
202
|
+
if (hasExplicitPaths ||
|
|
203
|
+
argv.config ||
|
|
204
|
+
argv.watch ||
|
|
205
|
+
argv.batch ||
|
|
206
|
+
argv.doctor ||
|
|
207
|
+
argv.inspect ||
|
|
208
|
+
argv["output-dir"] ||
|
|
209
|
+
argv["report-json"] ||
|
|
210
|
+
argv["report-html"] ||
|
|
211
|
+
(argv.storage && argv["apply-storage-plan"]))
|
|
212
|
+
throw new Error("Storage maintenance cannot be combined with optimization modes or reports.");
|
|
213
|
+
if (argv["apply-storage-plan"] && argv["storage-plan"])
|
|
214
|
+
throw new Error("Choose storage preview or apply, not both.");
|
|
215
|
+
}
|
|
216
|
+
else if (argv["storage-plan"])
|
|
217
|
+
throw new Error("--storage-plan requires --storage.");
|
|
218
|
+
if (!Number.isSafeInteger(argv["keep-revisions"]) || argv["keep-revisions"] < 1)
|
|
219
|
+
throw new Error("--keep-revisions must be an integer of at least 1.");
|
|
220
|
+
if (!Number.isSafeInteger(argv.jobs) || argv.jobs < 1 || argv.jobs > 4)
|
|
221
|
+
throw new Error("--jobs must be an integer between 1 and 4.");
|
|
222
|
+
if (argv.jobs !== 1 && !argv.batch)
|
|
223
|
+
throw new Error("--jobs requires --batch.");
|
|
224
|
+
if (argv.watch && argv.batch)
|
|
225
|
+
throw new Error("--watch cannot be combined with --batch.");
|
|
226
|
+
if (!Number.isSafeInteger(argv["watch-settle-ms"]) || argv["watch-settle-ms"] < 1000)
|
|
227
|
+
throw new Error("--watch-settle-ms must be an integer of at least 1000.");
|
|
228
|
+
if (argv.watch && (argv["report-json"] || argv["report-html"]))
|
|
229
|
+
throw new Error("Watch writes per-book JSON and HTML reports automatically.");
|
|
230
|
+
if (argv.batch || argv.watch) {
|
|
231
|
+
if (!argv["output-dir"])
|
|
232
|
+
throw new Error("--batch/--watch requires --output-dir.");
|
|
233
|
+
if (argv.doctor || argv.inspect)
|
|
234
|
+
throw new Error("--batch/--watch supports optimization only.");
|
|
235
|
+
if (hasExplicitPaths) {
|
|
236
|
+
throw new Error("--batch/--watch cannot be combined with explicit --input, --output or --temp.");
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
else if (argv["output-dir"])
|
|
240
|
+
throw new Error("--output-dir requires --batch or --watch.");
|
|
241
|
+
if (argv["report-html"] && (argv.doctor || argv.inspect))
|
|
242
|
+
throw new Error("--report-html is for optimization runs; use --report-json with --doctor.");
|
|
243
|
+
if (!Number.isInteger(argv["image-concurrency"]) ||
|
|
244
|
+
argv["image-concurrency"] < 1 ||
|
|
245
|
+
argv["image-concurrency"] > 64) {
|
|
246
|
+
throw new Error("--image-concurrency must be an integer between 1 and 64.");
|
|
247
|
+
}
|
|
248
|
+
if (!Number.isSafeInteger(argv["validation-timeout"]) ||
|
|
249
|
+
argv["validation-timeout"] <= 0 ||
|
|
250
|
+
argv["validation-timeout"] > 2_147_483_647) {
|
|
251
|
+
throw new Error("--validation-timeout must be a positive integer no larger than 2147483647.");
|
|
252
|
+
}
|
|
253
|
+
const jpgQuality = Number(argv["jpg-quality"]);
|
|
254
|
+
const pngQuality = Number(argv["png-quality"]);
|
|
255
|
+
const maxImageDim = argv["max-image-dim"];
|
|
256
|
+
if (jpgQuality < 0 || jpgQuality > 100) {
|
|
257
|
+
throw new Error("--jpg-quality must be between 0 and 100.");
|
|
258
|
+
}
|
|
259
|
+
if (pngQuality < 0 || pngQuality > 1) {
|
|
260
|
+
throw new Error("--png-quality must be between 0 and 1.");
|
|
261
|
+
}
|
|
262
|
+
if (maxImageDim !== undefined && Number(maxImageDim) < 0) {
|
|
263
|
+
throw new Error("--max-image-dim must be 0 or greater.");
|
|
264
|
+
}
|
|
265
|
+
if (argv["author-config"] && argv.preset !== "author" && argv["author-workflow"] !== true) {
|
|
266
|
+
throw new Error("--author-config requires --preset author or --author-workflow.");
|
|
267
|
+
}
|
|
268
|
+
return true;
|
|
269
|
+
})
|
|
270
|
+
.parseAsync();
|
|
271
|
+
// yargs exposes both kebab-case and camelCase keys at runtime; `Args`
|
|
272
|
+
// reflects that. A single assertion is enough — no `unknown` bridge.
|
|
273
|
+
return applyPipelineOptions(parsed);
|
|
274
|
+
}
|
|
275
|
+
export { parseArguments };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type ContentProcessingOptions } from "./processors/epub-processor.js";
|
|
2
|
+
import type { Args } from "./types.js";
|
|
3
|
+
export { runWatch, type WatchOptions, type WatchReport, type WatchSignal } from "./watch.js";
|
|
4
|
+
export { planStorage, saveStoragePlan, applyStoragePlan } from "./storage.js";
|
|
5
|
+
export type { StoragePlan, StorageRevision } from "./storage.js";
|
|
6
|
+
export { runBatch, type BatchReport } from "./batch.js";
|
|
7
|
+
export type { BatchItem } from "./batch.js";
|
|
8
|
+
export type { Args, Preset } from "./types.js";
|
|
9
|
+
export type { ContentProcessingOptions } from "./processors/epub-processor.js";
|
|
10
|
+
export type { PipelineReport, StepReport, StepStatus } from "./utils/run-report.js";
|
|
11
|
+
export type { EpubCheckReport } from "./utils/epubcheck-report.js";
|
|
12
|
+
export { reportWarning, reportError } from "./utils/diagnostics.js";
|
|
13
|
+
export { formatFileSize, reportFileSizeComparison } from "./utils/file-size.js";
|
|
14
|
+
export interface OptimizeOptions extends ContentProcessingOptions {
|
|
15
|
+
/** Prepare extracted content only; never create or replace the output EPUB. */
|
|
16
|
+
skipPackaging?: boolean;
|
|
17
|
+
}
|
|
18
|
+
/** Optimize, validate and publish through the same pipeline as the CLI. */
|
|
19
|
+
export declare function optimizeEPUB(args?: Args, options?: OptimizeOptions): Promise<{
|
|
20
|
+
success: boolean;
|
|
21
|
+
input: string;
|
|
22
|
+
output: string;
|
|
23
|
+
}>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { parseArguments } from "./cli.js";
|
|
2
|
+
import { runOptimization } from "./optimization.js";
|
|
3
|
+
import { processEpubContent } from "./processors/epub-processor.js";
|
|
4
|
+
export { runWatch } from "./watch.js";
|
|
5
|
+
export { planStorage, saveStoragePlan, applyStoragePlan } from "./storage.js";
|
|
6
|
+
export { runBatch } from "./batch.js";
|
|
7
|
+
export { reportWarning, reportError } from "./utils/diagnostics.js";
|
|
8
|
+
export { formatFileSize, reportFileSizeComparison } from "./utils/file-size.js";
|
|
9
|
+
/** Optimize, validate and publish through the same pipeline as the CLI. */
|
|
10
|
+
export async function optimizeEPUB(args, options = {}) {
|
|
11
|
+
// Keep the caller's options intact when feature detection adjusts processing.
|
|
12
|
+
const resolvedArgs = { ...(args ?? (await parseArguments())) };
|
|
13
|
+
if (resolvedArgs.storage || resolvedArgs.applyStoragePlan)
|
|
14
|
+
throw new Error("Use storage maintenance functions for storage operations.");
|
|
15
|
+
if (resolvedArgs.watch)
|
|
16
|
+
throw new Error("Use runWatch(args, options) for watch optimization.");
|
|
17
|
+
if (resolvedArgs.batch)
|
|
18
|
+
throw new Error("Use runBatch(args) for batch optimization.");
|
|
19
|
+
if (options.skipPackaging) {
|
|
20
|
+
return processEpubContent(resolvedArgs, options);
|
|
21
|
+
}
|
|
22
|
+
await runOptimization(resolvedArgs, options);
|
|
23
|
+
return { success: true, input: resolvedArgs.input, output: resolvedArgs.output };
|
|
24
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { type ContentProcessingOptions } from "./processors/epub-processor.js";
|
|
3
|
+
import type { Args } from "./types.js";
|
|
4
|
+
import type { PipelineReport } from "./utils/run-report.js";
|
|
5
|
+
export declare function runOptimization(args: Args, processingOptions?: ContentProcessingOptions & {
|
|
6
|
+
onReport?: (report: PipelineReport) => void;
|
|
7
|
+
}): Promise<void>;
|