docxkeun 0.0.0-stage → 0.1.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.
Files changed (138) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +252 -2
  4. package/dist/api/editor.d.ts +253 -0
  5. package/dist/api/editor.js +1121 -0
  6. package/dist/api/index.d.ts +3 -0
  7. package/dist/api/index.js +3 -0
  8. package/dist/api/parts.d.ts +21 -0
  9. package/dist/api/parts.js +66 -0
  10. package/dist/api/positions.d.ts +57 -0
  11. package/dist/api/positions.js +229 -0
  12. package/dist/comments/read.d.ts +26 -0
  13. package/dist/comments/read.js +66 -0
  14. package/dist/crypto/aes.d.ts +18 -0
  15. package/dist/crypto/aes.js +229 -0
  16. package/dist/crypto/index.d.ts +4 -0
  17. package/dist/crypto/index.js +8 -0
  18. package/dist/crypto/sha.d.ts +14 -0
  19. package/dist/crypto/sha.js +297 -0
  20. package/dist/fonts/bundled.d.ts +26 -0
  21. package/dist/fonts/bundled.js +41 -0
  22. package/dist/fonts/embedded.d.ts +5 -0
  23. package/dist/fonts/embedded.js +42 -0
  24. package/dist/fonts/index.d.ts +6 -0
  25. package/dist/fonts/index.js +6 -0
  26. package/dist/fonts/odttf.d.ts +7 -0
  27. package/dist/fonts/odttf.js +22 -0
  28. package/dist/fonts/registry.d.ts +57 -0
  29. package/dist/fonts/registry.js +126 -0
  30. package/dist/fonts/sfnt.d.ts +91 -0
  31. package/dist/fonts/sfnt.js +416 -0
  32. package/dist/fonts/subset.d.ts +12 -0
  33. package/dist/fonts/subset.js +143 -0
  34. package/dist/index.d.ts +15 -0
  35. package/dist/index.js +18 -0
  36. package/dist/layout/blocks.d.ts +56 -0
  37. package/dist/layout/blocks.js +422 -0
  38. package/dist/layout/engine.d.ts +13 -0
  39. package/dist/layout/engine.js +471 -0
  40. package/dist/layout/fonts.d.ts +11 -0
  41. package/dist/layout/fonts.js +73 -0
  42. package/dist/layout/index.d.ts +5 -0
  43. package/dist/layout/index.js +4 -0
  44. package/dist/layout/lines.d.ts +194 -0
  45. package/dist/layout/lines.js +511 -0
  46. package/dist/layout/paint.d.ts +38 -0
  47. package/dist/layout/paint.js +217 -0
  48. package/dist/layout/style.d.ts +42 -0
  49. package/dist/layout/style.js +95 -0
  50. package/dist/layout/types.d.ts +172 -0
  51. package/dist/layout/types.js +1 -0
  52. package/dist/model/content.d.ts +218 -0
  53. package/dist/model/content.js +696 -0
  54. package/dist/model/document.d.ts +110 -0
  55. package/dist/model/document.js +275 -0
  56. package/dist/model/fields.d.ts +17 -0
  57. package/dist/model/fields.js +77 -0
  58. package/dist/model/index.d.ts +8 -0
  59. package/dist/model/index.js +8 -0
  60. package/dist/model/numbering.d.ts +53 -0
  61. package/dist/model/numbering.js +245 -0
  62. package/dist/model/props.d.ts +230 -0
  63. package/dist/model/props.js +505 -0
  64. package/dist/model/styles.d.ts +72 -0
  65. package/dist/model/styles.js +178 -0
  66. package/dist/model/theme.d.ts +21 -0
  67. package/dist/model/theme.js +102 -0
  68. package/dist/model/units.d.ts +27 -0
  69. package/dist/model/units.js +81 -0
  70. package/dist/opc/constants.d.ts +53 -0
  71. package/dist/opc/constants.js +70 -0
  72. package/dist/opc/index.d.ts +3 -0
  73. package/dist/opc/index.js +3 -0
  74. package/dist/opc/package.d.ts +66 -0
  75. package/dist/opc/package.js +282 -0
  76. package/dist/opc/paths.d.ts +12 -0
  77. package/dist/opc/paths.js +61 -0
  78. package/dist/pdf/export.d.ts +25 -0
  79. package/dist/pdf/export.js +326 -0
  80. package/dist/pdf/fonts.d.ts +19 -0
  81. package/dist/pdf/fonts.js +122 -0
  82. package/dist/pdf/images.d.ts +13 -0
  83. package/dist/pdf/images.js +264 -0
  84. package/dist/pdf/index.d.ts +4 -0
  85. package/dist/pdf/index.js +4 -0
  86. package/dist/pdf/objects.d.ts +38 -0
  87. package/dist/pdf/objects.js +148 -0
  88. package/dist/pdf/writer.d.ts +19 -0
  89. package/dist/pdf/writer.js +58 -0
  90. package/dist/react/index.d.ts +28 -0
  91. package/dist/react/index.js +39 -0
  92. package/dist/render/canvas-fonts.d.ts +8 -0
  93. package/dist/render/canvas-fonts.js +87 -0
  94. package/dist/render/editing.d.ts +109 -0
  95. package/dist/render/editing.js +830 -0
  96. package/dist/render/index.d.ts +5 -0
  97. package/dist/render/index.js +5 -0
  98. package/dist/render/navigation.d.ts +41 -0
  99. package/dist/render/navigation.js +105 -0
  100. package/dist/render/selection.d.ts +15 -0
  101. package/dist/render/selection.js +50 -0
  102. package/dist/render/svg.d.ts +14 -0
  103. package/dist/render/svg.js +68 -0
  104. package/dist/render/viewer.d.ts +170 -0
  105. package/dist/render/viewer.js +617 -0
  106. package/dist/security/cfb.d.ts +11 -0
  107. package/dist/security/cfb.js +286 -0
  108. package/dist/security/encryption.d.ts +24 -0
  109. package/dist/security/encryption.js +283 -0
  110. package/dist/security/index.d.ts +11 -0
  111. package/dist/security/index.js +21 -0
  112. package/dist/security/pdf.d.ts +29 -0
  113. package/dist/security/pdf.js +114 -0
  114. package/dist/security/policy.d.ts +62 -0
  115. package/dist/security/policy.js +141 -0
  116. package/dist/security/protection.d.ts +49 -0
  117. package/dist/security/protection.js +255 -0
  118. package/dist/util/bytes.d.ts +53 -0
  119. package/dist/util/bytes.js +232 -0
  120. package/dist/util/crc32.d.ts +2 -0
  121. package/dist/util/crc32.js +17 -0
  122. package/dist/util/text.d.ts +10 -0
  123. package/dist/util/text.js +88 -0
  124. package/dist/xml/dom.d.ts +60 -0
  125. package/dist/xml/dom.js +131 -0
  126. package/dist/xml/index.d.ts +4 -0
  127. package/dist/xml/index.js +4 -0
  128. package/dist/xml/ns.d.ts +41 -0
  129. package/dist/xml/ns.js +137 -0
  130. package/dist/xml/parser.d.ts +16 -0
  131. package/dist/xml/parser.js +203 -0
  132. package/dist/xml/serialize.d.ts +6 -0
  133. package/dist/xml/serialize.js +71 -0
  134. package/dist/zip/deflate.d.ts +7 -0
  135. package/dist/zip/deflate.js +42 -0
  136. package/dist/zip/zip.d.ts +33 -0
  137. package/dist/zip/zip.js +216 -0
  138. package/package.json +96 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ All notable changes to docxkeun and docxkeun-fonts. Versions follow [semantic versioning](https://semver.org); while the version is 0.x, minor versions may contain breaking changes.
4
+
5
+ ## 0.1.0 (unreleased)
6
+
7
+ First public release (beta).
8
+
9
+ ### docxkeun
10
+
11
+ - Read and write `.docx` with zero runtime dependencies: own zip, XML, OPC and document model. Parts you do not change are written back byte-for-byte.
12
+ - Word-like layout: styles, lists, tabs, tables (merged cells, repeated header rows), sections, columns, headers/footers, footnotes, page numbers, inline images.
13
+ - Browser viewer: one SVG per page with selectable text, comment sidebar, links, bookmarks, zoom.
14
+ - Typing directly on the pages: caret, selection, IME input, clipboard (plain text), shortcuts, undo/redo.
15
+ - Code API: find/replace across runs, `{{placeholder}}` and content-control filling, formatting, paragraphs, hyperlinks, bookmarks, threaded comments.
16
+ - Navigation between headings, bookmarks and hyperlinks, with back/forward history.
17
+ - Locked regions (Word content controls that cannot be edited) and editable ranges.
18
+ - Word document protection with passwords, an `AccessPolicy` for app roles, and password-to-open encryption (MS-OFFCRYPTO Agile, AES-256).
19
+ - Native PDF export from the same layout: embedded font subsets, searchable text, links, outline, comments, AES-256 encryption with permission flags.
20
+ - React binding without a React dependency.
21
+
22
+ ### docxkeun-fonts
23
+
24
+ - Carlito, Caladea and Liberation Sans/Serif/Mono (SIL OFL 1.1), metric-compatible with Calibri, Cambria, Arial, Times New Roman and Courier New.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kevin Jeremia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,253 @@
1
- # Temporary Holding Version
1
+ # docxkeun
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
+ [![CI](https://github.com/kevinkjs/docxkeun/actions/workflows/ci.yml/badge.svg)](https://github.com/kevinkjs/docxkeun/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/docxkeun)](https://www.npmjs.com/package/docxkeun)
5
+ [![license: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
6
+
7
+ Read, render, edit and convert `.docx` files in the browser (and Node), with **zero runtime dependencies**. Everything is implemented in this package: zip, XML, the document model, a page layout engine, an SVG viewer, a PDF writer, and the cryptography for password-protected files.
8
+
9
+ > **Beta.** docxkeun is new. It is tested against its own test suite and independent implementations, but not yet broadly against files made by Microsoft Word. See [Status and limitations](#status-and-limitations), and please [report](https://github.com/kevinkjs/docxkeun/issues) documents that render or save wrongly.
10
+
11
+ | Area | What you get |
12
+ |---|---|
13
+ | Read / write | Open `.docx` (also `.dotx`/`.docm`), edit through a code API, save. Parts you did not touch are written back byte-for-byte; unknown markup is preserved. |
14
+ | Render | Paginated, Word-like layout: styles, lists, tabs, tables, sections, columns, headers/footers, footnotes, page numbers, inline images. One SVG per page with real, selectable text. |
15
+ | PDF | Native PDF from the same layout: embedded font subsets, searchable text, links, bookmarks as named destinations, an outline from headings, comments as annotations. |
16
+ | Permissions | Word protection (read-only / comments / tracked changes / forms) with editable ranges, an app-level `AccessPolicy`, password-to-open `.docx` encryption, PDF passwords and permission flags. |
17
+ | Comments, anchors, links | Threaded comments (all five Word comment parts), bookmarks, internal and external hyperlinks, field-code links. |
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ npm install docxkeun docxkeun-fonts
23
+ ```
24
+
25
+ `docxkeun-fonts` is optional (about 7 MB of open fonts, see [Fonts](#fonts)); without it the viewer measures the browser's own fonts, and PDF export needs font files you provide.
26
+
27
+ | Import | What it contains |
28
+ |---|---|
29
+ | `docxkeun` | Open, create and save documents; fonts; layout; comments |
30
+ | `docxkeun/editor` | `DocxEditor`: the code API for changes |
31
+ | `docxkeun/viewer` | `DocxViewer`, typing on the page, navigation |
32
+ | `docxkeun/pdf` | `exportPdf` |
33
+ | `docxkeun/security` | Protection, `AccessPolicy`, password-to-open, PDF security |
34
+ | `docxkeun/react` | React binding (bring your own React) |
35
+
36
+ **Runtime support:** current Chrome, Edge, Firefox and Safari (16.4+), and Node 20.12+. docxkeun is ESM-only; Node 22.12+ can also `require()` it.
37
+
38
+ ## Quick start
39
+
40
+ ```ts
41
+ import { openDocx, FontRegistry, loadBundledFonts } from 'docxkeun';
42
+ import { DocxViewer } from 'docxkeun/viewer';
43
+ import { fontUrls } from 'docxkeun-fonts';
44
+
45
+ const fonts = new FontRegistry();
46
+ await loadBundledFonts(fonts, { urls: fontUrls }); // see "Fonts" below
47
+
48
+ const viewer = new DocxViewer(document.getElementById('viewer')!, { fonts });
49
+ await viewer.load(fileFromInput); // Uint8Array | ArrayBuffer | Blob
50
+ viewer.on('linkclick', (e) => console.log(e.target)); // call e.preventDefault() to handle it yourself
51
+ viewer.scrollToAnchor('payment'); // bookmarks
52
+ ```
53
+
54
+ Without registered fonts the viewer still works: it measures the viewer's system fonts with the canvas API. Exact layout and PDF export need font files.
55
+
56
+ ### Jumping between bookmarks, links and headings
57
+
58
+ ```ts
59
+ const { headings, bookmarks, links } = viewer.navigation; // each in document order, with page and position
60
+ viewer.goTo(bookmarks[0], { history: true }); // scroll there; the target briefly lights up
61
+ viewer.next('link'); viewer.previous('link'); // also 'bookmark' and 'heading'
62
+ viewer.back(); viewer.forward(); // like a browser, after following an internal link
63
+ viewer.on('navigate', ({ target, location }) => highlightInMyPanel(target));
64
+ ```
65
+
66
+ - Clicking an internal link jumps to its bookmark and records history, so `back()` returns to the link.
67
+ - Each link target has its text (`label`), its `link` (URL or bookmark name) and, for internal links, its `destination`. A link that wraps onto two lines is one target.
68
+ - Links in headers and footers are left out, since they repeat on every page.
69
+ - Bookmarks whose names start with `_` (`_Toc…`, `_Hlk…`, `_GoBack`) are marked `hidden`, as Word hides them. `next`/`previous` skip them unless you pass `{ includeHidden: true }`.
70
+ - `collectNavTargets(layout)` from `docxkeun/viewer` gives the same lists without a viewer (e.g. in Node).
71
+
72
+ The playground shows these lists in a side panel, with ↑/↓ buttons per kind, Back/Forward, and Alt+←/→.
73
+
74
+ ### Typing on the page
75
+
76
+ ```ts
77
+ const viewer = new DocxViewer(el, { fonts, editable: true }); // or { editable: { guard: policy } }
78
+ viewer.on('editerror', ({ error }) => toast(error.message)); // e.g. PermissionError under read-only protection
79
+ viewer.editing!.undo();
80
+ viewer.setEditable(false); // back to view-only
81
+ ```
82
+
83
+ Click to place the caret and type. Supported: text and IME input, Backspace/Delete (Alt/Ctrl for words), Enter (new paragraph, following the style's "next" style), Shift+Enter (line break), Tab, arrow keys, Home/End, Shift to select, double-click a word, drag to select, Cmd/Ctrl+A, copy/cut/paste as plain text, Cmd/Ctrl+B/I/U on a selection, Cmd/Ctrl+Z / Shift+Z / Y for undo and redo, and Cmd/Ctrl-click to follow a link. Every change goes through `DocxEditor`, so the same access guard applies and everything the editor does not understand stays in the file.
84
+
85
+ ### Editing from code
86
+
87
+ ```ts
88
+ import { DocxEditor } from 'docxkeun/editor';
89
+
90
+ const editor = new DocxEditor(viewer.document!); // the viewer re-renders on every change
91
+
92
+ editor.fillTemplate({ name: 'PT Contoh', amount: 'USD 1,200' }); // {{name}} even when split across runs, plus content controls by tag
93
+ const [match] = editor.find('royalty rate');
94
+ editor.formatRange(match, { bold: true, color: 'C00000' });
95
+ await editor.addHyperlink(match, { url: 'https://example.com/terms' });
96
+ editor.addBookmark(editor.find('Payment terms')[0], 'payment');
97
+ await editor.addHyperlink(editor.find('see payment')[0], { bookmark: 'payment' });
98
+
99
+ // Comments on the user's selection in the viewer
100
+ const range = editor.rangeFromSelection(viewer.getSelection()!);
101
+ const id = await editor.addComment(range, { author: 'Rina Pratama', text: 'Confirm with finance' });
102
+ await editor.replyToComment(id, { author: 'Budi', text: 'Confirmed.' });
103
+ await editor.resolveComment(id);
104
+
105
+ const bytes = await viewer.document!.save();
106
+ ```
107
+
108
+ Also available: `insertText`, `appendText`, `replaceRange`, `replaceAll`, `deleteRange` (across paragraphs), `insertParagraph`, `deleteParagraph`, `setParagraphStyle`, `removeHyperlink`, `hyperlinks()`, `bookmarks()`, `removeBookmark`, `editComment`, `deleteComment`, `addEditableRange`, `removeEditableRange`.
109
+
110
+ ### PDF
111
+
112
+ ```ts
113
+ import { exportPdf } from 'docxkeun/pdf';
114
+ import { pdfSecurity } from 'docxkeun/security';
115
+
116
+ const pdf = await exportPdf(doc, { fonts, layout: viewer.layout }); // reuse the on-screen layout
117
+
118
+ const locked = await exportPdf(doc, {
119
+ fonts,
120
+ encryption: pdfSecurity({ userPassword: 'open-me', permissions: { copy: false, print: 'lowQuality' } }),
121
+ });
122
+ ```
123
+
124
+ ### Permissions
125
+
126
+ ```ts
127
+ import { AccessPolicy, setProtection, readProtection } from 'docxkeun/security';
128
+
129
+ // Word's own protection (stored in the file, honoured by Word)
130
+ await setProtection(doc, 'readOnly', { password: 'owner-secret' });
131
+ editor.addEditableRange(editor.find('[counterparty notes]')[0], { group: 'everyone' });
132
+ editor.addEditableRange(editor.find('Budi only')[0], { editor: 'budi@example.com' });
133
+
134
+ // App-level roles, combined with the document's protection
135
+ const policy = new AccessPolicy(doc, { user: { id: 'budi@example.com', name: 'Budi' }, role: 'editor' });
136
+ const guarded = new DocxEditor(doc, policy); // every call is checked; throws PermissionError
137
+ policy.can('comment'); // for enabling UI
138
+ new DocxViewer(el, { fonts, highlightRange: policy.highlightRange }); // shade what this user may edit
139
+ ```
140
+
141
+ Roles: `viewer` (read, export), `commenter` (comments; edit/delete own), `editor` (edits, subject to document protection and editable ranges), `owner` (everything, including protection).
142
+
143
+ ### Locked regions
144
+
145
+ Lock specific text against editing while the rest of the document stays editable (the opposite of editable ranges). Locks are Word content controls marked "contents cannot be edited", so Word enforces them too, without turning on document protection.
146
+
147
+ ```ts
148
+ const id = editor.lockRange(editor.find('3.75% of the gross revenue')[0], { title: 'Agreed royalty rate' });
149
+ editor.lockParagraphs(firstPara, lastPara, { title: 'Signature clause', mode: 'contentAndControl' });
150
+ editor.lockedRegions(); // [{ id, mode, title, text, block, el }], including locks Word wrote
151
+ editor.unlock(id);
152
+ ```
153
+
154
+ - Any edit that touches locked text throws `LockedRegionError`: typing, delete, replace, formatting, links, splitting or joining paragraphs. So does deleting a range that contains a whole locked region. Typing on the page reports it through the viewer's `editerror` event.
155
+ - Comments, bookmarks and reading are still allowed.
156
+ - Typing right at the edge of a locked region goes just outside it, and Enter at the start or end of a locked block adds a paragraph outside it, as in Word.
157
+ - `mode`:
158
+ - `'content'` (default): the text can't be edited.
159
+ - `'contentAndControl'`: it also can't be deleted.
160
+ - `'control'`: it can't be deleted, but its text can be edited.
161
+ - Inside one paragraph the exact text is locked. A range across paragraphs locks those whole paragraphs.
162
+ - `fillTemplate` and `fillContentControls` skip locked placeholders unless you pass `{ includeLocked: true }`.
163
+ - With an `AccessPolicy`, only owners can lock or unlock.
164
+ - The viewer shades locked text with a light hatch; turn that off with `showLockedRegions: false`.
165
+ - Like Word's own locks, this stops edits in Word and docxkeun, but anyone with Word can still change a control's properties. To make that impossible as well, also turn on document protection.
166
+
167
+ ### Password-to-open `.docx`
168
+
169
+ ```ts
170
+ import 'docxkeun/security'; // enables encrypted files in open/save
171
+
172
+ const doc = await openDocx(bytes, { password }); // PasswordRequiredError / WrongPasswordError
173
+ const encrypted = await doc.save({ password: 'new-password' });
174
+ ```
175
+
176
+ Encryption is MS-OFFCRYPTO Agile (AES-256-CBC, SHA-512, 100,000 rounds, HMAC integrity), the same scheme Word uses. Office 2007 "Standard" encryption can be read.
177
+
178
+ ### React
179
+
180
+ ```tsx
181
+ import * as React from 'react';
182
+ import { createDocxViewerComponent } from 'docxkeun/react';
183
+ const DocxView = createDocxViewerComponent(React); // no React dependency in docxkeun itself
184
+
185
+ <DocxView file={bytes} fonts={fonts} onReady={(viewer) => setViewer(viewer)} />
186
+ ```
187
+
188
+ ## Fonts
189
+
190
+ Word documents name fonts (Calibri, Times New Roman...) but rarely contain them, and browsers cannot read the system's font files. For exact layout and for PDF export, layout needs font files in a `FontRegistry`.
191
+
192
+ The companion package [`docxkeun-fonts`](packages/fonts/README.md) has open fonts with the same character widths as Office's defaults (SIL OFL 1.1, about 7 MB, 20 files): Carlito for Calibri, Caladea for Cambria, Liberation Sans for Arial, Liberation Serif for Times New Roman, Liberation Mono for Courier New. Those names map automatically.
193
+
194
+ ```ts
195
+ import { fontUrls } from 'docxkeun-fonts';
196
+
197
+ // Browser: bundlers (Vite, webpack 5, Rollup) copy the font files into your build
198
+ await loadBundledFonts(fonts, { urls: fontUrls });
199
+ await loadBundledFonts(fonts, { urls: fontUrls, families: ['Carlito'] });
200
+
201
+ // Hosting the .ttf files yourself
202
+ await loadBundledFonts(fonts, { baseUrl: 'https://cdn.example.com/docxkeun-fonts/' });
203
+
204
+ // Node
205
+ import { readFile } from 'node:fs/promises';
206
+ await loadBundledFonts(fonts, { load: (file) => readFile(fontUrls[file]) });
207
+ ```
208
+
209
+ Load only the families you need with `families` to save bandwidth (Carlito alone is 2.7 MB; Caladea is 330 KB). Other options:
210
+ - `registry.alias('Corporate Sans', 'Liberation Sans')` maps any other name.
211
+ - Fonts embedded in the document are supported: `await registerEmbeddedFonts(doc, registry)`.
212
+ - `registry.fallbacks = ['Carlito']` sets what unknown fonts use.
213
+
214
+ TrueType, OpenType (CFF) and `.ttc` collections are supported. PDF embedding respects a font's "restricted license" flag.
215
+
216
+ ## Security model, honestly
217
+
218
+ - **Password-to-open `.docx` and PDF user passwords are real encryption** (AES-256).
219
+ - **Word document protection, editable ranges, PDF permission flags and `AccessPolicy` are restrictions, not encryption.** Word and PDF viewers honour them, but anyone can strip them from a file, and client-side checks can be bypassed. If your server stores documents, re-check permissions there before accepting changes.
220
+ - Documents are untrusted input. All text is escaped when rendered, external links only open with allowed schemes (`http:`, `https:`, `mailto:`, `tel:` by default), images referenced by URL are not loaded unless you opt in, and the XML parser never expands external entities.
221
+
222
+ ## Status and limitations
223
+
224
+ Working and tested (98 tests): zip/XML/OPC round-trips, styles and numbering, layout and pagination, viewer, editing, comments, links, bookmarks, PDF export, document protection, access policy, `.docx` encryption, PDF encryption.
225
+
226
+ Verified against independent implementations so far:
227
+ - Crypto primitives against FIPS/RFC test vectors and Node's crypto.
228
+ - PDF output and AES-256 PDF encryption opened by Chrome's PDF viewer (with and without an open password).
229
+
230
+ **Still to verify against files made by Microsoft Word:** layout fidelity (line and page breaks), the Word protection password hash (the Excel-compatible low half is confirmed), and opening docxkeun-encrypted files in Word / decrypting Word-encrypted files.
231
+
232
+ Not yet supported:
233
+ - Text wrapping around floating images and text boxes. Floating images are placed but text does not flow around them; DrawingML shapes and text boxes are not drawn.
234
+ - Right-to-left text and complex-script shaping (Arabic, Hebrew, Indic), ligatures and GPOS kerning.
235
+ - EMF/WMF, GIF and BMP images (drawn as placeholders in PDF), charts, SmartArt, equations (shown as plain text).
236
+ - Recording tracked changes. Existing insertions are shown and deletions hidden.
237
+ - Column balancing on continuous section breaks.
238
+ - In-page typing re-lays out the whole document on every keystroke (about 20–35 ms for a few pages), so very long documents will feel slow. Typing into headers, footers, footnotes and text boxes is not supported, there is no formatting toolbar beyond the shortcuts, pasting keeps text only, and the caret does not yet move through images.
239
+
240
+ ## Development
241
+
242
+ ```bash
243
+ pnpm install
244
+ pnpm test # vitest
245
+ pnpm dev # playground at http://localhost:5199
246
+ pnpm build # dist/
247
+ ```
248
+
249
+ Tests and the playground use the fonts in `packages/fonts`. Two optional checks compare them with Arial and Times New Roman when those are installed. See [CONTRIBUTING.md](CONTRIBUTING.md) for how to contribute and release, and [SECURITY.md](SECURITY.md) to report a vulnerability.
250
+
251
+ ## License
252
+
253
+ [MIT](LICENSE) © Kevin Jeremia. The fonts in `docxkeun-fonts` are under the SIL Open Font License 1.1.
@@ -0,0 +1,253 @@
1
+ import type { DocParagraph, Block } from '../model/content.js';
2
+ import type { DocxDocument } from '../model/document.js';
3
+ import { type XmlElement } from '../xml/index.js';
4
+ import { EditError, type DocPosition, type DocRange } from './positions.js';
5
+ export type EditAction = 'edit' | 'format' | 'comment' | 'reply' | 'resolveComment' | 'editComment' | 'deleteComment' | 'link' | 'bookmark' | 'fillForm' | 'protect';
6
+ /**
7
+ * How a locked region is locked (Word's content-control locking, w:sdtPr/w:lock):
8
+ * 'content' = the text cannot be edited; 'contentAndControl' = and the region cannot be deleted;
9
+ * 'control' = the region cannot be deleted, but its text can be edited.
10
+ */
11
+ export type LockMode = 'content' | 'contentAndControl' | 'control';
12
+ /** Tag docxkeun puts on the content controls it creates to lock text. */
13
+ export declare const LOCK_TAG = "docxkeun-lock";
14
+ export interface LockedRegion {
15
+ /** The content control's w:id. */
16
+ id: string;
17
+ mode: LockMode;
18
+ title?: string;
19
+ tag?: string;
20
+ text: string;
21
+ /** Whether it wraps whole paragraphs (block) or text inside a paragraph (inline). */
22
+ block: boolean;
23
+ el: XmlElement;
24
+ }
25
+ /** An edit touched text inside a locked region. */
26
+ export declare class LockedRegionError extends EditError {
27
+ readonly region: XmlElement;
28
+ name: string;
29
+ constructor(region: XmlElement, title: string | undefined);
30
+ }
31
+ /** The lock mode of a content control, if it is locked. */
32
+ export declare function lockModeOf(sdt: XmlElement): LockMode | undefined;
33
+ /** Checks every edit (see docxkeun/security's AccessPolicy). Throw to refuse. */
34
+ export interface EditGuard {
35
+ assert(action: EditAction, range?: DocRange, detail?: {
36
+ commentAuthor?: string;
37
+ }): void;
38
+ }
39
+ export interface TextFormat {
40
+ bold?: boolean;
41
+ italic?: boolean;
42
+ underline?: boolean | 'single' | 'double' | 'dotted' | 'dash' | 'wave' | 'thick';
43
+ strike?: boolean;
44
+ color?: string;
45
+ highlight?: string;
46
+ /** Points. */
47
+ size?: number;
48
+ font?: string;
49
+ style?: string;
50
+ vertAlign?: 'superscript' | 'subscript' | 'baseline';
51
+ caps?: boolean;
52
+ smallCaps?: boolean;
53
+ hidden?: boolean;
54
+ }
55
+ export interface CommentInput {
56
+ author: string;
57
+ text: string;
58
+ initials?: string;
59
+ date?: Date;
60
+ }
61
+ export interface Match extends DocRange {
62
+ text: string;
63
+ /** Capture groups for regular-expression searches. */
64
+ groups: string[];
65
+ paragraph: XmlElement;
66
+ }
67
+ export interface TextSegment {
68
+ start: number;
69
+ end: number;
70
+ /** w:t, or a one-character item such as w:tab, w:br or w:sym. */
71
+ node: XmlElement;
72
+ }
73
+ /** Concatenated text of a paragraph and where each character lives in the XML. */
74
+ export interface ParagraphText {
75
+ paragraph: XmlElement;
76
+ text: string;
77
+ segments: TextSegment[];
78
+ }
79
+ /** Every paragraph of a block list (including table cells), in document order. */
80
+ export declare function paragraphsOf(blocks: Block[], out?: DocParagraph[]): DocParagraph[];
81
+ export declare function paragraphText(para: DocParagraph): ParagraphText;
82
+ /**
83
+ * XML position of character offset `k` in a paragraph. With side 'start' the position is at the
84
+ * start of the segment holding character k; with 'end' it is at the end of the segment holding
85
+ * character k-1 (so insertions there inherit the formatting of the text before).
86
+ */
87
+ export declare function positionAt(pt: ParagraphText, k: number, side: 'start' | 'end'): DocPosition | undefined;
88
+ /** Run children for a string: text, tabs and line breaks. */
89
+ export declare function runContent(text: string): XmlElement[];
90
+ /** Apply TextFormat to a w:rPr element (created when missing). */
91
+ export declare function applyFormat(run: XmlElement, format: TextFormat): void;
92
+ export declare class DocxEditor {
93
+ readonly doc: DocxDocument;
94
+ readonly guard?: EditGuard | undefined;
95
+ constructor(doc: DocxDocument, guard?: EditGuard | undefined);
96
+ private get root();
97
+ private get body();
98
+ private index;
99
+ private changed;
100
+ private check;
101
+ /** The locked content control around a node, if any. */
102
+ private lockAround;
103
+ /** Throw LockedRegionError when a range touches a locked region (or would delete one). */
104
+ private assertUnlocked;
105
+ /** Whether a range touches a locked region. */
106
+ isLocked(range: DocRange): boolean;
107
+ /** Set while filling locked content on purpose (fillTemplate with includeLocked). */
108
+ private bypassLocks;
109
+ /** Convert a viewer selection (inline positions) into an editor range. */
110
+ rangeFromSelection(sel: {
111
+ start: {
112
+ inline: {
113
+ node: XmlElement;
114
+ };
115
+ offset: number;
116
+ };
117
+ end: {
118
+ inline: {
119
+ node: XmlElement;
120
+ };
121
+ offset: number;
122
+ };
123
+ }): DocRange;
124
+ /** Every paragraph of the body, including those in tables, in document order. */
125
+ paragraphs(): DocParagraph[];
126
+ /** Range covering a paragraph's text (undefined for paragraphs without text). */
127
+ paragraphRange(paragraph: XmlElement | DocParagraph): DocRange | undefined;
128
+ /** Find text (or a regular expression) within paragraphs, across run boundaries. */
129
+ find(query: string | RegExp): Match[];
130
+ /** Text covered by a range. */
131
+ textOf(range: DocRange): string;
132
+ /**
133
+ * Insert text at a position, formatted like the run it lands in (plus optional format).
134
+ * Returns the position right after the inserted text. A position whose node is a w:p means
135
+ * "inside this (empty) paragraph".
136
+ */
137
+ insertText(at: DocPosition, text: string, format?: TextFormat): DocPosition;
138
+ /** Join a paragraph with the one right after it (Backspace at the start of the second). */
139
+ mergeParagraphs(first: XmlElement, second: XmlElement): void;
140
+ /** Split a paragraph at a position (Enter). Returns the new, second paragraph. */
141
+ splitParagraph(at: DocPosition): XmlElement;
142
+ /** Append text at the end of a paragraph. */
143
+ appendText(paragraph: XmlElement, text: string, format?: TextFormat): XmlElement;
144
+ /** Delete a range (it may span paragraphs, but not table cells). */
145
+ deleteRange(range: DocRange): void;
146
+ /** Replace a range with text formatted like the range's first run. */
147
+ replaceRange(range: DocRange, text: string, format?: TextFormat): void;
148
+ /** Replace every match; returns how many were replaced. */
149
+ replaceAll(query: string | RegExp, replacement: string | ((m: Match) => string)): number;
150
+ /**
151
+ * Fill `{{name}}` placeholders (and content controls whose tag or title is a key).
152
+ * Returns the keys that were found.
153
+ */
154
+ fillTemplate(data: Record<string, string | number | boolean | null | undefined>, pattern?: RegExp, options?: {
155
+ includeLocked?: boolean;
156
+ }): string[];
157
+ private withLocks;
158
+ /** Set the text of content controls (w:sdt) by tag or title. Locked ones are skipped unless `includeLocked`. */
159
+ fillContentControls(data: Record<string, string | number | boolean | null | undefined>, options?: {
160
+ includeLocked?: boolean;
161
+ }): string[];
162
+ /** Apply character formatting to a range. */
163
+ formatRange(range: DocRange, format: TextFormat): void;
164
+ /** Remove the content of a range, returning the sentinels at its (now adjacent) ends. */
165
+ private cut;
166
+ private removeRange;
167
+ /** Insert a paragraph before or after a block (or at the start/end of the body). */
168
+ insertParagraph(where: {
169
+ before?: XmlElement;
170
+ after?: XmlElement;
171
+ } | 'start' | 'end', text?: string, options?: {
172
+ style?: string;
173
+ format?: TextFormat;
174
+ }): XmlElement;
175
+ deleteParagraph(paragraph: XmlElement): void;
176
+ setParagraphStyle(paragraph: XmlElement, styleId: string): void;
177
+ /** Turn a range (within one paragraph) into a hyperlink to a URL or a bookmark. */
178
+ addHyperlink(range: DocRange, target: {
179
+ url: string;
180
+ } | {
181
+ bookmark: string;
182
+ }, tooltip?: string): Promise<XmlElement>;
183
+ /** Unwrap a w:hyperlink, keeping its text. */
184
+ removeHyperlink(link: XmlElement): void;
185
+ /** Every w:hyperlink in the body with its target. */
186
+ hyperlinks(): Array<{
187
+ el: XmlElement;
188
+ url?: string;
189
+ anchor?: string;
190
+ tooltip?: string;
191
+ text: string;
192
+ }>;
193
+ addBookmark(range: DocRange, name: string): void;
194
+ bookmarks(): Array<{
195
+ id: string;
196
+ name: string;
197
+ }>;
198
+ removeBookmark(name: string): void;
199
+ /** Let a user (w:ed, e.g. an e-mail or DOMAIN\\user) or a group (w:edGrp, e.g. "everyone") edit a range. */
200
+ addEditableRange(range: DocRange, who: {
201
+ editor?: string;
202
+ group?: 'everyone' | 'editors' | 'owners' | 'administrators' | 'contributors' | 'current' | 'none' | string;
203
+ }): string;
204
+ editableRanges(): Array<{
205
+ id: string;
206
+ editor?: string;
207
+ group?: string;
208
+ }>;
209
+ removeEditableRange(id: string): void;
210
+ /** The locked inline region whose first or last character is at `pos`. */
211
+ private lockEdge;
212
+ /** A locked block of paragraphs that `pos` sits at the very start or end of. */
213
+ private blockLockEdge;
214
+ /**
215
+ * Lock a range against editing. Inside one paragraph the exact text is locked; a range that
216
+ * spans paragraphs locks those whole paragraphs. Stored as a Word content control, so Word
217
+ * enforces the lock too. Returns the region's id.
218
+ */
219
+ lockRange(range: DocRange, options?: {
220
+ title?: string;
221
+ tag?: string;
222
+ mode?: LockMode;
223
+ }): string;
224
+ /** Lock whole paragraphs (from `first` to `last`). */
225
+ lockParagraphs(first: XmlElement, last?: XmlElement, options?: {
226
+ title?: string;
227
+ tag?: string;
228
+ mode?: LockMode;
229
+ }): string;
230
+ /** Every locked content control in the body. */
231
+ lockedRegions(): LockedRegion[];
232
+ /**
233
+ * Remove a lock. Regions docxkeun created are unwrapped completely; other content controls
234
+ * keep their control and only lose the lock.
235
+ */
236
+ unlock(id: string): void;
237
+ /** Add a comment anchored to a range. Returns the new comment id. */
238
+ addComment(range: DocRange, input: CommentInput): Promise<string>;
239
+ /** Reply to a comment (Word threads replies on the same anchor). */
240
+ replyToComment(parentId: string, input: CommentInput): Promise<string>;
241
+ /** Mark a comment thread resolved (done) or open again. */
242
+ resolveComment(id: string, resolved?: boolean): Promise<void>;
243
+ /** Replace a comment's text. */
244
+ editComment(id: string, text: string): Promise<void>;
245
+ /** Delete a comment, its replies and its anchors. */
246
+ deleteComment(id: string): Promise<void>;
247
+ private commentElement;
248
+ private ensureParaId;
249
+ private writeComment;
250
+ private ensureCharacterStyle;
251
+ }
252
+ export type { DocPosition, DocRange };
253
+ export { EditError };