|
| 1 | +import { existsSync, readdirSync, statSync } from "node:fs"; |
| 2 | +import { join } from "node:path"; |
| 3 | + |
| 4 | +const binDir = join("bin"); |
| 5 | +const zopflipngPath = join(binDir, "zopflipng.exe"); |
| 6 | +const imgDir = join("docs", "md", "img"); |
| 7 | +const downloadUrl = "https://drpleaserespect.github.io/drpleaserespect-webassets/compiled_binaries/google/zopflipng.exe"; |
| 8 | + |
| 9 | +async function ensureZopflipng(): Promise<void> { |
| 10 | + if (existsSync(zopflipngPath)) { |
| 11 | + console.log(`using cached ${zopflipngPath}`); |
| 12 | + return; |
| 13 | + } |
| 14 | + console.log(`downloading zopflipng.exe from ${downloadUrl}`); |
| 15 | + const resp = await fetch(downloadUrl); |
| 16 | + if (!resp.ok) { |
| 17 | + throw new Error(`download failed: ${resp.status} ${resp.statusText}`); |
| 18 | + } |
| 19 | + const data = await resp.arrayBuffer(); |
| 20 | + await Bun.write(zopflipngPath, data); |
| 21 | + console.log(`saved ${zopflipngPath}`); |
| 22 | +} |
| 23 | + |
| 24 | +async function compressImage(pngPath: string): Promise<void> { |
| 25 | + const sizeBefore = statSync(pngPath).size; |
| 26 | + // zopflipng overwrites in-place when input and output are the same |
| 27 | + const proc = Bun.spawn([zopflipngPath, "-y", pngPath, pngPath], { |
| 28 | + stdout: "pipe", |
| 29 | + stderr: "pipe", |
| 30 | + }); |
| 31 | + const exitCode = await proc.exited; |
| 32 | + if (exitCode !== 0) { |
| 33 | + const stderr = await new Response(proc.stderr).text(); |
| 34 | + console.log(` warning: zopflipng failed on ${pngPath}: ${stderr.trim()}`); |
| 35 | + return; |
| 36 | + } |
| 37 | + const sizeAfter = statSync(pngPath).size; |
| 38 | + const saved = sizeBefore - sizeAfter; |
| 39 | + if (saved > 0) { |
| 40 | + console.log(` ${pngPath}: ${sizeBefore} -> ${sizeAfter} (saved ${saved} bytes)`); |
| 41 | + } else { |
| 42 | + console.log(` ${pngPath}: ${sizeBefore} bytes (already optimal)`); |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +async function main(): Promise<void> { |
| 47 | + await ensureZopflipng(); |
| 48 | + |
| 49 | + const files = readdirSync(imgDir) |
| 50 | + .filter((f) => f.toLowerCase().endsWith(".png")) |
| 51 | + .map((f) => join(imgDir, f)); |
| 52 | + |
| 53 | + console.log(`compressing ${files.length} PNG files in ${imgDir}`); |
| 54 | + for (const file of files) { |
| 55 | + await compressImage(file); |
| 56 | + } |
| 57 | + console.log("done"); |
| 58 | +} |
| 59 | + |
| 60 | +if (import.meta.main) { |
| 61 | + await main(); |
| 62 | +} |
0 commit comments