@canvakit/export 0.0.0-stage → 0.2.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/dist/index.mjs ADDED
@@ -0,0 +1,1114 @@
1
+ import { render } from '@canvakit/core';
2
+ import { execFile, execFileSync, spawn } from 'child_process';
3
+ import { promisify } from 'util';
4
+ import { existsSync, mkdtempSync, writeFileSync, readFileSync, rmSync } from 'fs';
5
+ import { tmpdir } from 'os';
6
+ import { join } from 'path';
7
+ import JSZip from 'jszip';
8
+ import juice from 'juice';
9
+
10
+ /**
11
+ * @canvakit/export v0.1.0
12
+ * Export a canvakit render to HTML / HTML-zip / PNG / PDF.
13
+ */
14
+
15
+ var pexec = promisify(execFile);
16
+ var CANDIDATES = [
17
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
18
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
19
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
20
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
21
+ "google-chrome",
22
+ "google-chrome-stable",
23
+ "chromium",
24
+ "chromium-browser",
25
+ "chrome"
26
+ ];
27
+ function onPath(cmd) {
28
+ try {
29
+ execFileSync(process.platform === "win32" ? "where" : "which", [cmd], {
30
+ stdio: "ignore"
31
+ });
32
+ return true;
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+ function findChrome() {
38
+ const override = process.env.CANVAKIT_CHROME ?? process.env.CHROME_PATH ?? process.env.PUPPETEER_EXECUTABLE_PATH;
39
+ if (override) {
40
+ if (existsSync(override)) return override;
41
+ throw new Error(
42
+ `CANVAKIT_CHROME/CHROME_PATH points at "${override}" but it does not exist`
43
+ );
44
+ }
45
+ for (const c of CANDIDATES) {
46
+ if (c.startsWith("/") || c.includes(":\\")) {
47
+ if (existsSync(c)) return c;
48
+ } else if (onPath(c)) {
49
+ return c;
50
+ }
51
+ }
52
+ throw new Error(
53
+ "no Chrome/Chromium found for PDF/PNG export \u2014 install Chrome, or set CANVAKIT_CHROME to a binary (or inject a ChromeRenderer)"
54
+ );
55
+ }
56
+ var baseFlags = (waitMs) => [
57
+ "--headless=new",
58
+ "--disable-gpu",
59
+ "--hide-scrollbars",
60
+ "--no-first-run",
61
+ "--no-sandbox",
62
+ `--virtual-time-budget=${waitMs}`
63
+ ];
64
+ async function withChromeOutput(chrome, html, outName, flagsFor) {
65
+ const dir = mkdtempSync(join(tmpdir(), "canvakit-export-"));
66
+ try {
67
+ const htmlPath = join(dir, "input.html");
68
+ const outPath = join(dir, outName);
69
+ writeFileSync(htmlPath, html, "utf8");
70
+ await pexec(chrome, flagsFor(`file://${htmlPath}`, outPath), {
71
+ timeout: 6e4,
72
+ maxBuffer: 1 << 26
73
+ });
74
+ if (!existsSync(outPath)) {
75
+ throw new Error(`Chrome produced no ${outName}`);
76
+ }
77
+ return readFileSync(outPath);
78
+ } finally {
79
+ rmSync(dir, { recursive: true, force: true });
80
+ }
81
+ }
82
+ function localChromeRenderer(chrome) {
83
+ const bin = () => chrome ?? findChrome();
84
+ return {
85
+ async toPdf(html, page = {}) {
86
+ const wait = page.waitMs ?? 1200;
87
+ return withChromeOutput(
88
+ bin(),
89
+ html,
90
+ "out.pdf",
91
+ (url, out) => [
92
+ ...baseFlags(wait),
93
+ "--no-pdf-header-footer",
94
+ page.landscape ? "--landscape" : null,
95
+ page.scale ? `--force-device-scale-factor=${page.scale}` : null,
96
+ `--print-to-pdf=${out}`,
97
+ url
98
+ ].filter((f) => f !== null)
99
+ );
100
+ },
101
+ async toPng(html, page = {}) {
102
+ const wait = page.waitMs ?? 1200;
103
+ return withChromeOutput(bin(), html, "out.png", (url, out) => [
104
+ ...baseFlags(wait),
105
+ `--force-device-scale-factor=${page.scale ?? 2}`,
106
+ `--screenshot=${out}`,
107
+ url
108
+ ]);
109
+ }
110
+ };
111
+ }
112
+
113
+ // src/renderer.ts
114
+ function resolveRenderer(opts = {}) {
115
+ if (opts.renderer) return opts.renderer;
116
+ const which = process.env.CANVAKIT_RENDERER?.trim().toLowerCase();
117
+ if (which && which !== "local") {
118
+ throw new Error(
119
+ `CANVAKIT_RENDERER="${which}" selects an engine @canvakit/export does not bundle \u2014 pass { renderer } with a ${which} adapter, or unset it to use the local system-Chrome engine (set CANVAKIT_CHROME for the binary).`
120
+ );
121
+ }
122
+ return localChromeRenderer(opts.chrome);
123
+ }
124
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
125
+ var SYS_FONT = "-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif";
126
+ function chromeBox(inner) {
127
+ return `<div style="font-size:9px;font-family:${SYS_FONT};color:#8b90b8;width:100%;padding:0 16mm;-webkit-print-color-adjust:exact;">${inner}</div>`;
128
+ }
129
+ var PAGE_NO = `<span style="font-variant-numeric:tabular-nums;"><span class="pageNumber"></span> / <span class="totalPages"></span></span>`;
130
+ function slotsTemplate(hf, pageNumbers, pageNumbersSlot, stringSlot) {
131
+ const slots = !hf ? {} : typeof hf === "string" ? { [stringSlot]: hf } : { ...hf };
132
+ if (pageNumbers) {
133
+ const prev = slots[pageNumbersSlot];
134
+ slots[pageNumbersSlot] = prev ? `${prev} ${PAGE_NO}` : PAGE_NO;
135
+ }
136
+ if (!slots.left && !slots.center && !slots.right) return "<div></div>";
137
+ const cell = (c, align) => `<span style="flex:1;text-align:${align};">${c ?? ""}</span>`;
138
+ return chromeBox(
139
+ `<div style="display:flex;width:100%;align-items:center;">${cell(slots.left, "left")}${cell(slots.center, "center")}${cell(slots.right, "right")}</div>`
140
+ );
141
+ }
142
+ function getWebSocketCtor() {
143
+ const ctor = globalThis.WebSocket;
144
+ if (typeof ctor !== "function") {
145
+ throw new Error(
146
+ "cdpChromeRenderer needs a global WebSocket (Node 20.10+/22). Upgrade Node, or use the default CLI renderer (no header/footer/page numbers), or inject a renderer."
147
+ );
148
+ }
149
+ return ctor;
150
+ }
151
+ async function withCdp(chrome, html, waitMs, run) {
152
+ const port = 9200 + Math.floor(Math.random() * 700);
153
+ const dir = mkdtempSync(join(tmpdir(), "canvakit-cdp-"));
154
+ const htmlPath = join(dir, "input.html");
155
+ writeFileSync(htmlPath, html, "utf8");
156
+ const proc = spawn(
157
+ chrome,
158
+ [
159
+ "--headless=new",
160
+ "--disable-gpu",
161
+ "--no-first-run",
162
+ "--no-default-browser-check",
163
+ "--no-sandbox",
164
+ `--remote-debugging-port=${port}`,
165
+ "about:blank"
166
+ ],
167
+ { stdio: "ignore" }
168
+ );
169
+ const cleanup = () => {
170
+ try {
171
+ proc.kill();
172
+ } catch {
173
+ }
174
+ rmSync(dir, { recursive: true, force: true });
175
+ };
176
+ try {
177
+ let wsUrl;
178
+ for (let i = 0; i < 40 && !wsUrl; i++) {
179
+ await sleep(250);
180
+ try {
181
+ const res = await fetch(`http://127.0.0.1:${port}/json`);
182
+ const targets = await res.json();
183
+ wsUrl = targets.find((t) => t.type === "page")?.webSocketDebuggerUrl;
184
+ } catch {
185
+ }
186
+ }
187
+ if (!wsUrl) throw new Error("CDP endpoint not reachable");
188
+ const WebSocketCtor = getWebSocketCtor();
189
+ const ws = new WebSocketCtor(wsUrl);
190
+ let nextId = 1;
191
+ const pending = /* @__PURE__ */ new Map();
192
+ const send = (method, params = {}) => new Promise((resolve) => {
193
+ const id = nextId++;
194
+ pending.set(id, resolve);
195
+ ws.send(JSON.stringify({ id, method, params }));
196
+ });
197
+ await new Promise((resolve) => {
198
+ ws.onopen = resolve;
199
+ });
200
+ ws.onmessage = (ev) => {
201
+ const msg = JSON.parse(ev.data);
202
+ if (msg.id != null && pending.has(msg.id)) {
203
+ pending.get(msg.id)(msg.result ?? {});
204
+ pending.delete(msg.id);
205
+ }
206
+ };
207
+ await send("Page.enable");
208
+ await send("Page.navigate", { url: `file://${htmlPath}` });
209
+ await sleep(waitMs);
210
+ const result = await run(send);
211
+ ws.close();
212
+ return result;
213
+ } finally {
214
+ cleanup();
215
+ }
216
+ }
217
+ async function withCdpConnect(browserWSEndpoint, html, waitMs, run) {
218
+ const WebSocketCtor = getWebSocketCtor();
219
+ const ws = new WebSocketCtor(browserWSEndpoint);
220
+ let nextId = 1;
221
+ const pending = /* @__PURE__ */ new Map();
222
+ const sendRaw = (method, params = {}, sessionId) => new Promise((resolve) => {
223
+ const id = nextId++;
224
+ pending.set(id, resolve);
225
+ ws.send(
226
+ JSON.stringify({
227
+ id,
228
+ method,
229
+ params,
230
+ ...sessionId ? { sessionId } : {}
231
+ })
232
+ );
233
+ });
234
+ await new Promise((resolve) => {
235
+ ws.onopen = resolve;
236
+ });
237
+ ws.onmessage = (ev) => {
238
+ const msg = JSON.parse(ev.data);
239
+ if (msg.id != null && pending.has(msg.id)) {
240
+ pending.get(msg.id)(msg.result ?? {});
241
+ pending.delete(msg.id);
242
+ }
243
+ };
244
+ let targetId;
245
+ try {
246
+ const created = await sendRaw("Target.createTarget", { url: "about:blank" });
247
+ targetId = created.targetId;
248
+ const attached = await sendRaw("Target.attachToTarget", {
249
+ targetId,
250
+ flatten: true
251
+ });
252
+ const sessionId = attached.sessionId;
253
+ if (!sessionId)
254
+ throw new Error("CDP connect: attachToTarget gave no sessionId");
255
+ const send = (method, params = {}) => sendRaw(method, params, sessionId);
256
+ await send("Page.enable");
257
+ const tree = await send("Page.getFrameTree");
258
+ const frameId = tree.frameTree?.frame?.id;
259
+ if (!frameId) throw new Error("CDP connect: no main frame id");
260
+ await send("Page.setDocumentContent", { frameId, html });
261
+ await sleep(waitMs);
262
+ return await run(send);
263
+ } finally {
264
+ try {
265
+ if (targetId) await sendRaw("Target.closeTarget", { targetId });
266
+ } catch {
267
+ }
268
+ ws.close();
269
+ }
270
+ }
271
+ function cdpChromeRenderer(opts = {}) {
272
+ const bin = () => opts.chrome ?? findChrome();
273
+ const wait = opts.waitMs ?? 2500;
274
+ const display = Boolean(opts.header || opts.footer || opts.pageNumbers);
275
+ const endpoint = () => opts.browserWSEndpoint ?? (process.env.CANVAKIT_BROWSER_WS_ENDPOINT?.trim() || void 0);
276
+ const drive = (html, waitMs, run) => {
277
+ const ws = endpoint();
278
+ return ws ? withCdpConnect(ws, html, waitMs, run) : withCdp(bin(), html, waitMs, run);
279
+ };
280
+ return {
281
+ async toPdf(html, page = {}) {
282
+ const data = await drive(html, page.waitMs ?? wait, async (send) => {
283
+ const pnSlot = opts.pageNumbersSlot ?? "right";
284
+ const res = await send("Page.printToPDF", {
285
+ printBackground: page.background ?? true,
286
+ preferCSSPageSize: true,
287
+ landscape: page.landscape ?? false,
288
+ // The ONLY thing that actually shrinks page count: Chrome lays out
289
+ // a virtual print viewport at 1/scale before fragmenting into
290
+ // pages, so page breaks are computed against the scaled content.
291
+ // CSS `zoom`/`transform` are paint-time — Chrome's print-layout
292
+ // pass ignores them entirely, so they never move a page break.
293
+ scale: page.scale ?? 1,
294
+ displayHeaderFooter: display,
295
+ headerTemplate: slotsTemplate(opts.header, false, pnSlot, "left"),
296
+ footerTemplate: slotsTemplate(
297
+ opts.footer,
298
+ Boolean(opts.pageNumbers),
299
+ pnSlot,
300
+ "center"
301
+ )
302
+ });
303
+ return res.data;
304
+ });
305
+ return Buffer.from(data, "base64");
306
+ },
307
+ async toPng(html, page = {}) {
308
+ const data = await drive(html, page.waitMs ?? wait, async (send) => {
309
+ const metrics = await send("Page.getLayoutMetrics");
310
+ const size = metrics.cssContentSize ?? metrics.contentSize;
311
+ const res = await send("Page.captureScreenshot", {
312
+ format: "png",
313
+ captureBeyondViewport: true,
314
+ ...size ? {
315
+ clip: {
316
+ x: 0,
317
+ y: 0,
318
+ width: size.width,
319
+ height: size.height,
320
+ scale: page.scale ?? 2
321
+ }
322
+ } : {}
323
+ });
324
+ return res.data;
325
+ });
326
+ return Buffer.from(data, "base64");
327
+ }
328
+ };
329
+ }
330
+
331
+ // src/medium.ts
332
+ var DEFAULTS = {
333
+ // Responsive, interactive — the in-app default. No page geometry.
334
+ web: { format: "html-zip", page: {} },
335
+ // Paginated print — A4 portrait with print margins. Document chrome (running
336
+ // header/footer, page numbers, TOC) is added by the document renderer.
337
+ document: {
338
+ format: "pdf",
339
+ page: { background: true },
340
+ pageSpec: {
341
+ size: "A4",
342
+ orientation: "portrait",
343
+ margin: "18mm",
344
+ pageNumbers: true
345
+ }
346
+ },
347
+ // Landscape 16:9 slides, edge-to-edge.
348
+ presentation: {
349
+ format: "pdf",
350
+ page: { background: true },
351
+ pageSpec: { size: "16:9", margin: "0" }
352
+ },
353
+ // A single fixed-dimension frame — full-page screenshot at 2× for sharpness.
354
+ image: { format: "png", page: { scale: 2 } }
355
+ };
356
+ function mediumDefaults(medium) {
357
+ return DEFAULTS[medium];
358
+ }
359
+ function mergePageSpec(base, override) {
360
+ if (!base) return override;
361
+ if (!override) return base;
362
+ return { ...base, ...override };
363
+ }
364
+ var ASPECTS = {
365
+ "16:9": "1280px 720px",
366
+ "4:3": "1024px 768px",
367
+ "1:1": "1080px 1080px"
368
+ };
369
+ var NAMED_PAPER = /^(A3|A4|A5|Letter|Legal|Tabloid)$/i;
370
+ function resolvePageSize(size, orientation) {
371
+ if (!size) return orientation ?? null;
372
+ const s = size.trim();
373
+ if (NAMED_PAPER.test(s)) return orientation ? `${s} ${orientation}` : s;
374
+ if (ASPECTS[s]) return ASPECTS[s];
375
+ const px = s.match(/^(\d+)\s*[x×]\s*(\d+)$/i);
376
+ if (px) return `${px[1]}px ${px[2]}px`;
377
+ return s;
378
+ }
379
+ function pageCssFor(spec) {
380
+ if (!spec) return null;
381
+ const rules = [];
382
+ const decls = [];
383
+ const size = resolvePageSize(spec.size, spec.orientation);
384
+ if (size) decls.push(` size: ${size};`);
385
+ if (spec.margin != null) decls.push(` margin: ${spec.margin};`);
386
+ if (decls.length) rules.push(`@page {
387
+ ${decls.join("\n")}
388
+ }`);
389
+ if (spec.cover) rules.push(`@page :first { margin: 0; }`);
390
+ return rules.length ? rules.join("\n") : null;
391
+ }
392
+ function wantsDocumentChrome(spec) {
393
+ return Boolean(spec && (spec.header || spec.footer || spec.pageNumbers));
394
+ }
395
+ function applyPageCss(html, css) {
396
+ if (!css) return html;
397
+ const style = `<style data-canvakit="page">
398
+ ${css}
399
+ </style>`;
400
+ const headOpen = html.match(/<head[^>]*>/i);
401
+ if (headOpen?.index != null) {
402
+ const at = headOpen.index + headOpen[0].length;
403
+ return html.slice(0, at) + style + html.slice(at);
404
+ }
405
+ return style + html;
406
+ }
407
+
408
+ // src/document.ts
409
+ async function loadPdfjs() {
410
+ try {
411
+ return await import('pdfjs-dist/legacy/build/pdf.mjs');
412
+ } catch {
413
+ throw new Error(
414
+ "renderDocumentPdf needs `pdfjs-dist` (TOC page extraction). Install it: pnpm add pdfjs-dist"
415
+ );
416
+ }
417
+ }
418
+ async function loadPdfLib() {
419
+ try {
420
+ return await import('pdf-lib');
421
+ } catch {
422
+ throw new Error(
423
+ "renderDocumentPdf needs `pdf-lib` (merge + clickable TOC links). Install it: pnpm add pdf-lib"
424
+ );
425
+ }
426
+ }
427
+ var stripTags = (h) => h.replace(/<[^>]+>/g, "");
428
+ var decodeEntities = (s) => s.replace(/&#(\d+);/g, (_, d) => String.fromCharCode(Number(d))).replace(
429
+ /&#x([0-9a-f]+);/gi,
430
+ (_, h) => String.fromCharCode(parseInt(h, 16))
431
+ ).replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
432
+ var matchKey = (s) => decodeEntities(s).toLowerCase().replace(/[^a-z0-9]+/g, "");
433
+ var norm = matchKey;
434
+ function makeSlugger() {
435
+ const seen = /* @__PURE__ */ new Map();
436
+ return (text) => {
437
+ const base = decodeEntities(stripTags(text)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "h";
438
+ const n = (seen.get(base) ?? 0) + 1;
439
+ seen.set(base, n);
440
+ return n === 1 ? base : `${base}-${n}`;
441
+ };
442
+ }
443
+ function extractToc(html, levels, exclude = []) {
444
+ const slugger = makeSlugger();
445
+ const excluded = new Set(exclude.map(matchKey));
446
+ const toc = [];
447
+ const out = html.replace(
448
+ /<h([1-6])([^>]*)>([\s\S]*?)<\/h\1>/gi,
449
+ (m, lvl, attrs, inner) => {
450
+ const level = Number(lvl);
451
+ const label = stripTags(inner).replace(/\s+/g, " ").trim();
452
+ if (!levels.includes(level) || !label) return m;
453
+ if (excluded.has(matchKey(label))) return m;
454
+ const idMatch = attrs.match(/\bid=["']([^"']+)["']/);
455
+ const slug = idMatch?.[1] ?? slugger(label);
456
+ toc.push({ level, label, slug });
457
+ const attrs2 = idMatch ? attrs : `${attrs} id="${slug}"`;
458
+ return `<h${lvl}${attrs2}>${inner}</h${lvl}>`;
459
+ }
460
+ );
461
+ return { html: out, toc };
462
+ }
463
+ async function extractPageMap(pdfBytes, toc) {
464
+ const pdfjs = await loadPdfjs();
465
+ const doc = await pdfjs.getDocument({
466
+ data: new Uint8Array(Buffer.from(pdfBytes)),
467
+ useSystemFonts: true
468
+ }).promise;
469
+ const pagesText = [];
470
+ for (let p = 1; p <= doc.numPages; p++) {
471
+ const page = await doc.getPage(p);
472
+ const tc = await page.getTextContent();
473
+ pagesText.push(norm(tc.items.map((i) => i.str ?? "").join("")));
474
+ }
475
+ const map = {};
476
+ for (const e of toc) {
477
+ const needle = norm(e.label);
478
+ const idx = pagesText.findIndex((t) => t.includes(needle));
479
+ if (idx >= 0) map[e.slug] = idx + 1;
480
+ }
481
+ return map;
482
+ }
483
+ var DEFAULT_TOC_CSS = `
484
+ .ck-toc{ padding-top:4mm; font-family:system-ui,-apple-system,'Segoe UI',sans-serif; color:#16181d; }
485
+ .ck-toc-h{ font-size:20pt; font-weight:700; margin:0 0 8mm; }
486
+ .ck-toc-row{ display:flex; align-items:baseline; gap:3mm; padding:1.2mm 0; font-size:10.5pt; text-decoration:none; color:#16181d; }
487
+ .ck-toc-row.lvl1{ font-weight:700; margin-top:5mm; color:#4f46e5; }
488
+ .ck-toc-label{ flex:none; } .ck-toc-dots{ flex:1; border-bottom:1px dotted #c7cbe0; transform:translateY(-1px); }
489
+ .ck-toc-page{ flex:none; color:#5b6170; font-variant-numeric:tabular-nums; }
490
+ `;
491
+ function buildTocHtml(toc, pageMap, title, extraCss, pageCss, head) {
492
+ const rows = toc.map((e) => {
493
+ const page = pageMap[e.slug] ?? "";
494
+ return `<a class="ck-toc-row lvl${e.level}" href="#${e.slug}"><span class="ck-toc-label">${e.label}</span><span class="ck-toc-dots"></span><span class="ck-toc-page">${page}</span></a>`;
495
+ }).join("");
496
+ return `<!doctype html><html><head><meta charset="utf-8">${head ?? ""}<style>${pageCss ?? ""}${DEFAULT_TOC_CSS}${extraCss ?? ""}</style></head><body><nav class="ck-toc"><div class="ck-toc-h">${title}</div>${rows}</nav></body></html>`;
497
+ }
498
+ async function mergePdfs(parts) {
499
+ const { PDFDocument } = await loadPdfLib();
500
+ const out = await PDFDocument.create();
501
+ const counts = [];
502
+ for (const part of parts) {
503
+ const src = await PDFDocument.load(new Uint8Array(Buffer.from(part)));
504
+ const idxs = src.getPageIndices();
505
+ counts.push(idxs.length);
506
+ const copied = await out.copyPages(src, idxs);
507
+ for (const p of copied) out.addPage(p);
508
+ }
509
+ return { bytes: Buffer.from(await out.save()), counts };
510
+ }
511
+ async function stampTocLinks(mergedBytes, toc, pageMap, coverPages, tocPages) {
512
+ const pdfjs = await loadPdfjs();
513
+ const { PDFDocument, PDFName, PDFArray } = await loadPdfLib();
514
+ const tocPageNos = Array.from(
515
+ { length: tocPages },
516
+ (_, i) => coverPages + 1 + i
517
+ );
518
+ const doc = await pdfjs.getDocument({
519
+ data: new Uint8Array(Buffer.from(mergedBytes)),
520
+ useSystemFonts: true
521
+ }).promise;
522
+ const rowsByPage = /* @__PURE__ */ new Map();
523
+ for (const pageNo of tocPageNos) {
524
+ const page = await doc.getPage(pageNo);
525
+ const tc = await page.getTextContent();
526
+ const rows = /* @__PURE__ */ new Map();
527
+ for (const it of tc.items) {
528
+ if (!it.str?.trim() || !it.transform) continue;
529
+ const x = it.transform[4] ?? 0;
530
+ const y = it.transform[5] ?? 0;
531
+ const key = Math.round(y);
532
+ let r = rows.get(key);
533
+ if (!r) {
534
+ r = { y, parts: [] };
535
+ rows.set(key, r);
536
+ }
537
+ r.parts.push({ x, str: it.str });
538
+ }
539
+ rowsByPage.set(
540
+ pageNo,
541
+ [...rows.values()].map((r) => ({
542
+ y: r.y,
543
+ text: norm(
544
+ r.parts.sort((a, b) => a.x - b.x).map((p) => p.str).join("")
545
+ )
546
+ }))
547
+ );
548
+ }
549
+ const pdf = await PDFDocument.load(new Uint8Array(Buffer.from(mergedBytes)));
550
+ const pages = pdf.getPages();
551
+ let stamped = 0;
552
+ const warnings = [];
553
+ for (const e of toc) {
554
+ const lp = pageMap[e.slug];
555
+ if (lp == null) {
556
+ warnings.push(`${e.slug}: no content page found`);
557
+ continue;
558
+ }
559
+ const label = norm(e.label).slice(0, 40);
560
+ let foundY = null;
561
+ let foundPageNo = null;
562
+ for (const pageNo of tocPageNos) {
563
+ const row = rowsByPage.get(pageNo)?.find((r) => label && r.text.includes(label));
564
+ if (row) {
565
+ foundY = row.y;
566
+ foundPageNo = pageNo;
567
+ break;
568
+ }
569
+ }
570
+ if (foundY == null || foundPageNo == null) {
571
+ warnings.push(`${e.slug}: TOC row not located`);
572
+ continue;
573
+ }
574
+ const targetPhysical = coverPages + tocPages + lp;
575
+ const targetPage = pages[targetPhysical - 1];
576
+ const tocPage = pages[foundPageNo - 1];
577
+ if (!targetPage || !tocPage) {
578
+ warnings.push(`${e.slug}: target page ${targetPhysical} out of range`);
579
+ continue;
580
+ }
581
+ const width = tocPage.getWidth();
582
+ const annot = pdf.context.obj({
583
+ Type: "Annot",
584
+ Subtype: "Link",
585
+ Rect: [36, foundY - 4, width - 36, foundY + 13],
586
+ Border: [0, 0, 0],
587
+ Dest: [targetPage.ref, PDFName.of("Fit")]
588
+ });
589
+ const ref = pdf.context.register(annot);
590
+ let annots = tocPage.node.get(PDFName.of("Annots"));
591
+ if (!(annots instanceof PDFArray)) {
592
+ annots = pdf.context.obj([]);
593
+ tocPage.node.set(PDFName.of("Annots"), annots);
594
+ }
595
+ annots.push(ref);
596
+ stamped++;
597
+ }
598
+ return { bytes: Buffer.from(await pdf.save()), stamped, warnings };
599
+ }
600
+ async function renderDocumentPdf(opts) {
601
+ const levels = opts.tocLevels ?? [1, 2];
602
+ const specIn = { ...opts.pageSpec };
603
+ delete specIn.cover;
604
+ const baseSpec = {
605
+ size: "A4",
606
+ orientation: "portrait",
607
+ margin: "18mm",
608
+ ...specIn
609
+ };
610
+ const warnings = [];
611
+ const { html: contentWithIds, toc } = extractToc(
612
+ opts.contentHtml,
613
+ levels,
614
+ opts.tocExclude
615
+ );
616
+ const contentSpec = { ...baseSpec};
617
+ const contentRenderer = cdpChromeRenderer({
618
+ header: opts.header,
619
+ footer: opts.footer,
620
+ pageNumbers: true,
621
+ pageNumbersSlot: opts.pageNumbersSlot,
622
+ chrome: opts.chrome
623
+ });
624
+ const contentPdf = await contentRenderer.toPdf(
625
+ applyPageCss(contentWithIds, pageCssFor(contentSpec)),
626
+ { scale: opts.scale }
627
+ );
628
+ const pageMap = toc.length ? await extractPageMap(contentPdf, toc) : {};
629
+ for (const e of toc)
630
+ if (pageMap[e.slug] == null) warnings.push(`${e.slug}: page not located`);
631
+ const plain = cdpChromeRenderer({ chrome: opts.chrome });
632
+ const tocCss = pageCssFor(baseSpec);
633
+ const tocPdf = toc.length ? await plain.toPdf(
634
+ buildTocHtml(
635
+ toc,
636
+ pageMap,
637
+ opts.tocTitle ?? "Contents",
638
+ opts.tocCss,
639
+ tocCss,
640
+ opts.tocHead
641
+ )
642
+ ) : null;
643
+ const fullBleedCss = pageCssFor({ ...baseSpec, margin: "0", cover: true });
644
+ const renderFullBleed = (html) => {
645
+ const list = html == null ? [] : Array.isArray(html) ? html : [html];
646
+ return Promise.all(
647
+ list.map((h) => plain.toPdf(applyPageCss(h, fullBleedCss)))
648
+ );
649
+ };
650
+ const coverPdfs = await renderFullBleed(opts.coverHtml);
651
+ const backPdfs = await renderFullBleed(opts.backHtml);
652
+ const order = [...coverPdfs, tocPdf, contentPdf, ...backPdfs].filter(
653
+ (b) => b != null
654
+ );
655
+ if (order.length === 1) {
656
+ return {
657
+ bytes: contentPdf,
658
+ pages: await countPages(contentPdf),
659
+ toc,
660
+ pageMap,
661
+ warnings
662
+ };
663
+ }
664
+ const { bytes: merged, counts } = await mergePdfs(order);
665
+ const coverPages = counts.slice(0, coverPdfs.length).reduce((a, b) => a + b, 0);
666
+ const tocPages = tocPdf ? counts[coverPdfs.length] ?? 0 : 0;
667
+ if (!tocPdf) {
668
+ return {
669
+ bytes: merged,
670
+ pages: await countPages(merged),
671
+ toc,
672
+ pageMap,
673
+ warnings
674
+ };
675
+ }
676
+ const stamp = await stampTocLinks(merged, toc, pageMap, coverPages, tocPages);
677
+ warnings.push(...stamp.warnings);
678
+ return {
679
+ bytes: stamp.bytes,
680
+ pages: await countPages(stamp.bytes),
681
+ toc,
682
+ pageMap,
683
+ warnings
684
+ };
685
+ }
686
+ async function countPages(pdf) {
687
+ const { PDFDocument } = await loadPdfLib();
688
+ const doc = await PDFDocument.load(new Uint8Array(Buffer.from(pdf)));
689
+ return doc.getPageIndices().length;
690
+ }
691
+
692
+ // src/cover.ts
693
+ var escapeHtml = (s) => s.replace(
694
+ /[&<>"]/g,
695
+ (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c] ?? c
696
+ );
697
+ function titleize(name) {
698
+ return name.replace(/[-_]+/g, " ").replace(/\s+/g, " ").trim().replace(/\b\w/g, (c) => c.toUpperCase()) || "Document";
699
+ }
700
+ function autoCoverHtml(name, subtitle) {
701
+ const sub = subtitle ? `<p style="margin:1.5rem 0 0;font:400 16px/1.4 ui-sans-serif,system-ui,sans-serif;color:#9aa3b2;letter-spacing:.03em">${escapeHtml(subtitle)}</p>` : "";
702
+ return `<!doctype html><html><head><meta charset="utf-8"></head><body style="margin:0"><div style="height:100vh;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center;padding:0 12%;box-sizing:border-box;background:#0f172a;color:#fff"><h1 style="margin:0;font:700 44px/1.15 Georgia,'Times New Roman',serif;letter-spacing:-.01em">${escapeHtml(titleize(name))}</h1>` + sub + `</div></body></html>`;
703
+ }
704
+ function resolveCover(cover, name, subtitle) {
705
+ if (typeof cover === "string") return cover;
706
+ if (cover === true) return autoCoverHtml(name, subtitle);
707
+ return void 0;
708
+ }
709
+ function extractAssetUrls(html) {
710
+ const urls = /* @__PURE__ */ new Set();
711
+ const re = /(?:src|href)\s*=\s*["']([^"']+)["']/gi;
712
+ let m;
713
+ while ((m = re.exec(html)) !== null) {
714
+ const url = m[1].trim();
715
+ if (!url || url.startsWith("data:") || url.startsWith("#")) continue;
716
+ urls.add(url);
717
+ }
718
+ return [...urls];
719
+ }
720
+ function assetName(url, index) {
721
+ const path = url.split(/[?#]/)[0] ?? url;
722
+ const tail = path.split("/").filter(Boolean).pop() ?? "asset";
723
+ const safe = tail.replace(/[^\w.-]/g, "_").slice(-48) || "asset";
724
+ return `asset-${index}-${safe}`;
725
+ }
726
+ async function defaultFetchAsset(url) {
727
+ try {
728
+ const abs = /^https?:\/\//.test(url) ? url : null;
729
+ if (!abs) return null;
730
+ const res = await fetch(abs);
731
+ if (!res.ok) return null;
732
+ const buf = Buffer.from(await res.arrayBuffer());
733
+ return { bytes: buf, mime: res.headers.get("content-type") ?? void 0 };
734
+ } catch {
735
+ return null;
736
+ }
737
+ }
738
+ function rewriteRef(html, from, to) {
739
+ return html.split(`"${from}"`).join(`"${to}"`).split(`'${from}'`).join(`'${to}'`);
740
+ }
741
+ async function htmlToZip(html, opts = {}) {
742
+ const fetchAsset = opts.fetchAsset ?? defaultFetchAsset;
743
+ const zip = new JSZip();
744
+ const assets = zip.folder("assets");
745
+ let rewritten = html;
746
+ let i = 0;
747
+ for (const url of extractAssetUrls(html)) {
748
+ const got = await fetchAsset(url);
749
+ if (!got) continue;
750
+ const name = assetName(url, i++);
751
+ assets.file(name, got.bytes);
752
+ rewritten = rewriteRef(rewritten, url, `assets/${name}`);
753
+ }
754
+ zip.file("index.html", rewritten);
755
+ return zip.generateAsync({ type: "nodebuffer" });
756
+ }
757
+
758
+ // src/text.ts
759
+ var NAMED_ENTITIES = {
760
+ amp: "&",
761
+ lt: "<",
762
+ gt: ">",
763
+ quot: '"',
764
+ apos: "'",
765
+ nbsp: " ",
766
+ hellip: "\u2026",
767
+ mdash: "\u2014",
768
+ ndash: "\u2013",
769
+ rsquo: "\u2019",
770
+ lsquo: "\u2018",
771
+ ldquo: "\u201C",
772
+ rdquo: "\u201D",
773
+ copy: "\xA9",
774
+ reg: "\xAE",
775
+ trade: "\u2122",
776
+ deg: "\xB0",
777
+ times: "\xD7",
778
+ euro: "\u20AC",
779
+ pound: "\xA3"
780
+ };
781
+ function decodeEntities2(s) {
782
+ return s.replace(/&#(\d+);/g, (_, n) => safeCodePoint(Number(n))).replace(
783
+ /&#x([0-9a-f]+);/gi,
784
+ (_, n) => safeCodePoint(parseInt(n, 16))
785
+ ).replace(
786
+ /&([a-z0-9]+);/gi,
787
+ (m, name) => NAMED_ENTITIES[name.toLowerCase()] ?? m
788
+ );
789
+ }
790
+ function safeCodePoint(n) {
791
+ try {
792
+ return String.fromCodePoint(n);
793
+ } catch {
794
+ return "";
795
+ }
796
+ }
797
+ var stripTags2 = (h) => h.replace(/<[^>]+>/g, "");
798
+ function inlineMd(h) {
799
+ return h.replace(
800
+ /<a[^>]*href=["']([^"']*)["'][^>]*>([\s\S]*?)<\/a>/gi,
801
+ (_, href, t) => {
802
+ const txt = stripTags2(t).replace(/\s+/g, " ").trim();
803
+ return txt ? `[${txt}](${href})` : "";
804
+ }
805
+ ).replace(
806
+ /<(strong|b)[^>]*>([\s\S]*?)<\/\1>/gi,
807
+ (_, _tag, t) => `**${stripTags2(t).trim()}**`
808
+ ).replace(
809
+ /<(em|i)[^>]*>([\s\S]*?)<\/\1>/gi,
810
+ (_, _tag, t) => `*${stripTags2(t).trim()}*`
811
+ ).replace(
812
+ /<code[^>]*>([\s\S]*?)<\/code>/gi,
813
+ (_, t) => `\`${stripTags2(t).trim()}\``
814
+ );
815
+ }
816
+ function cellText(h) {
817
+ return decodeEntities2(stripTags2(h)).replace(/\s+/g, " ").trim().replace(/\|/g, "\\|");
818
+ }
819
+ function tableToMd(table) {
820
+ const rows = [];
821
+ const trs = table.match(/<tr[^>]*>[\s\S]*?<\/tr>/gi) ?? [];
822
+ for (const tr of trs) {
823
+ const cells = [];
824
+ const cellRe = /<(th|td)[^>]*>([\s\S]*?)<\/\1>/gi;
825
+ let m;
826
+ while ((m = cellRe.exec(tr)) !== null) cells.push(cellText(m[2] ?? ""));
827
+ if (cells.length) rows.push(cells);
828
+ }
829
+ if (!rows.length) return "";
830
+ const width = Math.max(...rows.map((r) => r.length));
831
+ const fmt = (r) => "| " + Array.from({ length: width }, (_, i) => r[i] ?? "").join(" | ") + " |";
832
+ const lines = [
833
+ fmt(rows[0] ?? []),
834
+ "| " + Array.from({ length: width }, () => "---").join(" | ") + " |",
835
+ ...rows.slice(1).map(fmt)
836
+ ];
837
+ return `
838
+
839
+ ${lines.join("\n")}
840
+
841
+ `;
842
+ }
843
+ function htmlToText(html) {
844
+ let s = html;
845
+ const body = s.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
846
+ if (body?.[1] != null) s = body[1];
847
+ s = s.replace(/<!--[\s\S]*?-->/g, "").replace(/<(script|style|svg|head|noscript|template)\b[\s\S]*?<\/\1>/gi, "");
848
+ const fences = [];
849
+ s = s.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi, (_, inner) => {
850
+ const code = decodeEntities2(stripTags2(inner)).replace(/\n+$/, "");
851
+ fences.push("```\n" + code + "\n```");
852
+ return `\0FENCE${fences.length - 1}\0`;
853
+ });
854
+ s = s.replace(
855
+ /<table[^>]*>([\s\S]*?)<\/table>/gi,
856
+ (_, t) => tableToMd(t)
857
+ );
858
+ for (let i = 1; i <= 6; i++) {
859
+ s = s.replace(
860
+ new RegExp(`<h${i}[^>]*>([\\s\\S]*?)<\\/h${i}>`, "gi"),
861
+ (_, inner) => `
862
+
863
+ ${"#".repeat(i)} ${inlineMd(inner).replace(/\s+/g, " ").trim()}
864
+
865
+ `
866
+ );
867
+ }
868
+ s = s.replace(
869
+ /<li[^>]*>([\s\S]*?)<\/li>/gi,
870
+ (_, inner) => `
871
+ - ${inlineMd(inner).replace(/\s+/g, " ").trim()}`
872
+ ).replace(/<\/(ul|ol)>/gi, "\n\n");
873
+ s = s.replace(
874
+ /<blockquote[^>]*>([\s\S]*?)<\/blockquote>/gi,
875
+ (_, inner) => {
876
+ const text = stripTags2(inlineMd(inner)).replace(/[ \t]+/g, " ").trim();
877
+ return "\n\n" + text.split("\n").map((l) => `> ${l.trim()}`).join("\n") + "\n\n";
878
+ }
879
+ );
880
+ s = s.replace(/<hr[^>]*\/?>/gi, "\n\n---\n\n").replace(/<br[^>]*\/?>/gi, "\n").replace(
881
+ /<\/(p|div|section|article|header|footer|main|tr|thead|tbody)>/gi,
882
+ "\n\n"
883
+ );
884
+ s = decodeEntities2(stripTags2(inlineMd(s)));
885
+ s = s.replace(/FENCE(\d+)/g, (_, i) => fences[Number(i)] ?? "");
886
+ return s.replace(/[ \t]+/g, " ").replace(/ *\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
887
+ }
888
+ function htmlToEmail(html) {
889
+ return juice(html, { removeStyleTags: true, preserveImportant: true });
890
+ }
891
+
892
+ // src/docx.ts
893
+ async function loadHtmlToDocx() {
894
+ try {
895
+ const mod = await import('@turbodocx/html-to-docx');
896
+ return mod.default ?? mod;
897
+ } catch {
898
+ throw new Error(
899
+ "toDocx needs `@turbodocx/html-to-docx`. Install it: pnpm add @turbodocx/html-to-docx"
900
+ );
901
+ }
902
+ }
903
+ function bodyInner(html) {
904
+ const m = html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
905
+ return m?.[1] ?? html;
906
+ }
907
+ function docxContent(html) {
908
+ return bodyInner(html).replace(/<!--[\s\S]*?-->/g, "").replace(/<(script|style|svg|noscript|template)\b[\s\S]*?<\/\1>/gi, "");
909
+ }
910
+ function composeDocxHtml(contentHtml, coverHtml) {
911
+ const parts = [
912
+ ...coverHtml ? [docxContent(coverHtml), `<div style="page-break-after: always"></div>`] : [],
913
+ docxContent(contentHtml)
914
+ ];
915
+ return `<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>${parts.join("")}</body></html>`;
916
+ }
917
+ function headerFooterText(spec) {
918
+ if (!spec) return void 0;
919
+ if (typeof spec === "string") return spec.trim() || void 0;
920
+ const parts = [spec.left, spec.center, spec.right].map((s) => s?.trim()).filter((s) => Boolean(s));
921
+ return parts.length ? parts.join(" \u2014 ") : void 0;
922
+ }
923
+ var escapeHtml2 = (s) => s.replace(
924
+ /[&<>"]/g,
925
+ (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c] ?? c
926
+ );
927
+ async function toDocx(html, opts = {}) {
928
+ const htmlToDocx = await loadHtmlToDocx();
929
+ const source = composeDocxHtml(html, opts.cover);
930
+ const headerHtml = opts.header ? `<p style="font-size:9pt;color:#5b6170">${escapeHtml2(opts.header)}</p>` : null;
931
+ const footerHtml = opts.footer ? `<p style="font-size:9pt;color:#5b6170">${escapeHtml2(opts.footer)}</p>` : null;
932
+ const wantsFooter = Boolean(opts.footer) || Boolean(opts.pageNumbers);
933
+ const out = await htmlToDocx(
934
+ source,
935
+ headerHtml,
936
+ {
937
+ orientation: opts.orientation ?? "portrait",
938
+ title: opts.title,
939
+ header: Boolean(opts.header),
940
+ footer: wantsFooter,
941
+ // pageNumber renders in the footer, so it needs `footer: true` (set above).
942
+ pageNumber: Boolean(opts.pageNumbers),
943
+ // Keep table rows on one page — the sane default for report tables.
944
+ table: { row: { cantSplit: true } }
945
+ },
946
+ footerHtml
947
+ );
948
+ if (Buffer.isBuffer(out)) return out;
949
+ if (out instanceof ArrayBuffer) return Buffer.from(out);
950
+ return Buffer.from(await out.arrayBuffer());
951
+ }
952
+
953
+ // src/export.ts
954
+ var noopFilesystem = {
955
+ readFile: async () => "",
956
+ readdir: async () => [],
957
+ exists: async () => false,
958
+ writeFile: async () => {
959
+ }
960
+ };
961
+ function resolveExport(opts) {
962
+ const md = opts.medium ? mediumDefaults(opts.medium) : null;
963
+ const format = opts.format ?? md?.format;
964
+ if (!format) {
965
+ throw new Error(
966
+ "exportHtml: `format` is required (or set `medium`, which supplies one)."
967
+ );
968
+ }
969
+ const page = { ...md?.page ?? {}, ...opts.page ?? {} };
970
+ const pageSpec = mergePageSpec(md?.pageSpec, opts.pageSpec);
971
+ const pageCss = format === "pdf" ? pageCssFor(pageSpec) : null;
972
+ return { format, name: opts.name ?? "canvas", page, pageSpec, pageCss };
973
+ }
974
+ function wantsRemoteBrowser() {
975
+ return Boolean(process.env.CANVAKIT_BROWSER_WS_ENDPOINT?.trim());
976
+ }
977
+ function pdfRenderer(opts, pageSpec) {
978
+ if (opts.renderer) return opts.renderer;
979
+ const env = process.env.CANVAKIT_RENDERER?.trim().toLowerCase();
980
+ const wantsScale = opts.page?.scale != null && opts.page.scale !== 1;
981
+ if (env === "cdp" || wantsDocumentChrome(pageSpec) || wantsScale || wantsRemoteBrowser()) {
982
+ return cdpChromeRenderer({
983
+ header: pageSpec?.header,
984
+ footer: pageSpec?.footer,
985
+ pageNumbers: pageSpec?.pageNumbers,
986
+ chrome: opts.chrome
987
+ });
988
+ }
989
+ return resolveRenderer(opts);
990
+ }
991
+ function pngRenderer(opts) {
992
+ if (opts.renderer) return opts.renderer;
993
+ const env = process.env.CANVAKIT_RENDERER?.trim().toLowerCase();
994
+ if (env === "cdp" || wantsRemoteBrowser()) {
995
+ return cdpChromeRenderer({ chrome: opts.chrome });
996
+ }
997
+ return resolveRenderer(opts);
998
+ }
999
+ function wantsDocument(opts, format) {
1000
+ if (opts.renderer) return false;
1001
+ return format === "pdf" && (opts.medium === "document" || opts.document != null);
1002
+ }
1003
+ async function exportDocumentPdf(html, opts, pageSpec, name, page) {
1004
+ const doc = opts.document ?? {};
1005
+ const { bytes } = await renderDocumentPdf({
1006
+ contentHtml: html,
1007
+ coverHtml: resolveCover(doc.cover, name, doc.coverSubtitle),
1008
+ tocTitle: doc.tocTitle,
1009
+ tocLevels: doc.tocLevels,
1010
+ header: pageSpec?.header,
1011
+ footer: pageSpec?.footer,
1012
+ pageSpec,
1013
+ chrome: opts.chrome,
1014
+ scale: page.scale
1015
+ });
1016
+ return bytes;
1017
+ }
1018
+ async function exportHtml(html, opts) {
1019
+ const { format, name, page, pageSpec, pageCss } = resolveExport(opts);
1020
+ switch (format) {
1021
+ case "html":
1022
+ return {
1023
+ format: "html",
1024
+ bytes: Buffer.from(html, "utf8"),
1025
+ mime: "text/html; charset=utf-8",
1026
+ filename: `${name}.html`
1027
+ };
1028
+ case "text":
1029
+ return {
1030
+ format: "text",
1031
+ bytes: Buffer.from(htmlToText(html), "utf8"),
1032
+ mime: "text/markdown; charset=utf-8",
1033
+ filename: `${name}.txt`
1034
+ };
1035
+ case "email-html":
1036
+ return {
1037
+ format: "email-html",
1038
+ bytes: Buffer.from(htmlToEmail(html), "utf8"),
1039
+ mime: "text/html; charset=utf-8",
1040
+ filename: `${name}.html`
1041
+ };
1042
+ case "html-zip":
1043
+ return {
1044
+ format: "html-zip",
1045
+ bytes: await htmlToZip(html, opts),
1046
+ mime: "application/zip",
1047
+ filename: `${name}.zip`
1048
+ };
1049
+ case "docx": {
1050
+ const doc = opts.medium === "document" || opts.document != null ? opts.document ?? {} : void 0;
1051
+ return {
1052
+ format: "docx",
1053
+ bytes: await toDocx(html, {
1054
+ title: name,
1055
+ cover: doc ? resolveCover(doc.cover, name, doc.coverSubtitle) : void 0,
1056
+ header: headerFooterText(pageSpec?.header),
1057
+ footer: headerFooterText(pageSpec?.footer),
1058
+ pageNumbers: pageSpec?.pageNumbers ?? doc != null,
1059
+ orientation: pageSpec?.orientation
1060
+ }),
1061
+ mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1062
+ filename: `${name}.docx`
1063
+ };
1064
+ }
1065
+ case "png": {
1066
+ const renderer = pngRenderer(opts);
1067
+ return {
1068
+ format: "png",
1069
+ bytes: await renderer.toPng(html, page),
1070
+ mime: "image/png",
1071
+ filename: `${name}.png`
1072
+ };
1073
+ }
1074
+ case "pdf": {
1075
+ if (wantsDocument(opts, format)) {
1076
+ return {
1077
+ format: "pdf",
1078
+ bytes: await exportDocumentPdf(html, opts, pageSpec, name, page),
1079
+ mime: "application/pdf",
1080
+ filename: `${name}.pdf`
1081
+ };
1082
+ }
1083
+ const renderer = pdfRenderer(opts, pageSpec);
1084
+ return {
1085
+ format: "pdf",
1086
+ bytes: await renderer.toPdf(applyPageCss(html, pageCss), page),
1087
+ mime: "application/pdf",
1088
+ filename: `${name}.pdf`
1089
+ };
1090
+ }
1091
+ }
1092
+ }
1093
+ async function exportCanvas(input, opts = {}) {
1094
+ const res = await render({
1095
+ ...input,
1096
+ filesystem: input.filesystem ?? noopFilesystem
1097
+ });
1098
+ const merged = {
1099
+ ...opts,
1100
+ medium: opts.medium ?? res.frontmatter?.medium,
1101
+ pageSpec: opts.pageSpec ?? res.frontmatter?.page
1102
+ };
1103
+ const artifact = await exportHtml(res.body, merged);
1104
+ return {
1105
+ ...artifact,
1106
+ warnings: res.warnings,
1107
+ statuses: res.statuses,
1108
+ meta: res.meta
1109
+ };
1110
+ }
1111
+
1112
+ export { applyPageCss, autoCoverHtml, cdpChromeRenderer, exportCanvas, exportHtml, extractAssetUrls, findChrome, htmlToEmail, htmlToText, htmlToZip, localChromeRenderer, matchKey, mediumDefaults, mergePageSpec, noopFilesystem, pageCssFor, renderDocumentPdf, resolveCover, resolvePageSize, resolveRenderer, titleize, wantsDocumentChrome };
1113
+ //# sourceMappingURL=index.mjs.map
1114
+ //# sourceMappingURL=index.mjs.map