@junejs/pdf-typst-wasm 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.
@@ -0,0 +1,186 @@
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
+ const text = new TextDecoder();
21
+ return {
22
+ addFont(data, scope) {
23
+ return x.add_font(put(data), data.length, scope === "document" ? 1 : 0);
24
+ },
25
+ clearDocumentFonts() {
26
+ x.clear_document_fonts();
27
+ },
28
+ compile(source) {
29
+ const bytes = utf8.encode(source);
30
+ const status = x.compile(put(bytes), bytes.length);
31
+ const out = output();
32
+ if (status !== 0) throw new TypstCompileError(text.decode(out));
33
+ return {
34
+ pdf: out,
35
+ missingGlyphs: [...text.decode(new Uint8Array(x.memory.buffer, x.missing_glyphs_ptr(), x.missing_glyphs_len()))]
36
+ };
37
+ },
38
+ memoryBytes() {
39
+ return x.memory.buffer.byteLength;
40
+ }
41
+ };
42
+ }
43
+ //#endregion
44
+ //#region src/renderer.ts
45
+ const MISSING_SHOWN = 10;
46
+ function createTypstWasmRenderer(defaultWasm, opts = {}) {
47
+ const providers = [...opts.fonts ?? []];
48
+ let engine;
49
+ const ready = () => engine ??= (async () => {
50
+ const e = await createEngine(typeof opts.wasm === "function" ? await opts.wasm() : opts.wasm ?? await defaultWasm());
51
+ const persistent = await Promise.all(providers.map((p) => p.persistent?.() ?? []));
52
+ for (const font of persistent.flat()) 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
+ egress: uniqueEgress(providers),
61
+ async render(doc) {
62
+ const source = typstSource(doc, { fonts: opts.fontFamilies });
63
+ const [e, documentFonts] = await Promise.all([ready(), fontsFor(doc, providers)]);
64
+ e.clearDocumentFonts();
65
+ for (const font of documentFonts.fonts) e.addFont(font, "document");
66
+ let out;
67
+ try {
68
+ out = e.compile(source);
69
+ } catch (err) {
70
+ if (err instanceof TypstCompileError) throw new PdfRenderError(`the document could not be typeset: ${err.message}`, { cause: err });
71
+ throw err;
72
+ } finally {
73
+ e.clearDocumentFonts();
74
+ }
75
+ if (out.missingGlyphs.length === 0) return out.pdf;
76
+ const message = missingGlyphsMessage(out.missingGlyphs, documentFonts.failed);
77
+ if (opts.onMissingGlyphs === "warn") {
78
+ console.warn(`[june] pdf-typst-wasm: ${message}`);
79
+ return out.pdf;
80
+ }
81
+ throw new PdfRenderError(message);
82
+ }
83
+ };
84
+ }
85
+ function uniqueEgress(providers) {
86
+ const seen = /* @__PURE__ */ new Map();
87
+ for (const e of providers.flatMap((p) => p.egress)) if (!seen.get(e.host) || e.sends === "document-characters") seen.set(e.host, {
88
+ host: e.host,
89
+ sends: e.sends
90
+ });
91
+ return [...seen.values()];
92
+ }
93
+ function documentText(doc) {
94
+ return [...new Set(doc.markdown.replace(/[\x00-\x7f]/g, ""))].join("");
95
+ }
96
+ async function fontsFor(doc, providers) {
97
+ const text = documentText(doc);
98
+ const loaders = providers.filter((p) => p.forDocument);
99
+ if (!text || loaders.length === 0) return {
100
+ fonts: [],
101
+ failed: []
102
+ };
103
+ const settled = await Promise.allSettled(loaders.map((p) => p.forDocument(text)));
104
+ const failure = (i, why) => `${loaders[i].name} failed (${why})`;
105
+ return {
106
+ fonts: settled.flatMap((s) => s.status === "fulfilled" ? s.value.fonts : []),
107
+ failed: settled.flatMap((s, i) => s.status === "rejected" ? [failure(i, s.reason instanceof Error ? s.reason.message : String(s.reason))] : (s.value.failed ?? []).map((why) => failure(i, why)))
108
+ };
109
+ }
110
+ function missingGlyphsMessage(missing, failed) {
111
+ return `no font available to the PDF renderer covers ${missing.slice(0, MISSING_SHOWN).join(" ")}${missing.length > MISSING_SHOWN ? ` (and ${missing.length - MISSING_SHOWN} more)` : ""}, so they would be missing from the document. ` + (failed.length ? `${failed.join("; ")}. ` : "") + "Remove them from the Markdown if they are decorative (emoji, symbols); otherwise tell the user the PDF can't include them until the app adds a font that covers them to typstWasmRenderer's `fonts` (localFonts or googleFontSubsets).";
112
+ }
113
+ //#endregion
114
+ //#region src/fonts.ts
115
+ function localFonts(input, opts = {}) {
116
+ const sources = [...input];
117
+ const fetcher = opts.fetch ?? fetch;
118
+ return {
119
+ name: "local-fonts",
120
+ egress: [...new Set(sources.filter((s) => typeof s === "string").map((url) => new URL(url).host))].map((host) => ({
121
+ host,
122
+ sends: "nothing"
123
+ })),
124
+ persistent: () => Promise.all(sources.map((s) => loadFont(s, fetcher)))
125
+ };
126
+ }
127
+ async function loadFont(source, fetcher) {
128
+ if (source instanceof Uint8Array) return source;
129
+ if (source instanceof ArrayBuffer) return new Uint8Array(source);
130
+ if (typeof source === "function") {
131
+ const data = await source();
132
+ return data instanceof Uint8Array ? data : new Uint8Array(data);
133
+ }
134
+ const res = await fetcher(source);
135
+ if (!res.ok) throw new Error(`font ${source}: HTTP ${res.status}`);
136
+ return new Uint8Array(await res.arrayBuffer());
137
+ }
138
+ function googleFontSubsets(opts) {
139
+ const fetcher = opts.fetch ?? fetch;
140
+ const wanted = opts.families.flatMap((f) => (f.weights ?? [400]).map((w) => [f.family, w]));
141
+ const cache = /* @__PURE__ */ new Map();
142
+ return {
143
+ name: "google-font-subsets",
144
+ egress: [{
145
+ host: "fonts.googleapis.com",
146
+ sends: "document-characters"
147
+ }, {
148
+ host: "fonts.gstatic.com",
149
+ sends: "document-characters"
150
+ }],
151
+ async forDocument(text) {
152
+ const settled = await Promise.allSettled(wanted.map(([family, weight]) => googleSubset(cache, family, weight, text, fetcher)));
153
+ return {
154
+ fonts: settled.flatMap((s) => s.status === "fulfilled" ? [s.value] : []),
155
+ failed: settled.flatMap((s, i) => s.status === "rejected" ? [`${wanted[i][0]} ${wanted[i][1]}: ${message(s.reason)}`] : [])
156
+ };
157
+ }
158
+ };
159
+ }
160
+ const message = (err) => err instanceof Error ? err.message : String(err);
161
+ 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";
162
+ const SUBSET_CACHE_MAX = 32;
163
+ function googleSubset(cache, family, weight, text, fetcher) {
164
+ const css = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family)}:wght@${weight}&text=${encodeURIComponent(text)}`;
165
+ const hit = cache.get(css);
166
+ if (hit) {
167
+ cache.delete(css);
168
+ cache.set(css, hit);
169
+ return hit;
170
+ }
171
+ const load = (async () => {
172
+ const res = await fetcher(css, { headers: { "user-agent": OLD_SAFARI } });
173
+ if (!res.ok) throw new Error(`Google Fonts CSS: HTTP ${res.status}`);
174
+ const url = (await res.text()).match(/src:\s*url\((.+?)\)/)?.[1];
175
+ if (!url) throw new Error("Google Fonts CSS named no font file");
176
+ const font = await fetcher(url);
177
+ if (!font.ok) throw new Error(`Google Fonts file: HTTP ${font.status}`);
178
+ return new Uint8Array(await font.arrayBuffer());
179
+ })();
180
+ load.catch(() => cache.delete(css));
181
+ cache.set(css, load);
182
+ if (cache.size > SUBSET_CACHE_MAX) cache.delete(cache.keys().next().value);
183
+ return load;
184
+ }
185
+ //#endregion
186
+ export { createEngine as a, TypstCompileError as i, localFonts as n, createTypstWasmRenderer as r, googleFontSubsets as t };
package/dist/node.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { a as FontProvider, c as googleFontSubsets, d as TypstCompileError, f as TypstEngine, h as createEngine, i as FontEgress, l as localFonts, m as WasmSource, n as TypstWasmRendererOptions, o as FontSource, p as TypstOutput, r as DocumentFonts, s as GoogleFont, t as TypstWasmRenderer, u as FontScope } from "./renderer-N0qDEY0c.js";
2
+ //#region src/node.d.ts
3
+ export declare const WASM_URL: URL;
4
+ export declare function typstWasmRenderer(opts?: TypstWasmRendererOptions): TypstWasmRenderer;
5
+ //#endregion
6
+ export { type DocumentFonts, type FontEgress, type FontProvider, type FontScope, type FontSource, type GoogleFont, TypstCompileError, type TypstEngine, type TypstOutput, type TypstWasmRenderer, type TypstWasmRendererOptions, type WasmSource, createEngine, googleFontSubsets, localFonts };
package/dist/node.js ADDED
@@ -0,0 +1,24 @@
1
+ import { a as createEngine, i as TypstCompileError, n as localFonts, r as createTypstWasmRenderer, t as googleFontSubsets } from "./fonts-GfZSxDhh.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; in a bundled or single-file build, pass the module through the \`wasm\` option`, { 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 { TypstCompileError, WASM_URL, createEngine, googleFontSubsets, localFonts, typstWasmRenderer };
@@ -0,0 +1,59 @@
1
+ import { PdfRenderer } from "@junejs/pdf";
2
+ //#region src/engine.d.ts
3
+ type FontScope = "persistent" | "document";
4
+ type TypstOutput = {
5
+ pdf: Uint8Array;
6
+ missingGlyphs: string[];
7
+ };
8
+ interface TypstEngine {
9
+ addFont(data: Uint8Array, scope: FontScope): number;
10
+ clearDocumentFonts(): void;
11
+ compile(source: string): TypstOutput;
12
+ memoryBytes(): number;
13
+ }
14
+ declare class TypstCompileError extends Error {
15
+ constructor(message: string);
16
+ }
17
+ type WasmSource = WebAssembly.Module | BufferSource;
18
+ declare function createEngine(wasm: WasmSource): Promise<TypstEngine>;
19
+ //#endregion
20
+ //#region src/fonts.d.ts
21
+ type FontEgress = {
22
+ host: string;
23
+ sends: "nothing" | "document-characters";
24
+ };
25
+ interface FontProvider {
26
+ readonly name: string;
27
+ readonly egress: readonly FontEgress[];
28
+ persistent?(): Promise<Uint8Array[]>;
29
+ forDocument?(text: string): Promise<DocumentFonts>;
30
+ }
31
+ type DocumentFonts = {
32
+ fonts: Uint8Array[];
33
+ failed?: string[];
34
+ };
35
+ type FontSource = Uint8Array | ArrayBuffer | string | (() => Promise<Uint8Array | ArrayBuffer>);
36
+ declare function localFonts(input: FontSource[], opts?: {
37
+ fetch?: typeof fetch;
38
+ }): FontProvider;
39
+ type GoogleFont = {
40
+ family: string;
41
+ weights?: number[];
42
+ };
43
+ declare function googleFontSubsets(opts: {
44
+ families: GoogleFont[];
45
+ fetch?: typeof fetch;
46
+ }): FontProvider;
47
+ //#endregion
48
+ //#region src/renderer.d.ts
49
+ type TypstWasmRendererOptions = {
50
+ wasm?: WasmSource | (() => Promise<WasmSource>);
51
+ fonts?: FontProvider[];
52
+ fontFamilies?: string[];
53
+ onMissingGlyphs?: "error" | "warn";
54
+ };
55
+ interface TypstWasmRenderer extends PdfRenderer {
56
+ readonly egress: readonly FontEgress[];
57
+ }
58
+ //#endregion
59
+ export { FontProvider as a, googleFontSubsets as c, TypstCompileError as d, TypstEngine as f, createEngine as h, FontEgress as i, localFonts as l, WasmSource as m, TypstWasmRendererOptions as n, FontSource as o, TypstOutput as p, DocumentFonts as r, GoogleFont as s, TypstWasmRenderer as t, FontScope as u };
Binary file
@@ -0,0 +1,5 @@
1
+ import { a as FontProvider, c as googleFontSubsets, d as TypstCompileError, f as TypstEngine, h as createEngine, i as FontEgress, l as localFonts, m as WasmSource, n as TypstWasmRendererOptions, o as FontSource, p as TypstOutput, r as DocumentFonts, s as GoogleFont, t as TypstWasmRenderer, u as FontScope } from "./renderer-N0qDEY0c.js";
2
+ //#region src/workerd.d.ts
3
+ export declare function typstWasmRenderer(opts?: TypstWasmRendererOptions): TypstWasmRenderer;
4
+ //#endregion
5
+ export { type DocumentFonts, type FontEgress, type FontProvider, type FontScope, type FontSource, type GoogleFont, TypstCompileError, type TypstEngine, type TypstOutput, type TypstWasmRenderer, type TypstWasmRendererOptions, type WasmSource, createEngine, googleFontSubsets, localFonts };
@@ -0,0 +1,8 @@
1
+ import { a as createEngine, i as TypstCompileError, n as localFonts, r as createTypstWasmRenderer, t as googleFontSubsets } from "./fonts-GfZSxDhh.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 { TypstCompileError, createEngine, googleFontSubsets, localFonts, typstWasmRenderer };
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@junejs/pdf-typst-wasm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.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
+ "bun": "./src/bun.ts",
13
+ "default": "./src/node.ts"
14
+ },
15
+ "bun": {
16
+ "workerd": "./src/workerd.ts",
17
+ "default": "./src/bun.ts"
18
+ },
19
+ "workerd": {
20
+ "types": "./dist/workerd.d.ts",
21
+ "default": "./dist/workerd.js"
22
+ },
23
+ "default": {
24
+ "types": "./dist/node.d.ts",
25
+ "default": "./dist/node.js"
26
+ }
27
+ },
28
+ "./typst.wasm": "./dist/typst.wasm"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "src/*.ts"
33
+ ],
34
+ "scripts": {
35
+ "build:wasm": "bun scripts/build-wasm.ts",
36
+ "build": "bun run build:wasm && tsdown",
37
+ "test": "bun test"
38
+ },
39
+ "dependencies": {
40
+ "@junejs/pdf": "^0.2.0"
41
+ },
42
+ "devDependencies": {
43
+ "@junejs/core": "^0.2.0",
44
+ "@junejs/server": "^0.2.0"
45
+ },
46
+ "keywords": [
47
+ "june",
48
+ "agent",
49
+ "pdf",
50
+ "typst",
51
+ "wasm",
52
+ "cloudflare-workers"
53
+ ],
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
57
+ "repository": {
58
+ "type": "git",
59
+ "url": "git+https://github.com/junebuild/june.git",
60
+ "directory": "packages/pdf-typst-wasm"
61
+ }
62
+ }
package/src/bun.ts ADDED
@@ -0,0 +1,40 @@
1
+ // @junejs/pdf-typst-wasm on Bun (the `bun` export condition). Everything is node.ts's except
2
+ // how the engine module is found: here it is imported `with { type: "file" }`, which
3
+ // `bun build --compile` sees and embeds, and which yields the module's path inside the binary
4
+ // (/$bunfs/…). node.ts reads ../dist/typst.wasm by URL at first render, which the bundler can't
5
+ // see, so a compiled app failed its first render_pdf (#367).
6
+ //
7
+ // A dynamic import, on the first render: a process that never renders a PDF never reads the
8
+ // 29 MiB, and a repo checkout without the built module still loads this file (its tests skip).
9
+ // The bundler embeds the file when it exists and doesn't check when it doesn't (verified on Bun
10
+ // 1.4.2): a binary compiled from a checkout without it fails at first render, with the message
11
+ // below. A published package always ships it.
12
+
13
+ import { readFile } from "node:fs/promises";
14
+
15
+ import type { WasmSource } from "./engine";
16
+ import { createTypstWasmRenderer, type TypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
17
+
18
+ // The same names as node.ts; the local typstWasmRenderer below takes precedence over its own.
19
+ export * from "./node";
20
+
21
+ let compiled: Promise<WebAssembly.Module> | undefined;
22
+ async function loadWasm(): Promise<WasmSource> {
23
+ return (compiled ??= (async () => {
24
+ let path: string;
25
+ try {
26
+ // wasm.d.ts types a .wasm import as a module (workerd); with type "file" it is a path.
27
+ path = ((await import("../dist/typst.wasm", { with: { type: "file" } })) as unknown as { default: string }).default;
28
+ } catch (err) {
29
+ throw new Error("@junejs/pdf-typst-wasm: dist/typst.wasm is missing — in the June repo, run `bun run build` in packages/pdf-typst-wasm", { cause: err });
30
+ }
31
+ return WebAssembly.compile((await readFile(path)) as Uint8Array<ArrayBuffer>);
32
+ })().catch((err: unknown) => {
33
+ compiled = undefined;
34
+ throw err;
35
+ }));
36
+ }
37
+
38
+ export function typstWasmRenderer(opts: TypstWasmRendererOptions = {}): TypstWasmRenderer {
39
+ return createTypstWasmRenderer(loadWasm, opts);
40
+ }
package/src/engine.ts ADDED
@@ -0,0 +1,85 @@
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 type TypstOutput = {
9
+ pdf: Uint8Array;
10
+ // Characters no loaded font covers, each once, in document order: they render blank or go
11
+ // missing from the PDF's text. Empty when every character has a glyph.
12
+ missingGlyphs: string[];
13
+ };
14
+
15
+ export interface TypstEngine {
16
+ // Register a font file; returns the number of faces it held (0: not a font).
17
+ addFont(data: Uint8Array, scope: FontScope): number;
18
+ // Drop the document-scoped fonts.
19
+ clearDocumentFonts(): void;
20
+ // Typst source → PDF bytes. Throws TypstCompileError with the document's diagnostics.
21
+ compile(source: string): TypstOutput;
22
+ // The engine's linear memory, in bytes (it only grows).
23
+ memoryBytes(): number;
24
+ }
25
+
26
+ export class TypstCompileError extends Error {
27
+ constructor(message: string) {
28
+ super(message);
29
+ this.name = "TypstCompileError";
30
+ }
31
+ }
32
+
33
+ type Exports = {
34
+ memory: WebAssembly.Memory;
35
+ alloc(len: number): number;
36
+ init(): number;
37
+ add_font(ptr: number, len: number, document: number): number;
38
+ clear_document_fonts(): void;
39
+ compile(ptr: number, len: number): number;
40
+ output_ptr(): number;
41
+ output_len(): number;
42
+ missing_glyphs_ptr(): number;
43
+ missing_glyphs_len(): number;
44
+ };
45
+
46
+ export type WasmSource = WebAssembly.Module | BufferSource;
47
+
48
+ export async function createEngine(wasm: WasmSource): Promise<TypstEngine> {
49
+ // A Module instantiates to an Instance; bytes to { module, instance }.
50
+ const made = (await WebAssembly.instantiate(wasm as BufferSource, {})) as unknown as WebAssembly.Instance | WebAssembly.WebAssemblyInstantiatedSource;
51
+ const instance = made instanceof WebAssembly.Instance ? made : made.instance;
52
+ const x = instance.exports as unknown as Exports;
53
+ x.init(); // embedded fonts now, not inside the first render
54
+
55
+ // Copy bytes into the module's memory; the callee takes ownership of the buffer. The view
56
+ // is taken after alloc, which may grow (and so detach) the memory.
57
+ const put = (bytes: Uint8Array): number => {
58
+ const ptr = x.alloc(bytes.length);
59
+ new Uint8Array(x.memory.buffer, ptr, bytes.length).set(bytes);
60
+ return ptr;
61
+ };
62
+ const output = (): Uint8Array => new Uint8Array(x.memory.buffer, x.output_ptr(), x.output_len()).slice();
63
+ const utf8 = new TextEncoder();
64
+ const text = new TextDecoder();
65
+
66
+ return {
67
+ addFont(data, scope) {
68
+ return x.add_font(put(data), data.length, scope === "document" ? 1 : 0);
69
+ },
70
+ clearDocumentFonts() {
71
+ x.clear_document_fonts();
72
+ },
73
+ compile(source) {
74
+ const bytes = utf8.encode(source);
75
+ const status = x.compile(put(bytes), bytes.length);
76
+ const out = output();
77
+ if (status !== 0) throw new TypstCompileError(text.decode(out));
78
+ const missing = text.decode(new Uint8Array(x.memory.buffer, x.missing_glyphs_ptr(), x.missing_glyphs_len()));
79
+ return { pdf: out, missingGlyphs: [...missing] };
80
+ },
81
+ memoryBytes() {
82
+ return x.memory.buffer.byteLength;
83
+ },
84
+ };
85
+ }
package/src/fonts.ts ADDED
@@ -0,0 +1,122 @@
1
+ // Font providers (#371): where a PDF's fonts come from decides where the document goes. A
2
+ // provider fetching per-document subsets sends the document's characters to a third party;
3
+ // one reading bundled bytes sends nothing. That is the app's or the installer's call, so the
4
+ // renderer makes no network call unless the app lists a provider that does, and every
5
+ // provider declares its `egress` — what leaves the process, and to which host — so an app
6
+ // can show the trade-off (a doctor check, its docs) without reading this source.
7
+ //
8
+ // `egress` is a description, not enforcement: a provider an app writes can omit or misstate
9
+ // it. Network policy belongs to the `fetch` a provider is given, or to the host.
10
+ //
11
+ // Nothing here depends on PDF types, so @junejs/og's Google Fonts loading could move onto
12
+ // the same providers later.
13
+
14
+ export type FontEgress = {
15
+ host: string;
16
+ // "nothing": a fixed request (a font file by URL). "document-characters": the request
17
+ // carries the characters of the document being rendered.
18
+ sends: "nothing" | "document-characters";
19
+ };
20
+
21
+ export interface FontProvider {
22
+ // Shown in errors ("google-font-subsets: HTTP 503").
23
+ readonly name: string;
24
+ // Every host this provider contacts; empty when it never touches the network.
25
+ readonly egress: readonly FontEgress[];
26
+ // Font files registered once, for the renderer's lifetime. A failure fails the render and
27
+ // is retried by the next one.
28
+ persistent?(): Promise<Uint8Array[]>;
29
+ // Font files for one document, given its non-ASCII characters; dropped after it. A failure
30
+ // costs only the characters nothing else covers, and the missing glyphs error names it:
31
+ // report a partial one in `failed` and keep the fonts that loaded; a throw loses them all.
32
+ forDocument?(text: string): Promise<DocumentFonts>;
33
+ }
34
+
35
+ export type DocumentFonts = { fonts: Uint8Array[]; failed?: string[] };
36
+
37
+ // A font file: bytes, a URL fetched once, or a loader.
38
+ export type FontSource = Uint8Array | ArrayBuffer | string | (() => Promise<Uint8Array | ArrayBuffer>);
39
+
40
+ // The app's own font files, read once. Offline unless a source is a URL, which is fetched once
41
+ // at startup and sends nothing about any document.
42
+ // `sources` is copied, so `egress` always names what `persistent` fetches.
43
+ export function localFonts(input: FontSource[], opts: { fetch?: typeof fetch } = {}): FontProvider {
44
+ const sources = [...input];
45
+ const fetcher = opts.fetch ?? fetch;
46
+ const hosts = [...new Set(sources.filter((s): s is string => typeof s === "string").map((url) => new URL(url).host))];
47
+ return {
48
+ name: "local-fonts",
49
+ egress: hosts.map((host) => ({ host, sends: "nothing" as const })),
50
+ persistent: () => Promise.all(sources.map((s) => loadFont(s, fetcher))),
51
+ };
52
+ }
53
+
54
+ async function loadFont(source: FontSource, fetcher: typeof fetch): Promise<Uint8Array> {
55
+ if (source instanceof Uint8Array) return source;
56
+ if (source instanceof ArrayBuffer) return new Uint8Array(source);
57
+ if (typeof source === "function") {
58
+ const data = await source();
59
+ return data instanceof Uint8Array ? data : new Uint8Array(data);
60
+ }
61
+ const res = await fetcher(source);
62
+ if (!res.ok) throw new Error(`font ${source}: HTTP ${res.status}`);
63
+ return new Uint8Array(await res.arrayBuffer());
64
+ }
65
+
66
+ export type GoogleFont = { family: string; weights?: number[] };
67
+
68
+ // Per document, each family cut to the document's non-ASCII characters by Google Fonts, the
69
+ // way @junejs/og loads fonts: a subset is a few KB where a whole CJK family is tens of MB.
70
+ // The name says the trade-off: the characters go to fonts.googleapis.com in the request, and
71
+ // the font file's fonts.gstatic.com URL encodes them too.
72
+ export function googleFontSubsets(opts: { families: GoogleFont[]; fetch?: typeof fetch }): FontProvider {
73
+ const fetcher = opts.fetch ?? fetch;
74
+ const wanted = opts.families.flatMap((f) => (f.weights ?? [400]).map((w) => [f.family, w] as const));
75
+ // Per provider: a subset fetched through one provider's `fetch` must not answer another's.
76
+ const cache = new Map<string, Promise<Uint8Array>>();
77
+ return {
78
+ name: "google-font-subsets",
79
+ egress: [
80
+ { host: "fonts.googleapis.com", sends: "document-characters" },
81
+ { host: "fonts.gstatic.com", sends: "document-characters" },
82
+ ],
83
+ async forDocument(text) {
84
+ // Each weight on its own: a bold that fails costs only the bold, never the regular.
85
+ const settled = await Promise.allSettled(wanted.map(([family, weight]) => googleSubset(cache, family, weight, text, fetcher)));
86
+ return {
87
+ fonts: settled.flatMap((s) => (s.status === "fulfilled" ? [s.value] : [])),
88
+ failed: settled.flatMap((s, i) => (s.status === "rejected" ? [`${wanted[i]![0]} ${wanted[i]![1]}: ${message(s.reason)}`] : [])),
89
+ };
90
+ },
91
+ };
92
+ }
93
+
94
+ const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
95
+
96
+ // Google Fonts answers an old Safari with TTF, which Typst reads (it does not read WOFF2).
97
+ // Cached, bounded, least recently used out: a re-render of the same document fetches nothing.
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
+
101
+ function googleSubset(cache: Map<string, Promise<Uint8Array>>, family: string, weight: number, text: string, fetcher: typeof fetch): Promise<Uint8Array> {
102
+ const css = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family)}:wght@${weight}&text=${encodeURIComponent(text)}`;
103
+ const hit = cache.get(css);
104
+ if (hit) {
105
+ cache.delete(css);
106
+ cache.set(css, hit); // most recently used last
107
+ return hit;
108
+ }
109
+ const load = (async () => {
110
+ const res = await fetcher(css, { headers: { "user-agent": OLD_SAFARI } });
111
+ if (!res.ok) throw new Error(`Google Fonts CSS: HTTP ${res.status}`);
112
+ const url = (await res.text()).match(/src:\s*url\((.+?)\)/)?.[1];
113
+ if (!url) throw new Error("Google Fonts CSS named no font file");
114
+ const font = await fetcher(url);
115
+ if (!font.ok) throw new Error(`Google Fonts file: HTTP ${font.status}`);
116
+ return new Uint8Array(await font.arrayBuffer());
117
+ })();
118
+ load.catch(() => cache.delete(css)); // never cache a failure
119
+ cache.set(css, load);
120
+ if (cache.size > SUBSET_CACHE_MAX) cache.delete(cache.keys().next().value!);
121
+ return load;
122
+ }
package/src/node.ts ADDED
@@ -0,0 +1,37 @@
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() }); // offline: embedded fonts only
8
+
9
+ import type { WasmSource } from "./engine";
10
+ import { createTypstWasmRenderer, type TypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
11
+
12
+ export { type TypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
13
+ export { googleFontSubsets, localFonts, type DocumentFonts, type FontEgress, type FontProvider, type FontSource, type GoogleFont } from "./fonts";
14
+ export { createEngine, TypstCompileError, type FontScope, type TypstEngine, type TypstOutput, type WasmSource } from "./engine";
15
+
16
+ export const WASM_URL = new URL("../dist/typst.wasm", import.meta.url);
17
+
18
+ let compiled: Promise<WebAssembly.Module> | undefined;
19
+ async function loadWasm(): Promise<WasmSource> {
20
+ return (compiled ??= (async () => {
21
+ const [{ readFile }, { fileURLToPath }] = await Promise.all([import("node:fs/promises"), import("node:url")]);
22
+ let bytes: Uint8Array;
23
+ try {
24
+ bytes = await readFile(fileURLToPath(WASM_URL));
25
+ } catch (err) {
26
+ 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; in a bundled or single-file build, pass the module through the \`wasm\` option`, { cause: err });
27
+ }
28
+ return WebAssembly.compile(bytes as Uint8Array<ArrayBuffer>);
29
+ })().catch((err: unknown) => {
30
+ compiled = undefined;
31
+ throw err;
32
+ }));
33
+ }
34
+
35
+ export function typstWasmRenderer(opts: TypstWasmRendererOptions = {}): TypstWasmRenderer {
36
+ return createTypstWasmRenderer(loadWasm, opts);
37
+ }
@@ -0,0 +1,140 @@
1
+ // typstWasmRenderer — a PdfRenderer on this package's engine (src/lib.rs): @junejs/pdf's
2
+ // Markdown → Typst source, compiled by a PDF-only Typst build with zero imports, so it runs
3
+ // 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
+ // always there, so a Latin document needs nothing and the default makes no network call;
9
+ // • `fonts` — the app's providers (fonts.ts). Their order is not a preference: Typst picks
10
+ // by `fontFamilies`, then falls back to the most similar font that has the glyph. A provider's
11
+ // persistent fonts are registered once; its per-document fonts (a CJK subset cut to one
12
+ // document's characters) are dropped after the document, so they never pile up.
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
+ // A character none of those fonts covers would come out blank: a wrong document that looks
18
+ // right, which an agent would hand to its user as if it were right (#368). So it is a
19
+ // PdfRenderError by default, naming the characters and any provider that failed; the model
20
+ // reads it and can drop a decorative emoji or tell the user. `onMissingGlyphs: "warn"` is for
21
+ // an app that accepts the gaps.
22
+
23
+ import { PdfRenderError, typstSource, type PdfDocument, type PdfRenderer } from "@junejs/pdf";
24
+
25
+ import { createEngine, TypstCompileError, type TypstEngine, type WasmSource } from "./engine";
26
+ import type { FontEgress, FontProvider } from "./fonts";
27
+
28
+ export type TypstWasmRendererOptions = {
29
+ // The engine module. Default: the dist/typst.wasm this package ships, loaded the way the
30
+ // host runtime needs (see node.ts / workerd.ts).
31
+ wasm?: WasmSource | (() => Promise<WasmSource>);
32
+ // Where fonts beyond the embedded ones come from (default: none, so no network call):
33
+ // localFonts([...]), googleFontSubsets({ families }), or a provider the app writes. Read
34
+ // once, here: `egress` must describe the providers that actually render.
35
+ fonts?: FontProvider[];
36
+ // Font families in order of preference; Typst falls back to any loaded font with the glyph.
37
+ fontFamilies?: string[];
38
+ // Characters no loaded font covers: "error" (default) throws a PdfRenderError naming them;
39
+ // "warn" logs them and returns the PDF with those characters blank.
40
+ onMissingGlyphs?: "error" | "warn";
41
+ };
42
+
43
+ export interface TypstWasmRenderer extends PdfRenderer {
44
+ // Every host the configured fonts contact, and what each is sent; empty means the renderer
45
+ // works offline. Declared by the providers, not observed (see fonts.ts).
46
+ readonly egress: readonly FontEgress[];
47
+ }
48
+
49
+ // How many missing characters a message names before it counts the rest.
50
+ const MISSING_SHOWN = 10;
51
+
52
+ export function createTypstWasmRenderer(defaultWasm: () => Promise<WasmSource>, opts: TypstWasmRendererOptions = {}): TypstWasmRenderer {
53
+ const providers = [...(opts.fonts ?? [])];
54
+ let engine: Promise<TypstEngine> | undefined;
55
+
56
+ const ready = (): Promise<TypstEngine> =>
57
+ (engine ??= (async () => {
58
+ const wasm = typeof opts.wasm === "function" ? await opts.wasm() : (opts.wasm ?? (await defaultWasm()));
59
+ const e = await createEngine(wasm);
60
+ const persistent = await Promise.all(providers.map((p) => p.persistent?.() ?? []));
61
+ for (const font of persistent.flat()) e.addFont(font, "persistent");
62
+ return e;
63
+ })().catch((err: unknown) => {
64
+ engine = undefined; // a failed start (an unreachable font URL) is retried by the next render
65
+ throw err;
66
+ }));
67
+
68
+ return {
69
+ name: "typst-wasm",
70
+ egress: uniqueEgress(providers),
71
+ async render(doc: PdfDocument): Promise<Uint8Array> {
72
+ const source = typstSource(doc, { fonts: opts.fontFamilies });
73
+ const [e, documentFonts] = await Promise.all([ready(), fontsFor(doc, providers)]);
74
+ // From here on, synchronous: no other render can interleave.
75
+ e.clearDocumentFonts();
76
+ for (const font of documentFonts.fonts) e.addFont(font, "document");
77
+ let out;
78
+ try {
79
+ out = e.compile(source);
80
+ } catch (err) {
81
+ if (err instanceof TypstCompileError) throw new PdfRenderError(`the document could not be typeset: ${err.message}`, { cause: err });
82
+ throw err;
83
+ } finally {
84
+ e.clearDocumentFonts();
85
+ }
86
+ if (out.missingGlyphs.length === 0) return out.pdf;
87
+ const message = missingGlyphsMessage(out.missingGlyphs, documentFonts.failed);
88
+ if (opts.onMissingGlyphs === "warn") {
89
+ console.warn(`[june] pdf-typst-wasm: ${message}`);
90
+ return out.pdf;
91
+ }
92
+ throw new PdfRenderError(message);
93
+ },
94
+ };
95
+ }
96
+
97
+ function uniqueEgress(providers: FontProvider[]): FontEgress[] {
98
+ const seen = new Map<string, FontEgress>();
99
+ for (const e of providers.flatMap((p) => p.egress)) {
100
+ const prior = seen.get(e.host);
101
+ // A host sent the document's characters by any provider is sent them, full stop.
102
+ if (!prior || e.sends === "document-characters") seen.set(e.host, { host: e.host, sends: e.sends });
103
+ }
104
+ return [...seen.values()];
105
+ }
106
+
107
+ // The document's characters outside ASCII, the text a per-document font must cover. The
108
+ // title rides in the PDF metadata, not the body, so it needs no glyphs.
109
+ function documentText(doc: PdfDocument): string {
110
+ return [...new Set(doc.markdown.replace(/[\x00-\x7f]/g, ""))].join("");
111
+ }
112
+
113
+ // The per-document fonts that loaded, and a line for each provider that failed. A failure
114
+ // doesn't fail the render by itself: another font may cover the characters, and if none
115
+ // does, the missing glyphs error carries the line as the reason.
116
+ async function fontsFor(doc: PdfDocument, providers: FontProvider[]): Promise<{ fonts: Uint8Array[]; failed: string[] }> {
117
+ const text = documentText(doc);
118
+ const loaders = providers.filter((p) => p.forDocument);
119
+ if (!text || loaders.length === 0) return { fonts: [], failed: [] };
120
+ const settled = await Promise.allSettled(loaders.map((p) => p.forDocument!(text)));
121
+ const failure = (i: number, why: string) => `${loaders[i]!.name} failed (${why})`;
122
+ return {
123
+ fonts: settled.flatMap((s) => (s.status === "fulfilled" ? s.value.fonts : [])),
124
+ failed: settled.flatMap((s, i) =>
125
+ s.status === "rejected" ? [failure(i, s.reason instanceof Error ? s.reason.message : String(s.reason))] : (s.value.failed ?? []).map((why) => failure(i, why)),
126
+ ),
127
+ };
128
+ }
129
+
130
+ // Written for the model, which reads it as render_pdf's error, and for the app's logs.
131
+ function missingGlyphsMessage(missing: string[], failed: string[]): string {
132
+ const shown = missing.slice(0, MISSING_SHOWN).join(" ");
133
+ const more = missing.length > MISSING_SHOWN ? ` (and ${missing.length - MISSING_SHOWN} more)` : "";
134
+ return (
135
+ `no font available to the PDF renderer covers ${shown}${more}, so they would be missing from the document. ` +
136
+ (failed.length ? `${failed.join("; ")}. ` : "") +
137
+ "Remove them from the Markdown if they are decorative (emoji, symbols); otherwise tell the user the PDF can't include them " +
138
+ "until the app adds a font that covers them to typstWasmRenderer's `fonts` (localFonts or googleFontSubsets)."
139
+ );
140
+ }
package/src/wasm.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ // A `.wasm` import is a compiled module on workerd (wrangler's CompiledWasm rule).
2
+ declare module "*.wasm" {
3
+ const module: WebAssembly.Module;
4
+ export default module;
5
+ }
package/src/workerd.ts ADDED
@@ -0,0 +1,20 @@
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() }); // offline: embedded fonts only
9
+
10
+ // The same path from src/ (the repo) and from dist/ (the published package).
11
+ import wasm from "../dist/typst.wasm";
12
+ import { createTypstWasmRenderer, type TypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
13
+
14
+ export { type TypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
15
+ export { googleFontSubsets, localFonts, type DocumentFonts, type FontEgress, type FontProvider, type FontSource, type GoogleFont } from "./fonts";
16
+ export { createEngine, TypstCompileError, type FontScope, type TypstEngine, type TypstOutput, type WasmSource } from "./engine";
17
+
18
+ export function typstWasmRenderer(opts: TypstWasmRendererOptions = {}): TypstWasmRenderer {
19
+ return createTypstWasmRenderer(async () => wasm, opts);
20
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.