@folijs/docx 0.0.0-stage → 0.3.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 (79) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +21 -0
  3. package/README.md +141 -2
  4. package/dist/export/content.d.ts +17 -0
  5. package/dist/export/content.d.ts.map +1 -0
  6. package/dist/export/content.js +165 -0
  7. package/dist/export/content.js.map +1 -0
  8. package/dist/export/index.d.ts +14 -0
  9. package/dist/export/index.d.ts.map +1 -0
  10. package/dist/export/index.js +352 -0
  11. package/dist/export/index.js.map +1 -0
  12. package/dist/export/parts.d.ts +24 -0
  13. package/dist/export/parts.d.ts.map +1 -0
  14. package/dist/export/parts.js +413 -0
  15. package/dist/export/parts.js.map +1 -0
  16. package/dist/export/properties.d.ts +39 -0
  17. package/dist/export/properties.d.ts.map +1 -0
  18. package/dist/export/properties.js +506 -0
  19. package/dist/export/properties.js.map +1 -0
  20. package/dist/export/xmlout.d.ts +63 -0
  21. package/dist/export/xmlout.d.ts.map +1 -0
  22. package/dist/export/xmlout.js +194 -0
  23. package/dist/export/xmlout.js.map +1 -0
  24. package/dist/import/content.d.ts +35 -0
  25. package/dist/import/content.d.ts.map +1 -0
  26. package/dist/import/content.js +370 -0
  27. package/dist/import/content.js.map +1 -0
  28. package/dist/import/index.d.ts +26 -0
  29. package/dist/import/index.d.ts.map +1 -0
  30. package/dist/import/index.js +96 -0
  31. package/dist/import/index.js.map +1 -0
  32. package/dist/import/ooxml.d.ts +38 -0
  33. package/dist/import/ooxml.d.ts.map +1 -0
  34. package/dist/import/ooxml.js +70 -0
  35. package/dist/import/ooxml.js.map +1 -0
  36. package/dist/import/parts.d.ts +35 -0
  37. package/dist/import/parts.d.ts.map +1 -0
  38. package/dist/import/parts.js +365 -0
  39. package/dist/import/parts.js.map +1 -0
  40. package/dist/import/properties.d.ts +50 -0
  41. package/dist/import/properties.d.ts.map +1 -0
  42. package/dist/import/properties.js +403 -0
  43. package/dist/import/properties.js.map +1 -0
  44. package/dist/import/report.d.ts +28 -0
  45. package/dist/import/report.d.ts.map +1 -0
  46. package/dist/import/report.js +42 -0
  47. package/dist/import/report.js.map +1 -0
  48. package/dist/index.d.ts +6 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.js +6 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/package.d.ts +70 -0
  53. package/dist/package.d.ts.map +1 -0
  54. package/dist/package.js +259 -0
  55. package/dist/package.js.map +1 -0
  56. package/dist/xml.d.ts +79 -0
  57. package/dist/xml.d.ts.map +1 -0
  58. package/dist/xml.js +384 -0
  59. package/dist/xml.js.map +1 -0
  60. package/dist/zip.d.ts +66 -0
  61. package/dist/zip.d.ts.map +1 -0
  62. package/dist/zip.js +356 -0
  63. package/dist/zip.js.map +1 -0
  64. package/package.json +36 -3
  65. package/src/export/content.ts +229 -0
  66. package/src/export/index.ts +445 -0
  67. package/src/export/parts.ts +545 -0
  68. package/src/export/properties.ts +608 -0
  69. package/src/export/xmlout.ts +225 -0
  70. package/src/import/content.ts +413 -0
  71. package/src/import/index.ts +126 -0
  72. package/src/import/ooxml.ts +77 -0
  73. package/src/import/parts.ts +423 -0
  74. package/src/import/properties.ts +504 -0
  75. package/src/import/report.ts +64 -0
  76. package/src/index.ts +24 -0
  77. package/src/package.ts +328 -0
  78. package/src/xml.ts +443 -0
  79. package/src/zip.ts +401 -0
@@ -0,0 +1,225 @@
1
+ /** Writing XML: escaping, elements, and reading back the verbatim fragments the model keeps. */
2
+
3
+ import { W } from "../import/ooxml.js";
4
+ import { DocxError } from "../package.js";
5
+ import { parseXml, type XmlElement } from "../xml.js";
6
+
7
+ /**
8
+ * Throws when `text` has a character XML 1.0 cannot hold (control characters other than tab
9
+ * and line ends, lone surrogates, U+FFFE, U+FFFF): no file Word opens could carry it.
10
+ */
11
+ export function checkCharacters(text: string, where: string): void {
12
+ for (let i = 0; i < text.length; i++) {
13
+ const c = text.charCodeAt(i);
14
+ let bad = false;
15
+ if (c < 0x20) bad = c !== 0x09 && c !== 0x0a && c !== 0x0d;
16
+ else if (c >= 0xd800 && c <= 0xdbff) {
17
+ const next = text.charCodeAt(i + 1);
18
+ if (next >= 0xdc00 && next <= 0xdfff) i++;
19
+ else bad = true;
20
+ } else bad = (c >= 0xdc00 && c <= 0xdfff) || c === 0xfffe || c === 0xffff;
21
+ if (bad) {
22
+ throw new DocxError(
23
+ `${where}: character U+${c.toString(16).toUpperCase().padStart(4, "0")} cannot be written to a .docx`,
24
+ );
25
+ }
26
+ }
27
+ }
28
+
29
+ /** Character data: `&`, `<`, `>` escaped (characters XML cannot hold refused). */
30
+ export function escapeText(text: string): string {
31
+ checkCharacters(text, "text");
32
+ return text.replace(/[&<>]/g, (c) => (c === "&" ? "&amp;" : c === "<" ? "&lt;" : "&gt;"));
33
+ }
34
+
35
+ /** An attribute value: also `"`, and tabs and line ends as references (XML normalizes them). */
36
+ export function escapeAttribute(value: string): string {
37
+ checkCharacters(value, "attribute");
38
+ return value.replace(/[&<>"\t\n\r]/g, (c) => `&#${c.charCodeAt(0)};`);
39
+ }
40
+
41
+ export type Attrs = Readonly<Record<string, string | number | boolean | undefined | null>>;
42
+
43
+ /** `<name a="1">children</name>`, or `<name a="1"/>` without children; undefined attributes left out. */
44
+ export function el(name: string, attrs: Attrs = {}, children = ""): string {
45
+ let out = `<${name}`;
46
+ for (const [key, value] of Object.entries(attrs)) {
47
+ if (value === undefined || value === null) continue;
48
+ out += ` ${key}="${escapeAttribute(typeof value === "boolean" ? (value ? "1" : "0") : String(value))}"`;
49
+ }
50
+ return children ? `${out}>${children}</${name}>` : `${out}/>`;
51
+ }
52
+
53
+ /** `w:` element with a `w:val`. */
54
+ export function val(local: string, value: string | number | undefined): string {
55
+ return value === undefined ? "" : el(`w:${local}`, { "w:val": value });
56
+ }
57
+
58
+ /** An on/off property: `<w:b/>`, or `<w:b w:val="0"/>` when off. */
59
+ export function onOff(local: string, value: boolean | null | undefined): string {
60
+ if (value === undefined || value === null) return "";
61
+ return value ? el(`w:${local}`) : el(`w:${local}`, { "w:val": "0" });
62
+ }
63
+
64
+ /**
65
+ * Namespace declarations in scope for a part's verbatim fragments: its root's `xmlns`
66
+ * attributes, written on a wrapper so a fragment such as `<w:pPr>…</w:pPr>` parses.
67
+ */
68
+ export interface Namespaces {
69
+ readonly declarations: string;
70
+ /** The prefixes declared (`w`, `w14`…). */
71
+ readonly prefixes: ReadonlySet<string>;
72
+ }
73
+
74
+ /** The namespaces Word declares on its parts, so content imported from Word fits a new part. */
75
+ const WORD_NAMESPACES: Record<string, string> = {
76
+ wpc: "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas",
77
+ mc: "http://schemas.openxmlformats.org/markup-compatibility/2006",
78
+ o: "urn:schemas-microsoft-com:office:office",
79
+ r: "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
80
+ m: "http://schemas.openxmlformats.org/officeDocument/2006/math",
81
+ v: "urn:schemas-microsoft-com:vml",
82
+ wp14: "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing",
83
+ wp: "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
84
+ w10: "urn:schemas-microsoft-com:office:word",
85
+ w: W,
86
+ w14: "http://schemas.microsoft.com/office/word/2010/wordml",
87
+ w15: "http://schemas.microsoft.com/office/word/2012/wordml",
88
+ w16cex: "http://schemas.microsoft.com/office/word/2018/wordml/cex",
89
+ w16cid: "http://schemas.microsoft.com/office/word/2016/wordml/cid",
90
+ w16: "http://schemas.microsoft.com/office/word/2018/wordml",
91
+ w16du: "http://schemas.microsoft.com/office/word/2023/wordml/word16du",
92
+ w16sdtdh: "http://schemas.microsoft.com/office/word/2020/wordml/sdtdatahash",
93
+ w16se: "http://schemas.microsoft.com/office/word/2015/wordml/symex",
94
+ wpg: "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup",
95
+ wpi: "http://schemas.microsoft.com/office/word/2010/wordprocessingInk",
96
+ wne: "http://schemas.microsoft.com/office/word/2006/wordml",
97
+ wps: "http://schemas.microsoft.com/office/word/2010/wordprocessingShape",
98
+ a: "http://schemas.openxmlformats.org/drawingml/2006/main",
99
+ pic: "http://schemas.openxmlformats.org/drawingml/2006/picture",
100
+ };
101
+
102
+ export const DEFAULT_NAMESPACES: Namespaces = {
103
+ declarations: Object.entries(WORD_NAMESPACES)
104
+ .map(([prefix, uri]) => `xmlns:${prefix}="${uri}"`)
105
+ .join(" "),
106
+ prefixes: new Set(Object.keys(WORD_NAMESPACES)),
107
+ };
108
+
109
+ /** Attributes of a new part's root: Word's namespaces, its extensions ignorable. */
110
+ export const NEW_ROOT_ATTRIBUTES = `${DEFAULT_NAMESPACES.declarations} mc:Ignorable="w14 w15 w16se w16cid w16 w16cex w16sdtdh w16du wp14"`;
111
+
112
+ export function namespacesOf(root: XmlElement, source: string): Namespaces {
113
+ const declared = root.attributes.filter((a) => a.name === "xmlns" || a.prefix === "xmlns");
114
+ if (!declared.length) return DEFAULT_NAMESPACES;
115
+ return {
116
+ declarations: declared.map((a) => source.slice(a.start, a.end)).join(" "),
117
+ prefixes: new Set(declared.map((a) => (a.prefix === "xmlns" ? a.local : ""))),
118
+ };
119
+ }
120
+
121
+ /**
122
+ * A verbatim fragment (`ext`, `runExt`, an opaque node's XML) parsed in the part's namespaces:
123
+ * exactly one element (named `expected` when given), with its offsets into the returned
124
+ * source. Anything else could not be written into the part as well-formed XML: DocxError.
125
+ */
126
+ export function fragment(
127
+ xml: string,
128
+ namespaces: Namespaces,
129
+ expected?: string,
130
+ ): { element: XmlElement; source: string } {
131
+ const source = `<fragment ${namespaces.declarations}>${xml}</fragment>`;
132
+ let doc: ReturnType<typeof parseXml>;
133
+ try {
134
+ doc = parseXml(source);
135
+ } catch (error) {
136
+ throw new DocxError(`Verbatim XML that does not fit the part: ${(error as Error).message}`, {
137
+ cause: error,
138
+ });
139
+ }
140
+ const children = doc.root.children.filter((c) => c.kind !== "text" || c.text.trim() !== "");
141
+ const element = children[0];
142
+ if (children.length !== 1 || element?.kind !== "element") {
143
+ throw new DocxError("Verbatim XML must be exactly one element");
144
+ }
145
+ if (expected && (element.ns !== W || element.local !== expected)) {
146
+ throw new DocxError(`Verbatim XML must be a w:${expected}, not ${element.name}`);
147
+ }
148
+ return { element, source };
149
+ }
150
+
151
+ /**
152
+ * An element's `attributes` bag as written (` name="value"`…). A name the writer already
153
+ * writes, or a prefix not declared in the part (nor by the bag itself), would make the element
154
+ * ill-formed: DocxError.
155
+ */
156
+ export function bagXml(
157
+ bag: unknown,
158
+ namespaces: Namespaces,
159
+ written: readonly string[] = [],
160
+ ): string {
161
+ if (!bag || typeof bag !== "object") return "";
162
+ const entries = Object.entries(bag as Record<string, string>);
163
+ const own = new Set(
164
+ entries.filter(([name]) => name.startsWith("xmlns:")).map(([name]) => name.slice(6)),
165
+ );
166
+ let out = "";
167
+ for (const [name, value] of entries) {
168
+ if (written.includes(name))
169
+ throw new DocxError(`Attribute ${name} is written from the model, not from the bag`);
170
+ const colon = name.indexOf(":");
171
+ const prefix = colon === -1 ? "" : name.slice(0, colon);
172
+ if (
173
+ prefix &&
174
+ prefix !== "xmlns" &&
175
+ prefix !== "xml" &&
176
+ !namespaces.prefixes.has(prefix) &&
177
+ !own.has(prefix)
178
+ ) {
179
+ throw new DocxError(`Attribute ${name}: prefix ${prefix} is not declared in the part`);
180
+ }
181
+ out += ` ${name}="${escapeAttribute(value)}"`;
182
+ }
183
+ return out;
184
+ }
185
+
186
+ /**
187
+ * The children of a properties element in the order Word requires. `modeled` are the children
188
+ * the model owns: written from `generated` or not at all (a property removed in the editor must
189
+ * not come back from the original). Every other child of `original` (unknown to Foli) is kept
190
+ * verbatim at its place in `order`, or at the end when `order` does not name it (extensions
191
+ * such as `w14:ligatures`, which Word writes last).
192
+ */
193
+ export function merged(
194
+ order: readonly string[],
195
+ modeled: ReadonlySet<string>,
196
+ generated: ReadonlyMap<string, string>,
197
+ original: { element: XmlElement; source: string } | undefined,
198
+ ): string {
199
+ const kept = new Map<string, string[]>();
200
+ const tail: string[] = [];
201
+ if (original) {
202
+ for (const c of original.element.children) {
203
+ if (c.kind !== "element") continue;
204
+ const isW = c.ns === W;
205
+ if (isW && modeled.has(c.local)) continue;
206
+ const text = original.source.slice(c.start, c.end);
207
+ if (isW && order.includes(c.local)) kept.set(c.local, [...(kept.get(c.local) ?? []), text]);
208
+ else tail.push(text);
209
+ }
210
+ }
211
+ let out = "";
212
+ for (const local of order) out += generated.get(local) ?? (kept.get(local) ?? []).join("");
213
+ return out + tail.join("");
214
+ }
215
+
216
+ /** The original element's own attributes, as written (`w:rsidR`… on `w:pPr` is rare but kept). */
217
+ export function attributesOf(
218
+ original: { element: XmlElement; source: string } | undefined,
219
+ ): string {
220
+ if (!original) return "";
221
+ return original.element.attributes
222
+ .filter((a) => a.name !== "xmlns" && a.prefix !== "xmlns")
223
+ .map((a) => ` ${original.source.slice(a.start, a.end)}`)
224
+ .join("");
225
+ }
@@ -0,0 +1,413 @@
1
+ /**
2
+ * Body content (`w:body`, a comment's paragraphs) to schema v3 nodes. What Foli does not model
3
+ * yet becomes an opaque node holding the element's source verbatim, with a label to show (none
4
+ * for markers that have nothing to show: field characters, range ends).
5
+ */
6
+
7
+ import { type MarkJSON, type NodeJSON, schema } from "@folijs/core";
8
+ import type { DocxPackage, Relationship } from "../package.js";
9
+ import type { XmlElement, XmlNode } from "../xml.js";
10
+ import { attr, child, deepText, integer, isW, R, REL, textOf, W } from "./ooxml.js";
11
+ import {
12
+ attributeBag,
13
+ type Context,
14
+ mark,
15
+ paragraphProperties,
16
+ revisionMark,
17
+ runProperties,
18
+ setParagraph,
19
+ sourceOf,
20
+ } from "./properties.js";
21
+
22
+ export interface ContentContext extends Context {
23
+ readonly pkg: DocxPackage;
24
+ /** The part the content is in: relationship ids (hyperlinks) resolve against it. */
25
+ readonly part: string;
26
+ /** The tracked moves open at this point. */
27
+ readonly moves: Moves;
28
+ /** The part's relationship with this id (hyperlink targets). */
29
+ readonly relationship: (id: string) => Relationship | undefined;
30
+ }
31
+
32
+ /** Labels of the opaque elements that show something; anything else unknown shows its name. */
33
+ const BLOCK_LABELS: Record<string, string | null> = {
34
+ tbl: "table",
35
+ sdt: "content control",
36
+ altChunk: "embedded document",
37
+ customXml: "custom XML",
38
+ bookmarkStart: null,
39
+ bookmarkEnd: null,
40
+ commentRangeStart: null,
41
+ commentRangeEnd: null,
42
+ moveFromRangeStart: null,
43
+ moveFromRangeEnd: null,
44
+ moveToRangeStart: null,
45
+ moveToRangeEnd: null,
46
+ permStart: null,
47
+ permEnd: null,
48
+ };
49
+
50
+ const INLINE_LABELS: Record<string, string | null> = {
51
+ drawing: "picture",
52
+ pict: "picture",
53
+ object: "object",
54
+ sym: "symbol",
55
+ footnoteReference: "footnote",
56
+ endnoteReference: "endnote",
57
+ sdt: "content control",
58
+ oMath: "equation",
59
+ oMathPara: "equation",
60
+ ptab: "tab",
61
+ // Nothing to show: a field's structure, markers, a comment's own reference mark.
62
+ fldChar: null,
63
+ instrText: null,
64
+ annotationRef: null,
65
+ separator: null,
66
+ continuationSeparator: null,
67
+ footnoteRef: null,
68
+ endnoteRef: null,
69
+ permStart: null,
70
+ permEnd: null,
71
+ moveFromRangeStart: null,
72
+ moveFromRangeEnd: null,
73
+ moveToRangeStart: null,
74
+ moveToRangeEnd: null,
75
+ customXmlInsRangeStart: null,
76
+ customXmlInsRangeEnd: null,
77
+ customXmlDelRangeStart: null,
78
+ customXmlDelRangeEnd: null,
79
+ };
80
+
81
+ /** Recomputed by Word, never kept: spelling marks, the last rendered page breaks. */
82
+ const DROPPED = new Set(["proofErr", "lastRenderedPageBreak"]);
83
+
84
+ function label(table: Record<string, string | null>, element: XmlElement): string | null {
85
+ return Object.hasOwn(table, element.local)
86
+ ? (table[element.local] as string | null)
87
+ : element.local;
88
+ }
89
+
90
+ /**
91
+ * Block content: paragraphs, and every other block element as an opaque block. `section` is the
92
+ * body's last `w:sectPr` (the envelope's): any other one stays as an opaque block.
93
+ */
94
+ export function blocks(
95
+ nodes: readonly XmlNode[],
96
+ context: ContentContext,
97
+ section?: XmlElement,
98
+ ): NodeJSON[] {
99
+ const out: NodeJSON[] = [];
100
+ for (const node of nodes) {
101
+ if (node.kind !== "element" || node === section) continue;
102
+ if (isW(node, "p")) out.push(paragraph(node, context));
103
+ else if (node.ns === W && DROPPED.has(node.local)) context.report.dropped(node.name);
104
+ else {
105
+ context.report.opaque(node.name);
106
+ out.push({
107
+ type: "opaqueBlock",
108
+ attrs: withLabel({ xml: sourceOf(context, node) }, label(BLOCK_LABELS, node)),
109
+ });
110
+ }
111
+ }
112
+ return out;
113
+ }
114
+
115
+ function withLabel(attrs: Record<string, unknown>, value: string | null): Record<string, unknown> {
116
+ return value === null ? attrs : { ...attrs, label: value.slice(0, 255) || null };
117
+ }
118
+
119
+ export function paragraph(p: XmlElement, context: ContentContext): NodeJSON {
120
+ const attrs: Record<string, unknown> = paragraphProperties(child(p, "pPr"), context, true);
121
+ const bag = attributeBag(p, [], context);
122
+ if (bag) setParagraph(attrs, "attributes", bag, p.name, context);
123
+ const content: NodeJSON[] = [];
124
+ inlines(p.children, [], context, content);
125
+ return {
126
+ type: "paragraph",
127
+ ...(Object.keys(attrs).length ? { attrs } : {}),
128
+ ...(content.length ? { content } : {}),
129
+ };
130
+ }
131
+
132
+ /** `marks` with `m` added; undefined when `m` is missing or one of its type is already there. */
133
+ function withMark(marks: readonly MarkJSON[], m: MarkJSON | undefined): MarkJSON[] | undefined {
134
+ if (!m || marks.some((other) => other.type === m.type)) return undefined;
135
+ return [...marks, m];
136
+ }
137
+
138
+ const MARKER_TYPES: Record<string, string> = {
139
+ bookmarkStart: "bookmarkStart",
140
+ bookmarkEnd: "bookmarkEnd",
141
+ commentRangeStart: "commentStart",
142
+ commentRangeEnd: "commentEnd",
143
+ };
144
+
145
+ /** A paragraph's (or hyperlink's, or tracked change's) inline children, appended to `out`. */
146
+ function inlines(
147
+ nodes: readonly XmlNode[],
148
+ marks: readonly MarkJSON[],
149
+ context: ContentContext,
150
+ out: NodeJSON[],
151
+ ): void {
152
+ const node = (type: string, attrs?: Record<string, unknown>): NodeJSON => ({
153
+ type,
154
+ ...(attrs ? { attrs } : {}),
155
+ ...(marks.length ? { marks: [...marks] } : {}),
156
+ });
157
+ const opaque = (
158
+ element: XmlElement,
159
+ table = INLINE_LABELS,
160
+ labelValue = label(table, element),
161
+ ) => {
162
+ context.report.opaque(element.name);
163
+ out.push(node("opaqueInline", withLabel({ xml: sourceOf(context, element) }, labelValue)));
164
+ };
165
+ /** Its children with `m` added, or the whole element opaque when `m` cannot be (a link in a link…). */
166
+ const wrapped = (el: XmlElement, m: MarkJSON | undefined, labelValue: string | null) => {
167
+ const inner = withMark(marks, m);
168
+ if (inner) inlines(el.children, inner, context, out);
169
+ else opaque(el, INLINE_LABELS, labelValue);
170
+ };
171
+ for (const el of nodes) {
172
+ if (el.kind !== "element") continue;
173
+ if (!isW(el)) {
174
+ opaque(el, INLINE_LABELS, el.local === "AlternateContent" ? "alternate content" : el.local);
175
+ continue;
176
+ }
177
+ switch (el.local) {
178
+ case "pPr":
179
+ break;
180
+ case "r":
181
+ run(el, marks, context, out);
182
+ break;
183
+ case "hyperlink":
184
+ wrapped(el, link(el, context), deepText(el) || "link");
185
+ break;
186
+ case "ins":
187
+ case "del":
188
+ case "moveFrom":
189
+ case "moveTo": {
190
+ const type = el.local === "ins" || el.local === "moveTo" ? "insertion" : "deletion";
191
+ const move = el.local.startsWith("move")
192
+ ? (context.moves.current(el.local === "moveTo" ? "to" : "from") ?? "move")
193
+ : null;
194
+ wrapped(el, revisionMark(type, el, move, context), deepText(el) || null);
195
+ break;
196
+ }
197
+ case "bookmarkStart":
198
+ case "bookmarkEnd":
199
+ case "commentRangeStart":
200
+ case "commentRangeEnd": {
201
+ const type = MARKER_TYPES[el.local] as string;
202
+ const isStart = type === "bookmarkStart";
203
+ const bag = attributeBag(el, isStart ? ["w:id", "w:name"] : ["w:id"], context);
204
+ const attrs: Record<string, unknown> = { id: integer(attr(el, "id")) };
205
+ if (isStart) attrs.name = attr(el, "name") ?? "";
206
+ if (bag) attrs.attributes = bag;
207
+ const leaf = valid(node(type, attrs), el, context);
208
+ if (leaf) out.push(leaf);
209
+ else opaque(el, BLOCK_LABELS);
210
+ break;
211
+ }
212
+ case "moveFromRangeStart":
213
+ case "moveToRangeStart":
214
+ context.moves.open(
215
+ el.local.startsWith("moveFrom") ? "from" : "to",
216
+ attr(el, "id") ?? "",
217
+ attr(el, "name") ?? "move",
218
+ );
219
+ opaque(el);
220
+ break;
221
+ case "moveFromRangeEnd":
222
+ case "moveToRangeEnd":
223
+ context.moves.close(el.local.startsWith("moveFrom") ? "from" : "to", attr(el, "id") ?? "");
224
+ opaque(el);
225
+ break;
226
+ case "fldSimple":
227
+ opaque(el, INLINE_LABELS, deepText(el) || attr(el, "instr")?.trim() || "field");
228
+ break;
229
+ default:
230
+ if (DROPPED.has(el.local)) context.report.dropped(el.name);
231
+ else opaque(el);
232
+ }
233
+ }
234
+ }
235
+
236
+ /** The node if the schema accepts it (its marks were checked already); reported otherwise. */
237
+ function valid(json: NodeJSON, el: XmlElement, context: Context): NodeJSON | undefined {
238
+ try {
239
+ schema.nodeFromJSON(json);
240
+ return json;
241
+ } catch (error) {
242
+ context.report.unmodeled(el.name, (error as Error).message);
243
+ return undefined;
244
+ }
245
+ }
246
+
247
+ /**
248
+ * The tracked moves open at a point (`w:moveFromRangeStart` … `End`, by range id): the innermost
249
+ * open one names the moved content. Amortized constant time per operation.
250
+ */
251
+ export class Moves {
252
+ readonly #stacks = {
253
+ from: [] as { key: number; name: string }[],
254
+ to: [] as { key: number; name: string }[],
255
+ };
256
+ readonly #byId = new Map<string, number>();
257
+ readonly #open = new Set<number>();
258
+ #next = 0;
259
+
260
+ open(kind: "from" | "to", id: string, name: string): void {
261
+ const key = this.#next++;
262
+ this.#byId.set(`${kind}:${id}`, key);
263
+ this.#open.add(key);
264
+ this.#stacks[kind].push({ key, name });
265
+ }
266
+
267
+ close(kind: "from" | "to", id: string): void {
268
+ const key = this.#byId.get(`${kind}:${id}`);
269
+ if (key === undefined) return;
270
+ this.#byId.delete(`${kind}:${id}`);
271
+ this.#open.delete(key);
272
+ }
273
+
274
+ current(kind: "from" | "to"): string | undefined {
275
+ const stack = this.#stacks[kind];
276
+ // Closed ranges at the top are discarded once: each entry is popped at most once.
277
+ while (stack.length && !this.#open.has((stack.at(-1) as { key: number }).key)) stack.pop();
278
+ return stack.at(-1)?.name;
279
+ }
280
+ }
281
+
282
+ /** `w:hyperlink` as a link mark: the target from its relationship, or a bookmark. */
283
+ function link(el: XmlElement, context: ContentContext): MarkJSON | undefined {
284
+ const id = attr(el, "id", R);
285
+ const relationship = id === undefined ? undefined : context.relationship(id);
286
+ const href =
287
+ relationship?.type === REL.hyperlink || relationship?.external
288
+ ? relationship.target
289
+ : undefined;
290
+ const attrs = {
291
+ href: href ?? null,
292
+ anchor: attr(el, "anchor") ?? null,
293
+ tooltip: attr(el, "tooltip") ?? null,
294
+ attributes: attributeBag(el, ["w:anchor", "w:tooltip"], context) ?? null,
295
+ };
296
+ return mark({ type: "link", attrs }, el.name, context);
297
+ }
298
+
299
+ /** A run's content, each piece carrying the run's marks (its properties, verbatim in `runExt`). */
300
+ function run(
301
+ r: XmlElement,
302
+ outer: readonly MarkJSON[],
303
+ context: ContentContext,
304
+ out: NodeJSON[],
305
+ ): void {
306
+ const node = (
307
+ type: string,
308
+ marks: readonly MarkJSON[],
309
+ attrs?: Record<string, unknown>,
310
+ text?: string,
311
+ ): NodeJSON => ({
312
+ type,
313
+ ...(attrs ? { attrs } : {}),
314
+ ...(text === undefined ? {} : { text }),
315
+ ...(marks.length ? { marks: [...marks] } : {}),
316
+ });
317
+ // Editing session ids are Word's to recompute; any other run attribute has no home: the run
318
+ // stays whole, opaque.
319
+ const isRsid = (a: XmlElement["attributes"][number]) => a.ns === W && a.local.startsWith("rsid");
320
+ const unmodeled = r.attributes.find((a) => !isRsid(a));
321
+ if (unmodeled) {
322
+ context.report.opaque(`${r.name}@${unmodeled.name}`);
323
+ out.push(
324
+ node("opaqueInline", outer, withLabel({ xml: sourceOf(context, r) }, deepText(r) || null)),
325
+ );
326
+ return;
327
+ }
328
+ for (const a of r.attributes) context.report.dropped(`w:r@${a.name}`);
329
+ const rPr = child(r, "rPr");
330
+ let marks = [...outer];
331
+ for (const m of runProperties(rPr, context)) {
332
+ // A property the enclosing elements set (a hyperlink's style…): the run's own wins.
333
+ marks = [...marks.filter((other) => other.type !== m.type), m];
334
+ }
335
+ if (rPr) marks.push({ type: "runExt", attrs: { xml: sourceOf(context, rPr) } });
336
+ const before = out.length;
337
+ const text = (value: string) => {
338
+ if (value) out.push(node("text", marks, undefined, value));
339
+ };
340
+ for (const el of r.children) {
341
+ if (el.kind !== "element" || el === rPr) continue;
342
+ if (!isW(el)) {
343
+ opaqueRun(el, el.local === "AlternateContent" ? "alternate content" : el.local);
344
+ continue;
345
+ }
346
+ switch (el.local) {
347
+ case "t":
348
+ case "delText":
349
+ text(spaced(el));
350
+ break;
351
+ case "tab":
352
+ out.push(node("tab", marks));
353
+ break;
354
+ case "br": {
355
+ const type = attr(el, "type");
356
+ if (type === "page") out.push(node("pageBreak", marks));
357
+ else if (type === "column") out.push(node("columnBreak", marks));
358
+ else {
359
+ const clear = attr(el, "clear");
360
+ const leaf = valid(node("hardBreak", marks, clear ? { clear } : undefined), el, context);
361
+ if (leaf) out.push(leaf);
362
+ else opaqueRun(el);
363
+ }
364
+ break;
365
+ }
366
+ case "cr":
367
+ out.push(node("hardBreak", marks));
368
+ break;
369
+ case "noBreakHyphen":
370
+ text("‑");
371
+ break;
372
+ case "softHyphen":
373
+ text("­");
374
+ break;
375
+ case "commentReference": {
376
+ const bag = attributeBag(el, ["w:id"], context);
377
+ const attrs: Record<string, unknown> = { id: integer(attr(el, "id")) };
378
+ if (bag) attrs.attributes = bag;
379
+ const leaf = valid(node("commentReference", marks, attrs), el, context);
380
+ if (leaf) out.push(leaf);
381
+ else opaqueRun(el);
382
+ break;
383
+ }
384
+ default:
385
+ if (DROPPED.has(el.local)) context.report.dropped(el.name);
386
+ else opaqueRun(el);
387
+ }
388
+ }
389
+ // A run with properties and nothing else shows nothing; Word drops those too.
390
+ if (out.length === before) context.report.dropped("w:r (empty)");
391
+
392
+ function opaqueRun(el: XmlElement, labelValue = label(INLINE_LABELS, el)): void {
393
+ context.report.opaque(el.name);
394
+ out.push(
395
+ node("opaqueInline", marks, {
396
+ ...withLabel({ xml: sourceOf(context, el) }, labelValue),
397
+ run: true,
398
+ }),
399
+ );
400
+ }
401
+ }
402
+
403
+ /**
404
+ * A `w:t`'s text as Word reads it: without `xml:space="preserve"`, whitespace at its ends is not
405
+ * part of the text (Word writes `preserve` whenever it is).
406
+ */
407
+ function spaced(el: XmlElement): string {
408
+ const value = textOf(el);
409
+ const preserve = el.attributes.some(
410
+ (a) => a.local === "space" && a.prefix === "xml" && a.value === "preserve",
411
+ );
412
+ return preserve ? value : value.trim();
413
+ }