工农解放报第二期26.11

This commit is contained in:
Nobody committed 2026-11-12 11:13:28 +08:00
1 parent 97e84fa6c4
commit 5977b1b272
17 files changed
+604 -46

No files matched your search

@@ -1,5 +1,6 @@
import { assertEquals } from "@std/assert";
import { DocuBuilder } from "./docu_builder.ts";
import { md } from "../mdit/md.ts";
Deno.test("PDF rendering loads relative assets from configured file base", async () => {
const chromiumPath = Deno.env.get("CHROMIUM_PATH");
@@ -24,3 +25,65 @@ Deno.test("PDF rendering loads relative assets from configured file base", async
assertEquals((await Deno.stat(pdfPath)).size > 0, true);
await Deno.remove(pdfPath);
});
Deno.test("PDF rendering waits for remote Markdown images", async () => {
if (!Deno.env.get("CHROMIUM_PATH")) return;
const builder = new DocuBuilder({
asset_base: "../../assets",
journal: { build_js_script: false },
});
const pdfPath = await Deno.makeTempFile({ suffix: ".pdf" });
await builder.with_browser();
try {
await builder.build_as_pdf({ path: pdfPath, format: "A4" }, [
'<img src="https://imgbed.cmlmuf.org/i/2026/08/31/wd5mok.jpg" alt="Remote asset">',
]);
} finally {
await builder.close_browser();
}
assertEquals((await Deno.stat(pdfPath)).size > 0, true);
await Deno.remove(pdfPath);
});
Deno.test("PDF rendering embeds publication-relative asset images", async () => {
if (!Deno.env.get("CHROMIUM_PATH")) return;
const builder = new DocuBuilder({
asset_base: "../../assets",
journal: { build_js_script: false },
});
const resolvedHtml = (builder as any).resolveLocalAssetImages(
'<img src="../../../assets/pictures/rsf.png">' +
'<img src="https://example.test/remote.png">',
);
assertEquals(
resolvedHtml.includes('src="data:image/png;base64,'),
true,
);
assertEquals(
resolvedHtml.includes('src="https://example.test/remote.png"'),
true,
);
assertEquals(resolvedHtml.includes('loading="eager"'), false);
const markdownHtml = md.render(
"![Publication asset](../../../assets/pictures/rsf.png)",
);
const eagerHtml = (builder as any).resolveLocalAssetImages(markdownHtml);
assertEquals(eagerHtml.includes('loading="lazy"'), false);
assertEquals(eagerHtml.includes('loading="eager"'), true);
const pdfPath = await Deno.makeTempFile({ suffix: ".pdf" });
await builder.with_browser();
try {
await builder.build_as_pdf({ path: pdfPath, format: "A4" }, [
(builder as any).resolveLocalAssetImages(
'<img src="../../../assets/pictures/26.11.0_pictures/ef1be4ca769fc52e513e69e1-129si8u.png" alt="Publication asset">',
),
]);
} finally {
await builder.close_browser();
}
const pdfText = new TextDecoder().decode(await Deno.readFile(pdfPath));
assertEquals(pdfText.includes("/Subtype /Image"), true);
await Deno.remove(pdfPath);
});
+105 -13
View File
@@ -81,6 +81,49 @@ export class DocuBuilder {
.trim();
}
private resolveLocalAssetImages(html: string): string {
const eagerHtml = html.replace(
/(<img\b[^>]*\sloading=["'])lazy(["'])/gi,
"$1eager$2",
);
return eagerHtml.replace(
/(<img\b[^>]*\bsrc=["'])([^"']+)(["'])/gi,
(_match, prefix: string, source: string, suffix: string) => {
const assetMarker = source.match(/(?:^|\/)assets\/(.+)$/i);
if (/^[a-z][a-z\d+.-]*:/i.test(source)) {
return `${prefix}${source}${suffix}`;
}
try {
const assetUrl = assetMarker
? new URL(assetMarker[1], this.assetBaseHref)
: new URL(source, this.assetBaseHref);
const bytes = Deno.readFileSync(assetUrl);
let binary = "";
for (let offset = 0; offset < bytes.length; offset += 0x8000) {
binary += String.fromCharCode(
...bytes.subarray(offset, offset + 0x8000),
);
}
const extension = assetUrl
.pathname.split(".").at(-1)?.toLowerCase();
const mime = extension === "png"
? "image/png"
: extension === "webp"
? "image/webp"
: extension === "gif"
? "image/gif"
: "image/jpeg";
return `${prefix}data:${mime};base64,${btoa(binary)}${suffix}`;
} catch (error) {
console.warn(`Could not embed local image ${source}: ${error}`);
return `${prefix}${
assetMarker ? `${this.assetBaseHref}${assetMarker[1]}` : source
}${suffix}`;
}
},
);
}
async as_markdown() {
const turndownService = new TurndownService();
const html_page = await this.as_html_page();
@@ -125,17 +168,20 @@ export class DocuBuilder {
);
colume.pfiles.forEach((pfile) => {
const passageId = id++;
const html = md.render(this.render(pfile.content, {
document: {
title: pfile.meta.title,
index: pfile.meta.index,
file: pfile.full_name,
},
column: {
name: colume.name,
index: colume.index,
},
}));
const firstPassageClass = c_id === 1 ? " first-passage" : "";
const html = this.resolveLocalAssetImages(
md.render(this.render(pfile.content, {
document: {
title: pfile.meta.title,
index: pfile.meta.index,
file: pfile.full_name,
},
column: {
name: colume.name,
index: colume.index,
},
})),
);
let foundHeading = false;
const indexedHtml = html.replace(
/<h1(\b[^>]*)>([\s\S]*?)<\/h1>/i,
@@ -151,7 +197,7 @@ export class DocuBuilder {
);
const printableHtml = markedHtml;
this.pages.push(
`<div class="global c${c_id++} passages" id="page-${passageId}">${printableHtml}</div>`,
`<div class="global c${c_id++} passages${firstPassageClass}" id="page-${passageId}">${printableHtml}</div>`,
);
});
});
@@ -266,7 +312,53 @@ return document?.documentElement?.outerHTML ?? html;`,
const htmlPath = await Deno.makeTempFile({ suffix: ".html" });
try {
await Deno.writeTextFile(htmlPath, htmlWithBase);
await page.goto(pathToFileURL(htmlPath).href, { timeout: 120000 });
await page.goto(pathToFileURL(htmlPath).href, {
timeout: 120000,
waitUntil: "domcontentloaded",
});
// `page.goto(..., { waitUntil: "load" })` does not guarantee that
// every image has finished decoding before printing. Wait for each
// image explicitly so remote Markdown images are included in the PDF.
const failedImages = await page.evaluate(async () => {
// The project is type-checked without the DOM library; these values
// live in Chromium's page context, not in the Deno runtime.
const pageDocument = (globalThis as any).document;
const images = Array.from(pageDocument.images) as any[];
const timedOutImages = await Promise.all(images.map((image) => {
if (image.complete) return Promise.resolve(false);
return new Promise<boolean>((resolve) => {
let settled = false;
const finish = () => {
if (settled) return;
settled = true;
clearTimeout(timeout);
resolve(false);
};
const timeout = setTimeout(() => {
if (settled) return;
settled = true;
resolve(true);
}, 15000);
image.addEventListener("load", finish, { once: true });
image.addEventListener("error", finish, { once: true });
});
}));
const failed = images
.filter((image) => !image.naturalWidth)
.map((image) => image.currentSrc || image.src);
return failed.length > 0
? failed
: images.filter((_image, index) => timedOutImages[index])
.map((image) => image.currentSrc || image.src);
});
if (failedImages.length > 0) {
console.warn(
`Continuing PDF generation with ${failedImages.length} image(s) not loaded within 15 seconds: ${
failedImages.join(", ")
}`,
);
}
await page.pdf(pw_config);
} finally {