@betteroffice/docx 0.2.1 → 0.4.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 (91) hide show
  1. package/README.md +586 -3
  2. package/dist/chunk-24Z6ZVFZ.mjs +1 -0
  3. package/dist/chunk-2QHGQA3V.mjs +1 -0
  4. package/dist/{chunk-ACGKK7IB.mjs → chunk-3CYO46ML.mjs} +1 -1
  5. package/dist/chunk-6CHGYCFU.mjs +1 -0
  6. package/dist/chunk-AOWJ4WDE.mjs +1 -0
  7. package/dist/chunk-DLXIZBB6.mjs +1 -0
  8. package/dist/chunk-F2VBW6RB.mjs +1 -0
  9. package/dist/chunk-HPZFJGGM.mjs +0 -0
  10. package/dist/chunk-L2ML3DDI.mjs +1 -0
  11. package/dist/chunk-LIGZ75FP.mjs +1 -0
  12. package/dist/chunk-LT2GCWZ3.mjs +0 -0
  13. package/dist/chunk-ND3FBCB3.mjs +16 -0
  14. package/dist/chunk-NMDQHUQB.mjs +57 -0
  15. package/dist/chunk-NVN26RHH.mjs +1 -0
  16. package/dist/chunk-OK5UFGX3.mjs +1 -0
  17. package/dist/chunk-RZQ3OXZY.mjs +2 -0
  18. package/dist/chunk-YLFKV2NT.mjs +1 -0
  19. package/dist/collaboration/index.d.mts +9 -6
  20. package/dist/compareDocx-IHFPGIGV.mjs +1 -0
  21. package/dist/computeLayout-4MNWHE2T.mjs +1 -0
  22. package/dist/{content-CvEtPl0c.d.mts → content-BzoC6bSz.d.mts} +48 -8
  23. package/dist/core.d.mts +172 -9
  24. package/dist/core.mjs +1 -1
  25. package/dist/{displayListQueries-DF8F6fMl.d.mts → displayListQueries-H5YnU_hX.d.mts} +23 -5
  26. package/dist/docx/index.d.mts +5 -4
  27. package/dist/docx/index.mjs +1 -1
  28. package/dist/editor/index.d.mts +19 -9
  29. package/dist/editor/index.mjs +1 -1
  30. package/dist/{fontLoader-b8eicJKV.d.mts → fontLoader-BNSs0E8K.d.mts} +55 -2
  31. package/dist/{formatting-7zKCTu5a.d.mts → formatting-gqLFeJ9X.d.mts} +8 -0
  32. package/dist/{frameDelta-pA4jrQ1G.d.mts → frameDelta-ByU7HBuB.d.mts} +34 -3
  33. package/dist/generated/edit/docx_edit_bg.wasm +0 -0
  34. package/dist/generated/layout/docx_layout_bg.wasm +0 -0
  35. package/dist/generated/opc/ooxml_opc_bg.wasm +0 -0
  36. package/dist/generated/parse/docx_parse_bg.wasm +0 -0
  37. package/dist/index-CHy6_Yuo.d.mts +2026 -0
  38. package/dist/layout/index.d.mts +6 -6
  39. package/dist/layout/index.mjs +1 -1
  40. package/dist/layout/pagination/index.d.mts +4 -4
  41. package/dist/layout/render/index.d.mts +122 -33
  42. package/dist/layout/render/index.mjs +1 -1
  43. package/dist/loadWasmAsset-Cr95TImt.d.mts +25 -0
  44. package/dist/pagedExport---0Dlmzo.d.mts +907 -0
  45. package/dist/parseWasm-NLAG22EU.mjs +1 -0
  46. package/dist/plugin-api/RenderedDomContext.d.mts +12 -9
  47. package/dist/plugin-api/RenderedDomContext.mjs +1 -1
  48. package/dist/plugin-api/index.d.mts +21 -4
  49. package/dist/plugin-api/resolveItemPositions.d.mts +3 -3
  50. package/dist/rezip-Bxiq4Z_R.d.mts +24 -0
  51. package/dist/{rustDisplayList-BJqaN9tt.d.mts → rustDisplayList-LcRZHCSL.d.mts} +12 -4
  52. package/dist/{rustMeasureSource-C0EZB055.d.mts → rustMeasureSource-BkCx1FDx.d.mts} +14 -4
  53. package/dist/{selectiveSave-CRh-_Y_C.d.mts → selectiveSave-r-NMK6aI.d.mts} +1 -22
  54. package/dist/styles/index.d.mts +2 -2
  55. package/dist/{styles-7e-mq3c-.d.mts → styles-AryxLAhx.d.mts} +1 -1
  56. package/dist/types/content.d.mts +2 -2
  57. package/dist/types/document.d.mts +9 -6
  58. package/dist/{types-C4A8mWjU.d.mts → types-D6Pra38E.d.mts} +31 -5
  59. package/dist/utils/comments.d.mts +2 -2
  60. package/dist/utils/index.d.mts +20 -5
  61. package/dist/utils/index.mjs +1 -1
  62. package/dist/utils/stylePreview.d.mts +2 -2
  63. package/dist/wasm-GSI2XMOH.mjs +1 -0
  64. package/dist/wasm-K6DRABAA.mjs +1 -0
  65. package/dist/wasm-NF6B3AH7.mjs +1 -0
  66. package/dist/wasm-edit.d.mts +420 -28
  67. package/dist/wasm-edit.mjs +1 -1
  68. package/dist/wasm-layout.d.mts +9 -2
  69. package/dist/wasm-layout.mjs +1 -1
  70. package/dist/wasm-opc.d.mts +1 -1
  71. package/dist/wasm-opc.mjs +1 -1
  72. package/dist/wasm-parse.d.mts +1 -1
  73. package/dist/wasm-parse.mjs +1 -1
  74. package/dist/yrs/index.d.mts +8 -5
  75. package/dist/yrs/index.mjs +1 -1
  76. package/dist/yrs/residentEngineWorker.mjs +1 -1
  77. package/package.json +2 -2
  78. package/dist/chunk-5F6DLQZP.mjs +0 -1
  79. package/dist/chunk-6LQJAKOC.mjs +0 -1
  80. package/dist/chunk-AFMVSI4Z.mjs +0 -57
  81. package/dist/chunk-GD4VNJ64.mjs +0 -1
  82. package/dist/chunk-HLDJMU3R.mjs +0 -1
  83. package/dist/chunk-J7LNO6SM.mjs +0 -1
  84. package/dist/chunk-JHJLG4I6.mjs +0 -16
  85. package/dist/chunk-PGMXWI5X.mjs +0 -1
  86. package/dist/chunk-WRWRCBLK.mjs +0 -1
  87. package/dist/chunk-WTFRNX5K.mjs +0 -1
  88. package/dist/index-CHl2zLJ7.d.mts +0 -1142
  89. package/dist/loadWasmAsset-CMvnVkfA.d.mts +0 -3
  90. package/dist/wasm-7SOSHNGP.mjs +0 -1
  91. package/dist/wasm-ZQAVP7P2.mjs +0 -1
package/README.md CHANGED
@@ -53,9 +53,9 @@ provider.connect();
53
53
 
54
54
  `replica` can be a direct `YrsSession`, the worker-aware adapter returned by
55
55
  `createWorkerCollaborationReplica`, or the value published by the React
56
- editor's `collaboration.onReplica` callback. The provider speaks Yjs sync-v1;
57
- room routing, authentication, awareness, and reconnection policy remain
58
- transport concerns. Pass a persisted Yrs update as `collaboration.initialUpdate`
56
+ editor's `collaboration.onReplica` callback. The provider handles Yjs sync-v1 and
57
+ awareness; room routing, authentication, and reconnection remain transport
58
+ concerns. Pass a persisted Yrs update as `collaboration.initialUpdate`
59
59
  when a React editor joins an existing room so it hydrates the shared history
60
60
  instead of independently importing the same DOCX.
61
61
 
@@ -68,3 +68,586 @@ Package builds, demo startup, and CI run this step automatically.
68
68
 
69
69
  [JavaScript guide](https://docs.betteroffice.dev/docs/javascript) ·
70
70
  [Changelog](https://github.com/openooxml/betteroffice/blob/main/packages/docx/CHANGELOG.md) · Apache-2.0.
71
+
72
+ ### Undo capture modes and boundaries
73
+
74
+ `session.setUndoCaptureMode(mode)` selects how tracked local transactions are
75
+ combined into undo steps. `session.undoCaptureMode()` returns the current mode.
76
+
77
+ | Mode | Grouping |
78
+ | --- | --- |
79
+ | `auto` (default) | Edits within 500 ms coalesce; switching stories closes the group. |
80
+ | `manual` | Edits coalesce across pauses and stories until an explicit boundary. |
81
+
82
+ `session.addUndoBoundary()` closes the current group in any mode. Changing modes
83
+ also closes the group; setting the same mode again does not. Both operations
84
+ preserve undo/redo history and are safe before capture starts. Repeated boundaries
85
+ create no empty undo steps. Remote transactions remain outside local undo history.
86
+
87
+ ```ts
88
+ session.setUndoCaptureMode('manual');
89
+ session.insertText(firstLocation, 'Prefixo ');
90
+ session.insertText(secondLocation, 'Suffix');
91
+ session.addUndoBoundary();
92
+ session.deleteRange(markerRange);
93
+ session.addUndoBoundary();
94
+ session.setUndoCaptureMode('auto');
95
+ ```
96
+
97
+ The two insertions undo together; marker deletion is a separate step. Boundaries
98
+ are also available in automatic mode when a host action needs to be isolated from
99
+ surrounding typing. Undo/redo close capture as usual. Manual mode groups history;
100
+ edit batches provide atomic execution.
101
+ The host must close manual groups so later unrelated edits do not join them.
102
+
103
+ ### Paragraph identities
104
+
105
+ A session addresses paragraphs by session keys (`YrsLoc.paraId`); Word stores its
106
+ own paragraph ID (`w14:paraId`) in the file. A session anchor resolves on every
107
+ replica of one collaborative session, and each seeding open (`openDocx`, `seedFromDocx`, `documentToYrs`) starts a new one unless given a fixed
108
+ `generation`, as a deterministic shared seed needs. Source IDs are kept as authored, and every
109
+ paragraph authored in the session gets a fresh, valid ID that avoids every ID the
110
+ package already uses.
111
+
112
+ `saveYrsDocx(session)` saves a session opened from DOCX bytes and returns each saved
113
+ paragraph's persisted anchor, qualified by its package part:
114
+
115
+ ```ts
116
+ import { createYrsSession, saveYrsDocx } from '@betteroffice/docx/yrs';
117
+
118
+ const { secondParaId } = session.splitParagraph({ story: 'body', paraId, offset: 12 });
119
+ const saved = await saveYrsDocx(session);
120
+ const anchor = saved.paragraphs.find((p) => p.session.paraId === secondParaId)!.persisted;
121
+
122
+ const reopened = await createYrsSession();
123
+ reopened.openDocx(saved.bytes, true);
124
+ reopened.resolveParagraphAnchor(anchor); // { status: 'found', anchor: { kind: 'session', … } }
125
+ ```
126
+
127
+ `saved.conflicts` lists saved paragraphs whose ID the live session reassigned while the
128
+ save ran, such as by a duplicate repair after a remote update; their anchors find them in
129
+ the saved bytes only. The React editor's Save writes and records these IDs. `saveYrsDocx`
130
+ also returns anchors and preserves unchanged source parts. `session.persistParagraphIds()`
131
+ assigns IDs to source paragraphs without one across every story part, comments,
132
+ note separators and retained XML included, and repairs duplicates: source IDs and
133
+ saved IDs keep theirs over copies. It refuses, changing nothing, rather than guess at
134
+ an ambiguous comment reference. The change is replicated, stays out of undo history,
135
+ and later saves keep it; a save whose stories are otherwise unchanged patches the IDs
136
+ into the source bytes. `session.paragraphIdentities()` lists each paragraph's session,
137
+ persisted and exact-source anchors. A persisted anchor is scoped to the document the
138
+ host chose, and repeated source IDs resolve as `ambiguous`.
139
+
140
+ ### Selection state
141
+
142
+ `session.selectionContext(range)` aggregates the range for toolbars and
143
+ assistive technology. Toggle marks, including `superscript` and `subscript`,
144
+ are `true`, `false` or `'mixed'`; value marks such as `fontFamily`, `color` and
145
+ `highlight` are `null` when absent or not uniform. `highlight` reports Word's
146
+ highlight name (`'yellow'`) or an unmapped hex value. `toggleMark` accepts
147
+ `{ type: 'superscript' }` and `{ type: 'subscript' }`; adding one clears the other.
148
+
149
+ ### Version-checked edit batches
150
+
151
+ Read what you will target together with the session version, then apply a batch
152
+ against that version. Every step resolves against the state that was read; the
153
+ batch commits as one transaction or returns a typed refusal with nothing changed.
154
+
155
+ ```ts
156
+ const read = session.readParagraphs({ story: 'body', view: 'accepted' });
157
+ if (!read.ok) throw new Error(read.failure.message);
158
+ const clause = read.paragraphs.find((paragraph) => paragraph.text.startsWith('Term'))!;
159
+
160
+ const result = session.applyEdits({
161
+ expectVersion: read.version,
162
+ steps: [
163
+ {
164
+ op: 'replaceText',
165
+ target: { kind: 'search', text: '30 days', view: 'accepted',
166
+ within: { kind: 'paragraph', story: 'body', paraId: clause.paraId } },
167
+ text: '45 days',
168
+ expect: { text: '30 days' },
169
+ },
170
+ {
171
+ op: 'insertParagraphs',
172
+ target: { story: 'body', paraId: clause.paraId },
173
+ at: 'end',
174
+ paragraphs: [{ text: 'Renewal is automatic.' }],
175
+ },
176
+ ],
177
+ });
178
+ if (!result.ok) console.warn(result.failure.code, result.failure.message);
179
+ ```
180
+
181
+ `version()` changes with every committed change, local or remote (including
182
+ undo and redo), and when the session reopens its document. Tokens are scoped to
183
+ one session; after a lost response, read again rather than retrying with a new
184
+ version.
185
+
186
+ Offsets are UTF-16 positions into a paragraph's projected text. Each inline atom
187
+ (hard break, image, content control, note reference, field, other embed) is one
188
+ U+FFFC listed in `atoms`, tabs stay `\t`, and paragraph marks are excluded. The
189
+ `accepted` view includes pending insertions and hides pending deletions;
190
+ `original` does the reverse. `findText` is exact, case-sensitive and
191
+ paragraph-local, and a `search` target must match exactly once in its scope.
192
+
193
+ | Step | Effect |
194
+ | --- | --- |
195
+ | `insertText` | Inserts at the start or end of a target, formatted like typing there. |
196
+ | `replaceText` | Replaces a target's text inside one paragraph, keeping the paragraph. |
197
+ | `deleteText` | Deletes a target's text inside one paragraph. |
198
+ | `insertParagraphs` | Inserts complete paragraphs before or after an anchor, in the given or the anchor's style. |
199
+ | `deleteParagraphs` | Deletes a contiguous span of complete paragraphs without merging properties into a neighbour. |
200
+ | `setParagraphStyle` | Applies a document paragraph style with its paragraph and run formatting. |
201
+
202
+ Refusals carry a `code` (`stale-version`, `missing-target`, `ambiguous-target`,
203
+ `content-mismatch`, `overlapping-steps`, `locked-target`,
204
+ `tracked-revision-conflict`, `unsupported`, `invalid-step`, `limit-exceeded`),
205
+ the failing `stepIndex`, and the target. Editor hosts add `read-only` for an
206
+ editor that does not accept edits. Malformed requests throw.
207
+ `validateEdits(request)` runs the same checks and previews each step without
208
+ changing anything or reserving ids.
209
+
210
+ An applied batch is exactly one undo step in both capture modes; pass
211
+ `history: 'none'` to keep it out of undo history while preserving existing undo
212
+ and redo entries. `source: 'agent'` records provenance only. Add
213
+ `suggest: { author, date }` to a text step to record it as a tracked change.
214
+
215
+ Paragraph ids are session keys; inserted paragraphs get Word paragraph IDs as
216
+ typed ones do, so `saveYrsDocx` returns persisted anchors for them.
217
+
218
+ ### Host proposals
219
+
220
+ `session.proposeChanges()` records a round of reviewable tracked changes under
221
+ the host's own proposal ids. Each proposal names its paragraph by any paragraph
222
+ anchor, such as a persisted Word paragraph ID, and replaces, deletes
223
+ (`replaceWith: ''`) or inserts text:
224
+
225
+ ```ts
226
+ const result = session.proposeChanges({
227
+ expectVersion: session.version(),
228
+ proposals: [
229
+ {
230
+ id: 'p-17',
231
+ paragraph: { kind: 'persisted', story: { partUri: '/word/document.xml', kind: 'body' }, paraId: '1A2B3C4D' },
232
+ suggest: { author: 'Reviewer', date: new Date().toISOString() },
233
+ op: 'replaceText',
234
+ search: '30 days',
235
+ replaceWith: '45 days',
236
+ occurrence: 'all',
237
+ },
238
+ ],
239
+ });
240
+ ```
241
+
242
+ `occurrence` is `'first'` (the default), `'all'` or a one-based number, counting
243
+ non-overlapping matches of the accepted text. `search: ''` fills an empty
244
+ paragraph: it matches once, at the start of a paragraph whose accepted text is
245
+ empty (hyperlinks, fields, content controls and pending insertions count as
246
+ text), and refuses with `missing-target` anywhere else. Text typed into a
247
+ paragraph without runs takes the paragraph mark's run formatting, as in Word.
248
+ The round applies as one batch
249
+ outside undo history, or nothing changes and a typed refusal names the
250
+ `proposalId`: an ambiguous paragraph ID refuses with `ambiguous-target`, and
251
+ adjoining or overlapping proposals with `overlapping-steps`. Retrying an id with
252
+ the same edit is a no-op; the same id with another edit refuses with
253
+ `proposal-id-conflict`. Each record lists the revision ids its proposal created.
254
+
255
+ `session.setProposalStates()` marks proposals `accepted`, `rejected` or back to
256
+ `proposed`. Decisions keep the tracked revisions and change only how they render:
257
+ `proposalRevisionPreview(snapshot)` is the `revisionPreview` render environment
258
+ entry that shows accepted proposals as plain text and hides rejected ones. They
259
+ leave the document, its version and undo history untouched, and each change
260
+ increments `previewVersion`, which `expectPreviewVersion` checks
261
+ (`stale-preview`). `getProposals()` and `onProposalChange()` read and observe
262
+ the registry; opening another document forgets it.
263
+
264
+ `session.withdrawProposals({ expectVersion, ids })` ends proposals the host is
265
+ done with, settling each as its decision previews it: accepted ones apply as
266
+ plain text and rejected or undecided ones are removed, in one change outside
267
+ undo history. The document then reads as the preview did, so the next round's
268
+ searches match the text the reader saw. Ids that name no proposal are ignored.
269
+
270
+ ### Structured export
271
+
272
+ Export read-only structured JSON or Markdown with block and inline anchors and
273
+ diagnostics.
274
+
275
+ ```ts
276
+ import { exportDocxMarkdown, exportDocxStructured } from '@betteroffice/docx';
277
+
278
+ const content = await exportDocxStructured(bytes, {
279
+ revisionView: 'accepted',
280
+ stories: ['body', 'headers', 'footers'],
281
+ });
282
+ for (const block of content.stories[0].blocks) {
283
+ if (block.kind === 'heading') console.log(block.heading.outlineLevel, block.anchor);
284
+ }
285
+ const { markdown, anchors } = await exportDocxMarkdown(bytes, { revisionView: 'markup' });
286
+ ```
287
+
288
+ On a live session, `session.exportStructured(options)` and
289
+ `session.exportMarkdown(options)` return `{ ok: true, version, content }` from one
290
+ read of the committed state: anchors resolve against that version, and nothing is
291
+ committed, flushed or published. Bytes exports and `renderDocxMarkdown(content)`
292
+ return snapshot content and throw `DocxExportError` for unusable options. A
293
+ refusal's `failure` is `{ code, target, message }`, with `target: null` when it
294
+ concerns no anchor; `unsupported` means the session holds no document content.
295
+ `session.headings(story)` lists a story's headings classified the same way; the
296
+ legacy `collectHeadings` tree walker from `@betteroffice/docx/utils` is deprecated
297
+ in its favour.
298
+
299
+ Content is `schemaVersion: 1`: ordered stories (`body` by default; `headers`,
300
+ `footers`, `footnotes`, `endnotes` and `comments` only when selected), each a list
301
+ of paragraphs, headings (outline level and whether it came from direct formatting,
302
+ the style chain, document defaults or a `HeadingN` style id), list items (numbering
303
+ format and the rendered marker, counted as Word counts them: numbering instances of
304
+ one abstract definition continue each other unless one overrides a start and so
305
+ begins its own list, levels begin at `w:start` and restart as `w:lvlRestart` says),
306
+ tables on the source grid with spans, skipped grid columns and vertical-merge
307
+ continuations, content controls, section breaks, and placeholders naming the
308
+ source element of other content. Inlines cover text, tabs, line,
309
+ page and column breaks where the source has them, note and comment references,
310
+ fields with their cached result in result order, hyperlinks and nested fields
311
+ included, all anchored to the field (a numeric field's result
312
+ blocks stay inside the field), images (alt text and the relationship of the part
313
+ that owns them) and inline controls. A header or footer part
314
+ referenced through several relationships is one story with every section that
315
+ uses it while the copies hold the same content, and one story per copy with a
316
+ diagnostic once they differ. `revisionView` is required: `accepted` and
317
+ `original` project pending revisions like `readParagraphs`, and `markup` keeps
318
+ both with `revisions` attribution on each inline, moves as `moveFrom` and
319
+ `moveTo`. Other revision history exports as an anchored `unsupported`
320
+ placeholder with an `unsupported-revision` diagnostic.
321
+
322
+ Anchors use the batch offsets and session keys: a paragraph anchor's `paraId` is the
323
+ batch target key, and a range is paragraph-local UTF-16 in the view it
324
+ names, one U+FFFC per atom, the same shape the edit batches take; ranges from a
325
+ session export address the version it returned. Content without a session
326
+ location (comment bodies, omitted raw XML) carries a `sourcePart` anchor: the
327
+ part, its SHA-256, and element-child ordinals into its XML. Content with no
328
+ location of its own carries `{ kind: 'unlocated', story, reason }`: the reason is
329
+ `duplicate-paragraph-id` (a paragraph whose Word paragraph ID repeats an earlier one
330
+ opens with a session key of its own, and edits and merges repair a key two paragraphs
331
+ share, so only shared state written outside the engine has it), `story-too-large`,
332
+ `missing-story` or
333
+ `provenance-unavailable`. Comment metadata reads
334
+ the session's comment store once a field has been written there, and the source
335
+ until then. Ids are deterministic export-tree paths, and a bytes export is
336
+ identical across runs. Exports admit one top-level block at a time, charge text before copying it, and stop at
337
+ `maxBlocks` (10,000 by default, every nested block counted) or `maxBytes`
338
+ (8,388,608 by default, on the compact JSON) at a whole top-level block, set
339
+ `truncated`, and end with a `truncated` diagnostic; the prefix already admitted is
340
+ kept, and a larger `maxBytes` never keeps fewer blocks. Of a story longer than
341
+ four units per remaining byte beyond one million, only the leading paragraphs
342
+ within that bound are read: those that fit are kept, then the export stops and says
343
+ so. A comment body, field payload, shape or table cell past the bound is not read
344
+ at all. Markdown keeps story separators, headings, lists, tables (pipe tables, or
345
+ entity-escaped HTML, nested where needed, for merged or multi-block cells), attributed insertions and deletions, and a
346
+ `<!-- docx-export:N -->` marker per block, nested ones included, mapped to its
347
+ anchor in `anchors`. Only http, https, mailto and internal-anchor targets are linked,
348
+ judged after entity and percent decoding, and `&` in a target is written `&amp;`; document text, titles and alt text never keep a
349
+ line break or unescaped HTML.
350
+
351
+ ### Page fragments
352
+
353
+ A paged export attaches a page map to the structured content: the physical page,
354
+ section and displayed page label showing each block and inline, and the body,
355
+ header, footer or note occurrence it sits in.
356
+
357
+ ```ts
358
+ import { exportDocxStructuredWithPages, renderDocxMarkdownWithPages } from '@betteroffice/docx';
359
+
360
+ const paged = await exportDocxStructuredWithPages(
361
+ bytes,
362
+ { revisionView: 'markup', stories: ['body', 'headers', 'footnotes'], includeGeometry: true },
363
+ { fonts: [{ key: 'sans', data: fontBase64 }], defaultChain: ['sans'] }
364
+ );
365
+ paged.layout.pages; // pageIndex, displayedLabel, sectionIndex, parityFiller, size
366
+ paged.layout.fragments; // pageIndex, occurrenceId, nodeId, slice, continuation flags, geometry
367
+ const { markdown } = await renderDocxMarkdownWithPages(paged, { pageMarkers: true });
368
+ ```
369
+
370
+ `exportDocxStructuredWithPages` opens the bytes in a private session, registers
371
+ exactly the fonts it is given, as base64 data, in a measurement font store of its
372
+ own (a requirement `family|bold|italic` takes the chain named by its key, else by
373
+ its lowercase family, else `defaultChain`; nothing is looked up on the system and
374
+ no editor's fonts change), lays out every section, header, footer and note, and
375
+ exports from that one state. Its options are plain JSON: `measurementDefaults`
376
+ (`fontFamily`, `fontSize`), `renderEnvironment` (`showHiddenText`,
377
+ `defaultTabStopTwips`) and `compatibility`, all fingerprinted in the map's
378
+ provenance. A requirement left with no font, including the `measurementDefaults`
379
+ family text naming none falls back to, or any text measured with stand-in metrics
380
+ is refused as `layout-unavailable`, as is a live layout whose font store was
381
+ cleared or added to since.
382
+ The snapshot map is deterministic for the same bytes, fonts and options and
383
+ carries no session token. `session.exportStructuredWithPages(options)` reads the
384
+ region layout a session retains and lays nothing out, flushes nothing and loads no
385
+ font; the layout must have lowered the current version from the session's own
386
+ stories, with section, settings and note metadata that describe it and a
387
+ registered font for every requirement. Its map carries `documentVersion` and a
388
+ `layoutVersion` to pass back as `expectLayoutVersion`; its references describe the
389
+ authoritative layout of that version, which a later edit may supersede before it is
390
+ painted.
391
+
392
+ `pageIndex` counts physical pages from zero, blank parity pages included, while
393
+ `displayedNumber`/`displayedLabel` follow the section's PAGE numbering (restarts,
394
+ continuation and Roman or letter formats). A header or footer part stays one exported story with an occurrence
395
+ on every page showing it; a note has an occurrence where its note area is, which
396
+ may differ from its reference's page. Text slices are ranges in the export's own
397
+ offsets, split where the node, paragraph, view or page changes; atoms (fields,
398
+ controls, images, note marks, breaks) are sliced whole, and one split across
399
+ pages carries `partial` and an `anchor-only` diagnostic. Table
400
+ fragments list their row window with `continuedFromPrevious`, `continuedOnNext`
401
+ and `repeatedHeader`, and each cell paragraph has fragments of its own for the lines
402
+ its cell shows (a line the cell cuts through is listed with a `clipped-content`
403
+ diagnostic). Pages are
404
+ laid out with revision markup, so while a laid-out story holds pending revisions a
405
+ paged export reads the `markup` view, and `accepted` or `original` return
406
+ `unsupported-revision-layout`. The other refusal codes are `stale-document`,
407
+ `stale-layout` (stale section, settings or note metadata, fonts, options or
408
+ `expectLayoutVersion`), `layout-unavailable`, `layout-not-converged` and
409
+ `unsupported`.
410
+ Geometry is off by default; rectangles are unzoomed CSS pixels (96 per inch) from
411
+ the physical page's top-left corner. `maxFragments` (100,000 by default) and
412
+ `maxLayoutBytes` bound the map separately and mark it `truncated`; mapping stops a
413
+ page past the limit, so a truncated map leaves out the diagnostics of later pages
414
+ and of paragraphs no page shows. With
415
+ `pageMarkers`, Markdown follows each block marker with
416
+ `<!-- docx-pages: 0=i 1=ii -->` (labels percent-encoded) and writes no page break
417
+ into the text; a map from other content is refused. The map is `schemaVersion: 1`,
418
+ versioned apart from the content: additive fields keep the version, and a change
419
+ existing readers would misread bumps it.
420
+
421
+ ### Content controls
422
+
423
+ List a document's content controls and fill its plain- and rich-text controls in
424
+ one version-checked batch.
425
+
426
+ ```ts
427
+ const read = session.listContentControls();
428
+ if (!read.ok) throw new Error(read.failure.message);
429
+ const name = read.content.controls.find((control) => control.tag === 'customer.name')!;
430
+
431
+ const result = session.applyEdits({
432
+ expectVersion: read.version,
433
+ steps: [
434
+ { op: 'setContentControlText', target: { kind: 'id', controlId: name.controlId }, text: 'Ada Lovelace' },
435
+ { op: 'setContentControlText', target: { kind: 'tag', tag: 'customer.address' }, text: '12 Example Street\nLondon' },
436
+ ],
437
+ });
438
+ ```
439
+
440
+ Controls come in document order (body, headers, footers, footnotes, endnotes,
441
+ comments; a control before the controls inside it), each with the structured
442
+ export's control metadata (`controlId`, `ooxmlId`, `controlType`, `tag`, `alias`,
443
+ `lock`, `showingPlaceholder`, `dataBound`) plus `placement`, `anchor`,
444
+ `parentControlId`, `value` (its text with tabs as `\t` and line and paragraph
445
+ breaks as LF, or `unavailable` with a reason), `multiLine` and `effectiveLock`,
446
+ which folds in the locks of the controls containing it. `stories` narrows the read
447
+ to some categories; `maxControls` (10,000) and `maxBytes` (8,388,608) refuse with
448
+ `limit-exceeded` rather than returning part of the list, and `complete: false`
449
+ includes coverage diagnostics. Tags, aliases and
450
+ `ooxmlId`s match exactly and case-sensitively, and `findContentControls` returns
451
+ every match. `listDocxContentControls(bytes)` and
452
+ `findDocxContentControls(bytes, query)` read bytes without a session and throw
453
+ `DocxContentControlsError` for refused options. Concurrent fills from
454
+ collaborators resolve last-writer-wins for an inline control and merge like
455
+ concurrent typing for a block control.
456
+
457
+ A step's `target` is `{ kind: 'id', controlId }`, `{ kind: 'tag', tag }` or
458
+ `{ kind: 'ooxmlId', ooxmlId }`. `controlId` is a locator scoped to the
459
+ version or snapshot it was read at; list again after a version change. Tags are the template author's names for
460
+ controls. `ooxmlId` is the control's authored `w:id`, the identity that survives
461
+ save and reopen. A tag or `ooxmlId` write searches every story regardless of read
462
+ filters and needs exactly one control in the document to carry it.
463
+
464
+ `setContentControlText` replaces the content of a plain- or rich-text control
465
+ with plain text and clears its placeholder flag everywhere it is recorded,
466
+ leaving tags, aliases, ids, bindings and every other property as captured. CRLF
467
+ becomes LF; LF is a line break, except in a rich-text block control, where it
468
+ starts a paragraph: surviving paragraphs keep their ids and properties and new
469
+ ones take the first paragraph's style defaults. A plain-text control accepts LF
470
+ only when its `w:text` sets `w:multiLine` and keeps its lines in one paragraph.
471
+ The text takes the formatting of the control's first text run, or the control's
472
+ own run properties while it shows its placeholder. Equal text is a no-op unless
473
+ the placeholder still shows or a plain-text control holds several paragraphs,
474
+ which the fill joins into one. Refusals
475
+ carry the batch code and a `reason`: `missing-control`, `missing-tag` or
476
+ `missing-ooxml-id`, `ambiguous-control-id`, `ambiguous-tag` or
477
+ `ambiguous-ooxml-id`, `content-locked`, `bound-control`,
478
+ `unsupported-control-type`, `unsupported-children` (content other than text,
479
+ tabs and line breaks, such as bookmarks, fields or tables), `nested-controls`,
480
+ `unknown-lock`, `unsupported-suggestion`, `provenance-unavailable` (the session
481
+ was not opened from DOCX bytes), `unsupported-story` (a control kept only in
482
+ source XML, such as a comment body), `multiline-not-allowed` and `invalid-text`.
483
+ Checkbox, dropdown and date controls keep `setContentControlValue`; a
484
+ string passed to it fills a text control through the same step, and
485
+ `clearContentControlValue` never erases a text control's text.
486
+
487
+ ### Compare documents into tracked changes
488
+
489
+ Compare an original and a revised DOCX and get back the original with the
490
+ body text differences as tracked insertions and deletions, attributed to the
491
+ author and date you pass:
492
+
493
+ ```ts
494
+ import { compareDocx } from '@betteroffice/docx';
495
+
496
+ const result = await compareDocx(original, revised, {
497
+ author: 'Contract review',
498
+ date: '2024-05-06T09:30:00+02:00',
499
+ granularity: 'word',
500
+ unsupported: 'fail',
501
+ });
502
+ if (result.ok) {
503
+ for (const change of result.changes) console.log(change.id, change.kind, change.revised.text);
504
+ } else {
505
+ console.warn(result.diagnostics.map((diagnostic) => diagnostic.code));
506
+ }
507
+ ```
508
+
509
+ `compareDocx` compares the text of body paragraphs whose structure is unchanged. Both
510
+ packages are inspected in full before anything is authored, and any blocking
511
+ difference refuses the comparison with `{ ok: false, diagnostics }`; no partial
512
+ redline is ever returned. `unsupported: 'report'` keeps inspecting and returns
513
+ every diagnostic, bounded by `limits.maxDiagnostics`. Blocking codes are
514
+ `invalid-options`, `invalid-docx`, `existing-revisions` (anywhere, headers and
515
+ property revisions included), `paragraph-insertion`, `paragraph-deletion`,
516
+ `paragraph-move`, `ambiguous-alignment`, `table-change`, `structure-change`,
517
+ `field-change`, `object-change`, `content-control-change`, `formatting-change`,
518
+ `unsupported-content` and `unsupported-formatting` (a changed paragraph holding
519
+ content, or run properties, that edits cannot carry, such as fields,
520
+ hyperlinks, bookmarks, objects, page breaks, patterned shading or `w:lang`),
521
+ `out-of-scope-change` (headers, footers, notes, comments), `opaque-part-change`,
522
+ `provenance-unavailable`, `limit-exceeded`, `diagnostics-truncated`,
523
+ `batch-refused`, `serialization-failed` and `roundtrip-mismatch`.
524
+ `metadata-difference` (informational: modified dates, revision-session ids and
525
+ document statistics, kept from the original) and `ambiguous-identity` (a
526
+ warning: repeated paragraph ids, so changes are addressed by position) accompany
527
+ a result. Every part whose content type or content is XML is scanned for
528
+ revisions, and wrappers such as custom XML elements, body-level markers and
529
+ every part must match exactly; an XML-typed part that cannot be read refuses the
530
+ comparison.
531
+
532
+ Paragraphs are aligned conservatively: text unique to one paragraph on each side
533
+ anchors the alignment, crossing anchors are moves, one paragraph against one
534
+ between anchors is a replacement, and several need shared words and exactly one
535
+ best correspondence. Clearing a paragraph's text is a deletion; the paragraph
536
+ mark stays. Differences are reported by Unicode word, keeping punctuation and
537
+ whitespace tokens, or with `granularity: 'char'` by grapheme cluster. Each
538
+ change is one tracked replacement: deleted text keeps its formatting and
539
+ inserted text takes the revised formatting. Changes are ordered by original
540
+ position, `id` is `change-0`, `change-1` and so on, and their spans address the
541
+ inputs by part, SHA-256 and element-child path with paragraph-local UTF-16
542
+ offsets. `date` must be RFC 3339 with an explicit offset and is recorded in UTC;
543
+ the clock is never read. `author` must not be blank.
544
+
545
+ Only the changed paragraphs' content is rewritten; their start tags and
546
+ properties, every other paragraph and every other part keep the original's
547
+ bytes, and identical inputs return the original bytes. Rewritten runs carry the
548
+ session's formatting vocabulary, so run properties a style supplies are written
549
+ as direct formatting, and complex-script fonts, sizes, bold and italic are
550
+ written only as the source states them. The result is reopened and checked
551
+ against both inputs before it is returned, with each run's effective formatting
552
+ read from the XML, style toggles such as bold combined across every level of a
553
+ style's `basedOn` chain; a difference refuses with `roundtrip-mismatch`.
554
+ Defaults, which are also the ceilings: 32 MiB per input, 128 MiB inflated,
555
+ 10,000 paragraphs per input and 1,048,576 UTF-16 units of text in both inputs,
556
+ counted across every story while the parts are read, 250,000 alignment cells,
557
+ 4,000,000 diff cells, 128 changes, 256 diagnostics, 64 MiB of staged state,
558
+ 8 MiB of result JSON without the output package (at least 1 KiB) and a 64 MiB
559
+ output, the no-op included.
560
+ Review in BetterOffice is tested.
561
+
562
+ ### Editor plugin contract (deprecated)
563
+
564
+ `@betteroffice/docx/plugin-api` keeps its geometry and sidebar building blocks:
565
+ `RenderedDomContext`, `PositionCoordinates`, `SidebarItem`,
566
+ `createRenderedDomContext`, `createCanvasHostProjector` and
567
+ `resolveItemPositions`. The snapshot-based `EditorPluginCore`,
568
+ `PluginPanelProps`, `PanelConfig` and `SidebarItemContext` are deprecated: they
569
+ pass serialized `Document` snapshots and have no host that manages their
570
+ lifecycle. Host plugins for the React editor use `defineDocxPlugin` and the
571
+ `plugins` prop of
572
+ [`@betteroffice/docx-react`](https://www.npmjs.com/package/@betteroffice/docx-react),
573
+ which provide versioned reads, granted commands and edit batches, lifecycle
574
+ events and cleanup.
575
+
576
+ ### Reanchor an existing comment
577
+
578
+ `session.setCommentRanges(commentId, ranges)` replaces only the sticky anchors of
579
+ an existing comment. The id, author, date, body, reply relationship and resolution
580
+ state remain intact. Ranges use the same paragraph locations as `addComment`;
581
+ one range may span paragraphs, and separate ranges may address different stories.
582
+
583
+ Every range must be non-empty, ordered, and within existing paragraphs. An empty
584
+ list, unknown comment/story/paragraph, or invalid offset throws before any content
585
+ changes. The host supplies the surviving text's new range.
586
+
587
+ If replacement removes all commented text, the host must explicitly choose a new
588
+ non-empty range or handle the comment's removal. Rejected reanchoring leaves the
589
+ comment unchanged and does not roll back a text replacement already performed.
590
+
591
+ `saveYrsDocx()` writes the current ranges under the comment's own ID, with its
592
+ author, date, body, replies and resolution.
593
+
594
+ Reanchoring joins the current local undo capture, so an immediate replacement and
595
+ reanchor can undo together. Comment edits participate in the session's history;
596
+ undoing comment changes conservatively invalidates all stories for saved anchors.
597
+
598
+ The undo manager retains comment item boundaries with their undo/redo entries so
599
+ anchors inside replaced text survive repeated history traversal with Yrs 0.27.
600
+ Discarding history releases its bookkeeping; undo/redo traverses a local snapshot
601
+ when those boundaries need restoration.
602
+
603
+ ### External drop positions
604
+
605
+ `RenderedDomContext.getPositionAtPoint(clientX, clientY)` queries the same canvas
606
+ hit testing used for the caret. Pass viewport coordinates, such as a drop event's
607
+ `clientX` and `clientY`. Page scroll and CSS zoom are resolved from the live page
608
+ geometry. The query never changes selection or focus.
609
+
610
+ The result contains `position`, `pageIndex`, and `region`. Header/footer hits also
611
+ carry `rId`; footnote/endnote hits carry `noteId`. Positions are local to that
612
+ region's display stream in the layout the context renders, and shift with every
613
+ edit.
614
+
615
+ In React, `editorRef.getPositionAtPoint(clientX, clientY)` runs the same query and
616
+ adds `version` and `target`: the collapsed accepted-view range at the point, keyed
617
+ by session paragraph keys, in the body, header, footer, note or table cell story
618
+ the point is in. Use it as a text step's target with `expectVersion: version`:
619
+
620
+ ```ts
621
+ const hit = editorRef.current!.getPositionAtPoint(event.clientX, event.clientY);
622
+ if (hit) {
623
+ await editorRef.current!.applyEdits({
624
+ expectVersion: hit.version,
625
+ steps: [{ op: 'insertText', target: hit.target, at: 'start', text: '{{customer.name}}' }],
626
+ });
627
+ }
628
+ ```
629
+
630
+ It returns `null` while typed or composed input is pending and until the painted
631
+ pages show the current version (retry after `flushPendingInput()` or on the next
632
+ frame), and a batch applied after further typing refuses with `stale-version`, so a
633
+ drop never lands at a shifted position. Plugins get the same query as
634
+ `context.geometry.getPositionAtPoint`, with the layout's `layoutId`. The lower-level
635
+ `editorRef.getEditorRef()?.displayPositionToYrsLoc(hit)` maps a hit to its live
636
+ `YrsLoc` (offsets that count text a pending deletion hides) without the version
637
+ check; passing a number to it retains body mapping.
638
+
639
+ Text runs and their editable content boxes are accepted. Page margins, images,
640
+ page gaps, points outside pages, and queries without ready canvas geometry return
641
+ `null`.
642
+
643
+ ### Font loads per editor
644
+
645
+ Several editors can share one page. `createFontLoadScope()` gives each its own
646
+ font loads: `onFontsLoaded` and `onFontError` on a scope hear the loads made
647
+ through it and module-level ones, never another scope's. `registerDocumentFaces(faces, scope)`
648
+ registers a document's embedded faces under their own family names, or under
649
+ an alias when another open document embeds different faces under the same name,
650
+ and resolves to the family each was registered under. Draw with that map as
651
+ `DrawPageOptions.fontFamilies`. The scope holds the faces until its next
652
+ document or `dispose()`. `loadEmbeddedFontFamilies` does the same from a
653
+ package's font table.