@f-office/wasm 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,168 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separately separable from, or merely link (or bind by name) to the
46
+ interfaces of, the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated into the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Work; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Work, in at least one of the
111
+ following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own copyright
118
+ notice to Your own Derivative Works and may provide additional
119
+ or different license terms for use, reproduction, or distribution
120
+ of Your own Derivative Works, or for any such Derivative Works
121
+ as a whole, provided Your use, reproduction, or distribution
122
+ of the Work otherwise complies with the License.
123
+
124
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
125
+ any Contribution intentionally submitted for inclusion in the Work
126
+ by You to the Licensor shall be dual-licensed under the MIT License
127
+ and the Apache License, Version 2.0, without any additional terms or
128
+ conditions. Notwithstanding the above, nothing herein shall supersede
129
+ or modify the terms of any separate license agreement you may have
130
+ with Licensor regarding such Contributions.
131
+
132
+ 6. Trademarks. This License does not grant permission to use the trade
133
+ names, trademarks, service marks, or product names of the Licensor,
134
+ except as required for reasonable and customary use in describing the
135
+ origin of the Work and reproducing the content of the NOTICE file.
136
+
137
+ 7. Disclaimer of Warranty. Unless required by applicable law or
138
+ agreed to in writing, Licensor provides the Work (and its
139
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR
140
+ CONDITIONS OF ANY KIND, either express or implied. You are solely
141
+ responsible for determining the appropriateness of the Work and
142
+ assume any risks associated with Your exercise of permissions under
143
+ this License.
144
+
145
+ 8. Limitation of Liability. In no event and under no legal theory,
146
+ whether in tort (including negligence), contract, or otherwise,
147
+ unless required by applicable law (such as deliberate and grossly
148
+ negligent acts) or agreed to in writing, shall any Contributor be
149
+ liable for damages, including any direct, indirect, special,
150
+ incidental, or consequential damages of any character arising as a
151
+ result of this License or out of the use or inability to use the
152
+ Work (including but not limited to damages for loss of goodwill,
153
+ work stoppage, computer failure or malfunction, or any and all
154
+ other commercial damages or losses), even if such Contributor
155
+ has been advised of the possibility of such damages.
156
+
157
+ 9. Accepting Warranty or Additional Liability. While redistributing
158
+ the Work or Derivative Works thereof, You may choose to accept,
159
+ and charge a fee for, acceptance of support, warranty, or indemnity
160
+ obligations and/or other liability obligations and/or rights
161
+ consistent with this License. However, in accepting such obligations,
162
+ You may act only on Your own behalf and on Your own responsibility,
163
+ and not on behalf of any other Contributor, and only if You agree
164
+ to indemnify, defend, and hold each Contributor harmless for any
165
+ liability incurred by, or claims arising from, such Contributor
166
+ by reason of your accepting any such warranty or additional liability.
167
+
168
+ END OF TERMS AND CONDITIONS
package/NOTICE ADDED
@@ -0,0 +1,31 @@
1
+ F-Office
2
+ Copyright (c) 2026 Onur Solmaz and F-Office Contributors
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (Apache-2.0).
5
+
6
+ Third-Party Notices
7
+ -------------------
8
+
9
+ 1. DrawingML Preset Shape Definitions (`crates/f-office-drawingml/presets/NOTICE`)
10
+ Derived from ECMA-376 preset shape geometry definitions, Ecma International.
11
+ See `crates/f-office-drawingml/presets/NOTICE` for the full notice.
12
+
13
+ 2. Symbol Font Unicode Mappings (`crates/f-office-fonts`)
14
+ Based on `dingbat-to-unicode` (BSD-2-Clause License) and Unicode Consortium
15
+ mapping tables.
16
+
17
+ 3. Windows Code Page Tables (`crates/f-office-fonts`, `crates/f-office-docx`)
18
+ Derived from Unicode Consortium / Microsoft public code page mapping tables.
19
+
20
+ 4. Hyphenation Patterns (`crates/f-office-hyphenate/data/hyph-*.tex`)
21
+ TeX `hyph-utf8` hyphenation pattern files for English, French, and Spanish.
22
+ See the header of each `.tex` file for its individual copyright and license
23
+ notice.
24
+
25
+ 5. Open Fonts (optional `open-fonts` feature, enabled by default in `foffice`)
26
+ Provided via the independent `compatifont` project under the SIL Open Font
27
+ License 1.1 (OFL-1.1).
28
+
29
+ 6. Apache-2.0 and Permissive Rust Dependencies
30
+ Includes crates licensed under MIT, Apache-2.0, BSD-2-Clause, BSD-3-Clause,
31
+ Unicode-3.0, and Zlib (including `ab_glyph_rasterizer`, `zopfli`, and `ryu`).
package/README.md CHANGED
@@ -1,3 +1,80 @@
1
- # Temporary Holding Version
1
+ # `@f-office/wasm`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Render and convert DOCX documents to pixels and PDF with Microsoft Word's pagination in browsers and Node.js.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @f-office/wasm
9
+ ```
10
+
11
+ ## Quickstart (Browser or Node.js)
12
+
13
+ ```ts
14
+ import { init, Renderer, loadFontsFor } from "@f-office/wasm";
15
+
16
+ await init();
17
+
18
+ const renderer = new Renderer();
19
+ await loadFontsFor(renderer, docxBytes, async (family) => {
20
+ // Fetch TTF/OTF bytes for `family` from @compatifont/fonts, your CDN, or local storage.
21
+ return fetchFontFamily(family);
22
+ });
23
+
24
+ using doc = renderer.openDocx(docxBytes, { target: "word-win" });
25
+ console.log("pages:", doc.pageCount());
26
+
27
+ // Render page 0 at screen DPI
28
+ using page = doc.renderPage(0, 96 * (globalThis.devicePixelRatio ?? 1));
29
+ canvasCtx.putImageData(page.toImageData(), 0, 0);
30
+
31
+ // Export the entire document as a PDF
32
+ const pdfBytes = doc.writePdf();
33
+ ```
34
+
35
+ If your environment does not support `using` (`Symbol.dispose`), call `page.free()`, `doc.free()`, and `renderer.free()` in `finally` blocks.
36
+
37
+ ## Web Worker usage
38
+
39
+ Keep layout and rasterization off the main browser thread using `@f-office/wasm/worker`:
40
+
41
+ ```ts
42
+ import { createWorkerRenderer } from "@f-office/wasm/worker";
43
+
44
+ const worker = new Worker(new URL("@f-office/wasm/worker", import.meta.url), {
45
+ type: "module",
46
+ });
47
+ const client = createWorkerRenderer(worker);
48
+
49
+ await client.init();
50
+ await client.addFont(fontBytes);
51
+ const doc = await client.openDocx(docxBytes, { target: "word-win" });
52
+ const page = await client.renderPage(doc.id, 0, 96 * devicePixelRatio);
53
+ ctx.putImageData(new ImageData(page.pixels, page.width, page.height), 0, 0);
54
+ const pdf = await client.writePdf(doc.id);
55
+ await client.closeDocx(doc.id);
56
+ ```
57
+
58
+ ## Mobile & low-RAM guidance
59
+
60
+ WebAssembly linear memory can grow but never shrink. For phones and memory-constrained browser tabs:
61
+
62
+ - Open files with `{ limits: "mobile" }` to enforce bounded part, total, and XML node limits cleanly.
63
+ - Render only visible viewport tiles with `doc.renderRegion(pageIndex, { x, y, width, height }, dpi)` instead of full high-DPI pages.
64
+ - Use `createRecyclableWorkerRenderer(() => new Worker(...), { recycleAboveBytes: 128 * 1024 * 1024 })` from `@f-office/wasm/worker` so WASM linear memory is transparently returned to the OS when documents are closed.
65
+
66
+ ## Bundler notes
67
+
68
+ - **Vite**: add `@f-office/wasm` to `optimizeDeps.exclude` in `vite.config.ts` so Vite preserves the `.wasm` asset URL:
69
+ ```ts
70
+ export default {
71
+ optimizeDeps: { exclude: ["@f-office/wasm"] },
72
+ };
73
+ ```
74
+ - **Targets**: `"word-win"` (Microsoft Word for Windows) is the default and only stable target in v0.1. Preview `"word-mac"` and `"word-web"` targets remain in the repository behind Cargo's `preview-targets` feature and are not enabled in v0.1 builds.
75
+ - **Browser requirements**: WebAssembly SIMD128 (Chrome 91+, Firefox 89+, Safari 16.4+, Node.js 20+).
76
+ - **Fonts**: Browsers have no system font folder. Pair `@f-office/wasm` with the independent [Compatifont](https://github.com/osolmaz/compatifont) open fonts or your own font files.
77
+
78
+ ## License
79
+
80
+ Licensed under `Apache-2.0`.
@@ -0,0 +1,113 @@
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[]>;