@f-office/core 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -53,6 +53,7 @@ await client.addFont(fontBytes);
53
53
  const doc = await client.openDocx(docxBytes, { target: "word-win" });
54
54
  const page = await client.renderPage(doc.id, 0, 96 * devicePixelRatio);
55
55
  ctx.putImageData(new ImageData(page.pixels, page.width, page.height), 0, 0);
56
+ const matches = await client.search(doc.id, "F-Office", { caseSensitive: false });
56
57
  const pdf = await client.writePdf(doc.id);
57
58
  await client.closeDocx(doc.id);
58
59
  ```
@@ -65,6 +66,20 @@ WebAssembly linear memory can grow but never shrink. For phones and memory-const
65
66
  - Render only visible viewport tiles with `doc.renderRegion(pageIndex, { x, y, width, height }, dpi)` instead of full high-DPI pages.
66
67
  - Use `createRecyclableWorkerRenderer(() => new Worker(...), { recycleAboveBytes: 128 * 1024 * 1024 })` from `@f-office/core/worker` so WASM linear memory is transparently returned to the OS when documents are closed.
67
68
 
69
+ ## Content Security Policy (CSP)
70
+
71
+ When serving apps that run `@f-office/core` under a strict Content Security Policy:
72
+
73
+ ```text
74
+ script-src 'self' 'wasm-unsafe-eval';
75
+ worker-src 'self' blob:;
76
+ connect-src 'self' https://cdn.compatifont.com;
77
+ ```
78
+
79
+ - `'wasm-unsafe-eval'` allows WebAssembly compilation without enabling JavaScript `'unsafe-eval'`.
80
+ - `worker-src` is needed when loading `@f-office/core/worker` as a module worker.
81
+ - `connect-src` should include your font/WASM host (or `'self'` when self-hosted).
82
+
68
83
  ## Bundler notes
69
84
 
70
85
  - **Vite**: add `@f-office/core` to `optimizeDeps.exclude` in `vite.config.ts` so Vite preserves the `.wasm` asset URL:
@@ -75,7 +90,7 @@ WebAssembly linear memory can grow but never shrink. For phones and memory-const
75
90
  ```
76
91
  - **Targets**: `"word-win"` (Microsoft Word for Windows) is the default and only stable target.
77
92
  - **Browser requirements**: WebAssembly SIMD128 (Chrome 91+, Firefox 89+, Safari 16.4+, Node.js 20+).
78
- - **Fonts**: Browsers have no system font folder. Pair `@f-office/core` with the independent [Compatifont](https://github.com/osolmaz/compatifont) open fonts (`@compatifont/fonts`) or your own font files.
93
+ - **Fonts & WOFF2**: Browsers have no system font folder. Pair `@f-office/core` with the independent [Compatifont](https://github.com/osolmaz/compatifont) open fonts (`@compatifont/fonts`) or your own font files. `renderer.addFont()` accepts `.ttf`, `.otf`, `.ttc`, `.otc`, and pure-Rust decoded `.woff2`. Full-table WOFF2 preserves exact Word layout metrics; web-subsetted WOFF2 files may omit glyphs or OpenType tables required for identical line breaks.
79
94
 
80
95
  ## License
81
96
 
@@ -0,0 +1,7 @@
1
+ import type { WasmInitSource } from "./types.js";
2
+ export { createBlobSource, createMemorySource, createOpfsSource, Document, loadFontsFor, PageImage, Renderer, wasmMemoryBytes, type ByteSource, type FontFetcher, type FontNeed, type LimitProfile, type OpenOptions, type OpfsSyncAccessHandle, type OutlineEntry, type PageRect, type PageSizePoints, type PdfChunkCallback, type PixelRegion, type RenderedPageData, type SearchMatch, type SearchOptions, type SearchRange, type TargetId, type TextRun, type WasmInitSource, } from "./core.js";
3
+ /**
4
+ * Initializes the F-Office WebAssembly module in browsers and Web Workers. Safe to call multiple
5
+ * times; subsequent calls resolve immediately once initialized.
6
+ */
7
+ export declare function init(source?: WasmInitSource): Promise<void>;
@@ -0,0 +1,10 @@
1
+ import wasmInit from "./wasm/f_office_wasm.js";
2
+ import { initWithDefaultLoader } from "./core.js";
3
+ export { createBlobSource, createMemorySource, createOpfsSource, Document, loadFontsFor, PageImage, Renderer, wasmMemoryBytes, } from "./core.js";
4
+ /**
5
+ * Initializes the F-Office WebAssembly module in browsers and Web Workers. Safe to call multiple
6
+ * times; subsequent calls resolve immediately once initialized.
7
+ */
8
+ export function init(source) {
9
+ return initWithDefaultLoader((wasmUrl) => wasmInit({ module_or_path: wasmUrl }), source);
10
+ }
package/dist/core.d.ts ADDED
@@ -0,0 +1,121 @@
1
+ import { Document as RawDocument, PageImage as RawPageImage } from "./wasm/f_office_wasm.js";
2
+ import type { ByteSource, FontFetcher, FontNeed, OpenOptions, OutlineEntry, PageSizePoints, PdfChunkCallback, PixelRegion, SearchMatch, SearchOptions, TargetId, TextRun, WasmInitSource } from "./types.js";
3
+ export type { ByteSource, FontFetcher, FontNeed, LimitProfile, OpenOptions, OutlineEntry, PageRect, PageSizePoints, PdfChunkCallback, PixelRegion, RenderedPageData, SearchMatch, SearchOptions, SearchRange, TargetId, TextRun, WasmInitSource, } from "./types.js";
4
+ export { createBlobSource, createMemorySource, createOpfsSource, type OpfsSyncAccessHandle, } from "./source.js";
5
+ /**
6
+ * Returns the current byte length of the WebAssembly linear memory buffer, or `0` before
7
+ * `init()` completes. Useful for monitoring peak memory on mobile browsers.
8
+ */
9
+ export declare function wasmMemoryBytes(): number;
10
+ /** @internal Shared initializer parameterized by the runtime-specific default WASM loader. */
11
+ export declare function initWithDefaultLoader(loadDefault: (wasmUrl: URL) => Promise<{
12
+ memory: WebAssembly.Memory;
13
+ }>, source?: WasmInitSource): Promise<void>;
14
+ /** A rendered page image (RGBA bytes, dimensions, and drawing warnings). */
15
+ export declare class PageImage implements Disposable {
16
+ #private;
17
+ constructor(raw: RawPageImage);
18
+ /** Width in pixels. */
19
+ get width(): number;
20
+ /** Height in pixels. */
21
+ get height(): number;
22
+ /** Distinct warnings produced while drawing this page. */
23
+ warnings(): string[];
24
+ /**
25
+ * RGBA pixels copied out of WebAssembly memory, cached on first read so repeated
26
+ * accesses do not copy the buffer again.
27
+ */
28
+ get pixels(): Uint8ClampedArray;
29
+ /** Builds a browser `ImageData` backed by this page's RGBA pixels. */
30
+ toImageData(): ImageData;
31
+ /** Releases WebAssembly memory held by this page image. */
32
+ free(): void;
33
+ [Symbol.dispose](): void;
34
+ }
35
+ /** A laid-out DOCX document. Page indices are zero-based. */
36
+ export declare class Document implements Disposable {
37
+ #private;
38
+ constructor(raw: RawDocument);
39
+ /** Distinct layout warnings (such as substituted fonts or missing pictures). */
40
+ warnings(): string[];
41
+ /**
42
+ * Fonts looked up during layout that were missing from the renderer, including
43
+ * glyph-fallback families discovered after primary fonts were loaded.
44
+ */
45
+ fontNeeds(): FontNeed[];
46
+ /** Number of laid-out pages. */
47
+ pageCount(): number;
48
+ /** Width in pixels of page `index` when rendered at `dpi`. */
49
+ pageWidth(index: number, dpi: number): number;
50
+ /** Height in pixels of page `index` when rendered at `dpi`. */
51
+ pageHeight(index: number, dpi: number): number;
52
+ /** Width and height in points of every page in order. */
53
+ pageSizes(): PageSizePoints[];
54
+ /** Upright text runs of page `index` in painting order. */
55
+ textRuns(index: number): TextRun[];
56
+ /** Document headings in reading order. */
57
+ outline(): OutlineEntry[];
58
+ /**
59
+ * Searches all stories of the document over the compact text map without rendering offscreen
60
+ * pages, returning lightweight `{ page, rects, range, snippet }` matches.
61
+ */
62
+ search(query: string, options?: SearchOptions): SearchMatch[];
63
+ /** Renders page `index` at `dpi` pixels per inch on a white background. */
64
+ renderPage(index: number, dpi: number): PageImage;
65
+ /**
66
+ * Renders only the rectangular pixel tile `region` of page `index` at `dpi` pixels per inch.
67
+ * Ideal for mobile viewports and high-zoom viewing with constant memory.
68
+ */
69
+ renderRegion(index: number, region: PixelRegion, dpi: number): PageImage;
70
+ /** Writes all pages to a PDF file with fonts subset and embedded. */
71
+ writePdf(): Uint8Array;
72
+ /**
73
+ * Streams all pages as PDF 1.7 chunks into `onChunk` without allocating the full PDF in
74
+ * WebAssembly linear memory. Returns distinct PDF warnings.
75
+ */
76
+ writePdfTo(onChunk: PdfChunkCallback): string[];
77
+ /** Releases WebAssembly memory held by this document. */
78
+ free(): void;
79
+ [Symbol.dispose](): void;
80
+ }
81
+ /** Holds loaded fonts and opens DOCX documents into laid-out pages. */
82
+ export declare class Renderer implements Disposable {
83
+ #private;
84
+ constructor();
85
+ /** Returns the supported Word target IDs. */
86
+ static targets(): TargetId[];
87
+ /**
88
+ * Lists fonts requested by a DOCX file before any font is added.
89
+ * Defaults to `"word-win"`.
90
+ */
91
+ static fontsNeeded(docx: Uint8Array, target?: TargetId): FontNeed[];
92
+ /**
93
+ * Lists fonts requested by a DOCX file read lazily from a random-access `ByteSource` without
94
+ * copying the archive into WebAssembly linear memory.
95
+ */
96
+ static fontsNeededSource(source: ByteSource, target?: TargetId): FontNeed[];
97
+ /**
98
+ * Adds all faces from an OpenType font or collection (`.ttf`, `.otf`, `.ttc`, `.otc`) or a
99
+ * WOFF2 webfont (`.woff2`). Full-table WOFF2 preserves exact Word layout metrics; web-subsetted
100
+ * WOFF2 may omit glyphs or OpenType tables.
101
+ */
102
+ addFont(data: Uint8Array): number;
103
+ /** Adds art page border pictures. */
104
+ addArtPictures(data: Uint8Array): number;
105
+ /** Lays out a DOCX file with the fonts currently added to this renderer. */
106
+ openDocx(docx: Uint8Array, options?: OpenOptions): Document;
107
+ /**
108
+ * Lays out a DOCX file read lazily from a random-access `ByteSource` (such as
109
+ * `createBlobSource(file)` or `createOpfsSource(handle)` inside a Web Worker) without copying
110
+ * the full archive into WebAssembly linear memory.
111
+ */
112
+ openDocxSource(source: ByteSource, options?: OpenOptions): Document;
113
+ /** Releases WebAssembly memory held by this renderer. */
114
+ free(): void;
115
+ [Symbol.dispose](): void;
116
+ }
117
+ /**
118
+ * Discovers the fonts requested by `docx` (including glyph-fallback families),
119
+ * fetches each missing family once via `fetchFont`, and registers them on `renderer`.
120
+ */
121
+ export declare function loadFontsFor(renderer: Renderer, docx: Uint8Array, fetchFont: FontFetcher, options?: OpenOptions): Promise<string[]>;
package/dist/core.js ADDED
@@ -0,0 +1,374 @@
1
+ import wasmInit, { Renderer as RawRenderer, } from "./wasm/f_office_wasm.js";
2
+ export { createBlobSource, createMemorySource, createOpfsSource, } from "./source.js";
3
+ const DEFAULT_TARGET = "word-win";
4
+ let initPromise = null;
5
+ let wasmMemory = null;
6
+ /**
7
+ * Returns the current byte length of the WebAssembly linear memory buffer, or `0` before
8
+ * `init()` completes. Useful for monitoring peak memory on mobile browsers.
9
+ */
10
+ export function wasmMemoryBytes() {
11
+ return wasmMemory ? wasmMemory.buffer.byteLength : 0;
12
+ }
13
+ /** @internal Shared initializer parameterized by the runtime-specific default WASM loader. */
14
+ export function initWithDefaultLoader(loadDefault, source) {
15
+ if (initPromise !== null && source === undefined) {
16
+ return initPromise;
17
+ }
18
+ const pending = (async () => {
19
+ if (source !== undefined) {
20
+ const output = await wasmInit({ module_or_path: source });
21
+ wasmMemory = output.memory;
22
+ return;
23
+ }
24
+ const wasmUrl = new URL("./wasm/f_office_wasm_bg.wasm", import.meta.url);
25
+ const output = await loadDefault(wasmUrl);
26
+ wasmMemory = output.memory;
27
+ })();
28
+ if (source === undefined) {
29
+ initPromise = pending;
30
+ }
31
+ return pending;
32
+ }
33
+ function unwrapFontNeeds(raw) {
34
+ const out = [];
35
+ for (const item of raw) {
36
+ try {
37
+ out.push({
38
+ family: item.family ?? null,
39
+ tried: item.tried,
40
+ });
41
+ }
42
+ finally {
43
+ item.free();
44
+ }
45
+ }
46
+ return out;
47
+ }
48
+ function unwrapOutline(raw) {
49
+ const out = [];
50
+ for (const item of raw) {
51
+ try {
52
+ out.push({
53
+ level: item.level,
54
+ text: item.text,
55
+ page: item.page,
56
+ address: item.address,
57
+ });
58
+ }
59
+ finally {
60
+ item.free();
61
+ }
62
+ }
63
+ return out;
64
+ }
65
+ function unwrapTextRuns(raw) {
66
+ const out = [];
67
+ for (const item of raw) {
68
+ try {
69
+ out.push({
70
+ text: item.text,
71
+ size: item.size,
72
+ left: item.left,
73
+ top: item.top,
74
+ width: item.width,
75
+ height: item.height,
76
+ baseline: item.baseline,
77
+ glyphLefts: item.glyphLefts,
78
+ glyphWidths: item.glyphWidths,
79
+ glyphEnds: item.glyphEnds,
80
+ });
81
+ }
82
+ finally {
83
+ item.free();
84
+ }
85
+ }
86
+ return out;
87
+ }
88
+ function unwrapSearchMatches(raw) {
89
+ const out = [];
90
+ for (const item of raw) {
91
+ try {
92
+ const flat = item.rects;
93
+ const rects = [];
94
+ for (let i = 0; i + 3 < flat.length; i += 4) {
95
+ rects.push({
96
+ left: flat[i],
97
+ top: flat[i + 1],
98
+ width: flat[i + 2],
99
+ height: flat[i + 3],
100
+ });
101
+ }
102
+ const range = {
103
+ paragraph: item.paragraph,
104
+ start: item.start,
105
+ end: item.end,
106
+ };
107
+ const address = item.address;
108
+ if (address !== undefined) {
109
+ range.address = address;
110
+ }
111
+ out.push({
112
+ page: item.page,
113
+ rects,
114
+ range,
115
+ snippet: item.snippet,
116
+ });
117
+ }
118
+ finally {
119
+ item.free();
120
+ }
121
+ }
122
+ return out;
123
+ }
124
+ /** A rendered page image (RGBA bytes, dimensions, and drawing warnings). */
125
+ export class PageImage {
126
+ #raw;
127
+ #cachedPixels = null;
128
+ constructor(raw) {
129
+ this.#raw = raw;
130
+ }
131
+ /** Width in pixels. */
132
+ get width() {
133
+ return this.#raw.width;
134
+ }
135
+ /** Height in pixels. */
136
+ get height() {
137
+ return this.#raw.height;
138
+ }
139
+ /** Distinct warnings produced while drawing this page. */
140
+ warnings() {
141
+ return this.#raw.warnings();
142
+ }
143
+ /**
144
+ * RGBA pixels copied out of WebAssembly memory, cached on first read so repeated
145
+ * accesses do not copy the buffer again.
146
+ */
147
+ get pixels() {
148
+ let cached = this.#cachedPixels;
149
+ if (cached === null) {
150
+ cached = this.#raw.pixels;
151
+ this.#cachedPixels = cached;
152
+ }
153
+ return cached;
154
+ }
155
+ /** Builds a browser `ImageData` backed by this page's RGBA pixels. */
156
+ toImageData() {
157
+ const data = new Uint8ClampedArray(this.pixels);
158
+ return new ImageData(data, this.width, this.height);
159
+ }
160
+ /** Releases WebAssembly memory held by this page image. */
161
+ free() {
162
+ this.#raw.free();
163
+ }
164
+ [Symbol.dispose]() {
165
+ this.free();
166
+ }
167
+ }
168
+ /** A laid-out DOCX document. Page indices are zero-based. */
169
+ export class Document {
170
+ #raw;
171
+ constructor(raw) {
172
+ this.#raw = raw;
173
+ }
174
+ /** Distinct layout warnings (such as substituted fonts or missing pictures). */
175
+ warnings() {
176
+ return this.#raw.warnings();
177
+ }
178
+ /**
179
+ * Fonts looked up during layout that were missing from the renderer, including
180
+ * glyph-fallback families discovered after primary fonts were loaded.
181
+ */
182
+ fontNeeds() {
183
+ return unwrapFontNeeds(this.#raw.fontNeeds());
184
+ }
185
+ /** Number of laid-out pages. */
186
+ pageCount() {
187
+ return this.#raw.pageCount();
188
+ }
189
+ /** Width in pixels of page `index` when rendered at `dpi`. */
190
+ pageWidth(index, dpi) {
191
+ return this.#raw.pageWidth(index, dpi);
192
+ }
193
+ /** Height in pixels of page `index` when rendered at `dpi`. */
194
+ pageHeight(index, dpi) {
195
+ return this.#raw.pageHeight(index, dpi);
196
+ }
197
+ /** Width and height in points of every page in order. */
198
+ pageSizes() {
199
+ const flat = this.#raw.pageSizes();
200
+ const out = [];
201
+ for (let i = 0; i + 1 < flat.length; i += 2) {
202
+ out.push({ width: flat[i], height: flat[i + 1] });
203
+ }
204
+ return out;
205
+ }
206
+ /** Upright text runs of page `index` in painting order. */
207
+ textRuns(index) {
208
+ return unwrapTextRuns(this.#raw.textRuns(index));
209
+ }
210
+ /** Document headings in reading order. */
211
+ outline() {
212
+ return unwrapOutline(this.#raw.outline());
213
+ }
214
+ /**
215
+ * Searches all stories of the document over the compact text map without rendering offscreen
216
+ * pages, returning lightweight `{ page, rects, range, snippet }` matches.
217
+ */
218
+ search(query, options) {
219
+ return unwrapSearchMatches(this.#raw.search(query, options?.caseSensitive, options?.wholeWord, options?.maxResults));
220
+ }
221
+ /** Renders page `index` at `dpi` pixels per inch on a white background. */
222
+ renderPage(index, dpi) {
223
+ return new PageImage(this.#raw.renderPage(index, dpi));
224
+ }
225
+ /**
226
+ * Renders only the rectangular pixel tile `region` of page `index` at `dpi` pixels per inch.
227
+ * Ideal for mobile viewports and high-zoom viewing with constant memory.
228
+ */
229
+ renderRegion(index, region, dpi) {
230
+ return new PageImage(this.#raw.renderRegion(index, region.x, region.y, region.width, region.height, dpi));
231
+ }
232
+ /** Writes all pages to a PDF file with fonts subset and embedded. */
233
+ writePdf() {
234
+ return this.#raw.writePdf();
235
+ }
236
+ /**
237
+ * Streams all pages as PDF 1.7 chunks into `onChunk` without allocating the full PDF in
238
+ * WebAssembly linear memory. Returns distinct PDF warnings.
239
+ */
240
+ writePdfTo(onChunk) {
241
+ return this.#raw.writePdfTo(onChunk);
242
+ }
243
+ /** Releases WebAssembly memory held by this document. */
244
+ free() {
245
+ this.#raw.free();
246
+ }
247
+ [Symbol.dispose]() {
248
+ this.free();
249
+ }
250
+ }
251
+ /** Holds loaded fonts and opens DOCX documents into laid-out pages. */
252
+ export class Renderer {
253
+ #raw;
254
+ constructor() {
255
+ this.#raw = new RawRenderer();
256
+ }
257
+ /** Returns the supported Word target IDs. */
258
+ static targets() {
259
+ return RawRenderer.targets();
260
+ }
261
+ /**
262
+ * Lists fonts requested by a DOCX file before any font is added.
263
+ * Defaults to `"word-win"`.
264
+ */
265
+ static fontsNeeded(docx, target = DEFAULT_TARGET) {
266
+ return unwrapFontNeeds(RawRenderer.fontsNeeded(docx, target));
267
+ }
268
+ /**
269
+ * Lists fonts requested by a DOCX file read lazily from a random-access `ByteSource` without
270
+ * copying the archive into WebAssembly linear memory.
271
+ */
272
+ static fontsNeededSource(source, target = DEFAULT_TARGET) {
273
+ return unwrapFontNeeds(RawRenderer.fontsNeededSource(source.byteLength, (offset, length) => source.readAt(offset, length), target));
274
+ }
275
+ /**
276
+ * Adds all faces from an OpenType font or collection (`.ttf`, `.otf`, `.ttc`, `.otc`) or a
277
+ * WOFF2 webfont (`.woff2`). Full-table WOFF2 preserves exact Word layout metrics; web-subsetted
278
+ * WOFF2 may omit glyphs or OpenType tables.
279
+ */
280
+ addFont(data) {
281
+ return this.#raw.addFont(data);
282
+ }
283
+ /** Adds art page border pictures. */
284
+ addArtPictures(data) {
285
+ return this.#raw.addArtPictures(data);
286
+ }
287
+ /** Lays out a DOCX file with the fonts currently added to this renderer. */
288
+ openDocx(docx, options) {
289
+ const target = options?.target ?? DEFAULT_TARGET;
290
+ const now = options?.now;
291
+ const raw = options?.limits === "mobile"
292
+ ? this.#raw.openDocxMobile(docx, target, now)
293
+ : this.#raw.openDocx(docx, target, now);
294
+ return new Document(raw);
295
+ }
296
+ /**
297
+ * Lays out a DOCX file read lazily from a random-access `ByteSource` (such as
298
+ * `createBlobSource(file)` or `createOpfsSource(handle)` inside a Web Worker) without copying
299
+ * the full archive into WebAssembly linear memory.
300
+ */
301
+ openDocxSource(source, options) {
302
+ const target = options?.target ?? DEFAULT_TARGET;
303
+ const now = options?.now;
304
+ const mobile = options?.limits === "mobile";
305
+ const raw = this.#raw.openDocxSource(source.byteLength, (offset, length) => source.readAt(offset, length), target, now, mobile);
306
+ return new Document(raw);
307
+ }
308
+ /** Releases WebAssembly memory held by this renderer. */
309
+ free() {
310
+ this.#raw.free();
311
+ }
312
+ [Symbol.dispose]() {
313
+ this.free();
314
+ }
315
+ }
316
+ /**
317
+ * Discovers the fonts requested by `docx` (including glyph-fallback families),
318
+ * fetches each missing family once via `fetchFont`, and registers them on `renderer`.
319
+ */
320
+ export async function loadFontsFor(renderer, docx, fetchFont, options) {
321
+ const target = options?.target ?? DEFAULT_TARGET;
322
+ const attempted = new Set();
323
+ const added = [];
324
+ const fetchNeeds = async (needs) => {
325
+ let addedHere = 0;
326
+ for (const need of needs) {
327
+ for (const family of need.tried) {
328
+ const key = family.toLowerCase();
329
+ if (attempted.has(key)) {
330
+ continue;
331
+ }
332
+ attempted.add(key);
333
+ const result = await fetchFont(family);
334
+ if (!result) {
335
+ continue;
336
+ }
337
+ const files = Array.isArray(result) ? result : [result];
338
+ let loaded = false;
339
+ for (const bytes of files) {
340
+ if (bytes.byteLength > 0) {
341
+ renderer.addFont(bytes);
342
+ loaded = true;
343
+ }
344
+ }
345
+ if (loaded) {
346
+ added.push(family);
347
+ addedHere += 1;
348
+ break;
349
+ }
350
+ }
351
+ }
352
+ return addedHere;
353
+ };
354
+ await fetchNeeds(Renderer.fontsNeeded(docx, target));
355
+ // Second pass catches fallback fonts requested for glyphs absent from the primary fonts.
356
+ for (let pass = 0; pass < 3; pass += 1) {
357
+ const doc = renderer.openDocx(docx, options);
358
+ let remaining;
359
+ try {
360
+ remaining = doc.fontNeeds();
361
+ }
362
+ finally {
363
+ doc.free();
364
+ }
365
+ if (remaining.length === 0) {
366
+ break;
367
+ }
368
+ const newlyAdded = await fetchNeeds(remaining);
369
+ if (newlyAdded === 0) {
370
+ break;
371
+ }
372
+ }
373
+ return added;
374
+ }
package/dist/index.d.ts CHANGED
@@ -1,113 +1 @@
1
- import { Document as RawDocument, PageImage as RawPageImage } from "./wasm/f_office_wasm.js";
2
- import type { ByteSource, FontFetcher, FontNeed, OpenOptions, OutlineEntry, PageSizePoints, PdfChunkCallback, PixelRegion, TargetId, TextRun, WasmInitSource } from "./types.js";
3
- export type { ByteSource, FontFetcher, FontNeed, LimitProfile, OpenOptions, OutlineEntry, PageSizePoints, PdfChunkCallback, PixelRegion, RenderedPageData, TargetId, TextRun, WasmInitSource, } from "./types.js";
4
- export { createBlobSource, createMemorySource, createOpfsSource, type OpfsSyncAccessHandle, } from "./source.js";
5
- /**
6
- * Returns the current byte length of the WebAssembly linear memory buffer, or `0` before
7
- * `init()` completes. Useful for monitoring peak memory on mobile browsers.
8
- */
9
- export declare function wasmMemoryBytes(): number;
10
- /**
11
- * Initializes the F-Office WebAssembly module. Safe to call multiple times;
12
- * subsequent calls resolve immediately once initialized.
13
- */
14
- export declare function init(source?: WasmInitSource): Promise<void>;
15
- /** A rendered page image (RGBA bytes, dimensions, and drawing warnings). */
16
- export declare class PageImage implements Disposable {
17
- #private;
18
- constructor(raw: RawPageImage);
19
- /** Width in pixels. */
20
- get width(): number;
21
- /** Height in pixels. */
22
- get height(): number;
23
- /** Distinct warnings produced while drawing this page. */
24
- warnings(): string[];
25
- /**
26
- * RGBA pixels copied out of WebAssembly memory, cached on first read so repeated
27
- * accesses do not copy the buffer again.
28
- */
29
- get pixels(): Uint8ClampedArray;
30
- /** Builds a browser `ImageData` backed by this page's RGBA pixels. */
31
- toImageData(): ImageData;
32
- /** Releases WebAssembly memory held by this page image. */
33
- free(): void;
34
- [Symbol.dispose](): void;
35
- }
36
- /** A laid-out DOCX document. Page indices are zero-based. */
37
- export declare class Document implements Disposable {
38
- #private;
39
- constructor(raw: RawDocument);
40
- /** Distinct layout warnings (such as substituted fonts or missing pictures). */
41
- warnings(): string[];
42
- /**
43
- * Fonts looked up during layout that were missing from the renderer, including
44
- * glyph-fallback families discovered after primary fonts were loaded.
45
- */
46
- fontNeeds(): FontNeed[];
47
- /** Number of laid-out pages. */
48
- pageCount(): number;
49
- /** Width in pixels of page `index` when rendered at `dpi`. */
50
- pageWidth(index: number, dpi: number): number;
51
- /** Height in pixels of page `index` when rendered at `dpi`. */
52
- pageHeight(index: number, dpi: number): number;
53
- /** Width and height in points of every page in order. */
54
- pageSizes(): PageSizePoints[];
55
- /** Upright text runs of page `index` in painting order. */
56
- textRuns(index: number): TextRun[];
57
- /** Document headings in reading order. */
58
- outline(): OutlineEntry[];
59
- /** Renders page `index` at `dpi` pixels per inch on a white background. */
60
- renderPage(index: number, dpi: number): PageImage;
61
- /**
62
- * Renders only the rectangular pixel tile `region` of page `index` at `dpi` pixels per inch.
63
- * Ideal for mobile viewports and high-zoom viewing with constant memory.
64
- */
65
- renderRegion(index: number, region: PixelRegion, dpi: number): PageImage;
66
- /** Writes all pages to a PDF file with fonts subset and embedded. */
67
- writePdf(): Uint8Array;
68
- /**
69
- * Streams all pages as PDF 1.7 chunks into `onChunk` without allocating the full PDF in
70
- * WebAssembly linear memory. Returns distinct PDF warnings.
71
- */
72
- writePdfTo(onChunk: PdfChunkCallback): string[];
73
- /** Releases WebAssembly memory held by this document. */
74
- free(): void;
75
- [Symbol.dispose](): void;
76
- }
77
- /** Holds loaded fonts and opens DOCX documents into laid-out pages. */
78
- export declare class Renderer implements Disposable {
79
- #private;
80
- constructor();
81
- /** Returns the supported Word target IDs. */
82
- static targets(): TargetId[];
83
- /**
84
- * Lists fonts requested by a DOCX file before any font is added.
85
- * Defaults to `"word-win"`.
86
- */
87
- static fontsNeeded(docx: Uint8Array, target?: TargetId): FontNeed[];
88
- /**
89
- * Lists fonts requested by a DOCX file read lazily from a random-access `ByteSource` without
90
- * copying the archive into WebAssembly linear memory.
91
- */
92
- static fontsNeededSource(source: ByteSource, target?: TargetId): FontNeed[];
93
- /** Adds all faces from an OpenType font or collection (`.ttf`, `.otf`, `.ttc`, `.otc`). */
94
- addFont(data: Uint8Array): number;
95
- /** Adds art page border pictures. */
96
- addArtPictures(data: Uint8Array): number;
97
- /** Lays out a DOCX file with the fonts currently added to this renderer. */
98
- openDocx(docx: Uint8Array, options?: OpenOptions): Document;
99
- /**
100
- * Lays out a DOCX file read lazily from a random-access `ByteSource` (such as
101
- * `createBlobSource(file)` or `createOpfsSource(handle)` inside a Web Worker) without copying
102
- * the full archive into WebAssembly linear memory.
103
- */
104
- openDocxSource(source: ByteSource, options?: OpenOptions): Document;
105
- /** Releases WebAssembly memory held by this renderer. */
106
- free(): void;
107
- [Symbol.dispose](): void;
108
- }
109
- /**
110
- * Discovers the fonts requested by `docx` (including glyph-fallback families),
111
- * fetches each missing family once via `fetchFont`, and registers them on `renderer`.
112
- */
113
- export declare function loadFontsFor(renderer: Renderer, docx: Uint8Array, fetchFont: FontFetcher, options?: OpenOptions): Promise<string[]>;
1
+ export { createBlobSource, createMemorySource, createOpfsSource, Document, init, loadFontsFor, PageImage, Renderer, wasmMemoryBytes, type ByteSource, type FontFetcher, type FontNeed, type LimitProfile, type OpenOptions, type OpfsSyncAccessHandle, type OutlineEntry, type PageRect, type PageSizePoints, type PdfChunkCallback, type PixelRegion, type RenderedPageData, type SearchMatch, type SearchOptions, type SearchRange, type TargetId, type TextRun, type WasmInitSource, } from "./browser.js";