Skip to content

Commit 19cf9ef

Browse files
committed
self-contained: call esbuild in front of pandoc to resolve es6 modules correctly
1 parent cfec799 commit 19cf9ef

File tree

3 files changed

+33
-3
lines changed

3 files changed

+33
-3
lines changed

src/core/data-url.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { encode as base64Encode } from "encoding/base64";
1+
import { encodeBase64 as base64Encode } from "encoding/base64";
22

33
export function asDataUrl(
44
content: string | ArrayBuffer,

src/core/esbuild.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,8 @@ export async function esbuildCommand(
106106
if (result.success) {
107107
return result.stdout;
108108
} else {
109+
console.error(result.stderr);
110+
109111
throw new Error("esbuild command failed");
110112
}
111113
}

src/core/pandoc/self-contained.ts

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,34 @@
44
* Copyright (C) 2020-2023 Posit Software, PBC
55
*/
66

7-
import { basename, dirname } from "../../deno_ral/path.ts";
7+
import { basename, dirname, join } from "../../deno_ral/path.ts";
88
import { formatResourcePath, pandocBinaryPath } from "../../core/resources.ts";
99
import { execProcess } from "../../core/process.ts";
10+
import { parseHtml } from "../deno-dom.ts";
11+
import { Element, HTMLDocument } from "deno_dom/deno-dom-wasm-noinit.ts";
12+
import { esbuildCompile } from "../esbuild.ts";
13+
import { asDataUrl } from "../data-url.ts";
14+
15+
const bundleModules = async (dom: HTMLDocument, workingDir: string) => {
16+
const modules = dom.querySelectorAll("script[type='module']");
17+
for (const module of modules) {
18+
const src = (module as Element).getAttribute("src");
19+
if (src) {
20+
const srcName = join(workingDir, src);
21+
const srcDir = dirname(srcName);
22+
const jsSource = await esbuildCompile(
23+
Deno.readTextFileSync(srcName),
24+
srcDir,
25+
[],
26+
"esm",
27+
);
28+
(module as Element).setAttribute(
29+
"src",
30+
asDataUrl(jsSource!, "application/javascript"),
31+
);
32+
}
33+
}
34+
};
1035

1136
export const pandocIngestSelfContainedContent = async (
1237
file: string,
@@ -23,9 +48,12 @@ export const pandocIngestSelfContainedContent = async (
2348

2449
// The raw html contents
2550
const contents = Deno.readTextFileSync(file);
51+
const dom = await parseHtml(contents);
52+
await bundleModules(dom, workingDir);
53+
2654
const input: string[] = [];
2755
input.push("````````{=html}");
28-
input.push(contents);
56+
input.push(dom.documentElement!.outerHTML);
2957
input.push("````````");
3058

3159
// Run pandoc to suck in dependencies

0 commit comments

Comments
 (0)