@f-office/core 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,342 +1 @@
1
- import wasmInit, { initSync, 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
- function isNodeRuntime() {
7
- return (typeof process !== "undefined" &&
8
- typeof process.versions === "object" &&
9
- typeof process.versions.node === "string");
10
- }
11
- /**
12
- * Returns the current byte length of the WebAssembly linear memory buffer, or `0` before
13
- * `init()` completes. Useful for monitoring peak memory on mobile browsers.
14
- */
15
- export function wasmMemoryBytes() {
16
- return wasmMemory ? wasmMemory.buffer.byteLength : 0;
17
- }
18
- /**
19
- * Initializes the F-Office WebAssembly module. Safe to call multiple times;
20
- * subsequent calls resolve immediately once initialized.
21
- */
22
- export function init(source) {
23
- if (initPromise !== null && source === undefined) {
24
- return initPromise;
25
- }
26
- const pending = (async () => {
27
- if (source !== undefined) {
28
- const output = await wasmInit({ module_or_path: source });
29
- wasmMemory = output.memory;
30
- return;
31
- }
32
- const wasmUrl = new URL("./wasm/f_office_wasm_bg.wasm", import.meta.url);
33
- if (isNodeRuntime()) {
34
- const { readFile } = await import("node:fs/promises");
35
- const bytes = await readFile(wasmUrl);
36
- const output = initSync({ module: bytes });
37
- wasmMemory = output.memory;
38
- return;
39
- }
40
- const output = await wasmInit({ module_or_path: wasmUrl });
41
- wasmMemory = output.memory;
42
- })();
43
- if (source === undefined) {
44
- initPromise = pending;
45
- }
46
- return pending;
47
- }
48
- function unwrapFontNeeds(raw) {
49
- const out = [];
50
- for (const item of raw) {
51
- try {
52
- out.push({
53
- family: item.family ?? null,
54
- tried: item.tried,
55
- });
56
- }
57
- finally {
58
- item.free();
59
- }
60
- }
61
- return out;
62
- }
63
- function unwrapOutline(raw) {
64
- const out = [];
65
- for (const item of raw) {
66
- try {
67
- out.push({
68
- level: item.level,
69
- text: item.text,
70
- page: item.page,
71
- address: item.address,
72
- });
73
- }
74
- finally {
75
- item.free();
76
- }
77
- }
78
- return out;
79
- }
80
- function unwrapTextRuns(raw) {
81
- const out = [];
82
- for (const item of raw) {
83
- try {
84
- out.push({
85
- text: item.text,
86
- size: item.size,
87
- left: item.left,
88
- top: item.top,
89
- width: item.width,
90
- height: item.height,
91
- baseline: item.baseline,
92
- glyphLefts: item.glyphLefts,
93
- glyphWidths: item.glyphWidths,
94
- glyphEnds: item.glyphEnds,
95
- });
96
- }
97
- finally {
98
- item.free();
99
- }
100
- }
101
- return out;
102
- }
103
- /** A rendered page image (RGBA bytes, dimensions, and drawing warnings). */
104
- export class PageImage {
105
- #raw;
106
- #cachedPixels = null;
107
- constructor(raw) {
108
- this.#raw = raw;
109
- }
110
- /** Width in pixels. */
111
- get width() {
112
- return this.#raw.width;
113
- }
114
- /** Height in pixels. */
115
- get height() {
116
- return this.#raw.height;
117
- }
118
- /** Distinct warnings produced while drawing this page. */
119
- warnings() {
120
- return this.#raw.warnings();
121
- }
122
- /**
123
- * RGBA pixels copied out of WebAssembly memory, cached on first read so repeated
124
- * accesses do not copy the buffer again.
125
- */
126
- get pixels() {
127
- let cached = this.#cachedPixels;
128
- if (cached === null) {
129
- cached = this.#raw.pixels;
130
- this.#cachedPixels = cached;
131
- }
132
- return cached;
133
- }
134
- /** Builds a browser `ImageData` backed by this page's RGBA pixels. */
135
- toImageData() {
136
- const data = new Uint8ClampedArray(this.pixels);
137
- return new ImageData(data, this.width, this.height);
138
- }
139
- /** Releases WebAssembly memory held by this page image. */
140
- free() {
141
- this.#raw.free();
142
- }
143
- [Symbol.dispose]() {
144
- this.free();
145
- }
146
- }
147
- /** A laid-out DOCX document. Page indices are zero-based. */
148
- export class Document {
149
- #raw;
150
- constructor(raw) {
151
- this.#raw = raw;
152
- }
153
- /** Distinct layout warnings (such as substituted fonts or missing pictures). */
154
- warnings() {
155
- return this.#raw.warnings();
156
- }
157
- /**
158
- * Fonts looked up during layout that were missing from the renderer, including
159
- * glyph-fallback families discovered after primary fonts were loaded.
160
- */
161
- fontNeeds() {
162
- return unwrapFontNeeds(this.#raw.fontNeeds());
163
- }
164
- /** Number of laid-out pages. */
165
- pageCount() {
166
- return this.#raw.pageCount();
167
- }
168
- /** Width in pixels of page `index` when rendered at `dpi`. */
169
- pageWidth(index, dpi) {
170
- return this.#raw.pageWidth(index, dpi);
171
- }
172
- /** Height in pixels of page `index` when rendered at `dpi`. */
173
- pageHeight(index, dpi) {
174
- return this.#raw.pageHeight(index, dpi);
175
- }
176
- /** Width and height in points of every page in order. */
177
- pageSizes() {
178
- const flat = this.#raw.pageSizes();
179
- const out = [];
180
- for (let i = 0; i + 1 < flat.length; i += 2) {
181
- out.push({ width: flat[i], height: flat[i + 1] });
182
- }
183
- return out;
184
- }
185
- /** Upright text runs of page `index` in painting order. */
186
- textRuns(index) {
187
- return unwrapTextRuns(this.#raw.textRuns(index));
188
- }
189
- /** Document headings in reading order. */
190
- outline() {
191
- return unwrapOutline(this.#raw.outline());
192
- }
193
- /** Renders page `index` at `dpi` pixels per inch on a white background. */
194
- renderPage(index, dpi) {
195
- return new PageImage(this.#raw.renderPage(index, dpi));
196
- }
197
- /**
198
- * Renders only the rectangular pixel tile `region` of page `index` at `dpi` pixels per inch.
199
- * Ideal for mobile viewports and high-zoom viewing with constant memory.
200
- */
201
- renderRegion(index, region, dpi) {
202
- return new PageImage(this.#raw.renderRegion(index, region.x, region.y, region.width, region.height, dpi));
203
- }
204
- /** Writes all pages to a PDF file with fonts subset and embedded. */
205
- writePdf() {
206
- return this.#raw.writePdf();
207
- }
208
- /**
209
- * Streams all pages as PDF 1.7 chunks into `onChunk` without allocating the full PDF in
210
- * WebAssembly linear memory. Returns distinct PDF warnings.
211
- */
212
- writePdfTo(onChunk) {
213
- return this.#raw.writePdfTo(onChunk);
214
- }
215
- /** Releases WebAssembly memory held by this document. */
216
- free() {
217
- this.#raw.free();
218
- }
219
- [Symbol.dispose]() {
220
- this.free();
221
- }
222
- }
223
- /** Holds loaded fonts and opens DOCX documents into laid-out pages. */
224
- export class Renderer {
225
- #raw;
226
- constructor() {
227
- this.#raw = new RawRenderer();
228
- }
229
- /** Returns the supported Word target IDs. */
230
- static targets() {
231
- return RawRenderer.targets();
232
- }
233
- /**
234
- * Lists fonts requested by a DOCX file before any font is added.
235
- * Defaults to `"word-win"`.
236
- */
237
- static fontsNeeded(docx, target = DEFAULT_TARGET) {
238
- return unwrapFontNeeds(RawRenderer.fontsNeeded(docx, target));
239
- }
240
- /**
241
- * Lists fonts requested by a DOCX file read lazily from a random-access `ByteSource` without
242
- * copying the archive into WebAssembly linear memory.
243
- */
244
- static fontsNeededSource(source, target = DEFAULT_TARGET) {
245
- return unwrapFontNeeds(RawRenderer.fontsNeededSource(source.byteLength, (offset, length) => source.readAt(offset, length), target));
246
- }
247
- /** Adds all faces from an OpenType font or collection (`.ttf`, `.otf`, `.ttc`, `.otc`). */
248
- addFont(data) {
249
- return this.#raw.addFont(data);
250
- }
251
- /** Adds art page border pictures. */
252
- addArtPictures(data) {
253
- return this.#raw.addArtPictures(data);
254
- }
255
- /** Lays out a DOCX file with the fonts currently added to this renderer. */
256
- openDocx(docx, options) {
257
- const target = options?.target ?? DEFAULT_TARGET;
258
- const now = options?.now;
259
- const raw = options?.limits === "mobile"
260
- ? this.#raw.openDocxMobile(docx, target, now)
261
- : this.#raw.openDocx(docx, target, now);
262
- return new Document(raw);
263
- }
264
- /**
265
- * Lays out a DOCX file read lazily from a random-access `ByteSource` (such as
266
- * `createBlobSource(file)` or `createOpfsSource(handle)` inside a Web Worker) without copying
267
- * the full archive into WebAssembly linear memory.
268
- */
269
- openDocxSource(source, options) {
270
- const target = options?.target ?? DEFAULT_TARGET;
271
- const now = options?.now;
272
- const mobile = options?.limits === "mobile";
273
- const raw = this.#raw.openDocxSource(source.byteLength, (offset, length) => source.readAt(offset, length), target, now, mobile);
274
- return new Document(raw);
275
- }
276
- /** Releases WebAssembly memory held by this renderer. */
277
- free() {
278
- this.#raw.free();
279
- }
280
- [Symbol.dispose]() {
281
- this.free();
282
- }
283
- }
284
- /**
285
- * Discovers the fonts requested by `docx` (including glyph-fallback families),
286
- * fetches each missing family once via `fetchFont`, and registers them on `renderer`.
287
- */
288
- export async function loadFontsFor(renderer, docx, fetchFont, options) {
289
- const target = options?.target ?? DEFAULT_TARGET;
290
- const attempted = new Set();
291
- const added = [];
292
- const fetchNeeds = async (needs) => {
293
- let addedHere = 0;
294
- for (const need of needs) {
295
- for (const family of need.tried) {
296
- const key = family.toLowerCase();
297
- if (attempted.has(key)) {
298
- continue;
299
- }
300
- attempted.add(key);
301
- const result = await fetchFont(family);
302
- if (!result) {
303
- continue;
304
- }
305
- const files = Array.isArray(result) ? result : [result];
306
- let loaded = false;
307
- for (const bytes of files) {
308
- if (bytes.byteLength > 0) {
309
- renderer.addFont(bytes);
310
- loaded = true;
311
- }
312
- }
313
- if (loaded) {
314
- added.push(family);
315
- addedHere += 1;
316
- break;
317
- }
318
- }
319
- }
320
- return addedHere;
321
- };
322
- await fetchNeeds(Renderer.fontsNeeded(docx, target));
323
- // Second pass catches fallback fonts requested for glyphs absent from the primary fonts.
324
- for (let pass = 0; pass < 3; pass += 1) {
325
- const doc = renderer.openDocx(docx, options);
326
- let remaining;
327
- try {
328
- remaining = doc.fontNeeds();
329
- }
330
- finally {
331
- doc.free();
332
- }
333
- if (remaining.length === 0) {
334
- break;
335
- }
336
- const newlyAdded = await fetchNeeds(remaining);
337
- if (newlyAdded === 0) {
338
- break;
339
- }
340
- }
341
- return added;
342
- }
1
+ export { createBlobSource, createMemorySource, createOpfsSource, Document, Drawing, init, loadFontsFor, PageImage, Renderer, Session, wasmMemoryBytes, } from "./browser.js";
package/dist/node.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { WasmInitSource } from "./types.js";
2
+ export { createBlobSource, createMemorySource, createOpfsSource, Document, Drawing, loadFontsFor, PageImage, Renderer, Session, 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 Node.js by reading the bundled `.wasm` binary
5
+ * directly from disk when `source` is omitted.
6
+ */
7
+ export declare function init(source?: WasmInitSource): Promise<void>;
package/dist/node.js ADDED
@@ -0,0 +1,14 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { initSync } from "./wasm/f_office_wasm.js";
3
+ import { initWithDefaultLoader } from "./core.js";
4
+ export { createBlobSource, createMemorySource, createOpfsSource, Document, Drawing, loadFontsFor, PageImage, Renderer, Session, wasmMemoryBytes, } from "./core.js";
5
+ /**
6
+ * Initializes the F-Office WebAssembly module in Node.js by reading the bundled `.wasm` binary
7
+ * directly from disk when `source` is omitted.
8
+ */
9
+ export function init(source) {
10
+ return initWithDefaultLoader(async (wasmUrl) => {
11
+ const bytes = await readFile(wasmUrl);
12
+ return initSync({ module: bytes });
13
+ }, source);
14
+ }
package/dist/types.d.ts CHANGED
@@ -66,7 +66,48 @@ export interface TextRun {
66
66
  glyphWidths: Float64Array;
67
67
  glyphEnds: Uint32Array;
68
68
  }
69
- /** Async callback that fetches font file bytes (`.ttf`, `.otf`, `.ttc`, `.otc`) for a family. */
69
+ /** An axis-aligned rectangle on a page in typographic points (1/72 inch) from top-left. */
70
+ export interface PageRect {
71
+ left: number;
72
+ top: number;
73
+ width: number;
74
+ height: number;
75
+ }
76
+ /** Options for whole-document text search over the compact text map. */
77
+ export interface SearchOptions {
78
+ /** Match exact character case when `true`. Defaults to `false`. */
79
+ caseSensitive?: boolean;
80
+ /** Require word boundaries around each match when `true`. Defaults to `false`. */
81
+ wholeWord?: boolean;
82
+ /** Optional cap on the number of returned matches. */
83
+ maxResults?: number;
84
+ }
85
+ /** Logical UTF-16 character range of a search match within its paragraph. */
86
+ export interface SearchRange {
87
+ /** Zero-based paragraph index within the matched story. */
88
+ paragraph: number;
89
+ /** Start offset in UTF-16 code units within the paragraph text. */
90
+ start: number;
91
+ /** Exclusive end offset in UTF-16 code units within the paragraph text. */
92
+ end: number;
93
+ /** Stable paragraph address when present (for example `"p12"`). */
94
+ address?: string;
95
+ }
96
+ /** One search match returned by `Document.search()` / `WorkerRendererClient.search()`. */
97
+ export interface SearchMatch {
98
+ /** Zero-based page index where the match starts. */
99
+ page: number;
100
+ /** Highlight rectangles on `page` in typographic points (1/72 inch). */
101
+ rects: PageRect[];
102
+ /** Paragraph index, UTF-16 offsets, and optional stable address. */
103
+ range: SearchRange;
104
+ /** Short surrounding context excerpt from the matched paragraph. */
105
+ snippet: string;
106
+ }
107
+ /**
108
+ * Async callback that fetches font file bytes (`.ttf`, `.otf`, `.ttc`, `.otc`, or full-table
109
+ * `.woff2`) for a family.
110
+ */
70
111
  export type FontFetcher = (family: string) => Promise<Uint8Array[] | Uint8Array | null | undefined>;
71
112
  /** Optional source override passed to `init()`. */
72
113
  export type WasmInitSource = URL | string | Request | Response | BufferSource | WebAssembly.Module;