diff --git a/docs/content/docs/features/export/docx.mdx b/docs/content/docs/features/export/docx.mdx index aede75175d..02164b4c2f 100644 --- a/docs/content/docs/features/export/docx.mdx +++ b/docs/content/docs/features/export/docx.mdx @@ -132,3 +132,40 @@ const defaultOptions = { colors: COLORS_DEFAULT, // defaults from @blocknote/core }; ``` + +### Fonts + +DOCX embeds Inter 18pt for body text and Geist Mono for code by default. +Set `fontFamily` or `monoFontFamily` to change the styles. To use a custom +family on devices where it isn't installed, embed it with `fonts`: + +```typescript +import { DOCXExporter, docxDefaultSchemaMappings } from "@blocknote/xl-docx-exporter"; + +const response = await fetch("/fonts/Lato-Regular.ttf"); +if (!response.ok) throw new Error("Could not load Lato"); + +const exporter = new DOCXExporter(editor.schema, docxDefaultSchemaMappings, { + fontFamily: "Lato", + fonts: [{ name: "Lato", regular: await response.blob() }], +}); +``` + +Use static TrueType files that permit embedding, with one entry per family +and the name declared in the files. Each face accepts a `Blob` (including +`File`), `ArrayBuffer`, or `Uint8Array`. Add `bold`, `italic`, and +`boldItalic` when available. A supplied list replaces all bundled faces, +including the code font; use `fonts: []` to embed none. + +To use a font installed on the reader's machine without embedding it, set +its family name (for example, `fontFamily: "Marianne"`). For WOFF or WOFF2, +[unpack it once at build time](/docs/features/export/pdf#unpacking-webfonts) +and pass the resulting static `.ttf` file to `fonts`. If the result is +CFF/OpenType, use the installed family or obtain a static TrueType version. + +An unreadable file or unsupported format rejects the export with a +`FontEmbeddingError`. Use the family and face in the error to identify +which file to replace before retrying. + +If you supply `documentOptions.fonts` or `documentOptions.externalStyles` +when exporting, those override the corresponding generated values. diff --git a/docs/content/docs/features/export/odt.mdx b/docs/content/docs/features/export/odt.mdx index b5c35fc243..084d601b8a 100644 --- a/docs/content/docs/features/export/odt.mdx +++ b/docs/content/docs/features/export/odt.mdx @@ -107,3 +107,39 @@ const defaultOptions = { colors: COLORS_DEFAULT, // defaults from @blocknote/core }; ``` + +### Fonts + +ODT embeds Inter 18pt for body text and Geist Mono for code by default. +Set `fontFamily` or `monoFontFamily` to change the default body or code font. +The ODT template keeps its script-specific fonts for East Asian and complex +scripts, such as Arabic. To use a custom +family on devices where it isn't installed, embed it with `fonts`: + +```typescript +import { ODTExporter, odtDefaultSchemaMappings } from "@blocknote/xl-odt-exporter"; + +const response = await fetch("/fonts/Lato-Regular.ttf"); +if (!response.ok) throw new Error("Could not load Lato"); + +const exporter = new ODTExporter(editor.schema, odtDefaultSchemaMappings, { + fontFamily: "Lato", + fonts: [{ name: "Lato", regular: await response.blob() }], +}); +``` + +Use static TrueType files that permit embedding, with one entry per family +and the name declared in the files. Each face accepts a `Blob` (including +`File`), `ArrayBuffer`, or `Uint8Array`. Add `bold`, `italic`, and +`boldItalic` when available. A supplied list replaces all bundled faces, +including the code font; use `fonts: []` to embed none. + +To use a font installed on the reader's machine without embedding it, set +its family name (for example, `fontFamily: "Marianne"`). For WOFF or WOFF2, +[unpack it once at build time](/docs/features/export/pdf#unpacking-webfonts) +and pass the resulting static `.ttf` file to `fonts`. For other outlines, +use the installed family or obtain a static TrueType version. + +An unreadable file or unsupported format rejects the export with a +`FontEmbeddingError`. Use the family and face in the error to identify +which file to replace before retrying. diff --git a/docs/content/docs/features/export/pdf.mdx b/docs/content/docs/features/export/pdf.mdx index fc577af1ca..d580c76acb 100644 --- a/docs/content/docs/features/export/pdf.mdx +++ b/docs/content/docs/features/export/pdf.mdx @@ -150,29 +150,32 @@ diagrams as embedded vector graphics. See ### Fonts -By default, exports use a bundled font set matching the editor: Inter -(body), Geist Mono (code), New Computer Modern Math (math), and Noto Color -Emoji. To use your own fonts instead, pass the font bytes and the matching -family names to the constructor: +PDF exports bundle Inter 18pt (body), Geist Mono (code), New Computer +Modern Math, and Noto Color Emoji. Set `fonts` to replace the body, code, +and math fonts. **Noto Color Emoji remains the fallback when you supply +custom fonts.** Omit `emojiFont` to keep it. To replace it, supply your +own emoji font file and set `emojiFontFamily` to the family name in that +file. To disable the emoji fallback, set `emojiFont: []` and +`emojiFontFamily: undefined`. Set `fonts: []` to skip the bundled body, +code, and math fonts. ```typescript const exporter = new PDFExporter(editor.schema, typstDefaultSchemaMappings, { fontFamily: "My Font", monoFontFamily: "My Mono Font", - // Uint8Array[], or a promise of them - fonts: [myFontBytes, myMonoFontBytes], - // An emoji-capable font; replaces the default independently of `fonts` - emojiFont: myEmojiFontBytes, + fonts: [myFontBlob, myMonoFontBlob], }); ``` -Typst selects fonts by the family name embedded in the font file itself, so -the `fontFamily` options must match what your files declare. A mismatch -shows up as an `unknown font family` entry in the result's -`compileWarnings`. +Use the family names declared in the files. Typst reports unknown names +in `compileWarnings`. Pass TTF, OTF, or TTC files as `Blob` (including +`File`), `ArrayBuffer`, or `Uint8Array`. Unsupported or unreadable files +produce a `compileErrors` entry with the file's position in the body or +emoji list (starting at 1), so you can replace the offending file before +retrying. If you only have WOFF or WOFF2 files, see +[Unpacking webfonts](#unpacking-webfonts). -To extend the defaults rather than replace them (e.g. adding a CJK font as -a per-glyph fallback), spread the exported default loaders: +To add a fallback font alongside the defaults, use `loadDefaultBodyFonts()`: ```typescript import { @@ -188,6 +191,59 @@ const exporter = new PDFExporter(editor.schema, typstDefaultSchemaMappings, { }); ``` +#### Unpacking webfonts + +Use the original desktop font if available. If you only have webfonts and +know which ones you need before deployment, **decode them once at build +time**. Then pass the unpacked files to the exporters for embedding. This +saves each browser from repeating the conversion. Use static `.ttf` files +for fonts shared across PDF, DOCX, and ODT, and check that the font license +allows unpacking and embedding. + +On Node.js 22.12 or later, save this script as `unpack-font.mjs` and run +`node unpack-font.mjs Font-Regular.woff2`: + +```js +import { readFile, writeFile } from "node:fs/promises"; +import { decodeWebFont } from "@blocknote/xl-pdf-exporter/font"; + +const source = process.argv[2]; +const result = await decodeWebFont(await readFile(source)); +if (result.error !== undefined) { + throw new Error(`Could not unpack ${source}: ${result.error}`); +} +await writeFile( + `${source.replace(/\.woff2?$/i, "")}.${result.extension}`, + result.bytes, +); +``` + +The script accepts either `.woff` or `.woff2`. Repeat for each face you +need. Unpacking preserves the outlines: the result is `.ttf` or `.otf`. +PDF accepts either; DOCX and ODT embedding require static TrueType. + +For fonts selected at runtime, such as a user upload, the same opt-in +helper runs in the browser. It detects the format from the bytes and +accepts a `Blob` (including `File`), `ArrayBuffer`, or `Uint8Array`: + +```typescript +import { decodeWebFont } from "@blocknote/xl-pdf-exporter/font"; + +const result = await decodeWebFont(uploadedFile); +if (result.error !== undefined) { + throw new Error(`Could not unpack the font: ${result.error}`); +} +// Pass result.bytes to the exporter's fonts option. +``` + +WOFF uses the runtime's `DecompressionStream` API (Chrome 80+, +Firefox 113+, Safari 16.4+, or Node.js 18+). WOFF2 loads a WebAssembly +decoder on demand and requires Node.js 22.12+ on the server. If your +browser's Content Security Policy blocks WebAssembly or runtime JavaScript +generation, WOFF2 decoding returns `unsupported-runtime`. Use the build-time +approach for known fonts in that case. The helper limits both input and +unpacked output to 30 MiB. + ### Self-hosting the compiler The Typst compiler is a ~25MB wasm file from `@blocknote/xl-typst-compiler`, @@ -217,12 +273,9 @@ const defaultOptions = { dictionary: locales.en, // the colors used for highlighting, background colors and font colors colors: COLORS_DEFAULT, // defaults from @blocknote/core - // font families (DEFAULT_FONT_FAMILY / DEFAULT_MONO_FONT_FAMILY) and the - // font bytes they resolve against - see "Fonts" above + // font families; omit fonts and emojiFont to use the bundled files fontFamily: "Inter 18pt", monoFontFamily: "Geist Mono", - fonts: loadDefaultBodyFonts(), - emojiFont: loadDefaultEmojiFont(), // base font size in points fontSize: 12, // where the compiler wasm loads from - see "Self-hosting the compiler" diff --git a/packages/math-block/src/odt-exporter/__snapshots__/withMathMappings/content.xml b/packages/math-block/src/odt-exporter/__snapshots__/withMathMappings/content.xml index aefe0cdde9..757d370e95 100644 --- a/packages/math-block/src/odt-exporter/__snapshots__/withMathMappings/content.xml +++ b/packages/math-block/src/odt-exporter/__snapshots__/withMathMappings/content.xml @@ -1,13 +1,22 @@ - + + + + + + + + + + - + diff --git a/packages/math-block/src/odt-exporter/__snapshots__/withMathMappings/styles.xml b/packages/math-block/src/odt-exporter/__snapshots__/withMathMappings/styles.xml index 9a53dac929..dffec4b3f0 100644 --- a/packages/math-block/src/odt-exporter/__snapshots__/withMathMappings/styles.xml +++ b/packages/math-block/src/odt-exporter/__snapshots__/withMathMappings/styles.xml @@ -1,8 +1,29 @@ - - + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/xl-docx-exporter/package.json b/packages/xl-docx-exporter/package.json index ae9764083f..60270ef412 100644 --- a/packages/xl-docx-exporter/package.json +++ b/packages/xl-docx-exporter/package.json @@ -69,7 +69,7 @@ "@blocknote/core": "workspace:^", "@blocknote/xl-multi-column": "workspace:^", "buffer": "^6.0.3", - "docx": "^9.9.0", + "docx": "^9.10.0", "image-meta": "^0.2.2" }, "devDependencies": { diff --git a/packages/xl-docx-exporter/src/docx/__snapshots__/basic/styles-docx-9.14.xml b/packages/xl-docx-exporter/src/docx/__snapshots__/basic/styles-docx-9.14.xml index 14f7bdaa59..8196bc6203 100644 --- a/packages/xl-docx-exporter/src/docx/__snapshots__/basic/styles-docx-9.14.xml +++ b/packages/xl-docx-exporter/src/docx/__snapshots__/basic/styles-docx-9.14.xml @@ -609,7 +609,7 @@ - + @@ -806,7 +806,7 @@ - + @@ -1171,7 +1171,7 @@ - + diff --git a/packages/xl-docx-exporter/src/docx/__snapshots__/basic/styles.xml b/packages/xl-docx-exporter/src/docx/__snapshots__/basic/styles.xml index f9b7074174..a5464f70de 100644 --- a/packages/xl-docx-exporter/src/docx/__snapshots__/basic/styles.xml +++ b/packages/xl-docx-exporter/src/docx/__snapshots__/basic/styles.xml @@ -488,7 +488,7 @@ - + @@ -685,7 +685,7 @@ - + @@ -1050,7 +1050,7 @@ - + diff --git a/packages/xl-docx-exporter/src/docx/__snapshots__/noLocale/styles-docx-9.14.xml b/packages/xl-docx-exporter/src/docx/__snapshots__/noLocale/styles-docx-9.14.xml index 91565e2463..43e1e7880a 100644 --- a/packages/xl-docx-exporter/src/docx/__snapshots__/noLocale/styles-docx-9.14.xml +++ b/packages/xl-docx-exporter/src/docx/__snapshots__/noLocale/styles-docx-9.14.xml @@ -608,7 +608,7 @@ - + @@ -805,7 +805,7 @@ - + @@ -1170,7 +1170,7 @@ - + diff --git a/packages/xl-docx-exporter/src/docx/__snapshots__/noLocale/styles.xml b/packages/xl-docx-exporter/src/docx/__snapshots__/noLocale/styles.xml index 04604055f1..ede2d0360d 100644 --- a/packages/xl-docx-exporter/src/docx/__snapshots__/noLocale/styles.xml +++ b/packages/xl-docx-exporter/src/docx/__snapshots__/noLocale/styles.xml @@ -487,7 +487,7 @@ - + @@ -684,7 +684,7 @@ - + @@ -1049,7 +1049,7 @@ - + diff --git a/packages/xl-docx-exporter/src/docx/__snapshots__/withLocale/styles-docx-9.14.xml b/packages/xl-docx-exporter/src/docx/__snapshots__/withLocale/styles-docx-9.14.xml index f914617f6c..d524f35f90 100644 --- a/packages/xl-docx-exporter/src/docx/__snapshots__/withLocale/styles-docx-9.14.xml +++ b/packages/xl-docx-exporter/src/docx/__snapshots__/withLocale/styles-docx-9.14.xml @@ -609,7 +609,7 @@ - + @@ -806,7 +806,7 @@ - + @@ -1171,7 +1171,7 @@ - + diff --git a/packages/xl-docx-exporter/src/docx/__snapshots__/withLocale/styles.xml b/packages/xl-docx-exporter/src/docx/__snapshots__/withLocale/styles.xml index 84f5cd9fd4..a262c031c3 100644 --- a/packages/xl-docx-exporter/src/docx/__snapshots__/withLocale/styles.xml +++ b/packages/xl-docx-exporter/src/docx/__snapshots__/withLocale/styles.xml @@ -488,7 +488,7 @@ - + @@ -685,7 +685,7 @@ - + @@ -1050,7 +1050,7 @@ - + diff --git a/packages/xl-docx-exporter/src/docx/docxExporter.test.ts b/packages/xl-docx-exporter/src/docx/docxExporter.test.ts index f6ce9b0539..0f9b62207e 100644 --- a/packages/xl-docx-exporter/src/docx/docxExporter.test.ts +++ b/packages/xl-docx-exporter/src/docx/docxExporter.test.ts @@ -6,7 +6,9 @@ import { PartialBlock, } from "@blocknote/core"; import { de } from "@blocknote/core/locales"; +import { readFileSync } from "node:fs"; import { testDocument } from "../../../../tests/src/fixtures/exporters/testDocument.js"; +import { unreadableFontBlob } from "../../../../tests/src/fixtures/exporters/unreadableFont.js"; import { BlobReader, Entry, @@ -61,6 +63,60 @@ function getZIPEntryContent(entries: Entry[], fileName: string) { } describe("exporter", () => { + it("rejects a TrueType table that points past the font file", async () => { + const regular = readFileSync( + new URL( + "../../../../shared/assets/fonts/GeistMono-Regular.ttf", + import.meta.url, + ), + ); + regular.writeUInt32BE(regular.length + 4, 20); + const exporter = new DOCXExporter(schema, docxDefaultSchemaMappings, { + fonts: [{ name: "Geist Mono", regular }], + }); + await expect(exporter.toBlob([])).rejects.toThrow( + "Invalid TrueType table directory.", + ); + }); + + it("identifies an unreadable face in the export error", async () => { + const regular = await unreadableFontBlob(); + const exporter = new DOCXExporter(schema, docxDefaultSchemaMappings, { + fonts: [{ name: "Marianne", regular }], + }); + await expect(exporter.toBlob([])).rejects.toMatchObject({ + name: "FontEmbeddingError", + family: "Marianne", + face: "regular", + message: expect.stringContaining("Could not read the font file."), + }); + }); + + it("rejects duplicate custom font families before reading their faces", async () => { + const font = { name: "Marianne", regular: new Blob([]) }; + const exporter = new DOCXExporter(schema, docxDefaultSchemaMappings, { + fonts: [font, font], + }); + await expect(exporter.toBlob([])).rejects.toThrow( + 'duplicate font family "Marianne"', + ); + }); + + it("fails export when a supplied face is a webfont", async () => { + const exporter = new DOCXExporter(schema, docxDefaultSchemaMappings, { + fonts: [ + { name: "Marianne", regular: new Blob(["wOF2"], { type: "font/ttf" }) }, + ], + }); + await expect(exporter.toBlob([])).rejects.toMatchObject({ + name: "FontEmbeddingError", + message: expect.stringContaining("Marianne regular: WOFF2"), + }); + await expect(exporter.toBlob([], xmlOnlyOptions)).resolves.toBeInstanceOf( + Blob, + ); + }); + it( "should export a document", { timeout: 10000 }, @@ -80,6 +136,21 @@ describe("exporter", () => { const zip = new ZipReader(new BlobReader(blob)); const entries = await zip.getEntries(); + const fontTable = await getZIPEntryContent(entries, "word/fontTable.xml"); + const inter = fontTable.match( + /.*?<\/w:font>/, + )?.[0]; + for (const variant of ["Regular", "Bold", "Italic", "BoldItalic"]) { + expect(inter).toContain(`.*?<\/w:font>/, + )?.[0]; + expect(geist).toContain(" entry.filename.endsWith(".odttf")), + ).toHaveLength(5); + await expect( prettify(await getZIPEntryContent(entries, "word/document.xml")), ).toMatchFileSnapshot("__snapshots__/basic/document.xml"); @@ -89,6 +160,50 @@ describe("exporter", () => { }, ); + it.each(["blob", "arrayBuffer", "uint8Array"] as const)( + "selects installed families independently of embedded families supplied as %s", + async (source) => { + const geist = new Uint8Array( + readFileSync( + new URL( + "../../../../shared/assets/fonts/GeistMono-Regular.ttf", + import.meta.url, + ), + ), + ); + const exporter = new DOCXExporter(schema, docxDefaultSchemaMappings, { + fontFamily: "Geist Mono", + monoFontFamily: "Code & Mono", + fonts: [ + { + name: "Geist Mono", + regular: { + blob: new Blob([geist]), + arrayBuffer: geist.buffer, + uint8Array: geist, + }[source], + }, + ], + }); + const zip = new ZipReader(new BlobReader(await exporter.toBlob([]))); + try { + const entries = await zip.getEntries(); + const styles = await getZIPEntryContent(entries, "word/styles.xml"); + const fonts = await getZIPEntryContent(entries, "word/fontTable.xml"); + expect(styles).toContain('w:ascii="Geist Mono"'); + expect(styles).toContain('w:ascii="Code & Mono"'); + expect(fonts).not.toContain("Code & Mono"); + expect(fonts).not.toContain("Inter 18pt"); + expect( + entries.filter((entry) => entry.filename.endsWith(".odttf")), + ).toHaveLength(1); + expect(fonts.match(//g)).toHaveLength(1); + } finally { + await zip.close(); + } + }, + ); + it("should resolve distinct and repeated images to their original bytes in drawing order", async ({ partialBlocksToBlocksForTesting, }) => { diff --git a/packages/xl-docx-exporter/src/docx/docxExporter.ts b/packages/xl-docx-exporter/src/docx/docxExporter.ts index c1e722f8e7..c3922e7ab7 100644 --- a/packages/xl-docx-exporter/src/docx/docxExporter.ts +++ b/packages/xl-docx-exporter/src/docx/docxExporter.ts @@ -26,6 +26,11 @@ import { Exporter, ExporterOptions } from "@blocknote/core"; import { corsProxyResolveFileUrl } from "../corsProxy.js"; import { loadFileBuffer } from "../fontFile.js"; import { docxBlockMappingForDefaultSchema } from "./defaultSchema/blocks.js"; +import { + type FontSource, + readFontBytes, + readTrueTypeFace, +} from "./fontSource.js"; import { clampListLevel, DOCX_LIST_LEVEL_COUNT, @@ -40,6 +45,27 @@ import { // get constructor arg type from Document type DocumentOptions = Partial[0]>; + +/** Static TrueType faces that may be embedded in the document. */ +export type DocxFont = { + name: string; + regular: FontSource; + bold?: FontSource; + italic?: FontSource; + boldItalic?: FontSource; +}; + +export type DocxExporterOptions = Partial & { + /** Body family in BlockNote's styles. Defaults to Inter 18pt. */ + fontFamily?: string; + /** Code family in BlockNote's styles. Defaults to Geist Mono. */ + monoFontFamily?: string; + /** Families to embed instead of the bundled set. Names must be unique. */ + fonts?: readonly DocxFont[]; +}; + +const defaultBodyFamily = "Inter 18pt"; +const defaultMonoFamily = "Geist Mono"; type ListType = "bulletListItem" | "numberedListItem"; type ListDefinition = { type: ListType; @@ -75,6 +101,10 @@ export class DOCXExporter< IRunPropertiesOptions, TextRun > { + private readonly fontFamily: string; + private readonly monoFontFamily: string; + private readonly fonts: readonly DocxFont[] | undefined; + public constructor( /** * The schema of your editor. The mappings are automatically typed checked against this schema. @@ -93,18 +123,19 @@ export class DOCXExporter< IRunPropertiesOptions, TextRun >["mappings"], - options?: Partial, + options?: DocxExporterOptions, ) { const defaults = { colors: COLORS_DEFAULT, resolveFileUrl: corsProxyResolveFileUrl, } satisfies Partial; - const newOptions = { - ...defaults, - ...options, - }; - super(schema, mappings, newOptions); + const { fontFamily, monoFontFamily, fonts, ...exporterOptions } = + options ?? {}; + super(schema, mappings, { ...defaults, ...exporterOptions }); + this.fontFamily = fontFamily ?? defaultBodyFamily; + this.monoFontFamily = monoFontFamily ?? defaultMonoFamily; + this.fonts = fonts; } /** @@ -274,43 +305,65 @@ export class DOCXExporter< } protected async getFonts(): Promise { - // Unfortunately, loading the variable font doesn't work - // "./src/fonts/Inter-VariableFont_opsz,wght.ttf", - - const interFont = await loadFileBuffer( - await import("../../../../shared/assets/fonts/inter/Inter_18pt-Regular.ttf"), - ); - const geistMonoFont = await loadFileBuffer( - await import("../../../../shared/assets/fonts/GeistMono-Regular.ttf"), - ); - // `docx` requires each font's `data` to be a Node `Buffer`. We derive the - // exact expected type from `docx` itself (rather than referencing the - // global `Buffer` type, which isn't available in this package's tsconfig). + // type from docx because the browser Buffer polyfill has separate typings. type FontData = NonNullable[number]["data"]; + async function toFontData(font: FontSource): Promise { + const bytes = await readFontBytes(font); + const buffer = + globalThis.Buffer ?? (await import("buffer/index.js")).Buffer; + return buffer.from(bytes) as unknown as FontData; + } + async function customFace( + font: DocxFont, + face: keyof Omit, + source: FontSource, + ): Promise { + return toFontData(await readTrueTypeFace(source, font.name, face)); + } + async function load(module: Promise<{ default: string }>) { + return toFontData(await loadFileBuffer(await module)); + } - // In the browser `loadFileBuffer` resolves to an `ArrayBuffer`, which - // `docx` doesn't accept, so we convert it to a `Buffer` using the `buffer/` - // polyfill. In Node it's already a `Buffer` and can be used as-is. - // NOTE: the buffer/ import is intentional and as documented in the `buffer` - // package usage instructions: - // https://github.com/feross/buffer?tab=readme-ov-file#usage - const toFontData = async ( - font: Awaited>, - ): Promise => { - if (font instanceof ArrayBuffer) { - const BufferPolyfill = (await import("buffer/")).Buffer; - return BufferPolyfill.from(font) as unknown as FontData; + if (this.fonts !== undefined) { + const names = new Set(); + for (const { name } of this.fonts) { + if (names.has(name)) { + throw new Error( + `DOCX: duplicate font family "${name}". Provide one entry per family.`, + ); + } + names.add(name); } - return font as unknown as FontData; - }; + return Promise.all( + this.fonts.map(async (font) => { + const [data, bold, italic, boldItalic] = await Promise.all([ + customFace(font, "regular", font.regular), + font.bold && customFace(font, "bold", font.bold), + font.italic && customFace(font, "italic", font.italic), + font.boldItalic && customFace(font, "boldItalic", font.boldItalic), + ]); + return { name: font.name, data, bold, italic, boldItalic }; + }), + ); + } + const [data, bold, italic, boldItalic, mono] = await Promise.all([ + load( + import("../../../../shared/assets/fonts/inter/Inter_18pt-Regular.ttf"), + ), + load(import("../../../../shared/assets/fonts/inter/Inter_18pt-Bold.ttf")), + load( + import("../../../../shared/assets/fonts/inter/Inter_18pt-Italic.ttf"), + ), + load( + import("../../../../shared/assets/fonts/inter/Inter_18pt-BoldItalic.ttf"), + ), + load(import("../../../../shared/assets/fonts/GeistMono-Regular.ttf")), + ]); return [ - { name: "Inter", data: await toFontData(interFont) }, - { - name: "GeistMono", - data: await toFontData(geistMonoFont), - }, + { name: defaultBodyFamily, data, bold, italic, boldItalic }, + { name: defaultMonoFamily, data: mono }, ]; } @@ -322,10 +375,26 @@ export class DOCXExporter< protected async createDefaultDocumentOptions( locale?: string, listDefinitions = new Map(), + includeFonts = true, ): Promise { let externalStyles = (await import("./template/word/styles.xml?raw")) .default; + // Change only the font slots in the bundled styles. Caller-supplied XML + // still takes precedence when the document options are merged. + externalStyles = externalStyles.replace( + /\b(w:ascii|w:cs|w:eastAsia|w:hAnsi)="(Inter|GeistMono)"/g, + (_match, attribute, family) => { + const name = family === "Inter" ? this.fontFamily : this.monoFontFamily; + const escaped = name + .replaceAll("&", "&") + .replaceAll('"', """) + .replaceAll("<", "<") + .replaceAll(">", ">"); + return `${attribute}="${escaped}"`; + }, + ); + // Replace the language in styles.xml with the provided locale, or remove // the w:lang element entirely if no locale is provided (per ECMA-376 // ยง17.3.2.20: omitting w:lang lets the application auto-detect language). @@ -392,7 +461,7 @@ export class DOCXExporter< })), ], }, - fonts: await this.getFonts(), + fonts: includeFonts ? await this.getFonts() : undefined, defaultTabStop: 200, externalStyles, }; @@ -417,18 +486,18 @@ export class DOCXExporter< }, ) { const doc = await this.toDocxJsDocument(blocks, options); - type GlobalThis = typeof globalThis & { Buffer?: any }; - const prevBuffer = (globalThis as GlobalThis).Buffer; + const globals: { Buffer?: typeof Buffer } = globalThis; + if (globals.Buffer) { + return Packer.toBlob(doc); + } + const { Buffer: buffer } = await import("buffer/index.js"); + const prevBuffer = globals.Buffer; try { - if (!(globalThis as GlobalThis).Buffer) { - // load Buffer polyfill because docxjs requires this - (globalThis as GlobalThis).Buffer = ( - await import("buffer") - ).default.Buffer; - } + // docxjs also accesses Buffer as a global. + globals.Buffer ??= buffer as unknown as typeof Buffer; return Packer.toBlob(doc); } finally { - (globalThis as GlobalThis).Buffer = prevBuffer; + globals.Buffer = prevBuffer; } } @@ -458,6 +527,7 @@ export class DOCXExporter< ...(await this.createDefaultDocumentOptions( options.locale, listDefinitions, + !Object.hasOwn(options.documentOptions, "fonts"), )), ...options.documentOptions, sections: [ diff --git a/packages/xl-docx-exporter/src/docx/fontSource.ts b/packages/xl-docx-exporter/src/docx/fontSource.ts new file mode 100644 index 0000000000..ba982996ea --- /dev/null +++ b/packages/xl-docx-exporter/src/docx/fontSource.ts @@ -0,0 +1,109 @@ +/** An already-loaded font file. Accepts browser File and Node Buffer. */ +export type FontSource = Blob | ArrayBuffer | Uint8Array; + +/** A supplied face could not be embedded in the DOCX. */ +export class FontEmbeddingError extends Error { + public readonly exporter = "DOCX"; + + constructor( + public readonly family: string, + public readonly face: "regular" | "bold" | "italic" | "boldItalic", + reason: string, + options?: ErrorOptions, + ) { + super( + `DOCX: ${family} ${face}: ${reason} Supply a static TrueType font file.`, + options, + ); + this.name = "FontEmbeddingError"; + } +} + +export async function readFontBytes(source: FontSource): Promise { + const data = "arrayBuffer" in source ? await source.arrayBuffer() : source; + return ArrayBuffer.isView(data) ? data : new Uint8Array(data); +} + +export async function readTrueTypeFace( + source: FontSource, + family: string, + face: FontEmbeddingError["face"], +): Promise { + let bytes: Uint8Array; + try { + bytes = await readFontBytes(source); + } catch (error) { + if ( + typeof error !== "object" || + error === null || + !("name" in error) || + (error.name !== "NotReadableError" && + error.name !== "NotFoundError" && + error.name !== "SecurityError") + ) { + throw error; + } + throw new FontEmbeddingError( + family, + face, + "Could not read the font file.", + { + cause: error, + }, + ); + } + const signature = String.fromCharCode(...bytes.subarray(0, 4)); + switch (signature) { + case "\0\x01\0\0": + case "true": + break; + case "wOFF": + throw new FontEmbeddingError(family, face, "WOFF is not supported."); + case "wOF2": + throw new FontEmbeddingError(family, face, "WOFF2 is not supported."); + default: + throw new FontEmbeddingError(family, face, "Expected a TrueType font."); + } + + // Only inspect the sfnt directory to identify a static TrueType face. + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const tableCount = view.byteLength >= 12 ? view.getUint16(4) : 0; + const directoryEnd = 12 + tableCount * 16; + if (tableCount === 0 || directoryEnd > view.byteLength) { + throw new FontEmbeddingError( + family, + face, + "Invalid TrueType table directory.", + ); + } + const tags = new Set(); + for (let entry = 12; entry < directoryEnd; entry += 16) { + const offset = view.getUint32(entry + 8); + const size = view.getUint32(entry + 12); + if (offset < directoryEnd || offset + size > view.byteLength) { + throw new FontEmbeddingError( + family, + face, + "Invalid TrueType table directory.", + ); + } + tags.add(view.getUint32(entry)); + } + if (tags.has(0x66766172)) { + // fvar + throw new FontEmbeddingError( + family, + face, + "Variable fonts are not supported.", + ); + } + if (!tags.has(0x676c7966) || !tags.has(0x6c6f6361)) { + // glyf, loca + throw new FontEmbeddingError( + family, + face, + "Missing TrueType outline tables.", + ); + } + return bytes; +} diff --git a/packages/xl-docx-exporter/src/docx/index.ts b/packages/xl-docx-exporter/src/docx/index.ts index aa57d877d6..12198c53f2 100644 --- a/packages/xl-docx-exporter/src/docx/index.ts +++ b/packages/xl-docx-exporter/src/docx/index.ts @@ -1,4 +1,5 @@ export * from "./defaultSchema/index.js"; export * from "./docxExporter.js"; +export { FontEmbeddingError, type FontSource } from "./fontSource.js"; export { createDOCXParagraph } from "./mapping.js"; export type { DOCXBlock, DOCXBlockResult, DOCXColumn } from "./mapping.js"; diff --git a/packages/xl-odt-exporter/src/odt/__snapshots__/basic/content.xml b/packages/xl-odt-exporter/src/odt/__snapshots__/basic/content.xml index 84f4d521d3..e4a0991632 100644 --- a/packages/xl-odt-exporter/src/odt/__snapshots__/basic/content.xml +++ b/packages/xl-odt-exporter/src/odt/__snapshots__/basic/content.xml @@ -1,13 +1,22 @@ - + + + + + + + + + + - + @@ -83,7 +92,7 @@ - + diff --git a/packages/xl-odt-exporter/src/odt/__snapshots__/basic/styles.xml b/packages/xl-odt-exporter/src/odt/__snapshots__/basic/styles.xml index 9a53dac929..dffec4b3f0 100644 --- a/packages/xl-odt-exporter/src/odt/__snapshots__/basic/styles.xml +++ b/packages/xl-odt-exporter/src/odt/__snapshots__/basic/styles.xml @@ -1,8 +1,29 @@ - - + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/xl-odt-exporter/src/odt/__snapshots__/withCustomOptions/content.xml b/packages/xl-odt-exporter/src/odt/__snapshots__/withCustomOptions/content.xml index 5ccd11b60c..7826f20eba 100644 --- a/packages/xl-odt-exporter/src/odt/__snapshots__/withCustomOptions/content.xml +++ b/packages/xl-odt-exporter/src/odt/__snapshots__/withCustomOptions/content.xml @@ -1,13 +1,22 @@ - + + + + + + + + + + - + @@ -83,7 +92,7 @@ - + diff --git a/packages/xl-odt-exporter/src/odt/__snapshots__/withCustomOptions/styles.xml b/packages/xl-odt-exporter/src/odt/__snapshots__/withCustomOptions/styles.xml index 9a53dac929..dffec4b3f0 100644 --- a/packages/xl-odt-exporter/src/odt/__snapshots__/withCustomOptions/styles.xml +++ b/packages/xl-odt-exporter/src/odt/__snapshots__/withCustomOptions/styles.xml @@ -1,8 +1,29 @@ - - + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/xl-odt-exporter/src/odt/defaultSchema/styles.ts b/packages/xl-odt-exporter/src/odt/defaultSchema/styles.ts index a875e798c7..93732aea99 100644 --- a/packages/xl-odt-exporter/src/odt/defaultSchema/styles.ts +++ b/packages/xl-odt-exporter/src/odt/defaultSchema/styles.ts @@ -1,4 +1,5 @@ import { DefaultStyleSchema, StyleMapping } from "@blocknote/core"; +import { ODTExporter } from "../odtExporter.js"; export const odtStyleMappingForDefaultSchema: StyleMapping< DefaultStyleSchema, Record @@ -53,10 +54,15 @@ export const odtStyleMappingForDefaultSchema: StyleMapping< return { "fo:background-color": color }; }, - code: (val): Record => { + code: (val, exporter): Record => { if (!val) { return {}; } - return { "style:font-name": "Courier New" }; + return { + "style:font-name": + exporter instanceof ODTExporter + ? exporter.monoFontFamily + : "Courier New", + }; }, }; diff --git a/packages/xl-odt-exporter/src/odt/fontSource.ts b/packages/xl-odt-exporter/src/odt/fontSource.ts new file mode 100644 index 0000000000..7788ef45c4 --- /dev/null +++ b/packages/xl-odt-exporter/src/odt/fontSource.ts @@ -0,0 +1,105 @@ +/** An already-loaded font file. Accepts browser File and Node Buffer. */ +export type FontSource = Blob | ArrayBuffer | Uint8Array; + +/** A supplied face could not be embedded in the ODT. */ +export class FontEmbeddingError extends Error { + public readonly exporter = "ODT"; + + constructor( + public readonly family: string, + public readonly face: "regular" | "bold" | "italic" | "boldItalic", + reason: string, + options?: ErrorOptions, + ) { + super( + `ODT: ${family} ${face}: ${reason} Supply a static TrueType font file.`, + options, + ); + this.name = "FontEmbeddingError"; + } +} + +export async function readTrueTypeFace( + source: FontSource, + family: string, + face: FontEmbeddingError["face"], +): Promise { + let data: ArrayBuffer | Uint8Array; + try { + data = "arrayBuffer" in source ? await source.arrayBuffer() : source; + } catch (error) { + if ( + typeof error !== "object" || + error === null || + !("name" in error) || + (error.name !== "NotReadableError" && + error.name !== "NotFoundError" && + error.name !== "SecurityError") + ) { + throw error; + } + throw new FontEmbeddingError( + family, + face, + "Could not read the font file.", + { + cause: error, + }, + ); + } + const bytes = ArrayBuffer.isView(data) ? data : new Uint8Array(data); + const signature = String.fromCharCode(...bytes.subarray(0, 4)); + switch (signature) { + case "\0\x01\0\0": + case "true": + break; + case "wOFF": + throw new FontEmbeddingError(family, face, "WOFF is not supported."); + case "wOF2": + throw new FontEmbeddingError(family, face, "WOFF2 is not supported."); + default: + throw new FontEmbeddingError(family, face, "Expected a TrueType font."); + } + + // Only inspect the sfnt directory to identify a static TrueType face. + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const tableCount = view.byteLength >= 12 ? view.getUint16(4) : 0; + const directoryEnd = 12 + tableCount * 16; + if (tableCount === 0 || directoryEnd > view.byteLength) { + throw new FontEmbeddingError( + family, + face, + "Invalid TrueType table directory.", + ); + } + const tags = new Set(); + for (let entry = 12; entry < directoryEnd; entry += 16) { + const offset = view.getUint32(entry + 8); + const size = view.getUint32(entry + 12); + if (offset < directoryEnd || offset + size > view.byteLength) { + throw new FontEmbeddingError( + family, + face, + "Invalid TrueType table directory.", + ); + } + tags.add(view.getUint32(entry)); + } + if (tags.has(0x66766172)) { + // fvar + throw new FontEmbeddingError( + family, + face, + "Variable fonts are not supported.", + ); + } + if (!tags.has(0x676c7966) || !tags.has(0x6c6f6361)) { + // glyf, loca + throw new FontEmbeddingError( + family, + face, + "Missing TrueType outline tables.", + ); + } + return bytes; +} diff --git a/packages/xl-odt-exporter/src/odt/index.ts b/packages/xl-odt-exporter/src/odt/index.ts index f4a1c2c0c4..c1cf3ca5a3 100644 --- a/packages/xl-odt-exporter/src/odt/index.ts +++ b/packages/xl-odt-exporter/src/odt/index.ts @@ -1,3 +1,4 @@ export * from "./defaultSchema/index.js"; export * from "./odtExporter.js"; +export { FontEmbeddingError, type FontSource } from "./fontSource.js"; export * from "./util/createODTImageParagraph.js"; diff --git a/packages/xl-odt-exporter/src/odt/odtExporter.test.ts b/packages/xl-odt-exporter/src/odt/odtExporter.test.ts index 866cf6b76c..1bdee2681e 100644 --- a/packages/xl-odt-exporter/src/odt/odtExporter.test.ts +++ b/packages/xl-odt-exporter/src/odt/odtExporter.test.ts @@ -4,17 +4,139 @@ import { defaultBlockSpecs, } from "@blocknote/core"; import { testDocument } from "../../../../tests/src/fixtures/exporters/testDocument.js"; +import { unreadableFontBlob } from "../../../../tests/src/fixtures/exporters/unreadableFont.js"; import { describe, expect } from "vite-plus/test"; import { createElement } from "react"; import { odtDefaultSchemaMappings } from "./defaultSchema/index.js"; import { ODTExporter } from "./odtExporter.js"; import { ColumnBlock, ColumnListBlock } from "@blocknote/xl-multi-column"; +import { + BlobReader, + type Entry, + TextWriter, + Uint8ArrayWriter, + ZipReader, +} from "@zip.js/zip.js"; +import { readFileSync } from "node:fs"; + +const defaultSchema = BlockNoteSchema.create(); + +function getFile(entries: Entry[], name: string) { + const entry = entries.find((entry) => entry.filename === name); + if (!entry || entry.directory) { + throw new Error(`Missing ODT entry: ${name}`); + } + return entry; +} + +function getFontPaths(entries: Entry[]) { + return entries + .filter((entry) => !entry.directory && entry.filename.startsWith("Fonts/")) + .map((entry) => entry.filename); +} describe("exporter", () => { + it("rejects a TrueType table that points past the font file", async () => { + const regular = readFileSync( + new URL( + "../../../../shared/assets/fonts/GeistMono-Regular.ttf", + import.meta.url, + ), + ); + regular.writeUInt32BE(regular.length + 4, 20); + const exporter = new ODTExporter(defaultSchema, odtDefaultSchemaMappings, { + fonts: [{ name: "Geist Mono", regular }], + }); + await expect(exporter.toODTDocument([])).rejects.toThrow( + "Invalid TrueType table directory.", + ); + }); + + it("identifies an unreadable face in the export error", async () => { + const regular = await unreadableFontBlob(); + const exporter = new ODTExporter(defaultSchema, odtDefaultSchemaMappings, { + fonts: [{ name: "Marianne", regular }], + }); + await expect(exporter.toODTDocument([])).rejects.toMatchObject({ + name: "FontEmbeddingError", + family: "Marianne", + face: "regular", + message: expect.stringContaining("Could not read the font file."), + }); + }); + + it("rejects duplicate custom font families before reading their faces", async () => { + const font = { name: "Marianne", regular: new Blob([]) }; + const exporter = new ODTExporter(defaultSchema, odtDefaultSchemaMappings, { + fonts: [font, font], + }); + await expect(exporter.toODTDocument([])).rejects.toThrow( + 'duplicate font family "Marianne"', + ); + }); + + it("uses the configured monospace family for inline code and code blocks", async ({ + partialBlocksToBlocksForTesting, + }) => { + const exporter = new ODTExporter(defaultSchema, odtDefaultSchemaMappings, { + monoFontFamily: "Code & Mono", + fonts: [], + }); + const blob = await exporter.toODTDocument( + partialBlocksToBlocksForTesting(defaultSchema, [ + { + type: "paragraph", + content: [ + { type: "text", text: "inline code", styles: { code: true } }, + ], + }, + { type: "codeBlock", content: "block code" }, + ]), + ); + const zip = new ZipReader(new BlobReader(blob)); + try { + const entries = await zip.getEntries(); + const content = await getFile(entries, "content.xml").getData( + new TextWriter(), + ); + const styles = await getFile(entries, "styles.xml").getData( + new TextWriter(), + ); + expect(content).toMatch( + /block code', + ); + expect(styles).toMatch( + /]*style:font-name="Code & Mono"/, + ); + expect(getFontPaths(entries)).toEqual([]); + } finally { + await zip.close(); + } + }); + + it("fails export when a supplied face is a webfont", async () => { + const exporter = new ODTExporter(defaultSchema, odtDefaultSchemaMappings, { + fonts: [ + { name: "Marianne", regular: new Blob(["wOFF"], { type: "font/ttf" }) }, + ], + }); + await expect(exporter.toODTDocument([])).rejects.toMatchObject({ + name: "FontEmbeddingError", + message: expect.stringContaining("Marianne regular: WOFF"), + }); + }); + it( "should export a document", { timeout: 10000 }, - async ({ testResolveFileUrl, testODTDocumentAgainstSnapshot }) => { + async ({ + onTestFinished, + testResolveFileUrl, + testODTDocumentAgainstSnapshot, + }) => { const exporter = new ODTExporter( BlockNoteSchema.create({ blockSpecs: { @@ -28,6 +150,15 @@ describe("exporter", () => { { resolveFileUrl: testResolveFileUrl }, ); const odt = await exporter.toODTDocument(testDocument); + const zip = new ZipReader(new BlobReader(odt)); + onTestFinished(() => zip.close()); + expect(getFontPaths(await zip.getEntries()).sort()).toEqual([ + "Fonts/GeistMono-Regular.ttf", + "Fonts/Inter_18pt-Bold.ttf", + "Fonts/Inter_18pt-BoldItalic.ttf", + "Fonts/Inter_18pt-Italic.ttf", + "Fonts/Inter_18pt-Regular.ttf", + ]); await testODTDocumentAgainstSnapshot(odt, { styles: "__snapshots__/basic/styles.xml", content: "__snapshots__/basic/content.xml", @@ -35,6 +166,70 @@ describe("exporter", () => { }, ); + it.each(["blob", "arrayBuffer", "uint8Array"] as const)( + "selects families and embeds only the replacement faces supplied as %s", + async (source) => { + const geist = new Uint8Array( + readFileSync( + new URL( + "../../../../shared/assets/fonts/GeistMono-Regular.ttf", + import.meta.url, + ), + ), + ); + const exporter = new ODTExporter( + defaultSchema, + odtDefaultSchemaMappings, + { + fontFamily: "Geist Mono", + monoFontFamily: "Code & Mono", + fonts: [ + { + name: "Geist Mono", + regular: { + blob: new Blob([geist]), + arrayBuffer: geist.buffer, + uint8Array: geist, + }[source], + }, + ], + }, + ); + const zip = new ZipReader( + new BlobReader(await exporter.toODTDocument([])), + ); + try { + const entries = await zip.getEntries(); + const styles = await getFile(entries, "styles.xml").getData( + new TextWriter(), + ); + const content = await getFile(entries, "content.xml").getData( + new TextWriter(), + ); + const manifest = await getFile( + entries, + "META-INF/manifest.xml", + ).getData(new TextWriter()); + const fontPath = "Fonts/blocknote-0-regular.ttf"; + expect(styles).toContain('style:font-name="Geist Mono"'); + expect(styles).toContain('style:font-name="Code & Mono"'); + for (const xml of [styles, content]) { + expect(xml).toContain( + 'style:name="Code & Mono" svg:font-family="Code & Mono"', + ); + expect(xml).toContain(`xlink:href="${fontPath}"`); + } + expect(manifest).toContain(`manifest:full-path="${fontPath}"`); + expect( + await getFile(entries, fontPath).getData(new Uint8ArrayWriter()), + ).toEqual(geist); + expect(getFontPaths(entries)).toEqual([fontPath]); + } finally { + await zip.close(); + } + }, + ); + it("passes raw block and inline mapping results to custom mappings", async ({ partialBlocksToBlocksForTesting, }) => { diff --git a/packages/xl-odt-exporter/src/odt/odtExporter.tsx b/packages/xl-odt-exporter/src/odt/odtExporter.tsx index 867323e041..5899875a36 100644 --- a/packages/xl-odt-exporter/src/odt/odtExporter.tsx +++ b/packages/xl-odt-exporter/src/odt/odtExporter.tsx @@ -15,9 +15,56 @@ import { getImageDimensions } from "../imageDimensions.js"; import { BlobReader, BlobWriter, TextReader, ZipWriter } from "@zip.js/zip.js"; import { Fragment } from "react"; import { renderToString } from "react-dom/server"; +import { type FontSource, readTrueTypeFace } from "./fontSource.js"; import stylesXml from "./template/styles.xml?raw"; import { keyODTNodes } from "./util/keyODTNodes.js"; +/** Static TrueType faces that may be embedded in the document. */ +export type OdtFont = { + name: string; + regular: FontSource; + bold?: FontSource; + italic?: FontSource; + boldItalic?: FontSource; +}; + +export type OdtExporterOptions = Partial & { + /** Body family in BlockNote's styles. Defaults to Inter 18pt. */ + fontFamily?: string; + /** Code family in BlockNote's styles. Defaults to Geist Mono. */ + monoFontFamily?: string; + /** Families to embed instead of the bundled set. Names must be unique. */ + fonts?: readonly OdtFont[]; +}; + +type FontFace = { + name: string; + fileName: string; + data: Blob; + weight?: "normal" | "bold"; + style?: "normal" | "italic"; +}; + +const defaultBodyFamily = "Inter 18pt"; +const defaultMonoFamily = "Geist Mono"; +const fontVariants = { + regular: { weight: "normal", style: "normal" }, + bold: { weight: "bold", style: "normal" }, + italic: { weight: "normal", style: "italic" }, + boldItalic: { weight: "bold", style: "italic" }, +} as const satisfies Record< + keyof Omit, + Pick +>; + +function escapeFontName(name: string): string { + return name + .replaceAll("&", "&") + .replaceAll('"', """) + .replaceAll("<", "<") + .replaceAll(">", ">"); +} + export class ODTExporter< B extends BlockSchema, S extends StyleSchema, @@ -58,7 +105,9 @@ export class ODTExporter< private styleCounter = 0; private readonly registeredStyleNames = new Map(); - public readonly options: ExporterOptions; + private readonly fontFamily: string; + public readonly monoFontFamily: string; + private readonly fonts: readonly OdtFont[] | undefined; constructor( schema: BlockNoteSchema, @@ -71,7 +120,7 @@ export class ODTExporter< Record, React.ReactNode >["mappings"], - options?: Partial, + options?: OdtExporterOptions, ) { const defaults = { colors: COLORS_DEFAULT, @@ -80,30 +129,67 @@ export class ODTExporter< resolveFileUrl: corsProxyResolveFileUrl, } satisfies Partial; - super(schema, mappings, { ...defaults, ...options }); - this.options = { ...defaults, ...options }; + const { fontFamily, monoFontFamily, fonts, ...exporterOptions } = + options ?? {}; + super(schema, mappings, { ...defaults, ...exporterOptions }); + this.fontFamily = fontFamily ?? defaultBodyFamily; + this.monoFontFamily = monoFontFamily ?? defaultMonoFamily; + this.fonts = fonts; } - protected async loadFonts() { - const interFont = await loadFileBuffer( - await import("../../../../shared/assets/fonts/inter/Inter_18pt-Regular.ttf"), - ); - const geistMonoFont = await loadFileBuffer( - await import("../../../../shared/assets/fonts/GeistMono-Regular.ttf"), - ); + protected async loadFonts(): Promise { + async function load( + name: string, + fileName: string, + variant: keyof typeof fontVariants, + module: Promise<{ default: string }>, + ): Promise { + const data = await loadFileBuffer(await module); + return { + name, + fileName, + data: new Blob( + [data instanceof ArrayBuffer ? data : new Uint8Array(data)], + { + type: "font/ttf", + }, + ), + ...fontVariants[variant], + }; + } - return [ - { - name: "Inter 18pt", - fileName: "Inter_18pt-Regular.ttf", - data: new Blob([interFont as ArrayBuffer], { type: "font/ttf" }), - }, - { - name: "Geist Mono", - fileName: "GeistMono-Regular.ttf", - data: new Blob([geistMonoFont as ArrayBuffer], { type: "font/ttf" }), - }, - ]; + return Promise.all([ + load( + defaultBodyFamily, + "Inter_18pt-Regular.ttf", + "regular", + import("../../../../shared/assets/fonts/inter/Inter_18pt-Regular.ttf"), + ), + load( + defaultBodyFamily, + "Inter_18pt-Bold.ttf", + "bold", + import("../../../../shared/assets/fonts/inter/Inter_18pt-Bold.ttf"), + ), + load( + defaultBodyFamily, + "Inter_18pt-Italic.ttf", + "italic", + import("../../../../shared/assets/fonts/inter/Inter_18pt-Italic.ttf"), + ), + load( + defaultBodyFamily, + "Inter_18pt-BoldItalic.ttf", + "boldItalic", + import("../../../../shared/assets/fonts/inter/Inter_18pt-BoldItalic.ttf"), + ), + load( + defaultMonoFamily, + "GeistMono-Regular.ttf", + "regular", + import("../../../../shared/assets/fonts/GeistMono-Regular.ttf"), + ), + ]); } public transformStyledText(styledText: StyledText): React.ReactNode { @@ -203,12 +289,71 @@ export class ODTExporter< // Detect and remove XML namespaces (already defined in the root element) return stringifiedDoc.replace(xmlNamespacesRegEx, "<$1$2>"); }; + const customFonts = this.fonts ?? []; + const names = new Set(); + for (const { name } of customFonts) { + if (names.has(name)) { + throw new Error( + `ODT: duplicate font family "${name}". Provide one entry per family.`, + ); + } + names.add(name); + } + const fonts = this.fonts === undefined ? await this.loadFonts() : []; + for (const [index, font] of customFonts.entries()) { + for (const variant of [ + "regular", + "bold", + "italic", + "boldItalic", + ] as const) { + const data = font[variant]; + if (data) { + const bytes = await readTrueTypeFace(data, font.name, variant); + fonts.push({ + name: font.name, + fileName: `blocknote-${index}-${variant}.ttf`, + data: new Blob([new Uint8Array(bytes)], { type: "font/ttf" }), + ...fontVariants[variant], + }); + } + } + } const blockContent = keyODTNodes(await this.transformBlocks(blocks)); const styles = Array.from(this.automaticStyles, ([name, style]) => ( {style} )); const pictures = Array.from(this.pictures.values()); - const fonts = await this.loadFonts(); + const fontFamilies = new Map( + [this.fontFamily, this.monoFontFamily].map((name) => [name, []]), + ); + for (const font of fonts) { + const faces = fontFamilies.get(font.name); + if (faces) { + faces.push(font); + } else { + fontFamilies.set(font.name, [font]); + } + } + const fontDeclarations = Array.from(fontFamilies, ([name, faces]) => ( + + {faces.length > 0 && ( + + {faces.map((face) => ( + + + + ))} + + )} + + )); const header = xmlOptionToString(options?.header || ""); const footer = xmlOptionToString(options?.footer || ""); @@ -225,29 +370,7 @@ export class ODTExporter< xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" office:version="1.3" > - - {fonts.map((font) => { - return ( - - - - - - - - ); - })} - + {fontDeclarations} {styles} {(header || footer) && ( @@ -308,7 +431,7 @@ export class ODTExporter< {fonts.map((font) => { return ( @@ -346,9 +469,31 @@ export class ODTExporter< const contentXml = renderToString(content); const manifestXml = renderToString(manifestNode); + const generatedNames = new Set( + Array.from(fontFamilies.keys(), escapeFontName), + ); + const resolvedStylesXml = stylesXml + .replace( + /]*\/>\s*/g, + (declaration, name) => (generatedNames.has(name) ? "" : declaration), + ) + .replace( + /\b(style:font-name(?:-asian|-complex)?|fo:font-family)="(Inter 18pt|Geist Mono)"/g, + (_match, attribute, family) => { + const name = + family === defaultBodyFamily + ? this.fontFamily + : this.monoFontFamily; + return `${attribute}="${escapeFontName(name)}"`; + }, + ) + .replace( + "", + (openingTag) => openingTag + renderToString(<>{fontDeclarations}), + ); void zipWriter.add("content.xml", new TextReader(contentXml)); - void zipWriter.add("styles.xml", new TextReader(stylesXml)); + void zipWriter.add("styles.xml", new TextReader(resolvedStylesXml)); void zipWriter.add("META-INF/manifest.xml", new TextReader(manifestXml)); fonts.forEach((font) => { void zipWriter.add(`Fonts/${font.fileName}`, new BlobReader(font.data)); diff --git a/packages/xl-odt-exporter/src/odt/template/styles.xml b/packages/xl-odt-exporter/src/odt/template/styles.xml index 6b4e6e0530..42d3897558 100644 --- a/packages/xl-odt-exporter/src/odt/template/styles.xml +++ b/packages/xl-odt-exporter/src/odt/template/styles.xml @@ -28,9 +28,6 @@ xmlns:ooo="http://openoffice.org/2004/office" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" office:version="1.3"> - - diff --git a/packages/xl-pdf-exporter/package.json b/packages/xl-pdf-exporter/package.json index 2a03f8d14f..1623a61e34 100644 --- a/packages/xl-pdf-exporter/package.json +++ b/packages/xl-pdf-exporter/package.json @@ -54,6 +54,11 @@ "import": "./dist/blocknote-xl-pdf-exporter.js", "default": "./dist/blocknote-xl-pdf-exporter.js" }, + "./font": { + "types": "./types/src/font/index.d.ts", + "import": "./dist/font.js", + "default": "./dist/font.js" + }, "./react-pdf": { "types": "./types/src/react-pdf/index.d.ts", "import": "./dist/react-pdf.js", @@ -71,7 +76,8 @@ "@blocknote/core": "workspace:^", "@blocknote/xl-multi-column": "workspace:^", "@blocknote/xl-typst-exporter": "workspace:^", - "@blocknote/xl-typst-compiler": "workspace:^" + "@blocknote/xl-typst-compiler": "workspace:^", + "woff2-encoder": "3.0.0-beta.1" }, "devDependencies": { "@types/react": "^19.2.3", diff --git a/packages/xl-pdf-exporter/src/font/decodeWoff.ts b/packages/xl-pdf-exporter/src/font/decodeWoff.ts new file mode 100644 index 0000000000..509e9d1427 --- /dev/null +++ b/packages/xl-pdf-exporter/src/font/decodeWoff.ts @@ -0,0 +1,147 @@ +// https://www.w3.org/TR/WOFF/ +const WOFF_HEADER_SIZE = 44; +const WOFF_TABLE_SIZE = 20; +const SFNT_HEADER_SIZE = 12; +const SFNT_TABLE_SIZE = 16; +const MAX_FONT_SIZE = 30 * 1024 * 1024; + +function alignedSize(size: number) { + return Math.ceil(size / 4) * 4; +} + +async function inflateTable( + compressed: Uint8Array, + target: Uint8Array, +): Promise { + const reader = new Blob([new Uint8Array(compressed)]) + .stream() + .pipeThrough(new DecompressionStream("deflate")) + .getReader(); + let offset = 0; + try { + for (;;) { + const { value, done } = await reader.read(); + if (done) { + return offset === target.length; + } + if (value.length > target.length - offset) { + await reader.cancel(); + return false; + } + target.set(value, offset); + offset += value.length; + } + } catch (error) { + if (error instanceof TypeError) { + return false; + } + throw error; + } finally { + reader.releaseLock(); + } +} + +/** Unpack the WOFF container while preserving the original SFNT table order. */ +export async function decodeWoff( + input: Uint8Array, +): Promise< + | { error?: undefined; bytes: Uint8Array } + | { error: "invalid-woff" | "too-large" | "unsupported-runtime" } +> { + const view = new DataView(input.buffer, input.byteOffset, input.byteLength); + if ( + input.length < WOFF_HEADER_SIZE || + view.getUint32(8) !== input.length || + view.getUint16(14) !== 0 + ) { + return { error: "invalid-woff" }; + } + + const numTables = view.getUint16(12); + const directoryEnd = WOFF_HEADER_SIZE + numTables * WOFF_TABLE_SIZE; + const outputSize = view.getUint32(16); + if (outputSize > MAX_FONT_SIZE) { + return { error: "too-large" }; + } + // The SFNT searchRange and rangeShift fields are both uint16. + if (numTables === 0 || numTables >= 4096 || directoryEnd > input.length) { + return { error: "invalid-woff" }; + } + + const tables = []; + let previousTag = -1; + for (let index = 0; index < numTables; index++) { + const entry = WOFF_HEADER_SIZE + index * WOFF_TABLE_SIZE; + const tag = view.getUint32(entry); + const offset = view.getUint32(entry + 4); + const compressedSize = view.getUint32(entry + 8); + const size = view.getUint32(entry + 12); + if (tag <= previousTag || compressedSize > size) { + return { error: "invalid-woff" }; + } + previousTag = tag; + tables.push({ + offset, + compressedSize, + size, + directoryOffset: SFNT_HEADER_SIZE + index * SFNT_TABLE_SIZE, + tag, + checksum: view.getUint32(entry + 16), + }); + } + + // Directory entries stay sorted by tag, but the table data follows its order + // in the WOFF file. Reordering that data would invalidate checkSumAdjustment. + tables.sort( + (a, b) => a.offset - b.offset || a.compressedSize - b.compressedSize, + ); + let inputEnd = directoryEnd; + let outputEnd = SFNT_HEADER_SIZE + numTables * SFNT_TABLE_SIZE; + for (const table of tables) { + if (table.offset !== inputEnd) { + return { error: "invalid-woff" }; + } + inputEnd += alignedSize(table.compressedSize); + outputEnd += alignedSize(table.size); + } + if (inputEnd > input.length || outputEnd !== outputSize) { + return { error: "invalid-woff" }; + } + if ( + typeof DecompressionStream === "undefined" && + tables.some((table) => table.compressedSize !== table.size) + ) { + return { error: "unsupported-runtime" }; + } + + const bytes = new Uint8Array(outputSize); + const output = new DataView(bytes.buffer); + const entrySelector = Math.floor(Math.log2(numTables)); + const searchRange = 2 ** entrySelector * SFNT_TABLE_SIZE; + output.setUint32(0, view.getUint32(4)); + output.setUint16(4, numTables); + output.setUint16(6, searchRange); + output.setUint16(8, entrySelector); + output.setUint16(10, numTables * SFNT_TABLE_SIZE - searchRange); + + let offset = SFNT_HEADER_SIZE + numTables * SFNT_TABLE_SIZE; + for (const table of tables) { + const data = input.subarray( + table.offset, + table.offset + table.compressedSize, + ); + const target = bytes.subarray(offset, offset + table.size); + if (table.compressedSize === table.size) { + target.set(data); + } else if (!(await inflateTable(data, target))) { + return { error: "invalid-woff" }; + } + const entry = table.directoryOffset; + output.setUint32(entry, table.tag); + output.setUint32(entry + 4, table.checksum); + output.setUint32(entry + 8, offset); + output.setUint32(entry + 12, table.size); + offset += alignedSize(table.size); + } + return { bytes }; +} diff --git a/packages/xl-pdf-exporter/src/font/index.test.ts b/packages/xl-pdf-exporter/src/font/index.test.ts new file mode 100644 index 0000000000..5496f815e5 --- /dev/null +++ b/packages/xl-pdf-exporter/src/font/index.test.ts @@ -0,0 +1,184 @@ +import { readFileSync } from "node:fs"; +import { runInNewContext } from "node:vm"; +import { deflateSync } from "node:zlib"; +import { assert, expect, vi } from "vite-plus/test"; +import { compress } from "woff2-encoder"; +import { unreadableFontBlob } from "../../../../tests/src/fixtures/exporters/unreadableFont.js"; +import { decodeWebFont } from "./index.js"; + +function readFont(file: string) { + return readFileSync( + new URL(`../../../../shared/assets/fonts/${file}`, import.meta.url), + ); +} + +// Wrap an existing font's tables in WOFF, retaining their physical order. +function makeWoff(font: Buffer) { + const count = font.readUInt16BE(4); + const tables = Array.from({ length: count }, (_, index) => { + const entry = 12 + index * 16; + const offset = font.readUInt32BE(entry + 8); + const length = font.readUInt32BE(entry + 12); + const raw = font.subarray(offset, offset + length); + const compressed = deflateSync(raw); + return { + entry, + offset, + length, + data: compressed.length < length ? compressed : raw, + directoryOffset: 44 + index * 20, + }; + }); + const directoryEnd = 44 + count * 20; + const size = tables.reduce( + (end, table) => end + Math.ceil(table.data.length / 4) * 4, + directoryEnd, + ); + const woff = Buffer.alloc(size); + woff.write("wOFF"); + woff.writeUInt32BE(font.readUInt32BE(0), 4); + woff.writeUInt32BE(size, 8); + woff.writeUInt16BE(count, 12); + woff.writeUInt32BE(font.length, 16); + let offset = directoryEnd; + for (const table of tables.sort((a, b) => a.offset - b.offset)) { + const entry = table.directoryOffset; + woff.writeUInt32BE(font.readUInt32BE(table.entry), entry); + woff.writeUInt32BE(offset, entry + 4); + woff.writeUInt32BE(table.data.length, entry + 8); + woff.writeUInt32BE(table.length, entry + 12); + woff.writeUInt32BE(font.readUInt32BE(table.entry + 4), entry + 16); + table.data.copy(woff, offset); + offset += Math.ceil(table.data.length / 4) * 4; + } + return woff; +} + +it("reports when the browser blocks WebAssembly initialization", async () => { + const woff2 = await compress(readFont("GeistMono-Regular.ttf")); + const instantiate = vi + .spyOn(WebAssembly, "instantiate") + .mockRejectedValue( + new WebAssembly.CompileError("Blocked by Content Security Policy"), + ); + const log = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + expect((await decodeWebFont(woff2)).error).toBe("unsupported-runtime"); + } finally { + instantiate.mockRestore(); + log.mockRestore(); + } + expect((await decodeWebFont(woff2)).error).toBeUndefined(); +}); + +it("decodes TrueType and CFF webfonts in parallel", async () => { + const [ttf, otf] = await Promise.all( + ["GeistMono-Regular.ttf", "newcm/NewCMMath-Regular.otf"].map((file) => + compress(readFont(file)), + ), + ); + const [trueType, openType, repeated] = await Promise.all([ + decodeWebFont(new Blob([new Uint8Array(ttf)])), + decodeWebFont(new Uint8Array(otf).buffer), + decodeWebFont(ttf), + ]); + assert(trueType.error === undefined); + assert(openType.error === undefined); + expect(trueType.extension).toBe("ttf"); + expect(openType.extension).toBe("otf"); + expect(trueType.bytes.slice(0, 4)).toEqual(Uint8Array.of(0, 1, 0, 0)); + expect(openType.bytes.slice(0, 4)).toEqual(Uint8Array.of(79, 84, 84, 79)); + expect(repeated).toEqual(trueType); + + const otherRealm: Uint8Array = runInNewContext( + "const padded = new Uint8Array(input.length + 2); padded.set(input, 1); padded.subarray(1, -1);", + { input: ttf }, + ); + expect(await decodeWebFont(otherRealm)).toEqual(trueType); +}); + +it.for([ + ["GeistMono-Regular.ttf", "ttf"], + ["newcm/NewCMMath-Regular.otf", "otf"], +] as const)( + "restores the original SFNT bytes from WOFF (%s)", + async ([file, extension]) => { + const original = readFont(file); + const woff = makeWoff(original); + const result = await decodeWebFont( + new Blob([woff], { type: "font/woff2" }), + ); + assert(result.error === undefined); + expect(result.extension).toBe(extension); + expect(Buffer.compare(result.bytes, original)).toBe(0); + }, +); + +it("rejects malformed WOFF files before exposing a partial font", async () => { + const woff = makeWoff(readFont("GeistMono-Regular.ttf")); + const oversized = Buffer.from(woff); + oversized.writeUInt32BE(31 * 1024 * 1024, 16); + const badOffset = Buffer.from(woff); + badOffset.writeUInt32BE(0, 48); + const badDeflate = Buffer.from(woff); + const wrongInflatedSize = Buffer.from(woff); + for (let entry = 44; entry < 44 + woff.readUInt16BE(12) * 20; entry += 20) { + const tableSize = woff.readUInt32BE(entry + 12); + if (woff.readUInt32BE(entry + 8) < tableSize - 4) { + badDeflate[woff.readUInt32BE(entry + 4)] = 0; + wrongInflatedSize.writeUInt32BE(tableSize - 4, entry + 12); + wrongInflatedSize.writeUInt32BE(woff.readUInt32BE(16) - 4, 16); + break; + } + } + expect(await decodeWebFont(new Uint8Array())).toEqual({ + error: "not-webfont", + }); + expect(await decodeWebFont(woff.subarray(0, 12))).toEqual({ + error: "invalid-woff", + }); + expect(await decodeWebFont(badOffset)).toEqual({ error: "invalid-woff" }); + expect(await decodeWebFont(badDeflate)).toEqual({ error: "invalid-woff" }); + expect(await decodeWebFont(wrongInflatedSize)).toEqual({ + error: "invalid-woff", + }); + expect(await decodeWebFont(oversized)).toEqual({ error: "too-large" }); +}); + +it("returns explicit errors for unreadable, invalid, and oversized inputs", async () => { + const header = new Uint8Array(48); + header.set([0x77, 0x4f, 0x46, 0x32]); // wOF2 + const oversized = header.slice(); + new DataView(oversized.buffer).setUint32(16, 31 * 1024 * 1024); + expect(await decodeWebFont(await unreadableFontBlob())).toEqual({ + error: "unreadable", + }); + expect(await decodeWebFont(header)).toEqual({ error: "invalid-woff2" }); + expect(await decodeWebFont(oversized)).toEqual({ error: "too-large" }); +}); + +it("rejects oversized uploads without reading them", async () => { + const file = new Blob(); + vi.spyOn(file, "size", "get").mockReturnValue(31 * 1024 * 1024); + const read = vi.spyOn(file, "arrayBuffer"); + expect(await decodeWebFont(file)).toEqual({ error: "too-large" }); + expect(read).not.toHaveBeenCalled(); +}); + +it.for(["NotFoundError", "SecurityError"])( + "treats a browser %s as unreadable", + async (name) => { + const file = new Blob(); + vi.spyOn(file, "arrayBuffer").mockRejectedValue(new DOMException("", name)); + expect(await decodeWebFont(file)).toEqual({ error: "unreadable" }); + }, +); + +it("handles file-read errors from another realm", async () => { + const file = new Blob(); + const error: unknown = runInNewContext( + 'new class DOMException extends Error { name = "NotReadableError"; }', + ); + vi.spyOn(file, "arrayBuffer").mockRejectedValue(error); + expect(await decodeWebFont(file)).toEqual({ error: "unreadable" }); +}); diff --git a/packages/xl-pdf-exporter/src/font/index.ts b/packages/xl-pdf-exporter/src/font/index.ts new file mode 100644 index 0000000000..d59827ee76 --- /dev/null +++ b/packages/xl-pdf-exporter/src/font/index.ts @@ -0,0 +1,115 @@ +import { type FontSource, readFontBytes } from "../pdfua/fontSource.js"; + +const MAX_INPUT_SIZE = 30 * 1024 * 1024; + +/** The unpacked font bytes and their file format, or a reason decoding failed. */ +type DecodedFont = + | { error?: undefined; bytes: Uint8Array; extension: "ttf" | "otf" } + | { error: "unsupported-output" }; + +export type DecodeWebFontResult = + | DecodedFont + | { + error: + | "unreadable" + | "not-webfont" + | "invalid-woff" + | "invalid-woff2" + | "too-large" + | "unsupported-runtime"; + }; + +/** Unpack a single WOFF or WOFF2 font, detected from its signature. */ +export async function decodeWebFont( + source: FontSource, +): Promise { + const inputSize = "size" in source ? source.size : source.byteLength; + if (inputSize > MAX_INPUT_SIZE) { + return { error: "too-large" }; + } + const input = await readFontBytes(source); + if (input.error !== undefined) { + return { error: "unreadable" }; + } + switch (fontSignature(input.bytes)) { + case "wOFF": { + const { decodeWoff } = await import("./decodeWoff.js"); + const decoded = await decodeWoff(input.bytes); + return decoded.error === undefined + ? describeFont(decoded.bytes) + : decoded; + } + case "wOF2": { + const decoded = await unpackWoff2(input.bytes); + return decoded.error === undefined + ? describeFont(decoded.bytes) + : decoded; + } + default: + return { error: "not-webfont" }; + } +} + +async function unpackWoff2( + input: Uint8Array, +): Promise< + | { error?: undefined; bytes: Uint8Array } + | { error: "invalid-woff2" | "too-large" | "unsupported-runtime" } +> { + if (typeof WebAssembly === "undefined") { + return { error: "unsupported-runtime" }; + } + const { + default: decompress, + isWoff2Error, + preload, + } = await import("woff2-encoder/decompress"); + try { + await preload(); + } catch (error) { + if ( + error instanceof EvalError || + error instanceof WebAssembly.CompileError || + error instanceof WebAssembly.RuntimeError + ) { + // Emscripten wraps blocked WASM compilation in a RuntimeError. + return { error: "unsupported-runtime" }; + } + throw error; + } + try { + // The decoder uses instanceof; normalize views from other realms. + const bytes = new Uint8Array( + input.buffer, + input.byteOffset, + input.byteLength, + ); + return { bytes: await decompress(bytes) }; + } catch (error) { + if (isWoff2Error(error)) { + if (error.code === "MAX_SIZE_EXCEEDED") { + return { error: "too-large" }; + } + if (error.code === "DECOMPRESS_FAILED") { + return { error: "invalid-woff2" }; + } + } + throw error; + } +} + +function fontSignature(bytes: Uint8Array) { + return String.fromCharCode(...bytes.subarray(0, 4)); +} + +function describeFont(bytes: Uint8Array): DecodedFont { + switch (fontSignature(bytes)) { + case "\0\x01\0\0": + case "true": + return { bytes, extension: "ttf" }; + case "OTTO": + return { bytes, extension: "otf" }; + default: + return { error: "unsupported-output" }; + } +} diff --git a/packages/xl-pdf-exporter/src/index.ts b/packages/xl-pdf-exporter/src/index.ts index 651fe08c1b..268c5b3c3c 100644 --- a/packages/xl-pdf-exporter/src/index.ts +++ b/packages/xl-pdf-exporter/src/index.ts @@ -3,6 +3,7 @@ // single Typst mapping serves both the standalone `.typ` export // (@blocknote/xl-typst-exporter) and the PDF export. export * from "@blocknote/xl-typst-exporter"; +export type { FontSource } from "./pdfua/fontSource.js"; export { PDFExporter, type PdfExporterOptions, diff --git a/packages/xl-pdf-exporter/src/pdfExporter.test.ts b/packages/xl-pdf-exporter/src/pdfExporter.test.ts index 658e0c1f77..f5cc7ab6ff 100644 --- a/packages/xl-pdf-exporter/src/pdfExporter.test.ts +++ b/packages/xl-pdf-exporter/src/pdfExporter.test.ts @@ -7,6 +7,7 @@ import { typstDefaultSchemaMappings } from "@blocknote/xl-typst-exporter"; import { readFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { describe, expect } from "vite-plus/test"; +import { unreadableFontBlob } from "../../../tests/src/fixtures/exporters/unreadableFont.js"; import { loadDefaultBodyFonts, PDFExporter, @@ -84,6 +85,71 @@ function expectExported( } describe("PDFExporter", () => { + pdfTest( + "reports an unreadable emoji font as a compile error", + async ({ exporter, conforming }) => { + const result = await exporter({ + emojiFont: await unreadableFontBlob(), + }).toPDF(conforming, { lang: "en" }); + expect(result).toMatchObject({ + error: "compile-failed", + compileErrors: [ + { message: "Emoji font 1: Could not read the font file." }, + ], + }); + }, + ); + + pdfTest( + "fails export for invalid font files even alongside a supported font", + async ({ exporter, conforming }) => { + const encoder = new TextEncoder(); + const result = await exporter({ + fonts: [ + new Blob(["wOFF"], { type: "font/ttf" }), + new Blob([read(join(fontDir, "inter/Inter_18pt-Regular.ttf"))]), + encoder.encode("wOF2").buffer, + new Blob(["Not found"]), + ], + }).toPDF(conforming, { lang: "en" }); + expect(result).toMatchObject({ + error: "compile-failed", + compileErrors: [ + { message: "Body font 1: WOFF is not supported." }, + { message: "Body font 3: WOFF2 is not supported." }, + { message: "Body font 4: Unrecognized font format." }, + ], + }); + }, + ); + + pdfTest( + "accepts Blob and ArrayBuffer fonts, including byte-identical copies", + async ({ exporter, conforming }) => { + const regular = read(join(fontDir, "inter/Inter_18pt-Regular.ttf")); + const bold = read(join(fontDir, "inter/Inter_18pt-Bold.ttf")); + const result = await exporter({ + fonts: [new Blob([regular]), regular, bold.buffer], + }).toPDF(conforming, { lang: "en" }); + expect(expectExported(result).blob).toBeInstanceOf(Blob); + }, + ); + + pdfTest( + "fails export when Typst cannot parse a desktop font", + async ({ exporter, conforming }) => { + const result = await exporter({ + fonts: [new Uint8Array([0, 1, 0, 0])], + }).toPDF(conforming, { lang: "en" }); + expect(result).toMatchObject({ + error: "compile-failed", + compileErrors: [ + { message: "Body font 1: Typst could not load this font." }, + ], + }); + }, + ); + pdfTest( "rejects caller assets that collide with exporter-registered ones", async ({ exporter, partialBlocksToBlocksForTesting }) => { diff --git a/packages/xl-pdf-exporter/src/pdfExporter.ts b/packages/xl-pdf-exporter/src/pdfExporter.ts index a5057400f7..6eab9e1f66 100644 --- a/packages/xl-pdf-exporter/src/pdfExporter.ts +++ b/packages/xl-pdf-exporter/src/pdfExporter.ts @@ -24,6 +24,7 @@ import { loadDefaultBodyFonts, loadDefaultEmojiFont, } from "./pdfua/defaultFonts.js"; +import type { FontSource } from "./pdfua/fontSource.js"; /** * {@link PDFExporter}'s options: everything the *exporter* is (like the @@ -48,23 +49,25 @@ export type PdfExporterOptions = TypstExporterOptions & { */ wasm?: TypstCompileOptions["wasm"]; /** - * The body fonts (as bytes, or a promise of them) the exporter's + * The body font files (or a promise of them) the exporter's * `fontFamily` / `monoFontFamily` names resolve against. Defaults to the * bundled set matching the editor; to *extend* it, spread the exported * loader: `loadDefaultBodyFonts().then((f) => [...f, myCjkFont])`. * Typst selects fonts by the family name embedded in each file's own * name table; a referenced-but-missing family surfaces as an * `unknown font family` entry in the result's `compileWarnings`. + * Supply TTF, OTF, or TTC files. Unusable font files fail the export + * with `compileErrors`. */ - fonts: Uint8Array[] | Promise; + fonts: readonly FontSource[] | Promise; /** - * An emoji-capable font (or fonts) as bytes, or a promise of them - + * An emoji-capable font file (or files), or a promise of them - * what {@link TypstExporterOptions.emojiFontFamily} resolves against. * Defaults (independently of {@link fonts}) to the bundled Noto Color * Emoji. Browsers give the compiler no access to OS fonts, so without * one emoji render as missing glyphs (and fail PDF/UA). */ - emojiFont: Uint8Array | Uint8Array[] | Promise; + emojiFont: FontSource | FontSource[] | Promise; }; /** @@ -183,8 +186,8 @@ export class PDFExporter< I extends InlineContentSchema, > extends TypstExporter { private readonly wasm: TypstCompileOptions["wasm"]; - private readonly fonts: Promise; - private readonly emojiFont: Promise; + private readonly fonts: Promise | undefined; + private readonly emojiFont: Promise | undefined; public constructor( schema: BlockNoteSchema, @@ -217,19 +220,16 @@ export class PDFExporter< // supplied value (including an explicit `[]` for none) takes over. The // independence keeps the bytes consistent with the constructor's // independent `emojiFontFamily` default: custom body fonts don't - // silently drop emoji support, and vice versa. Values may be promises - // (the constructor stays sync); they resolve on first export. - this.fonts = - fonts === undefined ? loadDefaultBodyFonts() : Promise.resolve(fonts); + // silently drop emoji support, and vice versa. Bundled fonts start + // loading only when toPDF needs them. + this.fonts = fonts === undefined ? undefined : Promise.resolve(fonts); this.emojiFont = - emojiFont === undefined - ? loadDefaultEmojiFont() - : Promise.resolve(emojiFont); + emojiFont === undefined ? undefined : Promise.resolve(emojiFont); // A caller-supplied promise may reject before the first export awaits // it; these no-op handlers keep that from surfacing as an unhandled // rejection (the export still rejects with the real error). - this.fonts.catch(() => {}); - this.emojiFont.catch(() => {}); + this.fonts?.catch(() => {}); + this.emojiFont?.catch(() => {}); } /** @@ -285,7 +285,10 @@ export class PDFExporter< ); } } - const [fonts, emojiFont] = await Promise.all([this.fonts, this.emojiFont]); + const [fonts, emojiFont] = await Promise.all([ + this.fonts ?? loadDefaultBodyFonts(), + this.emojiFont ?? loadDefaultEmojiFont(), + ]); const resolved: TypstCompileOptions = { wasm: this.wasm, fonts, diff --git a/packages/xl-pdf-exporter/src/pdfua/compileTypst.browser.test.ts b/packages/xl-pdf-exporter/src/pdfua/compileTypst.browser.test.ts index 97aee7c382..a1268e1d34 100644 --- a/packages/xl-pdf-exporter/src/pdfua/compileTypst.browser.test.ts +++ b/packages/xl-pdf-exporter/src/pdfua/compileTypst.browser.test.ts @@ -6,6 +6,7 @@ import { compileTypstToPdf } from "./compileTypst.js"; // Bundled wasm so the compiler initializes fully offline. // eslint-disable-next-line import/no-unresolved import compilerWasmUrl from "@blocknote/xl-typst-compiler/wasm?url"; +import fontUrl from "../../../../shared/assets/fonts/GeistMono-Regular.ttf?url"; // Browser unit tests for the actual production compile path - the wasm // compiler the exporters ship to the browser, loaded through the bundler @@ -72,12 +73,12 @@ describe("compileTypstToPdf", () => { // A per-compile font set was impossible under the previous // page-singleton engine (fonts were fixed by the first compile); // compilers are now per-font-set instances, so this must just work. - // Invalid font bytes are ignored (0 faces), not fatal. const first = expectPdf(await compileTypstToPdf("one", OPTIONS)); + const font = await (await fetch(fontUrl)).arrayBuffer(); const second = expectPdf( await compileTypstToPdf("two", { ...OPTIONS, - fonts: [new Uint8Array([1, 2, 3])], + fonts: [font], }), ); expect(isPdf(first)).toBe(true); @@ -85,6 +86,17 @@ describe("compileTypstToPdf", () => { }, ); + it("rejects invalid font bytes with a typed diagnostic", async () => { + const result = await compileTypstToPdf("text", { + ...OPTIONS, + fonts: [new Uint8Array([1, 2, 3])], + }); + expect(result).toMatchObject({ + error: "compile-failed", + compileErrors: [{ message: "Body font 1: Unrecognized font format." }], + }); + }); + it( "returns typed diagnostics instead of output for broken markup", { timeout: 60000 }, diff --git a/packages/xl-pdf-exporter/src/pdfua/compileTypst.ts b/packages/xl-pdf-exporter/src/pdfua/compileTypst.ts index cf982c60d4..19598a5413 100644 --- a/packages/xl-pdf-exporter/src/pdfua/compileTypst.ts +++ b/packages/xl-pdf-exporter/src/pdfua/compileTypst.ts @@ -2,7 +2,9 @@ import { TypstCompiler, type CompilePdfResult, type TypstCompilerOptions, + type TypstDiagnostic, } from "@blocknote/xl-typst-compiler"; +import { type FontSource, readFontBytes } from "./fontSource.js"; export interface TypstCompileOptions { /** @@ -14,7 +16,7 @@ export interface TypstCompileOptions { */ wasm?: TypstCompilerOptions["wasm"]; /** - * Fonts (as bytes) to load into the compiler - the body fonts the + * Font files to load into the compiler - the body fonts the * source references (e.g. Inter, Geist Mono). This low-level function * has no defaults (`PDFExporter` adds those); the compiler ships no * fonts of its own: text renders only with supplied fonts, and a @@ -26,9 +28,10 @@ export interface TypstCompileOptions { * `fontFamily` options must match it exactly. A mismatch surfaces as an * `unknown font family` entry in the result's `compileWarnings`; * `TypstCompiler.fontFamilies` (from `@blocknote/xl-typst-compiler`) - * lists what a font file actually declares. + * lists what a font file actually declares. Supply TTF, OTF, or TTC + * files. Unsupported or unreadable font data fails compilation. */ - fonts?: Uint8Array[]; + fonts?: readonly FontSource[]; /** * The emoji source: an emoji-capable font (or fonts) as bytes. Unlike * react-pdf's image-based `emojiSource`, Typst renders emoji from a font, @@ -38,7 +41,7 @@ export interface TypstCompileOptions { * Loaded alongside {@link fonts} (this is just a clearer, dedicated * channel for it). */ - emojiFont?: Uint8Array | Uint8Array[]; + emojiFont?: FontSource | FontSource[]; /** * Image/asset files to map into the compiler's virtual filesystem, keyed * by the Typst path referenced in the source (e.g. `/assets/asset-0`). @@ -52,14 +55,36 @@ export interface TypstCompileOptions { creationTimestamp?: number; } -function fontList(options: TypstCompileOptions): Uint8Array[] { - const emojiFonts = - options.emojiFont === undefined - ? [] - : Array.isArray(options.emojiFont) - ? options.emojiFont - : [options.emojiFont]; - return [...(options.fonts ?? []), ...emojiFonts]; +function fontError( + label: string, + reason: string, + hint?: string, +): TypstDiagnostic { + return { + message: `${label}: ${reason}`, + hints: [hint ?? "Supply the original TTF, OTF, or TTC font file."], + }; +} + +function getFontFormatError( + bytes: Uint8Array, + label: string, +): TypstDiagnostic | undefined { + const webFontHint = + "Unpack the webfont with decodeWebFont from @blocknote/xl-pdf-exporter/font before supplying it."; + switch (String.fromCharCode(...bytes.subarray(0, 4))) { + case "\0\x01\0\0": + case "true": + case "OTTO": + case "ttcf": + return undefined; + case "wOFF": + return fontError(label, "WOFF is not supported.", webFontHint); + case "wOF2": + return fontError(label, "WOFF2 is not supported.", webFontHint); + default: + return fontError(label, "Unrecognized font format."); + } } /** @@ -79,14 +104,63 @@ export async function compileTypstToPdf( tagged?: boolean; } = {}, ): Promise { + const emojiFonts = [options.emojiFont ?? []].flat(); + const sources = [ + ...(options.fonts ?? []).map((source, index) => ({ + source, + label: `Body font ${index + 1}`, + })), + ...emojiFonts.map((source, index) => ({ + source, + label: `Emoji font ${index + 1}`, + })), + ]; + const inputs = await Promise.all( + sources.map(async ({ source, label }) => ({ + font: await readFontBytes(source), + label, + })), + ); + const fonts: { bytes: Uint8Array; label: string }[] = []; + const compileErrors: TypstDiagnostic[] = []; + for (const { font, label } of inputs) { + if (font.error !== undefined) { + compileErrors.push(fontError(label, font.error)); + continue; + } + const problem = getFontFormatError(font.bytes, label); + if (problem) { + compileErrors.push(problem); + } else { + fonts.push({ bytes: font.bytes, label }); + } + } + if (compileErrors.length) { + return { error: "compile-failed", compileErrors, compileWarnings: [] }; + } // A fresh instance per compile: the wasm module is loaded once globally // and Typst's caches are module-wide, so instance creation (including // parsing the fonts) costs single-digit milliseconds - not worth any // reuse scheme, and it keeps compiles fully independent. - const compiler = await TypstCompiler.create({ - wasm: options.wasm, - fonts: fontList(options), - }); + const compiler = await TypstCompiler.create({ wasm: options.wasm }); + const loaded: Uint8Array[] = []; + for (const { bytes, label } of fonts) { + if (compiler.addFont(bytes) > 0) { + loaded.push(bytes); + } else if ( + !loaded.some( + (font) => + font.length === bytes.length && + font.every((byte, index) => byte === bytes[index]), + ) + ) { + // Typst returns zero for both rejected files and byte-identical repeats. + compileErrors.push(fontError(label, "Typst could not load this font.")); + } + } + if (compileErrors.length) { + return { error: "compile-failed", compileErrors, compileWarnings: [] }; + } return compiler.compilePdf(typst, { assets: options.assets, pdfStandard: options.pdfStandard, diff --git a/packages/xl-pdf-exporter/src/pdfua/fontSource.ts b/packages/xl-pdf-exporter/src/pdfua/fontSource.ts new file mode 100644 index 0000000000..c9b90aa3e9 --- /dev/null +++ b/packages/xl-pdf-exporter/src/pdfua/fontSource.ts @@ -0,0 +1,24 @@ +/** An already-loaded font file. Accepts browser File and Node Buffer. */ +export type FontSource = Blob | ArrayBuffer | Uint8Array; + +export async function readFontBytes( + source: FontSource, +): Promise<{ bytes: Uint8Array; error?: undefined } | { error: string }> { + let data: ArrayBuffer | Uint8Array; + try { + data = "arrayBuffer" in source ? await source.arrayBuffer() : source; + } catch (error) { + if ( + typeof error !== "object" || + error === null || + !("name" in error) || + (error.name !== "NotReadableError" && + error.name !== "NotFoundError" && + error.name !== "SecurityError") + ) { + throw error; + } + return { error: "Could not read the font file." }; + } + return { bytes: ArrayBuffer.isView(data) ? data : new Uint8Array(data) }; +} diff --git a/packages/xl-pdf-exporter/vite.config.ts b/packages/xl-pdf-exporter/vite.config.ts index 671c506a7a..8f9981d250 100644 --- a/packages/xl-pdf-exporter/vite.config.ts +++ b/packages/xl-pdf-exporter/vite.config.ts @@ -65,6 +65,7 @@ export default defineConfig( "src/index.ts", ), "react-pdf": path.resolve(__dirname, "src/react-pdf/index.ts"), + font: path.resolve(__dirname, "src/font/index.ts"), }, name: "blocknote-xl-pdf-exporter", formats: ["es"], diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d17118a0b3..c93cc05791 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5416,7 +5416,7 @@ importers: specifier: ^6.0.3 version: 6.0.3 docx: - specifier: ^9.9.0 + specifier: ^9.10.0 version: 9.14.0 image-meta: specifier: ^0.2.2 @@ -5593,6 +5593,9 @@ importers: '@blocknote/xl-typst-exporter': specifier: workspace:^ version: link:../xl-typst-exporter + woff2-encoder: + specifier: 3.0.0-beta.1 + version: 3.0.0-beta.1 devDependencies: '@cantoo/pdf-lib': specifier: ^2.9.1 @@ -15268,6 +15271,10 @@ packages: wildcard@1.1.2: resolution: {integrity: sha512-DXukZJxpHA8LuotRwL0pP1+rS6CS7FF2qStDDE1C7DDg2rLud2PXRMuEDYIPhgEezwnlHNL4c+N6MfMTjCGTng==} + woff2-encoder@3.0.0-beta.1: + resolution: {integrity: sha512-OtKJpjJkwU2p38rdmQa71jzYXODz0GXC8smKYAbKjjLbhOq4BbGU4R47KkWIrXN7U2in7O+uAW/f0+/xTzJ89A==} + engines: {node: '>= 22.12'} + word-wrap@1.2.5: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} @@ -25643,6 +25650,8 @@ snapshots: wildcard@1.1.2: {} + woff2-encoder@3.0.0-beta.1: {} + word-wrap@1.2.5: {} wrap-ansi@6.2.0: diff --git a/tests/src/fixtures/exporters/unreadableFont.ts b/tests/src/fixtures/exporters/unreadableFont.ts new file mode 100644 index 0000000000..e826ba3221 --- /dev/null +++ b/tests/src/fixtures/exporters/unreadableFont.ts @@ -0,0 +1,19 @@ +import { openAsBlob } from "node:fs"; +import { mkdtemp, rmdir, unlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +export async function unreadableFontBlob(): Promise { + const directory = await mkdtemp(join(tmpdir(), "blocknote-font-")); + const file = join(directory, "font.ttf"); + try { + await writeFile(file, new Uint8Array([0, 1, 0, 0])); + try { + return await openAsBlob(file); + } finally { + await unlink(file); + } + } finally { + await rmdir(directory); + } +}