@junejs/pdf-typst-wasm 0.0.0-stage → 0.1.0-dev.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/node.d.ts +7 -0
- package/dist/node.js +24 -0
- package/dist/renderer--txXuJuD.d.ts +31 -0
- package/dist/renderer-CHKIXC79.js +127 -0
- package/dist/typst.wasm +0 -0
- package/dist/workerd.d.ts +6 -0
- package/dist/workerd.js +8 -0
- package/package.json +58 -4
- package/src/engine.ts +74 -0
- package/src/node.ts +38 -0
- package/src/renderer.ts +150 -0
- package/src/wasm.d.ts +5 -0
- package/src/workerd.ts +21 -0
- package/README.md +0 -3
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { a as FontScope, c as WasmSource, i as TypstWasmRendererOptions, l as createEngine, n as FontSource, o as TypstCompileError, r as GoogleFont, s as TypstEngine, t as DEFAULT_GOOGLE_FONTS } from "./renderer--txXuJuD.js";
|
|
2
|
+
import { PdfRenderer } from "@junejs/pdf";
|
|
3
|
+
//#region src/node.d.ts
|
|
4
|
+
export declare const WASM_URL: URL;
|
|
5
|
+
export declare function typstWasmRenderer(opts?: TypstWasmRendererOptions): PdfRenderer;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { DEFAULT_GOOGLE_FONTS, type FontScope, type FontSource, type GoogleFont, TypstCompileError, type TypstEngine, type TypstWasmRendererOptions, type WasmSource, createEngine };
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { i as createEngine, n as createTypstWasmRenderer, r as TypstCompileError, t as DEFAULT_GOOGLE_FONTS } from "./renderer-CHKIXC79.js";
|
|
2
|
+
//#region src/node.ts
|
|
3
|
+
const WASM_URL = new URL("../dist/typst.wasm", import.meta.url);
|
|
4
|
+
let compiled;
|
|
5
|
+
async function loadWasm() {
|
|
6
|
+
return compiled ??= (async () => {
|
|
7
|
+
const [{ readFile }, { fileURLToPath }] = await Promise.all([import("node:fs/promises"), import("node:url")]);
|
|
8
|
+
let bytes;
|
|
9
|
+
try {
|
|
10
|
+
bytes = await readFile(fileURLToPath(WASM_URL));
|
|
11
|
+
} catch (err) {
|
|
12
|
+
throw new Error(`@junejs/pdf-typst-wasm: ${fileURLToPath(WASM_URL)} is missing — in the June repo, run \`bun run build\` in packages/pdf-typst-wasm`, { cause: err });
|
|
13
|
+
}
|
|
14
|
+
return WebAssembly.compile(bytes);
|
|
15
|
+
})().catch((err) => {
|
|
16
|
+
compiled = void 0;
|
|
17
|
+
throw err;
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
function typstWasmRenderer(opts = {}) {
|
|
21
|
+
return createTypstWasmRenderer(loadWasm, opts);
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
export { DEFAULT_GOOGLE_FONTS, TypstCompileError, WASM_URL, createEngine, typstWasmRenderer };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { PdfRenderer } from "@junejs/pdf";
|
|
2
|
+
//#region src/engine.d.ts
|
|
3
|
+
type FontScope = "persistent" | "document";
|
|
4
|
+
interface TypstEngine {
|
|
5
|
+
addFont(data: Uint8Array, scope: FontScope): number;
|
|
6
|
+
clearDocumentFonts(): void;
|
|
7
|
+
compile(source: string): Uint8Array;
|
|
8
|
+
memoryBytes(): number;
|
|
9
|
+
}
|
|
10
|
+
declare class TypstCompileError extends Error {
|
|
11
|
+
constructor(message: string);
|
|
12
|
+
}
|
|
13
|
+
type WasmSource = WebAssembly.Module | BufferSource;
|
|
14
|
+
declare function createEngine(wasm: WasmSource): Promise<TypstEngine>;
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region src/renderer.d.ts
|
|
17
|
+
type FontSource = Uint8Array | ArrayBuffer | string | (() => Promise<Uint8Array | ArrayBuffer>);
|
|
18
|
+
type GoogleFont = {
|
|
19
|
+
family: string;
|
|
20
|
+
weights?: number[];
|
|
21
|
+
};
|
|
22
|
+
type TypstWasmRendererOptions = {
|
|
23
|
+
wasm?: WasmSource | (() => Promise<WasmSource>);
|
|
24
|
+
fonts?: FontSource[];
|
|
25
|
+
fontFamilies?: string[];
|
|
26
|
+
googleFonts?: GoogleFont[] | false;
|
|
27
|
+
fetch?: typeof fetch;
|
|
28
|
+
};
|
|
29
|
+
declare const DEFAULT_GOOGLE_FONTS: GoogleFont[];
|
|
30
|
+
//#endregion
|
|
31
|
+
export { FontScope as a, WasmSource as c, TypstWasmRendererOptions as i, createEngine as l, FontSource as n, TypstCompileError as o, GoogleFont as r, TypstEngine as s, DEFAULT_GOOGLE_FONTS as t };
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { PdfRenderError, typstSource } from "@junejs/pdf";
|
|
2
|
+
//#region src/engine.ts
|
|
3
|
+
var TypstCompileError = class extends Error {
|
|
4
|
+
constructor(message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "TypstCompileError";
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
async function createEngine(wasm) {
|
|
10
|
+
const made = await WebAssembly.instantiate(wasm, {});
|
|
11
|
+
const x = (made instanceof WebAssembly.Instance ? made : made.instance).exports;
|
|
12
|
+
x.init();
|
|
13
|
+
const put = (bytes) => {
|
|
14
|
+
const ptr = x.alloc(bytes.length);
|
|
15
|
+
new Uint8Array(x.memory.buffer, ptr, bytes.length).set(bytes);
|
|
16
|
+
return ptr;
|
|
17
|
+
};
|
|
18
|
+
const output = () => new Uint8Array(x.memory.buffer, x.output_ptr(), x.output_len()).slice();
|
|
19
|
+
const utf8 = new TextEncoder();
|
|
20
|
+
return {
|
|
21
|
+
addFont(data, scope) {
|
|
22
|
+
return x.add_font(put(data), data.length, scope === "document" ? 1 : 0);
|
|
23
|
+
},
|
|
24
|
+
clearDocumentFonts() {
|
|
25
|
+
x.clear_document_fonts();
|
|
26
|
+
},
|
|
27
|
+
compile(source) {
|
|
28
|
+
const bytes = utf8.encode(source);
|
|
29
|
+
const status = x.compile(put(bytes), bytes.length);
|
|
30
|
+
const out = output();
|
|
31
|
+
if (status !== 0) throw new TypstCompileError(new TextDecoder().decode(out));
|
|
32
|
+
return out;
|
|
33
|
+
},
|
|
34
|
+
memoryBytes() {
|
|
35
|
+
return x.memory.buffer.byteLength;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/renderer.ts
|
|
41
|
+
const DEFAULT_GOOGLE_FONTS = [{
|
|
42
|
+
family: "Noto Sans TC",
|
|
43
|
+
weights: [400, 700]
|
|
44
|
+
}];
|
|
45
|
+
function createTypstWasmRenderer(defaultWasm, opts = {}) {
|
|
46
|
+
const fetcher = opts.fetch ?? fetch;
|
|
47
|
+
const google = opts.googleFonts === false ? [] : opts.googleFonts ?? DEFAULT_GOOGLE_FONTS;
|
|
48
|
+
let engine;
|
|
49
|
+
const subsets = subsetCache(fetcher);
|
|
50
|
+
const ready = () => engine ??= (async () => {
|
|
51
|
+
const e = await createEngine(typeof opts.wasm === "function" ? await opts.wasm() : opts.wasm ?? await defaultWasm());
|
|
52
|
+
for (const font of await Promise.all((opts.fonts ?? []).map((f) => loadFont(f, fetcher)))) e.addFont(font, "persistent");
|
|
53
|
+
return e;
|
|
54
|
+
})().catch((err) => {
|
|
55
|
+
engine = void 0;
|
|
56
|
+
throw err;
|
|
57
|
+
});
|
|
58
|
+
return {
|
|
59
|
+
name: "typst-wasm",
|
|
60
|
+
async render(doc) {
|
|
61
|
+
const source = typstSource(doc, { fonts: opts.fontFamilies });
|
|
62
|
+
const [e, documentFonts] = await Promise.all([ready(), subsetsFor(doc, google, subsets)]);
|
|
63
|
+
e.clearDocumentFonts();
|
|
64
|
+
for (const font of documentFonts) e.addFont(font, "document");
|
|
65
|
+
try {
|
|
66
|
+
return e.compile(source);
|
|
67
|
+
} catch (err) {
|
|
68
|
+
if (err instanceof TypstCompileError) throw new PdfRenderError(`the document could not be typeset: ${err.message}`, { cause: err });
|
|
69
|
+
throw err;
|
|
70
|
+
} finally {
|
|
71
|
+
e.clearDocumentFonts();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
async function loadFont(source, fetcher) {
|
|
77
|
+
if (source instanceof Uint8Array) return source;
|
|
78
|
+
if (source instanceof ArrayBuffer) return new Uint8Array(source);
|
|
79
|
+
if (typeof source === "function") {
|
|
80
|
+
const data = await source();
|
|
81
|
+
return data instanceof Uint8Array ? data : new Uint8Array(data);
|
|
82
|
+
}
|
|
83
|
+
const res = await fetcher(source);
|
|
84
|
+
if (!res.ok) throw new Error(`font ${source}: HTTP ${res.status}`);
|
|
85
|
+
return new Uint8Array(await res.arrayBuffer());
|
|
86
|
+
}
|
|
87
|
+
function documentText(doc) {
|
|
88
|
+
return [...new Set(doc.markdown.replace(/[\x00-\x7f]/g, ""))].join("");
|
|
89
|
+
}
|
|
90
|
+
async function subsetsFor(doc, families, load) {
|
|
91
|
+
const text = documentText(doc);
|
|
92
|
+
if (!text || families.length === 0) return [];
|
|
93
|
+
const wanted = families.flatMap((f) => (f.weights ?? [400]).map((w) => [f.family, w]));
|
|
94
|
+
return (await Promise.all(wanted.map(([family, weight]) => load(family, weight, text).catch((err) => {
|
|
95
|
+
console.warn(`[june] pdf-typst-wasm: ${family} ${weight} for this document could not be fetched (${err instanceof Error ? err.message : String(err)}); its characters may render blank`);
|
|
96
|
+
})))).filter((f) => f !== void 0);
|
|
97
|
+
}
|
|
98
|
+
const OLD_SAFARI = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1";
|
|
99
|
+
const SUBSET_CACHE_MAX = 32;
|
|
100
|
+
function subsetCache(fetcher) {
|
|
101
|
+
const cache = /* @__PURE__ */ new Map();
|
|
102
|
+
return (family, weight, text) => googleSubset(cache, family, weight, text, fetcher);
|
|
103
|
+
}
|
|
104
|
+
function googleSubset(cache, family, weight, text, fetcher) {
|
|
105
|
+
const css = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family)}:wght@${weight}&text=${encodeURIComponent(text)}`;
|
|
106
|
+
const hit = cache.get(css);
|
|
107
|
+
if (hit) {
|
|
108
|
+
cache.delete(css);
|
|
109
|
+
cache.set(css, hit);
|
|
110
|
+
return hit;
|
|
111
|
+
}
|
|
112
|
+
const load = (async () => {
|
|
113
|
+
const res = await fetcher(css, { headers: { "user-agent": OLD_SAFARI } });
|
|
114
|
+
if (!res.ok) throw new Error(`Google Fonts CSS: HTTP ${res.status}`);
|
|
115
|
+
const url = (await res.text()).match(/src:\s*url\((.+?)\)/)?.[1];
|
|
116
|
+
if (!url) throw new Error("Google Fonts CSS named no font file");
|
|
117
|
+
const font = await fetcher(url);
|
|
118
|
+
if (!font.ok) throw new Error(`Google Fonts file: HTTP ${font.status}`);
|
|
119
|
+
return new Uint8Array(await font.arrayBuffer());
|
|
120
|
+
})();
|
|
121
|
+
load.catch(() => cache.delete(css));
|
|
122
|
+
cache.set(css, load);
|
|
123
|
+
if (cache.size > SUBSET_CACHE_MAX) cache.delete(cache.keys().next().value);
|
|
124
|
+
return load;
|
|
125
|
+
}
|
|
126
|
+
//#endregion
|
|
127
|
+
export { createEngine as i, createTypstWasmRenderer as n, TypstCompileError as r, DEFAULT_GOOGLE_FONTS as t };
|
package/dist/typst.wasm
ADDED
|
Binary file
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { a as FontScope, c as WasmSource, i as TypstWasmRendererOptions, l as createEngine, n as FontSource, o as TypstCompileError, r as GoogleFont, s as TypstEngine, t as DEFAULT_GOOGLE_FONTS } from "./renderer--txXuJuD.js";
|
|
2
|
+
import { PdfRenderer } from "@junejs/pdf";
|
|
3
|
+
//#region src/workerd.d.ts
|
|
4
|
+
export declare function typstWasmRenderer(opts?: TypstWasmRendererOptions): PdfRenderer;
|
|
5
|
+
//#endregion
|
|
6
|
+
export { DEFAULT_GOOGLE_FONTS, type FontScope, type FontSource, type GoogleFont, TypstCompileError, type TypstEngine, type TypstWasmRendererOptions, type WasmSource, createEngine };
|
package/dist/workerd.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { i as createEngine, n as createTypstWasmRenderer, r as TypstCompileError, t as DEFAULT_GOOGLE_FONTS } from "./renderer-CHKIXC79.js";
|
|
2
|
+
import wasm from "../dist/typst.wasm";
|
|
3
|
+
//#region src/workerd.ts
|
|
4
|
+
function typstWasmRenderer(opts = {}) {
|
|
5
|
+
return createTypstWasmRenderer(async () => wasm, opts);
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
8
|
+
export { DEFAULT_GOOGLE_FONTS, TypstCompileError, createEngine, typstWasmRenderer };
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@junejs/pdf-typst-wasm",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-dev.0",
|
|
4
|
+
"description": "June — a PdfRenderer on a Typst to PDF engine compiled to WebAssembly: no browser, no native binary, and it runs on Cloudflare Workers.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://june.build",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"source": {
|
|
11
|
+
"workerd": "./src/workerd.ts",
|
|
12
|
+
"default": "./src/node.ts"
|
|
13
|
+
},
|
|
14
|
+
"bun": {
|
|
15
|
+
"workerd": "./src/workerd.ts",
|
|
16
|
+
"default": "./src/node.ts"
|
|
17
|
+
},
|
|
18
|
+
"workerd": {
|
|
19
|
+
"types": "./dist/workerd.d.ts",
|
|
20
|
+
"default": "./dist/workerd.js"
|
|
21
|
+
},
|
|
22
|
+
"default": {
|
|
23
|
+
"types": "./dist/node.d.ts",
|
|
24
|
+
"default": "./dist/node.js"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"./typst.wasm": "./dist/typst.wasm"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"dist",
|
|
31
|
+
"src/*.ts"
|
|
32
|
+
],
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build:wasm": "bun scripts/build-wasm.ts",
|
|
35
|
+
"build": "bun run build:wasm && tsdown",
|
|
36
|
+
"test": "bun test"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@junejs/pdf": ">=0.1.0-dev.1"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@junejs/core": ">=0.2.0-dev.66"
|
|
43
|
+
},
|
|
44
|
+
"keywords": [
|
|
45
|
+
"june",
|
|
46
|
+
"agent",
|
|
47
|
+
"pdf",
|
|
48
|
+
"typst",
|
|
49
|
+
"wasm",
|
|
50
|
+
"cloudflare-workers"
|
|
51
|
+
],
|
|
52
|
+
"publishConfig": {
|
|
53
|
+
"access": "public"
|
|
54
|
+
},
|
|
55
|
+
"repository": {
|
|
56
|
+
"type": "git",
|
|
57
|
+
"url": "git+https://github.com/junebuild/june.git",
|
|
58
|
+
"directory": "packages/pdf-typst-wasm"
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/engine.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// The JS side of the engine's C ABI (src/lib.rs `ffi`). Plain WebAssembly, no host APIs, so
|
|
2
|
+
// it runs unchanged on Node, Bun, Deno and workerd. One instance is one engine: create it
|
|
3
|
+
// once per process or isolate and keep it — instantiating costs a fresh linear memory and
|
|
4
|
+
// re-registers the embedded fonts.
|
|
5
|
+
|
|
6
|
+
export type FontScope = "persistent" | "document";
|
|
7
|
+
|
|
8
|
+
export interface TypstEngine {
|
|
9
|
+
// Register a font file; returns the number of faces it held (0: not a font).
|
|
10
|
+
addFont(data: Uint8Array, scope: FontScope): number;
|
|
11
|
+
// Drop the document-scoped fonts.
|
|
12
|
+
clearDocumentFonts(): void;
|
|
13
|
+
// Typst source → PDF bytes. Throws TypstCompileError with the document's diagnostics.
|
|
14
|
+
compile(source: string): Uint8Array;
|
|
15
|
+
// The engine's linear memory, in bytes (it only grows).
|
|
16
|
+
memoryBytes(): number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class TypstCompileError extends Error {
|
|
20
|
+
constructor(message: string) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.name = "TypstCompileError";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
type Exports = {
|
|
27
|
+
memory: WebAssembly.Memory;
|
|
28
|
+
alloc(len: number): number;
|
|
29
|
+
init(): number;
|
|
30
|
+
add_font(ptr: number, len: number, document: number): number;
|
|
31
|
+
clear_document_fonts(): void;
|
|
32
|
+
compile(ptr: number, len: number): number;
|
|
33
|
+
output_ptr(): number;
|
|
34
|
+
output_len(): number;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export type WasmSource = WebAssembly.Module | BufferSource;
|
|
38
|
+
|
|
39
|
+
export async function createEngine(wasm: WasmSource): Promise<TypstEngine> {
|
|
40
|
+
// A Module instantiates to an Instance; bytes to { module, instance }.
|
|
41
|
+
const made = (await WebAssembly.instantiate(wasm as BufferSource, {})) as unknown as WebAssembly.Instance | WebAssembly.WebAssemblyInstantiatedSource;
|
|
42
|
+
const instance = made instanceof WebAssembly.Instance ? made : made.instance;
|
|
43
|
+
const x = instance.exports as unknown as Exports;
|
|
44
|
+
x.init(); // embedded fonts now, not inside the first render
|
|
45
|
+
|
|
46
|
+
// Copy bytes into the module's memory; the callee takes ownership of the buffer. The view
|
|
47
|
+
// is taken after alloc, which may grow (and so detach) the memory.
|
|
48
|
+
const put = (bytes: Uint8Array): number => {
|
|
49
|
+
const ptr = x.alloc(bytes.length);
|
|
50
|
+
new Uint8Array(x.memory.buffer, ptr, bytes.length).set(bytes);
|
|
51
|
+
return ptr;
|
|
52
|
+
};
|
|
53
|
+
const output = (): Uint8Array => new Uint8Array(x.memory.buffer, x.output_ptr(), x.output_len()).slice();
|
|
54
|
+
const utf8 = new TextEncoder();
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
addFont(data, scope) {
|
|
58
|
+
return x.add_font(put(data), data.length, scope === "document" ? 1 : 0);
|
|
59
|
+
},
|
|
60
|
+
clearDocumentFonts() {
|
|
61
|
+
x.clear_document_fonts();
|
|
62
|
+
},
|
|
63
|
+
compile(source) {
|
|
64
|
+
const bytes = utf8.encode(source);
|
|
65
|
+
const status = x.compile(put(bytes), bytes.length);
|
|
66
|
+
const out = output();
|
|
67
|
+
if (status !== 0) throw new TypstCompileError(new TextDecoder().decode(out));
|
|
68
|
+
return out;
|
|
69
|
+
},
|
|
70
|
+
memoryBytes() {
|
|
71
|
+
return x.memory.buffer.byteLength;
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
}
|
package/src/node.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// @junejs/pdf-typst-wasm on Node, Bun and Deno: the engine module is read from the
|
|
2
|
+
// dist/typst.wasm next to this file (relative to src/ in the repo, where `bun run build`
|
|
3
|
+
// writes it) and compiled once per process.
|
|
4
|
+
//
|
|
5
|
+
// import { pdfTools } from "@junejs/pdf";
|
|
6
|
+
// import { typstWasmRenderer } from "@junejs/pdf-typst-wasm";
|
|
7
|
+
// export default pdfTools({ renderer: typstWasmRenderer() });
|
|
8
|
+
|
|
9
|
+
import type { PdfRenderer } from "@junejs/pdf";
|
|
10
|
+
|
|
11
|
+
import type { WasmSource } from "./engine";
|
|
12
|
+
import { createTypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
|
|
13
|
+
|
|
14
|
+
export { DEFAULT_GOOGLE_FONTS, type FontSource, type GoogleFont, type TypstWasmRendererOptions } from "./renderer";
|
|
15
|
+
export { createEngine, TypstCompileError, type FontScope, type TypstEngine, type WasmSource } from "./engine";
|
|
16
|
+
|
|
17
|
+
export const WASM_URL = new URL("../dist/typst.wasm", import.meta.url);
|
|
18
|
+
|
|
19
|
+
let compiled: Promise<WebAssembly.Module> | undefined;
|
|
20
|
+
async function loadWasm(): Promise<WasmSource> {
|
|
21
|
+
return (compiled ??= (async () => {
|
|
22
|
+
const [{ readFile }, { fileURLToPath }] = await Promise.all([import("node:fs/promises"), import("node:url")]);
|
|
23
|
+
let bytes: Uint8Array;
|
|
24
|
+
try {
|
|
25
|
+
bytes = await readFile(fileURLToPath(WASM_URL));
|
|
26
|
+
} catch (err) {
|
|
27
|
+
throw new Error(`@junejs/pdf-typst-wasm: ${fileURLToPath(WASM_URL)} is missing — in the June repo, run \`bun run build\` in packages/pdf-typst-wasm`, { cause: err });
|
|
28
|
+
}
|
|
29
|
+
return WebAssembly.compile(bytes as Uint8Array<ArrayBuffer>);
|
|
30
|
+
})().catch((err: unknown) => {
|
|
31
|
+
compiled = undefined;
|
|
32
|
+
throw err;
|
|
33
|
+
}));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function typstWasmRenderer(opts: TypstWasmRendererOptions = {}): PdfRenderer {
|
|
37
|
+
return createTypstWasmRenderer(loadWasm, opts);
|
|
38
|
+
}
|
package/src/renderer.ts
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// typstWasmRenderer — a PdfRenderer on this package's engine (src/lib.rs): the same Markdown →
|
|
2
|
+
// Typst source as @junejs/pdf's typstRenderer, compiled by a PDF-only Typst build with zero
|
|
3
|
+
// imports, so it runs on Cloudflare Workers as well as Node, Bun and Deno.
|
|
4
|
+
//
|
|
5
|
+
// One engine per process or isolate, created on the first render and kept: an isolate's
|
|
6
|
+
// requests share 128 MB on Workers, so a render must not cost a fresh instance. Fonts:
|
|
7
|
+
// • embedded — Typst's defaults (Libertinus Serif, New Computer Modern, DejaVu Sans Mono);
|
|
8
|
+
// • `fonts` — the app's own, registered once for the engine's lifetime;
|
|
9
|
+
// • Google Fonts subsets — per document, the families in `googleFonts` (Noto Sans TC by
|
|
10
|
+
// default) cut to the document's own non-ASCII characters, the way @junejs/og loads
|
|
11
|
+
// fonts. A subset is a few KB where a whole CJK family is tens of MB, and it is dropped
|
|
12
|
+
// after the document, so subsets never pile up in the engine.
|
|
13
|
+
// Each render fetches what it needs first, then clears the previous document's fonts, adds
|
|
14
|
+
// its own and compiles with no await in between — concurrent renders can't see each other's
|
|
15
|
+
// fonts.
|
|
16
|
+
|
|
17
|
+
import { PdfRenderError, typstSource, type PdfDocument, type PdfRenderer } from "@junejs/pdf";
|
|
18
|
+
|
|
19
|
+
import { createEngine, TypstCompileError, type TypstEngine, type WasmSource } from "./engine";
|
|
20
|
+
|
|
21
|
+
export type FontSource = Uint8Array | ArrayBuffer | string | (() => Promise<Uint8Array | ArrayBuffer>);
|
|
22
|
+
|
|
23
|
+
export type GoogleFont = { family: string; weights?: number[] };
|
|
24
|
+
|
|
25
|
+
export type TypstWasmRendererOptions = {
|
|
26
|
+
// The engine module. Default: the dist/typst.wasm this package ships, loaded the way the
|
|
27
|
+
// host runtime needs (see node.ts / workerd.ts).
|
|
28
|
+
wasm?: WasmSource | (() => Promise<WasmSource>);
|
|
29
|
+
// Fonts registered once, for every document: bytes, a URL, or a loader.
|
|
30
|
+
fonts?: FontSource[];
|
|
31
|
+
// Font families in order of preference; Typst falls back to any loaded font with the glyph.
|
|
32
|
+
fontFamilies?: string[];
|
|
33
|
+
// Families fetched per document from Google Fonts, cut to the document's non-ASCII
|
|
34
|
+
// characters (default: Noto Sans TC, regular and bold). false: no network call — supply
|
|
35
|
+
// CJK fonts through `fonts`.
|
|
36
|
+
googleFonts?: GoogleFont[] | false;
|
|
37
|
+
// How fonts are fetched (default: global fetch).
|
|
38
|
+
fetch?: typeof fetch;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export const DEFAULT_GOOGLE_FONTS: GoogleFont[] = [{ family: "Noto Sans TC", weights: [400, 700] }];
|
|
42
|
+
|
|
43
|
+
export function createTypstWasmRenderer(defaultWasm: () => Promise<WasmSource>, opts: TypstWasmRendererOptions = {}): PdfRenderer {
|
|
44
|
+
const fetcher = opts.fetch ?? fetch;
|
|
45
|
+
const google = opts.googleFonts === false ? [] : (opts.googleFonts ?? DEFAULT_GOOGLE_FONTS);
|
|
46
|
+
let engine: Promise<TypstEngine> | undefined;
|
|
47
|
+
// Per renderer, not per module: a subset fetched through one renderer's `fetch` must not
|
|
48
|
+
// answer another renderer that was given a different one.
|
|
49
|
+
const subsets = subsetCache(fetcher);
|
|
50
|
+
|
|
51
|
+
const ready = (): Promise<TypstEngine> =>
|
|
52
|
+
(engine ??= (async () => {
|
|
53
|
+
const wasm = typeof opts.wasm === "function" ? await opts.wasm() : (opts.wasm ?? (await defaultWasm()));
|
|
54
|
+
const e = await createEngine(wasm);
|
|
55
|
+
for (const font of await Promise.all((opts.fonts ?? []).map((f) => loadFont(f, fetcher)))) e.addFont(font, "persistent");
|
|
56
|
+
return e;
|
|
57
|
+
})().catch((err: unknown) => {
|
|
58
|
+
engine = undefined; // a failed start (an unreachable font URL) is retried by the next render
|
|
59
|
+
throw err;
|
|
60
|
+
}));
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
name: "typst-wasm",
|
|
64
|
+
async render(doc: PdfDocument): Promise<Uint8Array> {
|
|
65
|
+
const source = typstSource(doc, { fonts: opts.fontFamilies });
|
|
66
|
+
const [e, documentFonts] = await Promise.all([ready(), subsetsFor(doc, google, subsets)]);
|
|
67
|
+
// From here on, synchronous: no other render can interleave.
|
|
68
|
+
e.clearDocumentFonts();
|
|
69
|
+
for (const font of documentFonts) e.addFont(font, "document");
|
|
70
|
+
try {
|
|
71
|
+
return e.compile(source);
|
|
72
|
+
} catch (err) {
|
|
73
|
+
if (err instanceof TypstCompileError) throw new PdfRenderError(`the document could not be typeset: ${err.message}`, { cause: err });
|
|
74
|
+
throw err;
|
|
75
|
+
} finally {
|
|
76
|
+
e.clearDocumentFonts();
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function loadFont(source: FontSource, fetcher: typeof fetch): Promise<Uint8Array> {
|
|
83
|
+
if (source instanceof Uint8Array) return source;
|
|
84
|
+
if (source instanceof ArrayBuffer) return new Uint8Array(source);
|
|
85
|
+
if (typeof source === "function") {
|
|
86
|
+
const data = await source();
|
|
87
|
+
return data instanceof Uint8Array ? data : new Uint8Array(data);
|
|
88
|
+
}
|
|
89
|
+
const res = await fetcher(source);
|
|
90
|
+
if (!res.ok) throw new Error(`font ${source}: HTTP ${res.status}`);
|
|
91
|
+
return new Uint8Array(await res.arrayBuffer());
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// The document's characters outside ASCII, the text a subset must cover. The title rides in
|
|
95
|
+
// the PDF metadata, not the body, so it needs no glyphs.
|
|
96
|
+
function documentText(doc: PdfDocument): string {
|
|
97
|
+
return [...new Set(doc.markdown.replace(/[\x00-\x7f]/g, ""))].join("");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
type SubsetLoader = (family: string, weight: number, text: string) => Promise<Uint8Array>;
|
|
101
|
+
|
|
102
|
+
async function subsetsFor(doc: PdfDocument, families: GoogleFont[], load: SubsetLoader): Promise<Uint8Array[]> {
|
|
103
|
+
const text = documentText(doc);
|
|
104
|
+
if (!text || families.length === 0) return [];
|
|
105
|
+
const wanted = families.flatMap((f) => (f.weights ?? [400]).map((w) => [f.family, w] as const));
|
|
106
|
+
const fonts = await Promise.all(
|
|
107
|
+
wanted.map(([family, weight]) =>
|
|
108
|
+
load(family, weight, text).catch((err: unknown) => {
|
|
109
|
+
// A font that can't be fetched costs glyphs, not the document: render without it.
|
|
110
|
+
console.warn(`[june] pdf-typst-wasm: ${family} ${weight} for this document could not be fetched (${err instanceof Error ? err.message : String(err)}); its characters may render blank`);
|
|
111
|
+
return undefined;
|
|
112
|
+
}),
|
|
113
|
+
),
|
|
114
|
+
);
|
|
115
|
+
return fonts.filter((f): f is Uint8Array => f !== undefined);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Google Fonts subsets a family to `text` and answers an old Safari with TTF, which Typst
|
|
119
|
+
// reads (it does not read WOFF2). Cached, bounded, least recently used out: a re-render of
|
|
120
|
+
// the same document fetches nothing.
|
|
121
|
+
const OLD_SAFARI = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1";
|
|
122
|
+
const SUBSET_CACHE_MAX = 32;
|
|
123
|
+
|
|
124
|
+
function subsetCache(fetcher: typeof fetch): SubsetLoader {
|
|
125
|
+
const cache = new Map<string, Promise<Uint8Array>>();
|
|
126
|
+
return (family, weight, text) => googleSubset(cache, family, weight, text, fetcher);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function googleSubset(cache: Map<string, Promise<Uint8Array>>, family: string, weight: number, text: string, fetcher: typeof fetch): Promise<Uint8Array> {
|
|
130
|
+
const css = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family)}:wght@${weight}&text=${encodeURIComponent(text)}`;
|
|
131
|
+
const hit = cache.get(css);
|
|
132
|
+
if (hit) {
|
|
133
|
+
cache.delete(css);
|
|
134
|
+
cache.set(css, hit); // most recently used last
|
|
135
|
+
return hit;
|
|
136
|
+
}
|
|
137
|
+
const load = (async () => {
|
|
138
|
+
const res = await fetcher(css, { headers: { "user-agent": OLD_SAFARI } });
|
|
139
|
+
if (!res.ok) throw new Error(`Google Fonts CSS: HTTP ${res.status}`);
|
|
140
|
+
const url = (await res.text()).match(/src:\s*url\((.+?)\)/)?.[1];
|
|
141
|
+
if (!url) throw new Error("Google Fonts CSS named no font file");
|
|
142
|
+
const font = await fetcher(url);
|
|
143
|
+
if (!font.ok) throw new Error(`Google Fonts file: HTTP ${font.status}`);
|
|
144
|
+
return new Uint8Array(await font.arrayBuffer());
|
|
145
|
+
})();
|
|
146
|
+
load.catch(() => cache.delete(css)); // never cache a failure
|
|
147
|
+
cache.set(css, load);
|
|
148
|
+
if (cache.size > SUBSET_CACHE_MAX) cache.delete(cache.keys().next().value!);
|
|
149
|
+
return load;
|
|
150
|
+
}
|
package/src/wasm.d.ts
ADDED
package/src/workerd.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// @junejs/pdf-typst-wasm on Cloudflare Workers (the `workerd` export condition): the engine
|
|
2
|
+
// module is imported, so wrangler uploads it as a compiled WebAssembly module and the
|
|
3
|
+
// runtime precompiles it — measured startup on the spike: 2 ms. The Worker needs Workers
|
|
4
|
+
// Paid: a warm one-page render takes ~40 ms of CPU, the Free plan allows 10.
|
|
5
|
+
//
|
|
6
|
+
// import { pdfTools } from "@junejs/pdf";
|
|
7
|
+
// import { typstWasmRenderer } from "@junejs/pdf-typst-wasm";
|
|
8
|
+
// export default pdfTools({ renderer: typstWasmRenderer() });
|
|
9
|
+
|
|
10
|
+
import type { PdfRenderer } from "@junejs/pdf";
|
|
11
|
+
|
|
12
|
+
// The same path from src/ (the repo) and from dist/ (the published package).
|
|
13
|
+
import wasm from "../dist/typst.wasm";
|
|
14
|
+
import { createTypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
|
|
15
|
+
|
|
16
|
+
export { DEFAULT_GOOGLE_FONTS, type FontSource, type GoogleFont, type TypstWasmRendererOptions } from "./renderer";
|
|
17
|
+
export { createEngine, TypstCompileError, type FontScope, type TypstEngine, type WasmSource } from "./engine";
|
|
18
|
+
|
|
19
|
+
export function typstWasmRenderer(opts: TypstWasmRendererOptions = {}): PdfRenderer {
|
|
20
|
+
return createTypstWasmRenderer(async () => wasm, opts);
|
|
21
|
+
}
|
package/README.md
DELETED