epub-optimizer 0.0.0-stage → 3.16.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/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,95 @@
|
|
|
1
|
+
import { reportInfo } from "./diagnostics.js";
|
|
2
|
+
import fs from "fs-extra";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createReadStream } from "node:fs";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { collectFiles, forEachFileLimited } from "./files.js";
|
|
7
|
+
import { TEMP_DIR_MARKER } from "./temp-dir.js";
|
|
8
|
+
export async function snapshotResources(root) {
|
|
9
|
+
const result = new Map();
|
|
10
|
+
await forEachFileLimited(await collectFiles(root, (file) => path.relative(root, file) !== TEMP_DIR_MARKER), async (file) => {
|
|
11
|
+
if (!(await fs.lstat(file)).isFile())
|
|
12
|
+
return;
|
|
13
|
+
const hash = createHash("sha256");
|
|
14
|
+
let bytes = 0;
|
|
15
|
+
for await (const chunk of createReadStream(file)) {
|
|
16
|
+
bytes += chunk.length;
|
|
17
|
+
hash.update(chunk);
|
|
18
|
+
}
|
|
19
|
+
result.set(path.relative(root, file).split(path.sep).join("/"), {
|
|
20
|
+
bytes,
|
|
21
|
+
digest: hash.digest("hex"),
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
return result;
|
|
25
|
+
}
|
|
26
|
+
export function compareResources(before, after) {
|
|
27
|
+
return [...new Set([...before.keys(), ...after.keys()])].sort().map((file) => {
|
|
28
|
+
const a = before.get(file), b = after.get(file);
|
|
29
|
+
return {
|
|
30
|
+
path: file,
|
|
31
|
+
status: !a ? "added" : !b ? "removed" : a.digest === b.digest ? "unchanged" : "modified",
|
|
32
|
+
beforeBytes: a?.bytes,
|
|
33
|
+
afterBytes: b?.bytes,
|
|
34
|
+
};
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
export function escapeHtml(value) {
|
|
38
|
+
return String(value ?? "").replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]);
|
|
39
|
+
}
|
|
40
|
+
function bytes(value) {
|
|
41
|
+
if (value === undefined)
|
|
42
|
+
return "—";
|
|
43
|
+
return `${(value / 1024).toLocaleString("en", { maximumFractionDigits: 1 })} KiB`;
|
|
44
|
+
}
|
|
45
|
+
export function htmlDocument(title, content) {
|
|
46
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><title>${escapeHtml(title)}</title><style>
|
|
47
|
+
body{margin:0;background:#f4f6fa;color:#19253b;font:16px/1.6 system-ui,sans-serif}main{max-width:1080px;margin:40px auto;padding:0 24px 48px}header{padding:28px;background:#172a45;color:white;border-radius:16px}h1{margin:0 0 8px;font-size:32px}h2{margin-top:32px}p{overflow-wrap:anywhere}.cards{display:flex;flex-wrap:wrap;gap:16px;margin:24px 0}.card{flex:1;min-width:160px;padding:20px;background:white;border:1px solid #dce2eb;border-radius:12px}.card strong{display:block;font-size:24px}.table{overflow-x:auto;background:white;border:1px solid #dce2eb;border-radius:12px}table{border-collapse:collapse;width:100%}th,td{padding:12px 16px;text-align:left;border-bottom:1px solid #e6eaf0;vertical-align:top}td:first-child{overflow-wrap:anywhere;max-width:480px}th{background:#eaf0f8}.success{color:#146744}.failed{color:#a32535}.skipped{color:#646b78}code{overflow-wrap:anywhere}pre{white-space:pre-wrap;overflow-wrap:anywhere}.validation-diagnostics th:last-child,.validation-diagnostics td:last-child{min-width:220px}details{margin:8px 0}li{overflow-wrap:anywhere}@media(max-width:600px){main{padding:0 12px}header{padding:20px}h1{font-size:25px}}@media print{body{background:white}main{margin:0}header{color:#19253b;background:white;border:1px solid #ddd}details{display:block}}
|
|
48
|
+
</style></head><body><main>${content}</main></body></html>`;
|
|
49
|
+
}
|
|
50
|
+
function renderValidationDiagnostics(validation) {
|
|
51
|
+
if (!validation)
|
|
52
|
+
return "";
|
|
53
|
+
const e = escapeHtml;
|
|
54
|
+
const totals = validation.totals;
|
|
55
|
+
const summary = totals
|
|
56
|
+
? `Fatal: ${e(totals.fatals)} · Errors: ${e(totals.errors)} · Warnings: ${e(totals.warnings)} · Informational: ${e(totals.infos)}`
|
|
57
|
+
: "Message totals unavailable.";
|
|
58
|
+
const rows = validation.messages
|
|
59
|
+
.map((message) => {
|
|
60
|
+
const locations = message.locations
|
|
61
|
+
.map((location) => {
|
|
62
|
+
const position = `${location.path}${location.line === undefined ? "" : `:${location.line}${location.column === undefined ? "" : `:${location.column}`}`}`;
|
|
63
|
+
return `<p><code>${e(position)}</code></p>${location.context === undefined ? "" : `<pre>${e(location.context)}</pre>`}`;
|
|
64
|
+
})
|
|
65
|
+
.join("");
|
|
66
|
+
return `<tr><td>${e(message.severity)}<br><code>${e(message.code)}</code></td><td>${e(message.message)}${message.suggestion ? `<p>${e(message.suggestion)}</p>` : ""}</td><td>${locations || "—"}${message.additionalLocations ? `<p>${e(message.additionalLocations)} additional locations not listed.</p>` : ""}</td></tr>`;
|
|
67
|
+
})
|
|
68
|
+
.join("");
|
|
69
|
+
return `<h2>EPUBCheck diagnostics</h2><p>Version: ${e(validation.checkerVersion ?? "unavailable")} · Diagnostic source: ${e(validation.source)} · Exit code: ${e(validation.exitCode ?? "unavailable")}</p><p>${summary}</p>${validation.diagnosticsError ? `<p class="failed">${e(validation.diagnosticsError)}</p>` : ""}${rows ? `<div class="table"><table class="validation-diagnostics"><thead><tr><th>Severity / code</th><th>Message / suggestion</th><th>Locations / context</th></tr></thead><tbody>${rows}</tbody></table></div>` : "<p>No detailed messages returned.</p>"}<p>EPUBCheck groups repeated diagnostics and limits reported locations. Totals may exceed the detailed entries shown.</p>`;
|
|
70
|
+
}
|
|
71
|
+
export function renderHtmlReport(report) {
|
|
72
|
+
const e = escapeHtml;
|
|
73
|
+
const validation = report.steps.find((step) => step.name === "Validate candidate EPUB");
|
|
74
|
+
const published = report.steps.some((step) => step.name === "Publish validated EPUB" && step.status === "success");
|
|
75
|
+
const rows = report.steps
|
|
76
|
+
.map((step) => `<tr><td>${e(step.name)}</td><td class="${e(step.status)}">${e(step.status)}</td><td>${(step.durationMs / 1000).toFixed(2)} s</td><td>${[...step.messages, ...(step.error ? [step.error] : [])].map((message) => `<p>${e(message)}</p>`).join("") || "—"}</td></tr>`)
|
|
77
|
+
.join("");
|
|
78
|
+
const resources = report.resources;
|
|
79
|
+
const counts = resources
|
|
80
|
+
? ["modified", "unchanged", "added", "removed"]
|
|
81
|
+
.map((status) => `${resources.filter((item) => item.status === status).length} ${status}`)
|
|
82
|
+
.join(" · ")
|
|
83
|
+
: "Resource comparison unavailable: processing did not reach the comparison stage.";
|
|
84
|
+
const resourceTable = resources
|
|
85
|
+
? `<div class="table"><table><thead><tr><th>Resource</th><th>Result</th><th>Before</th><th>After</th></tr></thead><tbody>${resources.map((item) => `<tr><td>${e(item.path)}</td><td>${e(item.status === "removed" ? "removed / replaced" : item.status)}</td><td>${bytes(item.beforeBytes)}</td><td>${bytes(item.afterBytes)}</td></tr>`).join("")}</tbody></table></div>`
|
|
86
|
+
: "";
|
|
87
|
+
const integrity = report.content?.integrity;
|
|
88
|
+
const diagnostics = renderValidationDiagnostics(report.validation);
|
|
89
|
+
return htmlDocument("EPUB optimization report", `<header><p>EPUB Optimizer · ${e(report.preset)}</p><h1>Optimization report</h1><p>${e(path.basename(report.input))}</p></header><div class="cards"><div class="card">Run result<strong class="${report.success ? "success" : "failed"}">${report.success ? "Completed" : "Failed"}</strong></div><div class="card">Archive size<strong>${bytes(report.sizes?.inputBytes)} → ${bytes(report.sizes?.outputBytes)}</strong></div><div class="card">Size reduction<strong>${report.sizes ? `${report.sizes.reductionPercent.toFixed(1)}%` : "Unavailable"}</strong></div></div><h2>Validation and output</h2><p>EPUBCheck: <strong>${e(validation?.status ?? "not run")}</strong> · Output publication: <strong>${published ? "completed" : "not completed"}</strong> · Content integrity: <strong>${integrity ? (integrity.valid ? "passed" : "failed") : "not checked"}</strong></p>${diagnostics}${report.error ? `<p class="failed">${e(report.error)}</p>` : ""}<p>Input: <code>${e(report.input)}</code><br>Output: <code>${e(report.output)}</code></p><p>Started: ${e(report.startedAt)} · Duration: ${((report.durationMs ?? 0) / 1000).toFixed(2)} s · Strict mode: ${report.strict ? "yes" : "no"}</p><h2>Transformations and diagnostics</h2><div class="table"><table><thead><tr><th>Step</th><th>Result</th><th>Time</th><th>Messages / skipped reasons</th></tr></thead><tbody>${rows}</tbody></table></div><h2>Resources before and after</h2><p>${e(counts)}</p><p>Byte changes describe extracted resources. PNG-to-JPEG conversion may appear as a removed resource and an added resource. Unchanged bytes do not certify rendering quality.</p>${resourceTable}<footer><p>Generated locally. This report contains paths and diagnostics from this run.</p></footer>`);
|
|
90
|
+
}
|
|
91
|
+
export async function writeHtmlReport(report, target) {
|
|
92
|
+
await fs.ensureDir(path.dirname(path.resolve(target)));
|
|
93
|
+
await fs.writeFile(target, renderHtmlReport(report), "utf8");
|
|
94
|
+
reportInfo(`Wrote HTML report: ${path.resolve(target)}`);
|
|
95
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import config from "./config.js";
|
|
2
|
+
/**
|
|
3
|
+
* Gets a localized label for the cover
|
|
4
|
+
* @param lang Optional language override (e.g. from CLI); falls back to config
|
|
5
|
+
*/
|
|
6
|
+
export function getCoverLabel(lang) {
|
|
7
|
+
const resolved = lang || config.lang || config.defaultLang;
|
|
8
|
+
return config.labels?.[resolved]?.cover;
|
|
9
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare function assertDistinctInputOutput(inputPath: string, outputPath: string): void;
|
|
2
|
+
export declare function assertSafeReportPath(reportPath: string, inputPath: string, outputPath: string): void;
|
|
3
|
+
export declare function assertSafeOutputTarget(outputPath: string): Promise<void>;
|
|
4
|
+
export declare function createCandidateOutputPath(outputPath: string): Promise<string>;
|
|
5
|
+
export declare function discardCandidateOutput(candidatePath: string | undefined): Promise<void>;
|
|
6
|
+
export declare function commitCandidateOutput(candidatePath: string, outputPath: string): Promise<void>;
|
|
7
|
+
/** Reject aliases and file/parent collisions across a complete batch plan. */
|
|
8
|
+
export declare function assertDistinctPathSet(paths: readonly string[]): void;
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import fs from "fs-extra";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
function normalizeComparisonPath(filePath) {
|
|
4
|
+
const normalized = path.normalize(filePath);
|
|
5
|
+
return process.platform === "darwin" || process.platform === "win32"
|
|
6
|
+
? normalized.toLowerCase()
|
|
7
|
+
: normalized;
|
|
8
|
+
}
|
|
9
|
+
function canonicalize(filePath) {
|
|
10
|
+
const suffix = [];
|
|
11
|
+
let current = path.resolve(filePath);
|
|
12
|
+
while (true) {
|
|
13
|
+
try {
|
|
14
|
+
return normalizeComparisonPath(path.join(fs.realpathSync(current), ...suffix));
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
const parent = path.dirname(current);
|
|
18
|
+
if (parent === current) {
|
|
19
|
+
return normalizeComparisonPath(path.resolve(filePath));
|
|
20
|
+
}
|
|
21
|
+
suffix.unshift(path.basename(current));
|
|
22
|
+
current = parent;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function isSamePathOrFile(firstPath, secondPath) {
|
|
27
|
+
if (canonicalize(firstPath) === canonicalize(secondPath)) {
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
const firstStats = fs.statSync(firstPath);
|
|
32
|
+
const secondStats = fs.statSync(secondPath);
|
|
33
|
+
return firstStats.dev === secondStats.dev && firstStats.ino === secondStats.ino;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function uniqueSiblingPath(outputPath, kind) {
|
|
40
|
+
const absoluteOutput = path.resolve(outputPath);
|
|
41
|
+
const outputDir = path.dirname(absoluteOutput);
|
|
42
|
+
const extension = path.extname(absoluteOutput);
|
|
43
|
+
const basename = path.basename(absoluteOutput, extension);
|
|
44
|
+
return path.join(outputDir, `.${basename}.${kind}-${process.pid}-${Date.now()}${extension}`);
|
|
45
|
+
}
|
|
46
|
+
export function assertDistinctInputOutput(inputPath, outputPath) {
|
|
47
|
+
if (isSamePathOrFile(inputPath, outputPath)) {
|
|
48
|
+
throw new Error("Input and output paths must be different. Use a separate output file to protect the original EPUB.");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export function assertSafeReportPath(reportPath, inputPath, outputPath) {
|
|
52
|
+
if (isSamePathOrFile(reportPath, inputPath) || isSamePathOrFile(reportPath, outputPath)) {
|
|
53
|
+
throw new Error("JSON report path must be different from the input and output EPUB paths.");
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
const stats = fs.lstatSync(reportPath);
|
|
57
|
+
if (!stats.isFile()) {
|
|
58
|
+
throw new Error(`JSON report path must be a regular file or not exist; refusing unsafe target: ${path.resolve(reportPath)}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (error.code !== "ENOENT") {
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export async function assertSafeOutputTarget(outputPath) {
|
|
68
|
+
try {
|
|
69
|
+
const stats = await fs.lstat(outputPath);
|
|
70
|
+
if (!stats.isFile()) {
|
|
71
|
+
throw new Error(`Output path must be a regular file or not exist; refusing unsafe target: ${path.resolve(outputPath)}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error.code !== "ENOENT") {
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
export async function createCandidateOutputPath(outputPath) {
|
|
81
|
+
const candidatePath = uniqueSiblingPath(outputPath, "candidate");
|
|
82
|
+
await fs.ensureDir(path.dirname(candidatePath));
|
|
83
|
+
return candidatePath;
|
|
84
|
+
}
|
|
85
|
+
export async function discardCandidateOutput(candidatePath) {
|
|
86
|
+
if (candidatePath) {
|
|
87
|
+
await fs.remove(candidatePath);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
export async function commitCandidateOutput(candidatePath, outputPath) {
|
|
91
|
+
const absoluteCandidate = path.resolve(candidatePath);
|
|
92
|
+
const absoluteOutput = path.resolve(outputPath);
|
|
93
|
+
const backupPath = uniqueSiblingPath(absoluteOutput, "backup");
|
|
94
|
+
await assertSafeOutputTarget(absoluteOutput);
|
|
95
|
+
const hadPreviousOutput = await fs.pathExists(absoluteOutput);
|
|
96
|
+
if (!(await fs.pathExists(absoluteCandidate))) {
|
|
97
|
+
throw new Error(`Validated candidate output does not exist: ${absoluteCandidate}`);
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
if (hadPreviousOutput) {
|
|
101
|
+
await fs.rename(absoluteOutput, backupPath);
|
|
102
|
+
}
|
|
103
|
+
await fs.rename(absoluteCandidate, absoluteOutput);
|
|
104
|
+
await fs.remove(backupPath);
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
if (hadPreviousOutput && (await fs.pathExists(backupPath))) {
|
|
108
|
+
await fs.remove(absoluteOutput);
|
|
109
|
+
await fs.rename(backupPath, absoluteOutput);
|
|
110
|
+
}
|
|
111
|
+
throw new Error(`Failed to publish validated EPUB: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** Reject aliases and file/parent collisions across a complete batch plan. */
|
|
115
|
+
export function assertDistinctPathSet(paths) {
|
|
116
|
+
const canonical = new Set();
|
|
117
|
+
const identities = new Set();
|
|
118
|
+
for (const file of paths) {
|
|
119
|
+
const normalized = canonicalize(file);
|
|
120
|
+
if (canonical.has(normalized))
|
|
121
|
+
throw new Error(`Batch paths must be distinct: ${file}`);
|
|
122
|
+
canonical.add(normalized);
|
|
123
|
+
let stats;
|
|
124
|
+
try {
|
|
125
|
+
stats = fs.statSync(file);
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
if (error.code !== "ENOENT")
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
if (stats) {
|
|
132
|
+
const identity = `${stats.dev}:${stats.ino}`;
|
|
133
|
+
if (identities.has(identity))
|
|
134
|
+
throw new Error(`Batch paths alias the same file: ${file}`);
|
|
135
|
+
identities.add(identity);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
for (const file of canonical) {
|
|
139
|
+
let parent = path.dirname(file);
|
|
140
|
+
while (parent !== path.dirname(parent)) {
|
|
141
|
+
if (canonical.has(parent))
|
|
142
|
+
throw new Error(`Batch file target is also a parent directory: ${parent}`);
|
|
143
|
+
parent = path.dirname(parent);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
/** Find the owning package from either a source or compiled module. */
|
|
5
|
+
export function findPackageRoot(moduleUrl) {
|
|
6
|
+
let dir = path.dirname(fileURLToPath(moduleUrl));
|
|
7
|
+
while (true) {
|
|
8
|
+
if (existsSync(path.join(dir, "package.json")))
|
|
9
|
+
return dir;
|
|
10
|
+
const parent = path.dirname(dir);
|
|
11
|
+
if (parent === dir)
|
|
12
|
+
throw new Error("package.json not found");
|
|
13
|
+
dir = parent;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
function safeDecodeUri(value) {
|
|
3
|
+
try {
|
|
4
|
+
return decodeURI(value);
|
|
5
|
+
}
|
|
6
|
+
catch {
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export function isSameOrInside(candidate, parent) {
|
|
11
|
+
const relative = path.relative(parent, candidate);
|
|
12
|
+
return (relative === "" || (!!relative && !relative.startsWith("..") && !path.isAbsolute(relative)));
|
|
13
|
+
}
|
|
14
|
+
export function resolvePathInside(rootDir, ownerDir, rawReference, label = "EPUB path") {
|
|
15
|
+
const pathPart = rawReference.split(/[?#]/, 1)[0] ?? "";
|
|
16
|
+
const decoded = safeDecodeUri(pathPart).replace(/\\/g, "/");
|
|
17
|
+
if (!decoded ||
|
|
18
|
+
decoded.startsWith("/") ||
|
|
19
|
+
decoded.startsWith("//") ||
|
|
20
|
+
decoded.includes("\0") ||
|
|
21
|
+
/^[a-z][a-z0-9+.-]*:/i.test(decoded)) {
|
|
22
|
+
throw new Error(`Refusing unsafe ${label}: ${rawReference}`);
|
|
23
|
+
}
|
|
24
|
+
const absoluteRoot = path.resolve(rootDir);
|
|
25
|
+
const resolved = path.resolve(ownerDir, decoded);
|
|
26
|
+
if (!isSameOrInside(resolved, absoluteRoot) || resolved === absoluteRoot) {
|
|
27
|
+
throw new Error(`Refusing ${label} outside EPUB root: ${rawReference}`);
|
|
28
|
+
}
|
|
29
|
+
return resolved;
|
|
30
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Args, Preset } from "../types.js";
|
|
2
|
+
interface RawPipelineOptions {
|
|
3
|
+
preset: Preset;
|
|
4
|
+
authorWorkflow?: boolean;
|
|
5
|
+
repair?: boolean;
|
|
6
|
+
convertPng?: boolean;
|
|
7
|
+
lazyLoading?: boolean;
|
|
8
|
+
maxImageDim?: number;
|
|
9
|
+
pngBackground?: string;
|
|
10
|
+
doctor?: boolean;
|
|
11
|
+
inspect?: boolean;
|
|
12
|
+
}
|
|
13
|
+
export interface ResolvedPipelineOptions {
|
|
14
|
+
preset: Preset;
|
|
15
|
+
authorWorkflow: boolean;
|
|
16
|
+
repair: boolean;
|
|
17
|
+
convertPng: boolean;
|
|
18
|
+
lazyLoading: boolean;
|
|
19
|
+
maxImageDim: number;
|
|
20
|
+
lossless: boolean;
|
|
21
|
+
pngBackground?: string;
|
|
22
|
+
}
|
|
23
|
+
/** An explicit opaque color; reject conflicting modes instead of silently ignoring it. */
|
|
24
|
+
export declare function resolvePngBackground(options: {
|
|
25
|
+
pngBackground?: unknown;
|
|
26
|
+
preset?: Preset;
|
|
27
|
+
lossless?: boolean;
|
|
28
|
+
convertPng?: boolean;
|
|
29
|
+
doctor?: boolean;
|
|
30
|
+
inspect?: boolean;
|
|
31
|
+
}): string | undefined;
|
|
32
|
+
export declare function resolvePipelineOptions(options: RawPipelineOptions): ResolvedPipelineOptions;
|
|
33
|
+
export declare function applyPipelineOptions(args: Args): Args;
|
|
34
|
+
export {};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** An explicit opaque color; reject conflicting modes instead of silently ignoring it. */
|
|
2
|
+
export function resolvePngBackground(options) {
|
|
3
|
+
const color = options.pngBackground;
|
|
4
|
+
if (color === undefined)
|
|
5
|
+
return undefined;
|
|
6
|
+
if (typeof color !== "string" || !/^#[0-9a-f]{6}$/i.test(color))
|
|
7
|
+
throw new Error("--png-background must be an opaque color in #RRGGBB format.");
|
|
8
|
+
if (options.lossless || options.preset === "lossless")
|
|
9
|
+
throw new Error("--png-background cannot be combined with the lossless preset.");
|
|
10
|
+
if (options.convertPng === false)
|
|
11
|
+
throw new Error("--png-background requires PNG-to-JPEG conversion; remove --no-convert-png.");
|
|
12
|
+
if (options.doctor || options.inspect)
|
|
13
|
+
throw new Error("--png-background is for optimization only, not doctor mode.");
|
|
14
|
+
return color.toLowerCase();
|
|
15
|
+
}
|
|
16
|
+
export function resolvePipelineOptions(options) {
|
|
17
|
+
const authorWorkflow = options.authorWorkflow === true || options.preset === "author";
|
|
18
|
+
const lossless = options.preset === "lossless";
|
|
19
|
+
const pngBackground = resolvePngBackground(options);
|
|
20
|
+
return {
|
|
21
|
+
preset: options.preset,
|
|
22
|
+
authorWorkflow,
|
|
23
|
+
repair: options.repair === true || authorWorkflow,
|
|
24
|
+
convertPng: options.convertPng ?? !lossless,
|
|
25
|
+
lazyLoading: options.lazyLoading ?? authorWorkflow,
|
|
26
|
+
maxImageDim: options.maxImageDim ?? (lossless ? 0 : 1600),
|
|
27
|
+
lossless,
|
|
28
|
+
...(pngBackground === undefined ? {} : { pngBackground }),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export function applyPipelineOptions(args) {
|
|
32
|
+
const resolved = resolvePipelineOptions(args);
|
|
33
|
+
return {
|
|
34
|
+
...args,
|
|
35
|
+
"author-workflow": resolved.authorWorkflow,
|
|
36
|
+
authorWorkflow: resolved.authorWorkflow,
|
|
37
|
+
repair: resolved.repair,
|
|
38
|
+
"convert-png": resolved.convertPng,
|
|
39
|
+
convertPng: resolved.convertPng,
|
|
40
|
+
"lazy-loading": resolved.lazyLoading,
|
|
41
|
+
lazyLoading: resolved.lazyLoading,
|
|
42
|
+
"max-image-dim": resolved.maxImageDim,
|
|
43
|
+
maxImageDim: resolved.maxImageDim,
|
|
44
|
+
lossless: resolved.lossless,
|
|
45
|
+
...(resolved.pngBackground === undefined
|
|
46
|
+
? {}
|
|
47
|
+
: { pngBackground: resolved.pngBackground, "png-background": resolved.pngBackground }),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Detect APNG without decoding pixels or buffering the compressed image.
|
|
3
|
+
* PNG requires acTL before the first IDAT; skip ancillary chunk payloads so
|
|
4
|
+
* strings inside metadata cannot be mistaken for animation control chunks.
|
|
5
|
+
* https://www.w3.org/TR/png-3/#acTL-chunk
|
|
6
|
+
*/
|
|
7
|
+
export declare function isAnimatedPng(filePath: string): Promise<boolean>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { open } from "node:fs/promises";
|
|
2
|
+
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
|
3
|
+
const MAX_CHUNKS = 1024;
|
|
4
|
+
/**
|
|
5
|
+
* Detect APNG without decoding pixels or buffering the compressed image.
|
|
6
|
+
* PNG requires acTL before the first IDAT; skip ancillary chunk payloads so
|
|
7
|
+
* strings inside metadata cannot be mistaken for animation control chunks.
|
|
8
|
+
* https://www.w3.org/TR/png-3/#acTL-chunk
|
|
9
|
+
*/
|
|
10
|
+
export async function isAnimatedPng(filePath) {
|
|
11
|
+
const file = await open(filePath, "r");
|
|
12
|
+
try {
|
|
13
|
+
const header = Buffer.alloc(8);
|
|
14
|
+
const signature = await file.read(header, 0, 8, 0);
|
|
15
|
+
if (signature.bytesRead !== 8 || !header.equals(PNG_SIGNATURE))
|
|
16
|
+
return false;
|
|
17
|
+
const size = (await file.stat()).size;
|
|
18
|
+
let offset = 8;
|
|
19
|
+
let chunks = 0;
|
|
20
|
+
while (offset + 12 <= size) {
|
|
21
|
+
// EPUB images are untrusted. Bound sequential I/O for pathological files
|
|
22
|
+
// with millions of tiny ancillary chunks, preserving the source on error.
|
|
23
|
+
if (++chunks > MAX_CHUNKS)
|
|
24
|
+
throw new Error("PNG animation scan chunk limit exceeded");
|
|
25
|
+
const { bytesRead } = await file.read(header, 0, 8, offset);
|
|
26
|
+
if (bytesRead !== 8)
|
|
27
|
+
break;
|
|
28
|
+
const length = header.readUInt32BE(0);
|
|
29
|
+
if (offset + length + 12 > size)
|
|
30
|
+
break;
|
|
31
|
+
const type = header.toString("ascii", 4, 8);
|
|
32
|
+
if (type === "acTL")
|
|
33
|
+
return true;
|
|
34
|
+
if (type === "IDAT" || type === "IEND")
|
|
35
|
+
return false;
|
|
36
|
+
offset += length + 12;
|
|
37
|
+
}
|
|
38
|
+
// Callers retain the source on errors; never rewrite an uncertain PNG.
|
|
39
|
+
throw new Error("Incomplete PNG chunk structure");
|
|
40
|
+
}
|
|
41
|
+
finally {
|
|
42
|
+
await file.close();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { ResourceChange } from "./html-report.js";
|
|
2
|
+
import type { EpubCheckReport } from "./epubcheck-report.js";
|
|
3
|
+
import type { Preset } from "../types.js";
|
|
4
|
+
import type { EpubContentMetrics, EpubIntegrityComparison } from "./epub-integrity.js";
|
|
5
|
+
export type StepStatus = "success" | "skipped" | "failed";
|
|
6
|
+
export interface StepReport {
|
|
7
|
+
name: string;
|
|
8
|
+
status: StepStatus;
|
|
9
|
+
durationMs: number;
|
|
10
|
+
messages: string[];
|
|
11
|
+
error?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface PipelineReport {
|
|
14
|
+
input: string;
|
|
15
|
+
output: string;
|
|
16
|
+
preset: Preset;
|
|
17
|
+
strict: boolean;
|
|
18
|
+
success: boolean;
|
|
19
|
+
startedAt: string;
|
|
20
|
+
tempDir?: string;
|
|
21
|
+
completedAt?: string;
|
|
22
|
+
durationMs?: number;
|
|
23
|
+
error?: string;
|
|
24
|
+
sizes?: {
|
|
25
|
+
inputBytes: number;
|
|
26
|
+
outputBytes: number;
|
|
27
|
+
savedBytes: number;
|
|
28
|
+
reductionPercent: number;
|
|
29
|
+
};
|
|
30
|
+
content?: {
|
|
31
|
+
before?: EpubContentMetrics;
|
|
32
|
+
after?: EpubContentMetrics;
|
|
33
|
+
integrity?: EpubIntegrityComparison;
|
|
34
|
+
};
|
|
35
|
+
resources?: ResourceChange[];
|
|
36
|
+
validation?: EpubCheckReport;
|
|
37
|
+
steps: StepReport[];
|
|
38
|
+
}
|
|
39
|
+
export declare function createPipelineReport(options: {
|
|
40
|
+
input: string;
|
|
41
|
+
output: string;
|
|
42
|
+
preset: Preset;
|
|
43
|
+
strict: boolean;
|
|
44
|
+
}): PipelineReport;
|
|
45
|
+
export declare function recordSkippedStep(report: PipelineReport, name: string, reason: string): void;
|
|
46
|
+
export declare function runReportedStep<T>(report: PipelineReport, name: string, strict: boolean, operation: () => Promise<T> | T): Promise<T>;
|
|
47
|
+
export declare function completePipelineReport(report: PipelineReport, error?: unknown): void;
|
|
48
|
+
export declare function writePipelineReport(report: PipelineReport, reportPath: string): Promise<void>;
|
|
49
|
+
export declare function printProfile(report: PipelineReport): void;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { collectDiagnostics, reportInfo } from "./diagnostics.js";
|
|
2
|
+
import fs from "fs-extra";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
export function createPipelineReport(options) {
|
|
5
|
+
return {
|
|
6
|
+
...options,
|
|
7
|
+
success: false,
|
|
8
|
+
startedAt: new Date().toISOString(),
|
|
9
|
+
steps: [],
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export function recordSkippedStep(report, name, reason) {
|
|
13
|
+
report.steps.push({
|
|
14
|
+
name,
|
|
15
|
+
status: "skipped",
|
|
16
|
+
durationMs: 0,
|
|
17
|
+
messages: [reason],
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
export async function runReportedStep(report, name, strict, operation) {
|
|
21
|
+
const startedAt = performance.now();
|
|
22
|
+
const messages = [];
|
|
23
|
+
try {
|
|
24
|
+
const result = await collectDiagnostics(operation, (diagnostic) => {
|
|
25
|
+
messages.push(diagnostic.message);
|
|
26
|
+
});
|
|
27
|
+
if (strict && messages.length > 0) {
|
|
28
|
+
throw new Error(`Strict mode rejected ${messages.length} warning/error message(s).`);
|
|
29
|
+
}
|
|
30
|
+
report.steps.push({
|
|
31
|
+
name,
|
|
32
|
+
status: "success",
|
|
33
|
+
durationMs: performance.now() - startedAt,
|
|
34
|
+
messages,
|
|
35
|
+
});
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
40
|
+
report.steps.push({
|
|
41
|
+
name,
|
|
42
|
+
status: "failed",
|
|
43
|
+
durationMs: performance.now() - startedAt,
|
|
44
|
+
messages,
|
|
45
|
+
error: message,
|
|
46
|
+
});
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export function completePipelineReport(report, error) {
|
|
51
|
+
const completedAt = new Date();
|
|
52
|
+
report.completedAt = completedAt.toISOString();
|
|
53
|
+
report.durationMs = completedAt.getTime() - new Date(report.startedAt).getTime();
|
|
54
|
+
report.success = error === undefined;
|
|
55
|
+
if (error !== undefined) {
|
|
56
|
+
report.error = error instanceof Error ? error.message : String(error);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
export async function writePipelineReport(report, reportPath) {
|
|
60
|
+
const absolutePath = path.resolve(reportPath);
|
|
61
|
+
await fs.ensureDir(path.dirname(absolutePath));
|
|
62
|
+
await fs.writeJson(absolutePath, report, { spaces: 2 });
|
|
63
|
+
reportInfo(`Wrote JSON report: ${absolutePath}`);
|
|
64
|
+
}
|
|
65
|
+
export function printProfile(report) {
|
|
66
|
+
reportInfo("\n=== Profile ===");
|
|
67
|
+
for (const step of report.steps) {
|
|
68
|
+
reportInfo(`${step.name}: ${step.status} (${step.durationMs.toFixed(0)} ms)`);
|
|
69
|
+
}
|
|
70
|
+
reportInfo(`Total: ${(report.durationMs ?? 0).toFixed(0)} ms`);
|
|
71
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const TEMP_DIR_MARKER = ".epub-optimizer-temp.json";
|
|
2
|
+
interface TempDirSafetyOptions {
|
|
3
|
+
inputPath?: string;
|
|
4
|
+
outputPath?: string;
|
|
5
|
+
cwd?: string;
|
|
6
|
+
homeDir?: string;
|
|
7
|
+
}
|
|
8
|
+
declare function assertSafeTempDir(tempDir: string, options?: TempDirSafetyOptions): string;
|
|
9
|
+
declare function removeTempDir(tempDir: string, options?: TempDirSafetyOptions): Promise<string>;
|
|
10
|
+
export declare function createManagedTempDir(tempDir: string, inputPath: string): Promise<void>;
|
|
11
|
+
export { assertSafeTempDir, removeTempDir };
|