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,190 @@
|
|
|
1
|
+
import { reportInfo } from "../utils/diagnostics.js";
|
|
2
|
+
import fs from "fs-extra";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { minify } from "html-minifier-terser";
|
|
5
|
+
import CleanCSS from "clean-css";
|
|
6
|
+
import * as cheerio from "cheerio";
|
|
7
|
+
import { minify as terserMinify } from "terser";
|
|
8
|
+
import config from "../utils/config.js";
|
|
9
|
+
import { isXHTMLContent, normalizeNamedEntities, normalizeVoidElements } from "../utils/xhtml.js";
|
|
10
|
+
import { collectFiles, forEachFileLimited, hasExtension } from "../utils/files.js";
|
|
11
|
+
import { collectManifestResources } from "../utils/epub-utils.js";
|
|
12
|
+
import { xhtmlStructure } from "../utils/xhtml-structure.js";
|
|
13
|
+
const HTML_EXTENSIONS = new Set([".xhtml", ".html"]);
|
|
14
|
+
const CSS_EXTENSIONS = new Set([".css"]);
|
|
15
|
+
const XHTML_QUERY = {
|
|
16
|
+
mediaTypes: new Set(["application/xhtml+xml"]),
|
|
17
|
+
extensions: new Set([".xhtml"]),
|
|
18
|
+
};
|
|
19
|
+
const RAW_TEXT_ELEMENTS = new Set(["script", "style"]);
|
|
20
|
+
const XML_MARKUP_RE = /[<&]|\]\]>/;
|
|
21
|
+
/**
|
|
22
|
+
* CleanCSS reports unsupported syntax as warnings and may still return a
|
|
23
|
+
* partial stylesheet. Accept only a complete, smaller result. Inline
|
|
24
|
+
* declarations and media queries need a temporary rule for its CSS parser.
|
|
25
|
+
*/
|
|
26
|
+
function minifyCssText(text, type, xhtml = false) {
|
|
27
|
+
// Serialized XML references and CDATA are not raw CSS. Passing them through
|
|
28
|
+
// an HTML/CSS parser can truncate references or discard the CDATA wrapper.
|
|
29
|
+
if (xhtml && XML_MARKUP_RE.test(text))
|
|
30
|
+
return text;
|
|
31
|
+
const input = type === "inline" ? `*{${text}}` : type === "media" ? `@media ${text}{a{top:0}}` : text;
|
|
32
|
+
const result = new CleanCSS({
|
|
33
|
+
// Retain the existing optimization levels for external and embedded CSS.
|
|
34
|
+
level: type === "external" ? 2 : 1,
|
|
35
|
+
inline: false,
|
|
36
|
+
}).minify(input);
|
|
37
|
+
if (result.errors.length > 0 || result.warnings.length > 0)
|
|
38
|
+
return text;
|
|
39
|
+
let styles = result.styles;
|
|
40
|
+
if (type === "inline" || type === "media") {
|
|
41
|
+
const match = styles.match(type === "inline" ? /^\*\{([\s\S]*)\}$/ : /^@media ([\s\S]*?)\s*\{[\s\S]*\}$/);
|
|
42
|
+
if (match?.[1] === undefined)
|
|
43
|
+
return text;
|
|
44
|
+
styles = match[1];
|
|
45
|
+
}
|
|
46
|
+
// A safe input can produce XML delimiters through CSS escape shortening.
|
|
47
|
+
if (xhtml && XML_MARKUP_RE.test(styles))
|
|
48
|
+
return text;
|
|
49
|
+
return Buffer.byteLength(styles) < Buffer.byteLength(text) ? styles : text;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Minify a script body or event attribute of an XHTML document. There the code
|
|
53
|
+
* is XML character data, so `<`, `&` and `]]>` are unsafe: CDATA-wrapped or
|
|
54
|
+
* entity-escaped code is kept byte for byte, and a result that would need
|
|
55
|
+
* escaping (for example `a&&b()`) is discarded in favour of the original.
|
|
56
|
+
*/
|
|
57
|
+
async function minifyXhtmlJS(text, inline) {
|
|
58
|
+
if (XML_MARKUP_RE.test(text))
|
|
59
|
+
return text;
|
|
60
|
+
try {
|
|
61
|
+
const result = await terserMinify(text, { parse: { bare_returns: inline === true } });
|
|
62
|
+
// Terser retains semicolons that form a required empty statement, such as
|
|
63
|
+
// the body of `while (poll());`. Keep its output syntactically complete.
|
|
64
|
+
const code = result.code;
|
|
65
|
+
return code === undefined || XML_MARKUP_RE.test(code) ? text : code;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return text;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Re-express CDATA sections outside script/style as escaped character data,
|
|
73
|
+
* which is equivalent XML. html-minifier parses HTML, where such a section is
|
|
74
|
+
* a bogus comment and would be dropped together with its text.
|
|
75
|
+
*/
|
|
76
|
+
function escapeCdataSections($) {
|
|
77
|
+
$("*")
|
|
78
|
+
.contents()
|
|
79
|
+
.filter((_, node) => node.type === "cdata")
|
|
80
|
+
.each((_, node) => {
|
|
81
|
+
const parentName = node.parent?.name ?? "";
|
|
82
|
+
if (RAW_TEXT_ELEMENTS.has(parentName.split(":").at(-1)?.toLowerCase() ?? ""))
|
|
83
|
+
return;
|
|
84
|
+
// cheerio only wraps a bare CDATA node when it is given as a list.
|
|
85
|
+
const section = $([node]);
|
|
86
|
+
section.replaceWith(section.text().replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"));
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Process HTML and CSS files in a directory recursively.
|
|
91
|
+
* Minifies HTML/XHTML and CSS files in parallel (bounded) to reduce file size.
|
|
92
|
+
* @param dir Directory to process
|
|
93
|
+
* @throws Error if any file fails to minify
|
|
94
|
+
*/
|
|
95
|
+
async function processHTML(dir) {
|
|
96
|
+
try {
|
|
97
|
+
const [archiveFiles, manifestFiles] = await Promise.all([
|
|
98
|
+
collectFiles(dir, (filePath) => hasExtension(filePath, HTML_EXTENSIONS) || hasExtension(filePath, CSS_EXTENSIONS)),
|
|
99
|
+
collectManifestResources(dir, XHTML_QUERY),
|
|
100
|
+
]);
|
|
101
|
+
const xhtmlFiles = new Set(manifestFiles.map((file) => path.resolve(file)));
|
|
102
|
+
const files = [...new Set([...archiveFiles.map((file) => path.resolve(file)), ...xhtmlFiles])];
|
|
103
|
+
await forEachFileLimited(files, async (filePath) => {
|
|
104
|
+
if (hasExtension(filePath, CSS_EXTENSIONS) && !xhtmlFiles.has(filePath)) {
|
|
105
|
+
await minifyCSS(filePath);
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
await minifyHTML(filePath, { xhtml: xhtmlFiles.has(filePath) });
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
throw new Error(`Failed to process HTML/CSS in ${dir}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Minify HTML/XHTML file using cheerio and html-minifier-terser
|
|
118
|
+
* @param filePath Path to HTML/XHTML file
|
|
119
|
+
* @throws Error if minification fails
|
|
120
|
+
*/
|
|
121
|
+
async function minifyHTML(filePath, options = {}) {
|
|
122
|
+
try {
|
|
123
|
+
const content = await fs.readFile(filePath, "utf8");
|
|
124
|
+
// Detect XHTML by content first — the file extension may be `.html` even
|
|
125
|
+
// for true XHTML (the EPUB spec doesn't mandate `.xhtml`). Extension is
|
|
126
|
+
// kept as a fallback signal.
|
|
127
|
+
const isXHTML = options.xhtml === true ||
|
|
128
|
+
isXHTMLContent(content) ||
|
|
129
|
+
hasExtension(filePath, XHTML_QUERY.extensions);
|
|
130
|
+
// Pre-close HTML5-style void elements before the XML parser sees them.
|
|
131
|
+
// Otherwise cheerio xmlMode treats `<link …>` as an opening tag and nests
|
|
132
|
+
// subsequent siblings inside it, producing invalid XHTML.
|
|
133
|
+
// Named references become numeric so output does not depend on an HTML
|
|
134
|
+
// entity DTD to resolve the intended characters.
|
|
135
|
+
const normalized = isXHTML ? normalizeNamedEntities(normalizeVoidElements(content)) : content;
|
|
136
|
+
// Preserve the spelling of references and UTF-8 characters. Decoding and
|
|
137
|
+
// serializing them again encodes style bodies as XML entities, which the
|
|
138
|
+
// subsequent HTML/CSS minifier interprets as CSS syntax instead of text.
|
|
139
|
+
const $ = cheerio.load(normalized, isXHTML ? { xml: { decodeEntities: false } } : {});
|
|
140
|
+
const originalStructure = isXHTML ? xhtmlStructure($) : undefined;
|
|
141
|
+
if (isXHTML)
|
|
142
|
+
escapeCdataSections($);
|
|
143
|
+
// Use .xml() for XHTML to preserve XML structure (self-closing tags, etc.)
|
|
144
|
+
const domContent = isXHTML ? $.xml() : $.html();
|
|
145
|
+
const minified = await minify(domContent, {
|
|
146
|
+
...config.htmlOptions,
|
|
147
|
+
// html-minifier-terser requires a promise here despite its sync types.
|
|
148
|
+
minifyCSS: (async (text, type) => minifyCssText(text, type, isXHTML)),
|
|
149
|
+
...(isXHTML
|
|
150
|
+
? {
|
|
151
|
+
// html-minifier-terser awaits minifyJS; its types only declare the sync form.
|
|
152
|
+
minifyJS: minifyXhtmlJS,
|
|
153
|
+
}
|
|
154
|
+
: {}),
|
|
155
|
+
});
|
|
156
|
+
if (isXHTML &&
|
|
157
|
+
xhtmlStructure(cheerio.load(minified, { xml: { decodeEntities: false } })) !==
|
|
158
|
+
originalStructure) {
|
|
159
|
+
reportInfo(`Keeping original ${path.basename(filePath)}: XHTML minification changed document structure.`);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
await fs.writeFile(filePath, minified);
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
throw new Error(`Failed to minify HTML file ${path.basename(filePath)}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Minify CSS file using CleanCSS
|
|
170
|
+
* @param filePath Path to CSS file
|
|
171
|
+
* @throws Error if minification fails
|
|
172
|
+
*/
|
|
173
|
+
async function minifyCSS(filePath) {
|
|
174
|
+
try {
|
|
175
|
+
const content = await fs.readFile(filePath, "utf8");
|
|
176
|
+
// Keep @import rules as written: by default CleanCSS inlines them from the
|
|
177
|
+
// current working directory, not from the stylesheet's own directory, and
|
|
178
|
+
// drops the rule when the file is not found there.
|
|
179
|
+
const minified = minifyCssText(content, "external");
|
|
180
|
+
if (minified === content) {
|
|
181
|
+
reportInfo(`Keeping original ${path.basename(filePath)}: CSS minification offered no safe reduction`);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
await fs.writeFile(filePath, minified);
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
throw new Error(`Failed to minify CSS file ${path.basename(filePath)}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
export { processHTML, minifyHTML, minifyCSS };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Convert large opaque PNGs, or explicitly flattened transparent PNGs, to JPEG.
|
|
3
|
+
* Runs conversions in parallel, then updates XHTML and OPF references
|
|
4
|
+
* in a single batched pass.
|
|
5
|
+
* @param maxDim Optional max width/height in px — resize is chained into
|
|
6
|
+
* the same sharp pass so converted JPEGs don't need a follow-up downscale
|
|
7
|
+
* (optimizeImages skips them).
|
|
8
|
+
* @returns Absolute paths of the newly-written JPEG files — callers pass
|
|
9
|
+
* this to optimizeImages as `skip` so the freshly-encoded JPEGs aren't
|
|
10
|
+
* re-encoded a second time.
|
|
11
|
+
* @throws Error if conversion fails catastrophically (per-file errors are logged).
|
|
12
|
+
*/
|
|
13
|
+
declare function convertPngToJpeg(epubDir: string, quality?: number, concurrency?: number, maxDim?: number, background?: string): Promise<Set<string>>;
|
|
14
|
+
export { convertPngToJpeg };
|
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
import { reportInfo, reportWarning } from "../utils/diagnostics.js";
|
|
2
|
+
import fs from "fs-extra";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import sharp from "sharp";
|
|
5
|
+
import * as cheerio from "cheerio";
|
|
6
|
+
import pLimit from "p-limit";
|
|
7
|
+
import { getOPFPath, getContentPath } from "../utils/epub-utils.js";
|
|
8
|
+
import { DEFAULT_FILE_CONCURRENCY } from "../utils/files.js";
|
|
9
|
+
import { isAnimatedPng } from "../utils/png-animation.js";
|
|
10
|
+
import { resolvePngBackground } from "../utils/pipeline-options.js";
|
|
11
|
+
const CONTENT_FILE_EXTENSIONS = new Set([".xhtml", ".html", ".css", ".svg"]);
|
|
12
|
+
const PNG_EXT_RE = /\.png$/i;
|
|
13
|
+
async function maybeConvertOne(pngFile, contentDir, quality, maxDim, background) {
|
|
14
|
+
try {
|
|
15
|
+
const originalSize = (await fs.stat(pngFile)).size;
|
|
16
|
+
if (originalSize < 200 * 1024) {
|
|
17
|
+
reportInfo(`Skipping small PNG: ${path.basename(pngFile)} (${formatBytes(originalSize)})`);
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
if (await isAnimatedPng(pngFile)) {
|
|
21
|
+
reportInfo(`Keeping animated PNG unchanged: ${path.basename(pngFile)}`);
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
const metadata = await sharp(pngFile).metadata();
|
|
25
|
+
if (metadata.hasAlpha && background === undefined) {
|
|
26
|
+
reportInfo(`Skipping PNG with transparency: ${path.basename(pngFile)}`);
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
const jpegFile = pngFile.replace(/\.png$/i, ".jpg");
|
|
30
|
+
if (await fs.pathExists(jpegFile)) {
|
|
31
|
+
reportWarning(`Skipping ${path.basename(pngFile)}: target JPEG already exists`);
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
// Chain resize + encode into the single sharp pass — avoids a follow-up
|
|
35
|
+
// downscale step on the freshly-written JPEG (which would otherwise be
|
|
36
|
+
// skipped by optimizeImages and stay at its original dimensions).
|
|
37
|
+
let pipeline = sharp(pngFile);
|
|
38
|
+
if (metadata.hasAlpha && background !== undefined) {
|
|
39
|
+
reportInfo(`Flattening PNG onto ${background} before JPEG conversion: ${path.basename(pngFile)}`);
|
|
40
|
+
pipeline = pipeline.flatten({ background });
|
|
41
|
+
}
|
|
42
|
+
if (maxDim) {
|
|
43
|
+
pipeline = pipeline.resize({
|
|
44
|
+
width: maxDim,
|
|
45
|
+
height: maxDim,
|
|
46
|
+
fit: "inside",
|
|
47
|
+
withoutEnlargement: true,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
await pipeline.jpeg({ quality, mozjpeg: true }).toFile(jpegFile);
|
|
51
|
+
const newSize = (await fs.stat(jpegFile)).size;
|
|
52
|
+
if (newSize >= originalSize) {
|
|
53
|
+
reportInfo(`Keeping PNG ${path.basename(pngFile)}: JPEG conversion would increase size`);
|
|
54
|
+
await fs.remove(jpegFile);
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
reportInfo(`Converted ${path.basename(pngFile)}: ${formatBytes(originalSize)} → ${formatBytes(newSize)} (${Math.round(((originalSize - newSize) / originalSize) * 100)}% smaller)`);
|
|
58
|
+
return {
|
|
59
|
+
pngFile,
|
|
60
|
+
jpegFile,
|
|
61
|
+
pngRel: toContentRel(contentDir, pngFile),
|
|
62
|
+
jpegRel: toContentRel(contentDir, jpegFile),
|
|
63
|
+
originalSize,
|
|
64
|
+
newSize,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
reportWarning(`Skipping conversion for ${path.basename(pngFile)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function collectFiles(dir, shouldInclude) {
|
|
73
|
+
const out = [];
|
|
74
|
+
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
75
|
+
await Promise.all(entries.map(async (entry) => {
|
|
76
|
+
const fullPath = path.join(dir, entry.name);
|
|
77
|
+
if (entry.isDirectory()) {
|
|
78
|
+
out.push(...(await collectFiles(fullPath, shouldInclude)));
|
|
79
|
+
}
|
|
80
|
+
else if (shouldInclude(fullPath)) {
|
|
81
|
+
out.push(fullPath);
|
|
82
|
+
}
|
|
83
|
+
}));
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
function toPosixPath(filePath) {
|
|
87
|
+
return filePath.split(path.sep).join("/");
|
|
88
|
+
}
|
|
89
|
+
function toContentRel(contentDir, filePath) {
|
|
90
|
+
return toPosixPath(path.relative(contentDir, filePath));
|
|
91
|
+
}
|
|
92
|
+
function safeDecodeUri(value) {
|
|
93
|
+
try {
|
|
94
|
+
return decodeURI(value);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return value;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function splitReference(rawReference) {
|
|
101
|
+
const hashIndex = rawReference.indexOf("#");
|
|
102
|
+
const queryIndex = rawReference.indexOf("?");
|
|
103
|
+
const suffixIndex = [hashIndex, queryIndex]
|
|
104
|
+
.filter((index) => index >= 0)
|
|
105
|
+
.sort((a, b) => a - b)[0];
|
|
106
|
+
if (suffixIndex === undefined) {
|
|
107
|
+
return { pathPart: rawReference, suffix: "" };
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
pathPart: rawReference.slice(0, suffixIndex),
|
|
111
|
+
suffix: rawReference.slice(suffixIndex),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function isExternalReference(pathPart) {
|
|
115
|
+
return (pathPart === "" ||
|
|
116
|
+
pathPart.startsWith("#") ||
|
|
117
|
+
pathPart.startsWith("//") ||
|
|
118
|
+
/^[a-z][a-z0-9+.-]*:/i.test(pathPart));
|
|
119
|
+
}
|
|
120
|
+
function resolveReference(ownerFile, contentDir, rawReference) {
|
|
121
|
+
const trimmedReference = rawReference.trim();
|
|
122
|
+
const { pathPart, suffix } = splitReference(trimmedReference);
|
|
123
|
+
if (isExternalReference(pathPart))
|
|
124
|
+
return null;
|
|
125
|
+
const decodedPath = safeDecodeUri(pathPart).replace(/\\/g, "/");
|
|
126
|
+
const targetPath = decodedPath.startsWith("/")
|
|
127
|
+
? path.resolve(contentDir, decodedPath.slice(1))
|
|
128
|
+
: path.resolve(path.dirname(ownerFile), decodedPath);
|
|
129
|
+
const relPath = path.relative(contentDir, targetPath);
|
|
130
|
+
if (relPath === "" || relPath.startsWith("..") || path.isAbsolute(relPath)) {
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
const posixRelPath = toPosixPath(relPath);
|
|
134
|
+
if (!PNG_EXT_RE.test(posixRelPath))
|
|
135
|
+
return null;
|
|
136
|
+
return { relPath: posixRelPath, suffix };
|
|
137
|
+
}
|
|
138
|
+
function replacementReference(ownerFile, contentDir, jpegRel, suffix) {
|
|
139
|
+
const ownerRel = toContentRel(contentDir, ownerFile);
|
|
140
|
+
const ownerDir = path.posix.dirname(ownerRel);
|
|
141
|
+
const relativeReference = path.posix.relative(ownerDir === "." ? "" : ownerDir, jpegRel);
|
|
142
|
+
return encodeURI(relativeReference) + suffix;
|
|
143
|
+
}
|
|
144
|
+
function getStats(statsByPng, pngRel) {
|
|
145
|
+
let stats = statsByPng.get(pngRel);
|
|
146
|
+
if (!stats) {
|
|
147
|
+
stats = { found: 0, planned: 0 };
|
|
148
|
+
statsByPng.set(pngRel, stats);
|
|
149
|
+
}
|
|
150
|
+
return stats;
|
|
151
|
+
}
|
|
152
|
+
function getReferenceToken(captured) {
|
|
153
|
+
const leadingWhitespace = captured.match(/^\s*/)?.[0].length ?? 0;
|
|
154
|
+
const trailingWhitespace = captured.match(/\s*$/)?.[0].length ?? 0;
|
|
155
|
+
let startOffset = leadingWhitespace;
|
|
156
|
+
let endOffset = captured.length - trailingWhitespace;
|
|
157
|
+
const token = captured.slice(startOffset, endOffset);
|
|
158
|
+
const quotePairs = [
|
|
159
|
+
["'", "'"],
|
|
160
|
+
['"', '"'],
|
|
161
|
+
["'", "'"],
|
|
162
|
+
["'", "'"],
|
|
163
|
+
["'", "'"],
|
|
164
|
+
[""", """],
|
|
165
|
+
[""", """],
|
|
166
|
+
[""", """],
|
|
167
|
+
];
|
|
168
|
+
for (const [open, close] of quotePairs) {
|
|
169
|
+
if (token.length >= open.length + close.length &&
|
|
170
|
+
token.slice(0, open.length).toLowerCase() === open.toLowerCase() &&
|
|
171
|
+
token.slice(-close.length).toLowerCase() === close.toLowerCase()) {
|
|
172
|
+
startOffset += open.length;
|
|
173
|
+
endOffset -= close.length;
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
const rawReference = captured.slice(startOffset, endOffset);
|
|
178
|
+
if (!rawReference)
|
|
179
|
+
return null;
|
|
180
|
+
return { rawReference, startOffset };
|
|
181
|
+
}
|
|
182
|
+
function addReferenceEdit(filePath, contentDir, rawReference, start, end, conversionsByPngRel, editsByFile, statsByPng) {
|
|
183
|
+
const resolved = resolveReference(filePath, contentDir, rawReference);
|
|
184
|
+
if (!resolved)
|
|
185
|
+
return;
|
|
186
|
+
const conversion = conversionsByPngRel.get(resolved.relPath);
|
|
187
|
+
if (!conversion)
|
|
188
|
+
return;
|
|
189
|
+
const stats = getStats(statsByPng, conversion.pngRel);
|
|
190
|
+
stats.found++;
|
|
191
|
+
const replacement = replacementReference(filePath, contentDir, conversion.jpegRel, resolved.suffix);
|
|
192
|
+
const edits = editsByFile.get(filePath) ?? [];
|
|
193
|
+
edits.push({
|
|
194
|
+
pngRel: conversion.pngRel,
|
|
195
|
+
start,
|
|
196
|
+
end,
|
|
197
|
+
replacement,
|
|
198
|
+
});
|
|
199
|
+
editsByFile.set(filePath, edits);
|
|
200
|
+
stats.planned++;
|
|
201
|
+
}
|
|
202
|
+
function scanSrcsetReferences(value, filePath, contentDir, valueOffset, conversionsByPngRel, editsByFile, statsByPng) {
|
|
203
|
+
let cursor = 0;
|
|
204
|
+
while (cursor <= value.length) {
|
|
205
|
+
const commaIndex = value.indexOf(",", cursor);
|
|
206
|
+
const segmentEnd = commaIndex === -1 ? value.length : commaIndex;
|
|
207
|
+
const segment = value.slice(cursor, segmentEnd);
|
|
208
|
+
const leadingWhitespace = segment.match(/^\s*/)?.[0].length ?? 0;
|
|
209
|
+
const rest = segment.slice(leadingWhitespace);
|
|
210
|
+
const urlLength = rest.search(/\s/);
|
|
211
|
+
const rawReference = rest.slice(0, urlLength === -1 ? rest.length : urlLength);
|
|
212
|
+
if (rawReference) {
|
|
213
|
+
const start = valueOffset + cursor + leadingWhitespace;
|
|
214
|
+
addReferenceEdit(filePath, contentDir, rawReference, start, start + rawReference.length, conversionsByPngRel, editsByFile, statsByPng);
|
|
215
|
+
}
|
|
216
|
+
if (commaIndex === -1)
|
|
217
|
+
break;
|
|
218
|
+
cursor = commaIndex + 1;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
function scanCssReferences(value, filePath, contentDir, valueOffset, conversionsByPngRel, editsByFile, statsByPng) {
|
|
222
|
+
const urlRegex = /url\(\s*(?:(["'])(.*?)\1|([^'")]*?))\s*\)/gis;
|
|
223
|
+
let urlMatch;
|
|
224
|
+
while ((urlMatch = urlRegex.exec(value)) !== null) {
|
|
225
|
+
const captured = urlMatch[2] ?? urlMatch[3] ?? "";
|
|
226
|
+
const token = getReferenceToken(captured);
|
|
227
|
+
if (!token)
|
|
228
|
+
continue;
|
|
229
|
+
const capturedStart = urlMatch[0].indexOf(captured);
|
|
230
|
+
const start = valueOffset + urlMatch.index + capturedStart + token.startOffset;
|
|
231
|
+
addReferenceEdit(filePath, contentDir, token.rawReference, start, start + token.rawReference.length, conversionsByPngRel, editsByFile, statsByPng);
|
|
232
|
+
}
|
|
233
|
+
scanImageSetReferences(value, filePath, contentDir, valueOffset, conversionsByPngRel, editsByFile, statsByPng);
|
|
234
|
+
}
|
|
235
|
+
function findFunctionEnd(value, bodyStart) {
|
|
236
|
+
let depth = 1;
|
|
237
|
+
let index = bodyStart;
|
|
238
|
+
while (index < value.length) {
|
|
239
|
+
const char = value[index];
|
|
240
|
+
if (char === '"' || char === "'") {
|
|
241
|
+
index++;
|
|
242
|
+
while (index < value.length) {
|
|
243
|
+
if (value[index] === "\\") {
|
|
244
|
+
index += 2;
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
if (value[index] === char)
|
|
248
|
+
break;
|
|
249
|
+
index++;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
else if (char === "(") {
|
|
253
|
+
depth++;
|
|
254
|
+
}
|
|
255
|
+
else if (char === ")") {
|
|
256
|
+
depth--;
|
|
257
|
+
if (depth === 0)
|
|
258
|
+
return index;
|
|
259
|
+
}
|
|
260
|
+
index++;
|
|
261
|
+
}
|
|
262
|
+
return -1;
|
|
263
|
+
}
|
|
264
|
+
function scanImageSetReferences(value, filePath, contentDir, valueOffset, conversionsByPngRel, editsByFile, statsByPng) {
|
|
265
|
+
const imageSetStartRegex = /\b(?:-webkit-)?image-set\s*\(/gis;
|
|
266
|
+
while (imageSetStartRegex.exec(value) !== null) {
|
|
267
|
+
const bodyStart = imageSetStartRegex.lastIndex;
|
|
268
|
+
const bodyEnd = findFunctionEnd(value, bodyStart);
|
|
269
|
+
if (bodyEnd === -1)
|
|
270
|
+
break;
|
|
271
|
+
const imageSetBody = value.slice(bodyStart, bodyEnd);
|
|
272
|
+
const quotedReferenceRegex = /(["'])(.*?)\1/gis;
|
|
273
|
+
let quotedMatch;
|
|
274
|
+
while ((quotedMatch = quotedReferenceRegex.exec(imageSetBody)) !== null) {
|
|
275
|
+
const beforeQuote = imageSetBody.slice(0, quotedMatch.index).trimEnd().toLowerCase();
|
|
276
|
+
if (beforeQuote.endsWith("url("))
|
|
277
|
+
continue;
|
|
278
|
+
const rawReference = quotedMatch[2];
|
|
279
|
+
if (!rawReference)
|
|
280
|
+
continue;
|
|
281
|
+
const start = valueOffset + bodyStart + quotedMatch.index + quotedMatch[0].indexOf(rawReference);
|
|
282
|
+
addReferenceEdit(filePath, contentDir, rawReference, start, start + rawReference.length, conversionsByPngRel, editsByFile, statsByPng);
|
|
283
|
+
}
|
|
284
|
+
imageSetStartRegex.lastIndex = bodyEnd + 1;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
function scanMarkupReferences(content, filePath, contentDir, conversionsByPngRel, editsByFile, statsByPng) {
|
|
288
|
+
const attributeRegex = /\b(src|href|xlink:href|style|srcset)\s*=\s*(["'])(.*?)\2/gis;
|
|
289
|
+
let attrMatch;
|
|
290
|
+
while ((attrMatch = attributeRegex.exec(content)) !== null) {
|
|
291
|
+
const attrName = attrMatch[1]?.toLowerCase();
|
|
292
|
+
const value = attrMatch[3];
|
|
293
|
+
if (attrName === undefined || value === undefined)
|
|
294
|
+
continue;
|
|
295
|
+
const valueOffset = attrMatch.index + attrMatch[0].indexOf(value);
|
|
296
|
+
if (attrName === "style") {
|
|
297
|
+
scanCssReferences(value, filePath, contentDir, valueOffset, conversionsByPngRel, editsByFile, statsByPng);
|
|
298
|
+
}
|
|
299
|
+
else if (attrName === "srcset") {
|
|
300
|
+
scanSrcsetReferences(value, filePath, contentDir, valueOffset, conversionsByPngRel, editsByFile, statsByPng);
|
|
301
|
+
}
|
|
302
|
+
else {
|
|
303
|
+
addReferenceEdit(filePath, contentDir, value, valueOffset, valueOffset + value.length, conversionsByPngRel, editsByFile, statsByPng);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
async function buildRewritePlan(contentDir, conversions) {
|
|
308
|
+
const conversionsByPngRel = new Map(conversions.map((conversion) => [conversion.pngRel, conversion]));
|
|
309
|
+
const editsByFile = new Map();
|
|
310
|
+
const statsByPng = new Map();
|
|
311
|
+
const contentFiles = await collectFiles(contentDir, (filePath) => CONTENT_FILE_EXTENSIONS.has(path.extname(filePath).toLowerCase()));
|
|
312
|
+
await Promise.all(contentFiles.map(async (filePath) => {
|
|
313
|
+
const content = await fs.readFile(filePath, "utf8");
|
|
314
|
+
if (!content.toLowerCase().includes(".png"))
|
|
315
|
+
return;
|
|
316
|
+
if (path.extname(filePath).toLowerCase() === ".css") {
|
|
317
|
+
scanCssReferences(content, filePath, contentDir, 0, conversionsByPngRel, editsByFile, statsByPng);
|
|
318
|
+
}
|
|
319
|
+
else {
|
|
320
|
+
scanMarkupReferences(content, filePath, contentDir, conversionsByPngRel, editsByFile, statsByPng);
|
|
321
|
+
}
|
|
322
|
+
}));
|
|
323
|
+
return { editsByFile, statsByPng };
|
|
324
|
+
}
|
|
325
|
+
async function buildOpfUpdatePlan(epubDir, contentDir, conversions) {
|
|
326
|
+
try {
|
|
327
|
+
const opfFile = await getOPFPath(epubDir);
|
|
328
|
+
const opfContent = await fs.readFile(opfFile, "utf8");
|
|
329
|
+
const $opf = cheerio.load(opfContent, { xmlMode: true });
|
|
330
|
+
const conversionByPngRel = new Map(conversions.map((conversion) => [conversion.pngRel, conversion]));
|
|
331
|
+
const updates = new Map();
|
|
332
|
+
const opfDir = path.dirname(opfFile);
|
|
333
|
+
$opf("item[href]").each((_, item) => {
|
|
334
|
+
const href = $opf(item).attr("href");
|
|
335
|
+
if (!href)
|
|
336
|
+
return;
|
|
337
|
+
const resolved = resolveReference(opfFile, contentDir, href);
|
|
338
|
+
if (!resolved)
|
|
339
|
+
return;
|
|
340
|
+
const conversion = conversionByPngRel.get(resolved.relPath);
|
|
341
|
+
if (!conversion)
|
|
342
|
+
return;
|
|
343
|
+
const nextHref = encodeURI(toPosixPath(path.relative(opfDir, conversion.jpegFile)));
|
|
344
|
+
updates.set(conversion.pngRel, nextHref);
|
|
345
|
+
});
|
|
346
|
+
return { opfFile, contentDir, updates };
|
|
347
|
+
}
|
|
348
|
+
catch (opfError) {
|
|
349
|
+
reportWarning(`Failed to inspect OPF file: ${opfError instanceof Error ? opfError.message : String(opfError)}`);
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
async function applyCommittedEdits(editsByFile, committedPngs) {
|
|
354
|
+
await Promise.all(Array.from(editsByFile.entries()).map(async ([filePath, edits]) => {
|
|
355
|
+
const committedEdits = edits
|
|
356
|
+
.filter((edit) => committedPngs.has(edit.pngRel))
|
|
357
|
+
.sort((a, b) => b.start - a.start);
|
|
358
|
+
if (committedEdits.length === 0)
|
|
359
|
+
return;
|
|
360
|
+
let content = await fs.readFile(filePath, "utf8");
|
|
361
|
+
for (const edit of committedEdits) {
|
|
362
|
+
content = content.slice(0, edit.start) + edit.replacement + content.slice(edit.end);
|
|
363
|
+
}
|
|
364
|
+
await fs.writeFile(filePath, content);
|
|
365
|
+
reportInfo(`Updated references in ${path.basename(filePath)}`);
|
|
366
|
+
}));
|
|
367
|
+
}
|
|
368
|
+
async function applyOpfUpdates(opfPlan, committedPngs) {
|
|
369
|
+
if (committedPngs.size === 0)
|
|
370
|
+
return;
|
|
371
|
+
const opfContent = await fs.readFile(opfPlan.opfFile, "utf8");
|
|
372
|
+
const $opf = cheerio.load(opfContent, { xmlMode: true });
|
|
373
|
+
let changed = 0;
|
|
374
|
+
$opf("item[href]").each((_, item) => {
|
|
375
|
+
const href = $opf(item).attr("href");
|
|
376
|
+
if (!href)
|
|
377
|
+
return;
|
|
378
|
+
const resolved = resolveReference(opfPlan.opfFile, opfPlan.contentDir, href);
|
|
379
|
+
if (!resolved)
|
|
380
|
+
return;
|
|
381
|
+
const updateHref = opfPlan.updates.get(resolved.relPath);
|
|
382
|
+
if (updateHref && committedPngs.has(resolved.relPath)) {
|
|
383
|
+
$opf(item).attr("href", updateHref);
|
|
384
|
+
$opf(item).attr("media-type", "image/jpeg");
|
|
385
|
+
changed++;
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
if (changed > 0) {
|
|
389
|
+
await fs.writeFile(opfPlan.opfFile, $opf.xml());
|
|
390
|
+
reportInfo(`Updated OPF file with ${changed} new JPEG reference(s)`);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Convert large opaque PNGs, or explicitly flattened transparent PNGs, to JPEG.
|
|
395
|
+
* Runs conversions in parallel, then updates XHTML and OPF references
|
|
396
|
+
* in a single batched pass.
|
|
397
|
+
* @param maxDim Optional max width/height in px — resize is chained into
|
|
398
|
+
* the same sharp pass so converted JPEGs don't need a follow-up downscale
|
|
399
|
+
* (optimizeImages skips them).
|
|
400
|
+
* @returns Absolute paths of the newly-written JPEG files — callers pass
|
|
401
|
+
* this to optimizeImages as `skip` so the freshly-encoded JPEGs aren't
|
|
402
|
+
* re-encoded a second time.
|
|
403
|
+
* @throws Error if conversion fails catastrophically (per-file errors are logged).
|
|
404
|
+
*/
|
|
405
|
+
async function convertPngToJpeg(epubDir, quality = 85, concurrency = DEFAULT_FILE_CONCURRENCY, maxDim, background) {
|
|
406
|
+
const pngBackground = resolvePngBackground({ pngBackground: background });
|
|
407
|
+
try {
|
|
408
|
+
reportInfo("Converting large PNG files to JPEG for better compression...");
|
|
409
|
+
const contentDir = await getContentPath(epubDir);
|
|
410
|
+
if (!(await fs.pathExists(contentDir))) {
|
|
411
|
+
reportInfo("Content directory not found, skipping PNG to JPEG conversion");
|
|
412
|
+
return new Set();
|
|
413
|
+
}
|
|
414
|
+
const pngFiles = await collectFiles(contentDir, (filePath) => PNG_EXT_RE.test(filePath));
|
|
415
|
+
if (pngFiles.length === 0) {
|
|
416
|
+
reportInfo("No PNG files found");
|
|
417
|
+
return new Set();
|
|
418
|
+
}
|
|
419
|
+
reportInfo(`Found ${pngFiles.length} PNG files to analyze`);
|
|
420
|
+
// Phase 1: convert in parallel — each task writes its own .jpg side-by-side.
|
|
421
|
+
const limit = pLimit(concurrency);
|
|
422
|
+
const results = await Promise.all(pngFiles.map((png) => limit(() => maybeConvertOne(png, contentDir, quality, maxDim, pngBackground))));
|
|
423
|
+
const conversions = results.filter((r) => r !== null);
|
|
424
|
+
if (conversions.length === 0) {
|
|
425
|
+
reportInfo("No PNG files were converted to JPEG");
|
|
426
|
+
return new Set();
|
|
427
|
+
}
|
|
428
|
+
// Phase 2: build a transaction plan. Nothing is rewritten until a PNG is
|
|
429
|
+
// proven safe to commit: referenced in supported content, all found
|
|
430
|
+
// references are planned, and the OPF manifest can be updated.
|
|
431
|
+
const [{ editsByFile, statsByPng }, opfPlan] = await Promise.all([
|
|
432
|
+
buildRewritePlan(contentDir, conversions),
|
|
433
|
+
buildOpfUpdatePlan(epubDir, contentDir, conversions),
|
|
434
|
+
]);
|
|
435
|
+
const committedPngs = new Set();
|
|
436
|
+
for (const conversion of conversions) {
|
|
437
|
+
const stats = statsByPng.get(conversion.pngRel) ?? { found: 0, planned: 0 };
|
|
438
|
+
const hasOpfUpdate = opfPlan?.updates.has(conversion.pngRel) ?? false;
|
|
439
|
+
if (!hasOpfUpdate) {
|
|
440
|
+
reportWarning(`Keeping PNG ${conversion.pngRel}: no matching OPF manifest item found`);
|
|
441
|
+
}
|
|
442
|
+
else if (stats.found === 0) {
|
|
443
|
+
reportWarning(`Keeping PNG ${conversion.pngRel}: no supported content references found`);
|
|
444
|
+
}
|
|
445
|
+
else if (stats.found !== stats.planned) {
|
|
446
|
+
reportWarning(`Keeping PNG ${conversion.pngRel}: planned ${stats.planned} rewrite(s) for ${stats.found} reference(s)`);
|
|
447
|
+
}
|
|
448
|
+
else {
|
|
449
|
+
committedPngs.add(conversion.pngRel);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
await applyCommittedEdits(editsByFile, committedPngs);
|
|
453
|
+
if (opfPlan) {
|
|
454
|
+
await applyOpfUpdates(opfPlan, committedPngs);
|
|
455
|
+
}
|
|
456
|
+
await Promise.all(conversions.map((conversion) => committedPngs.has(conversion.pngRel)
|
|
457
|
+
? fs.remove(conversion.pngFile)
|
|
458
|
+
: fs.remove(conversion.jpegFile)));
|
|
459
|
+
const committedConversions = conversions.filter((conversion) => committedPngs.has(conversion.pngRel));
|
|
460
|
+
if (committedConversions.length === 0) {
|
|
461
|
+
reportInfo("No PNG files were committed to JPEG conversion");
|
|
462
|
+
return new Set();
|
|
463
|
+
}
|
|
464
|
+
const totalSaved = committedConversions.reduce((sum, c) => sum + (c.originalSize - c.newSize), 0);
|
|
465
|
+
reportInfo(`Converted ${committedConversions.length} PNG files to JPEG, saving ${formatBytes(totalSaved)}`);
|
|
466
|
+
return new Set(committedConversions.map((c) => c.jpegFile));
|
|
467
|
+
}
|
|
468
|
+
catch (error) {
|
|
469
|
+
throw new Error(`Failed to convert PNG to JPEG: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
function formatBytes(bytes, decimals = 2) {
|
|
473
|
+
if (bytes === 0)
|
|
474
|
+
return "0 Bytes";
|
|
475
|
+
const k = 1024;
|
|
476
|
+
const dm = decimals < 0 ? 0 : decimals;
|
|
477
|
+
const sizes = ["Bytes", "KB", "MB", "GB"];
|
|
478
|
+
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
479
|
+
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
|
|
480
|
+
}
|
|
481
|
+
export { convertPngToJpeg };
|