@office-open/docx 0.10.12 → 0.10.13

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 (36) hide show
  1. package/dist/chart.d.mts +1 -0
  2. package/dist/chart.mjs +2 -0
  3. package/dist/{parts-B7Sfx_F0.mjs → comments-BKbOd_pv.mjs} +124 -5498
  4. package/dist/comments-BKbOd_pv.mjs.map +1 -0
  5. package/dist/context-B4Ffx12w.mjs +4467 -0
  6. package/dist/context-B4Ffx12w.mjs.map +1 -0
  7. package/dist/{core-properties-CIG9ZnsW.d.mts → core-properties-DIyQ18ti.d.mts} +59 -59
  8. package/dist/core-properties-DIyQ18ti.d.mts.map +1 -0
  9. package/dist/document-attributes-C6PDT-ap.mjs +60 -0
  10. package/dist/document-attributes-C6PDT-ap.mjs.map +1 -0
  11. package/dist/drawingml.d.mts +1 -0
  12. package/dist/drawingml.mjs +2 -0
  13. package/dist/{generate-DjODfjQ1.mjs → generate-B-rbYRj-.mjs} +15 -14
  14. package/dist/generate-B-rbYRj-.mjs.map +1 -0
  15. package/dist/generate.d.mts +1 -1
  16. package/dist/generate.mjs +1 -1
  17. package/dist/index.d.mts +2 -2
  18. package/dist/index.mjs +1156 -4
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/{parse-DDWWDGbX.mjs → parse-D8NipXPu.mjs} +186 -8
  21. package/dist/parse-D8NipXPu.mjs.map +1 -0
  22. package/dist/parse.d.mts +1 -1
  23. package/dist/parse.mjs +1 -1
  24. package/dist/patch/index.d.mts +1 -1
  25. package/dist/patch/index.d.mts.map +1 -1
  26. package/dist/patch/index.mjs +17 -11
  27. package/dist/patch/index.mjs.map +1 -1
  28. package/dist/smartart.d.mts +1 -0
  29. package/dist/smartart.mjs +2 -0
  30. package/package.json +16 -4
  31. package/dist/context-CiyAhqTX.mjs +0 -479
  32. package/dist/context-CiyAhqTX.mjs.map +0 -1
  33. package/dist/core-properties-CIG9ZnsW.d.mts.map +0 -1
  34. package/dist/generate-DjODfjQ1.mjs.map +0 -1
  35. package/dist/parse-DDWWDGbX.mjs.map +0 -1
  36. package/dist/parts-B7Sfx_F0.mjs.map +0 -1
@@ -0,0 +1,4467 @@
1
+ import { $ as parseRunProperties, C as FontWrapper, Q as stringifyRunProperties, Z as stringifyParagraphProperties, c as stringifyTableProperties, d as stringifyParagraphInline, et as stringifyElement, h as parseParagraph, i as parseTableRowPropertiesEl, it as WidthType, l as stringifyTableRowProperties, n as parseTableCellPropertiesEl, r as parseTablePropertiesEl, s as stringifyTableCellProperties, st as BorderStyle, xt as Media } from "./comments-BKbOd_pv.mjs";
2
+ import { DOCX_PARTS, Relationships, appPropertiesDesc, buildContentTypeOverrides, convertInchesToTwip, customPropertiesDesc, decimalNumber, derivePasswordHash, uniqueNumericIdCreator } from "@office-open/core";
3
+ import { attr, attrBool, attrMeasure, attrNum, escapeXml, findChild, js2xml, stringify, textOf, xml2js } from "@office-open/xml";
4
+ import { ChartCollection } from "@office-open/core/chart";
5
+ import { SmartArtCollection } from "@office-open/core/smartart";
6
+ //#region src/parts/paragraph/formatting/alignment.ts
7
+ /**
8
+ * Paragraph and table alignment module for WordprocessingML documents.
9
+ *
10
+ * This module provides justification (alignment) options for paragraphs and tables.
11
+ *
12
+ * Reference: http://officeopenxml.com/WPalignment.php
13
+ *
14
+ * @see http://officeopenxml.com/WPtableAlignment.php
15
+ * @see http://www.datypic.com/sc/ooxml/t-w_ST_Jc.html
16
+ *
17
+ * @module
18
+ */
19
+ /**
20
+ * Paragraph justification (alignment) types.
21
+ *
22
+ * Specifies the horizontal alignment of text within a paragraph.
23
+ *
24
+ * Reference: http://officeopenxml.com/WPalignment.php
25
+ *
26
+ * ## XSD Schema
27
+ * ```xml
28
+ * <xsd:simpleType name="ST_Jc">
29
+ * <xsd:restriction base="xsd:string">
30
+ * <xsd:enumeration value="start"/>
31
+ * <xsd:enumeration value="center"/>
32
+ * <xsd:enumeration value="end"/>
33
+ * <xsd:enumeration value="both"/>
34
+ * <xsd:enumeration value="mediumKashida"/>
35
+ * <xsd:enumeration value="distribute"/>
36
+ * <xsd:enumeration value="numTab"/>
37
+ * <xsd:enumeration value="highKashida"/>
38
+ * <xsd:enumeration value="lowKashida"/>
39
+ * <xsd:enumeration value="thaiDistribute"/>
40
+ * <xsd:enumeration value="left"/>
41
+ * <xsd:enumeration value="right"/>
42
+ * </xsd:restriction>
43
+ * </xsd:simpleType>
44
+ * ```
45
+ *
46
+ * @publicApi
47
+ */
48
+ const AlignmentType = {
49
+ /** Align Start */
50
+ START: "start",
51
+ /** Align Center */
52
+ CENTER: "center",
53
+ /** End */
54
+ END: "end",
55
+ /** Justified */
56
+ BOTH: "both",
57
+ /** Medium Kashida Length */
58
+ MEDIUM_KASHIDA: "mediumKashida",
59
+ /** Distribute All Characters Equally */
60
+ DISTRIBUTE: "distribute",
61
+ /** Align to List Tab */
62
+ NUM_TAB: "numTab",
63
+ /** Widest Kashida Length */
64
+ HIGH_KASHIDA: "highKashida",
65
+ /** Low Kashida Length */
66
+ LOW_KASHIDA: "lowKashida",
67
+ /** Thai Language Justification */
68
+ THAI_DISTRIBUTE: "thaiDistribute",
69
+ /** Align Left */
70
+ LEFT: "left",
71
+ /** Align Right */
72
+ RIGHT: "right",
73
+ /** Justified */
74
+ JUSTIFIED: "both"
75
+ };
76
+ //#endregion
77
+ //#region src/parts/numbering/level.ts
78
+ /**
79
+ * Number format types for list levels.
80
+ *
81
+ * Defines the various numbering formats available for list levels, including
82
+ * decimal, roman numerals, letters, and various international formats.
83
+ *
84
+ * Reference: http://officeopenxml.com/WPnumbering-numFmt.php
85
+ *
86
+ * @publicApi
87
+ */
88
+ const LevelFormat = {
89
+ /** Decimal numbering (1, 2, 3...). */
90
+ DECIMAL: "decimal",
91
+ /** Uppercase roman numerals (I, II, III...). */
92
+ UPPER_ROMAN: "upperRoman",
93
+ /** Lowercase roman numerals (i, ii, iii...). */
94
+ LOWER_ROMAN: "lowerRoman",
95
+ /** Uppercase letters (A, B, C...). */
96
+ UPPER_LETTER: "upperLetter",
97
+ /** Lowercase letters (a, b, c...). */
98
+ LOWER_LETTER: "lowerLetter",
99
+ /** Ordinal numbers (1st, 2nd, 3rd...). */
100
+ ORDINAL: "ordinal",
101
+ /** Cardinal text (one, two, three...). */
102
+ CARDINAL_TEXT: "cardinalText",
103
+ /** Ordinal text (first, second, third...). */
104
+ ORDINAL_TEXT: "ordinalText",
105
+ /** Hexadecimal numbering. */
106
+ HEX: "hex",
107
+ /** Chicago Manual of Style numbering. */
108
+ CHICAGO: "chicago",
109
+ /** Ideograph digital numbering. */
110
+ IDEOGRAPH__DIGITAL: "ideographDigital",
111
+ /** Japanese counting system. */
112
+ JAPANESE_COUNTING: "japaneseCounting",
113
+ /** Japanese aiueo ordering. */
114
+ AIUEO: "aiueo",
115
+ /** Japanese iroha ordering. */
116
+ IROHA: "iroha",
117
+ /** Full-width decimal numbering. */
118
+ DECIMAL_FULL_WIDTH: "decimalFullWidth",
119
+ /** Half-width decimal numbering. */
120
+ DECIMAL_HALF_WIDTH: "decimalHalfWidth",
121
+ /** Japanese legal numbering. */
122
+ JAPANESE_LEGAL: "japaneseLegal",
123
+ /** Japanese digital ten thousand numbering. */
124
+ JAPANESE_DIGITAL_TEN_THOUSAND: "japaneseDigitalTenThousand",
125
+ /** Decimal numbers enclosed in circles. */
126
+ DECIMAL_ENCLOSED_CIRCLE: "decimalEnclosedCircle",
127
+ /** Full-width decimal numbering variant 2. */
128
+ DECIMAL_FULL_WIDTH2: "decimalFullWidth2",
129
+ /** Full-width aiueo ordering. */
130
+ AIUEO_FULL_WIDTH: "aiueoFullWidth",
131
+ /** Full-width iroha ordering. */
132
+ IROHA_FULL_WIDTH: "irohaFullWidth",
133
+ /** Decimal with leading zeros. */
134
+ DECIMAL_ZERO: "decimalZero",
135
+ /** Bullet points. */
136
+ BULLET: "bullet",
137
+ /** Korean ganada ordering. */
138
+ GANADA: "ganada",
139
+ /** Korean chosung ordering. */
140
+ CHOSUNG: "chosung",
141
+ /** Decimal enclosed with fullstop. */
142
+ DECIMAL_ENCLOSED_FULLSTOP: "decimalEnclosedFullstop",
143
+ /** Decimal enclosed in parentheses. */
144
+ DECIMAL_ENCLOSED_PARENTHESES: "decimalEnclosedParen",
145
+ /** Decimal enclosed in circles (Chinese). */
146
+ DECIMAL_ENCLOSED_CIRCLE_CHINESE: "decimalEnclosedCircleChinese",
147
+ /** Ideograph enclosed in circles. */
148
+ IDEOGRAPH_ENCLOSED_CIRCLE: "ideographEnclosedCircle",
149
+ /** Traditional ideograph numbering. */
150
+ IDEOGRAPH_TRADITIONAL: "ideographTraditional",
151
+ /** Ideograph zodiac numbering. */
152
+ IDEOGRAPH_ZODIAC: "ideographZodiac",
153
+ /** Traditional ideograph zodiac numbering. */
154
+ IDEOGRAPH_ZODIAC_TRADITIONAL: "ideographZodiacTraditional",
155
+ /** Taiwanese counting system. */
156
+ TAIWANESE_COUNTING: "taiwaneseCounting",
157
+ /** Traditional ideograph legal numbering. */
158
+ IDEOGRAPH_LEGAL_TRADITIONAL: "ideographLegalTraditional",
159
+ /** Taiwanese counting thousand system. */
160
+ TAIWANESE_COUNTING_THOUSAND: "taiwaneseCountingThousand",
161
+ /** Taiwanese digital numbering. */
162
+ TAIWANESE_DIGITAL: "taiwaneseDigital",
163
+ /** Chinese counting system. */
164
+ CHINESE_COUNTING: "chineseCounting",
165
+ /** Simplified Chinese legal numbering. */
166
+ CHINESE_LEGAL_SIMPLIFIED: "chineseLegalSimplified",
167
+ /** Chinese counting thousand system. */
168
+ CHINESE_COUNTING_THOUSAND: "chineseCountingThousand",
169
+ /** Korean digital numbering. */
170
+ KOREAN_DIGITAL: "koreanDigital",
171
+ /** Korean counting system. */
172
+ KOREAN_COUNTING: "koreanCounting",
173
+ /** Korean legal numbering. */
174
+ KOREAN_LEGAL: "koreanLegal",
175
+ /** Korean digital numbering variant 2. */
176
+ KOREAN_DIGITAL2: "koreanDigital2",
177
+ /** Vietnamese counting system. */
178
+ VIETNAMESE_COUNTING: "vietnameseCounting",
179
+ /** Russian lowercase numbering. */
180
+ RUSSIAN_LOWER: "russianLower",
181
+ /** Russian uppercase numbering. */
182
+ RUSSIAN_UPPER: "russianUpper",
183
+ /** No numbering. */
184
+ NONE: "none",
185
+ /** Number enclosed in dashes. */
186
+ NUMBER_IN_DASH: "numberInDash",
187
+ /** Hebrew numbering variant 1. */
188
+ HEBREW1: "hebrew1",
189
+ /** Hebrew numbering variant 2. */
190
+ HEBREW2: "hebrew2",
191
+ /** Arabic alpha numbering. */
192
+ ARABIC_ALPHA: "arabicAlpha",
193
+ /** Arabic abjad numbering. */
194
+ ARABIC_ABJAD: "arabicAbjad",
195
+ /** Hindi vowels. */
196
+ HINDI_VOWELS: "hindiVowels",
197
+ /** Hindi consonants. */
198
+ HINDI_CONSONANTS: "hindiConsonants",
199
+ /** Hindi numbers. */
200
+ HINDI_NUMBERS: "hindiNumbers",
201
+ /** Hindi counting system. */
202
+ HINDI_COUNTING: "hindiCounting",
203
+ /** Thai letters. */
204
+ THAI_LETTERS: "thaiLetters",
205
+ /** Thai numbers. */
206
+ THAI_NUMBERS: "thaiNumbers",
207
+ /** Thai counting system. */
208
+ THAI_COUNTING: "thaiCounting",
209
+ /** Thai Baht text. */
210
+ BAHT_TEXT: "bahtText",
211
+ /** Dollar text. */
212
+ DOLLAR_TEXT: "dollarText",
213
+ /** Custom numbering format. */
214
+ CUSTOM: "custom"
215
+ };
216
+ /**
217
+ * Suffix types for list levels.
218
+ *
219
+ * Defines what follows the numbering text (tab, space, or nothing).
220
+ *
221
+ * @publicApi
222
+ */
223
+ const LevelSuffix = {
224
+ /** No separator after the numbering. */
225
+ NOTHING: "nothing",
226
+ /** Space character after the numbering. */
227
+ SPACE: "space",
228
+ /** Tab character after the numbering. */
229
+ TAB: "tab"
230
+ };
231
+ //#endregion
232
+ //#region src/parts/numbering/numbering.ts
233
+ /**
234
+ * Numbering module for WordprocessingML documents.
235
+ *
236
+ * Numbering provides support for numbered and bulleted lists.
237
+ * Pure string serialization — no XmlComponent inheritance.
238
+ *
239
+ * Reference: http://officeopenxml.com/WPnumbering.php
240
+ *
241
+ * @module
242
+ */
243
+ /** Namespace attributes for w:numbering (pre-computed constant). */
244
+ const NUMBERING_ATTRS = "xmlns:wpc=\"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:wp14=\"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" xmlns:w10=\"urn:schemas-microsoft-com:office:word\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\" xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\" xmlns:wpg=\"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup\" xmlns:wpi=\"http://schemas.microsoft.com/office/word/2010/wordprocessingInk\" xmlns:wne=\"http://schemas.microsoft.com/office/word/2006/wordml\" xmlns:wps=\"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\" mc:Ignorable=\"w14 w15 wp14\"";
245
+ /** Default bullet levels (9 levels: 0-8). */
246
+ const DEFAULT_BULLET_LEVELS = [
247
+ {
248
+ alignment: AlignmentType.LEFT,
249
+ format: LevelFormat.BULLET,
250
+ level: 0,
251
+ style: { paragraph: { indent: {
252
+ hanging: convertInchesToTwip(.25),
253
+ left: convertInchesToTwip(.5)
254
+ } } },
255
+ text: "●"
256
+ },
257
+ {
258
+ alignment: AlignmentType.LEFT,
259
+ format: LevelFormat.BULLET,
260
+ level: 1,
261
+ style: { paragraph: { indent: {
262
+ hanging: convertInchesToTwip(.25),
263
+ left: convertInchesToTwip(1)
264
+ } } },
265
+ text: "○"
266
+ },
267
+ {
268
+ alignment: AlignmentType.LEFT,
269
+ format: LevelFormat.BULLET,
270
+ level: 2,
271
+ style: { paragraph: { indent: {
272
+ hanging: convertInchesToTwip(.25),
273
+ left: 2160
274
+ } } },
275
+ text: "■"
276
+ },
277
+ {
278
+ alignment: AlignmentType.LEFT,
279
+ format: LevelFormat.BULLET,
280
+ level: 3,
281
+ style: { paragraph: { indent: {
282
+ hanging: convertInchesToTwip(.25),
283
+ left: 2880
284
+ } } },
285
+ text: "●"
286
+ },
287
+ {
288
+ alignment: AlignmentType.LEFT,
289
+ format: LevelFormat.BULLET,
290
+ level: 4,
291
+ style: { paragraph: { indent: {
292
+ hanging: convertInchesToTwip(.25),
293
+ left: 3600
294
+ } } },
295
+ text: "○"
296
+ },
297
+ {
298
+ alignment: AlignmentType.LEFT,
299
+ format: LevelFormat.BULLET,
300
+ level: 5,
301
+ style: { paragraph: { indent: {
302
+ hanging: convertInchesToTwip(.25),
303
+ left: 4320
304
+ } } },
305
+ text: "■"
306
+ },
307
+ {
308
+ alignment: AlignmentType.LEFT,
309
+ format: LevelFormat.BULLET,
310
+ level: 6,
311
+ style: { paragraph: { indent: {
312
+ hanging: convertInchesToTwip(.25),
313
+ left: 5040
314
+ } } },
315
+ text: "●"
316
+ },
317
+ {
318
+ alignment: AlignmentType.LEFT,
319
+ format: LevelFormat.BULLET,
320
+ level: 7,
321
+ style: { paragraph: { indent: {
322
+ hanging: convertInchesToTwip(.25),
323
+ left: 5760
324
+ } } },
325
+ text: "●"
326
+ },
327
+ {
328
+ alignment: AlignmentType.LEFT,
329
+ format: LevelFormat.BULLET,
330
+ level: 8,
331
+ style: { paragraph: { indent: {
332
+ hanging: convertInchesToTwip(.25),
333
+ left: 6480
334
+ } } },
335
+ text: "●"
336
+ }
337
+ ];
338
+ /**
339
+ * Numbering definitions for a WordprocessingML document.
340
+ *
341
+ * Pure data accumulator — no XmlComponent inheritance.
342
+ * Serializes via `serialize()` producing a complete XML part.
343
+ */
344
+ var Numbering = class {
345
+ abstractNumberingData = /* @__PURE__ */ new Map();
346
+ concreteNumberingData = /* @__PURE__ */ new Map();
347
+ referenceConfigMap = /* @__PURE__ */ new Map();
348
+ abstractNumUniqueNumericId = uniqueNumericIdCreator();
349
+ concreteNumUniqueNumericId = uniqueNumericIdCreator(1);
350
+ _numIdMacAtCleanup;
351
+ _numPicBullets;
352
+ constructor(options) {
353
+ this._numIdMacAtCleanup = options.numIdMacAtCleanup;
354
+ this._numPicBullets = options.numPicBullets;
355
+ if (options.config.length === 0) {
356
+ const defaultAbstractId = this.abstractNumUniqueNumericId();
357
+ this.abstractNumberingData.set("default-bullet-numbering", {
358
+ id: defaultAbstractId,
359
+ levels: DEFAULT_BULLET_LEVELS
360
+ });
361
+ this.concreteNumberingData.set("default-bullet-numbering", {
362
+ abstractNumId: defaultAbstractId,
363
+ instance: 0,
364
+ numId: 1,
365
+ overrideLevels: [{
366
+ num: 0,
367
+ start: 1
368
+ }],
369
+ reference: "default-bullet-numbering"
370
+ });
371
+ }
372
+ for (const con of options.config) {
373
+ this.abstractNumberingData.set(con.reference, {
374
+ id: this.abstractNumUniqueNumericId(),
375
+ levels: con.levels,
376
+ extraOptions: con.extraOptions
377
+ });
378
+ this.referenceConfigMap.set(con.reference, con.levels);
379
+ }
380
+ }
381
+ /** Serialize to word/numbering.xml content (with XML declaration). */
382
+ serialize() {
383
+ const parts = [];
384
+ parts.push(`<w:numbering ${NUMBERING_ATTRS}>`);
385
+ if (this._numPicBullets) for (const bullet of this._numPicBullets) if (bullet.pict) parts.push(`<w:numPicBullet w:numPicBulletId="${bullet.numPicBulletId}">${bullet.pict}</w:numPicBullet>`);
386
+ else parts.push(`<w:numPicBullet w:numPicBulletId="${bullet.numPicBulletId}"/>`);
387
+ for (const an of this.abstractNumberingData.values()) parts.push(stringifyAbstractNumbering(an.id, an.levels, an.extraOptions));
388
+ for (const cn of this.concreteNumberingData.values()) parts.push(stringifyConcreteNumbering(cn));
389
+ if (this._numIdMacAtCleanup !== void 0) parts.push(`<w:numIdMacAtCleanup w:val="${decimalNumber(this._numIdMacAtCleanup)}"/>`);
390
+ parts.push("</w:numbering>");
391
+ return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + parts.join("");
392
+ }
393
+ /**
394
+ * Creates a concrete numbering instance from an abstract numbering definition.
395
+ */
396
+ createConcreteNumberingInstance(reference, instance) {
397
+ const abstractNumbering = this.abstractNumberingData.get(reference);
398
+ if (!abstractNumbering) return;
399
+ const fullReference = `${reference}-${instance}`;
400
+ if (this.concreteNumberingData.has(fullReference)) return;
401
+ const firstLevelStartNumber = this.referenceConfigMap.get(reference)?.[0]?.start;
402
+ const overrideLevels = typeof firstLevelStartNumber === "number" && Number.isInteger(firstLevelStartNumber) && firstLevelStartNumber !== 1 ? [{
403
+ num: 0,
404
+ start: firstLevelStartNumber
405
+ }] : void 0;
406
+ this.concreteNumberingData.set(fullReference, {
407
+ abstractNumId: abstractNumbering.id,
408
+ instance,
409
+ numId: this.concreteNumUniqueNumericId(),
410
+ overrideLevels,
411
+ reference
412
+ });
413
+ }
414
+ /** Gets all concrete numbering instances. */
415
+ get concreteNumbering() {
416
+ return [...this.concreteNumberingData.values()];
417
+ }
418
+ /** Gets all reference configurations. */
419
+ get referenceConfig() {
420
+ return [...this.referenceConfigMap.values()];
421
+ }
422
+ };
423
+ function stringifyAbstractNumbering(id, levels, extraOptions) {
424
+ const parts = [];
425
+ const restartAttr = extraOptions?.restartNumberingAfterBreak !== void 0 ? ` w15:restartNumberingAfterBreak="${extraOptions.restartNumberingAfterBreak ? 1 : 0}"` : "";
426
+ parts.push(`<w:abstractNum w:abstractNumId="${decimalNumber(id)}"${restartAttr}>`);
427
+ if (extraOptions?.nsid !== void 0) parts.push(`<w:nsid w:val="${extraOptions.nsid}"/>`);
428
+ parts.push(`<w:multiLevelType w:val="${extraOptions?.multiLevelType ?? "hybridMultilevel"}"/>`);
429
+ if (extraOptions?.tmpl !== void 0) parts.push(`<w:tmpl w:val="${extraOptions.tmpl}"/>`);
430
+ if (extraOptions?.name !== void 0) parts.push(`<w:name w:val="${extraOptions.name}"/>`);
431
+ if (extraOptions?.styleLink !== void 0) parts.push(`<w:styleLink w:val="${extraOptions.styleLink}"/>`);
432
+ if (extraOptions?.numStyleLink !== void 0) parts.push(`<w:numStyleLink w:val="${extraOptions.numStyleLink}"/>`);
433
+ for (const level of levels) parts.push(stringifyLevel(level));
434
+ parts.push("</w:abstractNum>");
435
+ return parts.join("");
436
+ }
437
+ function stringifyConcreteNumbering(cn) {
438
+ const parts = [];
439
+ parts.push(`<w:num w:numId="${decimalNumber(cn.numId)}">`);
440
+ parts.push(`<w:abstractNumId w:val="${decimalNumber(cn.abstractNumId)}"/>`);
441
+ if (cn.overrideLevels) for (const level of cn.overrideLevels) if (level.start !== void 0) parts.push(`<w:lvlOverride w:ilvl="${level.num}"><w:startOverride w:val="${level.start}"/></w:lvlOverride>`);
442
+ else parts.push(`<w:lvlOverride w:ilvl="${level.num}"/>`);
443
+ parts.push("</w:num>");
444
+ return parts.join("");
445
+ }
446
+ function stringifyLevel(opts) {
447
+ const children = [];
448
+ children.push(`<w:start w:val="${decimalNumber(opts.start ?? 1)}"/>`);
449
+ if (opts.format) children.push(`<w:numFmt w:val="${opts.format}"/>`);
450
+ if (opts.lvlRestart !== void 0) children.push(`<w:lvlRestart w:val="${decimalNumber(opts.lvlRestart)}"/>`);
451
+ if (opts.suffix) children.push(`<w:suff w:val="${opts.suffix}"/>`);
452
+ if (opts.isLegalNumberingStyle) children.push("<w:isLgl/>");
453
+ if (opts.text !== void 0 || opts.textNull) {
454
+ const lvlTextAttrs = [];
455
+ if (opts.text !== void 0) lvlTextAttrs.push(`w:val="${opts.text}"`);
456
+ if (opts.textNull) lvlTextAttrs.push("w:null=\"1\"");
457
+ children.push(`<w:lvlText ${lvlTextAttrs.join(" ")}/>`);
458
+ }
459
+ if (opts.lvlPicBulletId !== void 0) children.push(`<w:lvlPicBulletId w:val="${decimalNumber(opts.lvlPicBulletId)}"/>`);
460
+ if (opts.legacy !== void 0) {
461
+ const legacyAttrs = [`w:legacy="${opts.legacy.enabled ?? true ? 1 : 0}"`];
462
+ if (opts.legacy.space !== void 0) legacyAttrs.push(`w:legacySpace="${opts.legacy.space}"`);
463
+ if (opts.legacy.indent !== void 0) legacyAttrs.push(`w:legacyIndent="${opts.legacy.indent}"`);
464
+ children.push(`<w:legacy ${legacyAttrs.join(" ")}/>`);
465
+ }
466
+ children.push(`<w:lvlJc w:val="${opts.alignment ?? AlignmentType.START}"/>`);
467
+ const pPrXml = stringifyParagraphProperties(opts.style && opts.style.paragraph).xml;
468
+ const rPrXml = stringifyRunProperties(opts.style && opts.style.run);
469
+ if (pPrXml) children.push(pPrXml);
470
+ if (rPrXml) children.push(rPrXml);
471
+ const lvlAttrs = [`w:ilvl="${decimalNumber(Math.min(opts.level, 9))}"`];
472
+ if (opts.w15Tentative !== void 0) lvlAttrs.push(`w15:tentative="${opts.w15Tentative ? 1 : 0}"`);
473
+ if (opts.templateCode !== void 0) lvlAttrs.push(`w:tplc="${opts.templateCode}"`);
474
+ if (opts.tentative !== void 0) lvlAttrs.push(`w:tentative="${opts.tentative ? 1 : 0}"`);
475
+ return `<w:lvl ${lvlAttrs.join(" ")}>${children.join("")}</w:lvl>`;
476
+ }
477
+ /**
478
+ * Parse w:numbering element into NumberingOptions.
479
+ */
480
+ function parseNumberingDefinitions(el, parseParagraphProperties, ctx) {
481
+ const abstractNums = /* @__PURE__ */ new Map();
482
+ for (const child of el.elements ?? []) {
483
+ if (child.name !== "w:abstractNum") continue;
484
+ const id = attr(child, "w:abstractNumId");
485
+ if (id !== void 0) abstractNums.set(id, child);
486
+ }
487
+ const numToAbstract = /* @__PURE__ */ new Map();
488
+ for (const child of el.elements ?? []) {
489
+ if (child.name !== "w:num") continue;
490
+ const numId = attr(child, "w:numId");
491
+ const abstractRef = findChild(child, "w:abstractNumId");
492
+ const abstractId = abstractRef ? attr(abstractRef, "w:val") : void 0;
493
+ if (numId !== void 0 && abstractId !== void 0) numToAbstract.set(numId, abstractId);
494
+ }
495
+ const configs = [];
496
+ for (const [numId, abstractId] of numToAbstract) {
497
+ const abstractEl = abstractNums.get(abstractId);
498
+ if (!abstractEl) continue;
499
+ const levels = [];
500
+ for (const child of abstractEl.elements ?? []) {
501
+ if (child.name !== "w:lvl") continue;
502
+ const levelOpts = parseLevelEl(child, parseParagraphProperties, ctx);
503
+ if (levelOpts) levels.push(levelOpts);
504
+ }
505
+ if (levels.length > 0) {
506
+ const extraOptions = {};
507
+ const nsidEl = findChild(abstractEl, "w:nsid");
508
+ if (nsidEl) {
509
+ const v = attr(nsidEl, "w:val");
510
+ if (v) extraOptions.nsid = v;
511
+ }
512
+ const multiLevelTypeEl = findChild(abstractEl, "w:multiLevelType");
513
+ if (multiLevelTypeEl) {
514
+ const v = attr(multiLevelTypeEl, "w:val");
515
+ if (v) extraOptions.multiLevelType = v;
516
+ }
517
+ const restartVal = attrBool(abstractEl, "w15:restartNumberingAfterBreak");
518
+ if (restartVal !== void 0) extraOptions.restartNumberingAfterBreak = restartVal;
519
+ const tmplEl = findChild(abstractEl, "w:tmpl");
520
+ if (tmplEl) {
521
+ const v = attr(tmplEl, "w:val");
522
+ if (v) extraOptions.tmpl = v;
523
+ }
524
+ configs.push({
525
+ reference: `list_${numId}`,
526
+ levels,
527
+ extraOptions
528
+ });
529
+ }
530
+ }
531
+ if (configs.length === 0) return void 0;
532
+ return { config: configs };
533
+ }
534
+ function parseLevelEl(el, parseParagraphProperties, ctx) {
535
+ const opts = {};
536
+ const level = attrNum(el, "w:ilvl");
537
+ if (level !== void 0) opts.level = level;
538
+ const start = findChild(el, "w:start");
539
+ if (start) {
540
+ const val = attrNum(start, "w:val");
541
+ if (val !== void 0) opts.start = val;
542
+ }
543
+ const lvlRestart = findChild(el, "w:lvlRestart");
544
+ if (lvlRestart) {
545
+ const val = attrNum(lvlRestart, "w:val");
546
+ if (val !== void 0) opts.lvlRestart = val;
547
+ }
548
+ const numFmt = findChild(el, "w:numFmt");
549
+ if (numFmt) {
550
+ const val = attr(numFmt, "w:val");
551
+ if (val) opts.format = val;
552
+ }
553
+ const suff = findChild(el, "w:suff");
554
+ if (suff) {
555
+ const val = attr(suff, "w:val");
556
+ if (val) opts.suffix = val;
557
+ }
558
+ if (findChild(el, "w:isLgl")) opts.isLegalNumberingStyle = true;
559
+ const lvlText = findChild(el, "w:lvlText");
560
+ if (lvlText) {
561
+ const val = attr(lvlText, "w:val");
562
+ if (val) opts.text = val;
563
+ const isNull = attrBool(lvlText, "w:null");
564
+ if (isNull) opts.textNull = isNull;
565
+ }
566
+ const lvlPicBulletId = findChild(el, "w:lvlPicBulletId");
567
+ if (lvlPicBulletId) {
568
+ const val = attrNum(lvlPicBulletId, "w:val");
569
+ if (val !== void 0) opts.lvlPicBulletId = val;
570
+ }
571
+ const legacyEl = findChild(el, "w:legacy");
572
+ if (legacyEl) {
573
+ const legacy = {};
574
+ const enabled = attrBool(legacyEl, "w:legacy");
575
+ if (enabled !== void 0) legacy.enabled = enabled;
576
+ const space = attrNum(legacyEl, "w:legacySpace");
577
+ if (space !== void 0) legacy.space = space;
578
+ const indent = attrNum(legacyEl, "w:legacyIndent");
579
+ if (indent !== void 0) legacy.indent = indent;
580
+ opts.legacy = legacy;
581
+ }
582
+ const lvlJc = findChild(el, "w:lvlJc");
583
+ if (lvlJc) {
584
+ const val = attr(lvlJc, "w:val");
585
+ if (val) opts.alignment = val;
586
+ }
587
+ const tplc = attr(el, "w:tplc");
588
+ if (tplc) opts.templateCode = tplc;
589
+ const tentative = attrBool(el, "w:tentative");
590
+ if (tentative !== void 0) opts.tentative = tentative;
591
+ const w15Tentative = attrBool(el, "w15:tentative");
592
+ if (w15Tentative !== void 0) opts.w15Tentative = w15Tentative;
593
+ const style = {};
594
+ const rPr = findChild(el, "w:rPr");
595
+ if (rPr) {
596
+ const runOpts = parseRunProperties(rPr);
597
+ if (Object.keys(runOpts).length > 0) style.run = runOpts;
598
+ }
599
+ const pPr = findChild(el, "w:pPr");
600
+ if (pPr) {
601
+ const paraOpts = parseParagraphProperties(pPr, ctx);
602
+ if (Object.keys(paraOpts).length > 0) style.paragraph = paraOpts;
603
+ }
604
+ if (Object.keys(style).length > 0) opts.style = style;
605
+ return Object.keys(opts).length > 0 ? opts : void 0;
606
+ }
607
+ //#endregion
608
+ //#region src/parts/styles/factory.ts
609
+ /**
610
+ * Build CT_Style style-level children (name…rsid), shared by paragraph/character/table styles.
611
+ * Order follows CT_Style sequence: name, aliases, basedOn, next, link, autoRedefine, hidden,
612
+ * uiPriority, semiHidden, unhideWhenUsed, qFormat, locked, personal, personalCompose,
613
+ * personalReply, rsid.
614
+ */
615
+ function stringifyStyleLevelChildren(opts) {
616
+ const parts = [`<w:name w:val="${escapeXml(opts.name ?? opts.id ?? "")}"/>`];
617
+ if (opts.aliases) parts.push(`<w:aliases w:val="${escapeXml(opts.aliases)}"/>`);
618
+ if (opts.basedOn) parts.push(`<w:basedOn w:val="${escapeXml(opts.basedOn)}"/>`);
619
+ if (opts.next) parts.push(`<w:next w:val="${escapeXml(opts.next)}"/>`);
620
+ if (opts.link) parts.push(`<w:link w:val="${escapeXml(opts.link)}"/>`);
621
+ if (opts.autoRedefine) parts.push("<w:autoRedefine/>");
622
+ if (opts.hidden) parts.push("<w:hidden/>");
623
+ if (opts.uiPriority !== void 0) parts.push(`<w:uiPriority w:val="${opts.uiPriority}"/>`);
624
+ if (opts.semiHidden) parts.push("<w:semiHidden/>");
625
+ if (opts.unhideWhenUsed) parts.push("<w:unhideWhenUsed/>");
626
+ if (opts.quickFormat) parts.push("<w:qFormat/>");
627
+ if (opts.locked) parts.push("<w:locked/>");
628
+ if (opts.personal) parts.push("<w:personal/>");
629
+ if (opts.personalCompose) parts.push("<w:personalCompose/>");
630
+ if (opts.personalReply) parts.push("<w:personalReply/>");
631
+ if (opts.rsid) parts.push(`<w:rsid w:val="${opts.rsid}"/>`);
632
+ return parts.join("");
633
+ }
634
+ /**
635
+ * Build the `<w:style>` opening tag: type/styleId plus the optional w:default
636
+ * and w:customStyle element attributes (CT_Style). Shared by paragraph/
637
+ * character/table styles.
638
+ */
639
+ function styleOpenTag(type, opts) {
640
+ let attrs = ` w:type="${type}" w:styleId="${escapeXml(opts.id ?? "")}"`;
641
+ if (opts.default) attrs += " w:default=\"1\"";
642
+ if (opts.customStyle) attrs += " w:customStyle=\"1\"";
643
+ return `<w:style${attrs}>`;
644
+ }
645
+ /** Build `<w:style>` XML for a paragraph style. */
646
+ function stringifyParagraphStyle(opts) {
647
+ const children = [stringifyStyleLevelChildren(opts)];
648
+ const pPr = stringifyParagraphProperties(opts.paragraph).xml;
649
+ if (pPr) children.push(pPr);
650
+ const rPr = stringifyRunProperties(opts.run);
651
+ if (rPr) children.push(rPr);
652
+ return `${styleOpenTag("paragraph", opts)}${children.join("")}</w:style>`;
653
+ }
654
+ /** Build `<w:style>` XML for a character style. */
655
+ function stringifyCharacterStyle(opts) {
656
+ const children = [stringifyStyleLevelChildren(opts)];
657
+ const rPr = stringifyRunProperties(opts.run);
658
+ if (rPr) children.push(rPr);
659
+ return `${styleOpenTag("character", opts)}${children.join("")}</w:style>`;
660
+ }
661
+ /** Build `<w:tblStylePr>` XML for a conditional table style format. */
662
+ function stringifyConditionalTableStyle(opts) {
663
+ const children = [];
664
+ const pPr = stringifyParagraphProperties(opts.paragraph).xml;
665
+ if (pPr) children.push(pPr);
666
+ const rPr = stringifyRunProperties(opts.run);
667
+ if (rPr) children.push(rPr);
668
+ if (opts.table) {
669
+ const tblPr = stringifyTableProperties(opts.table);
670
+ if (tblPr) children.push(tblPr);
671
+ }
672
+ if (opts.row) {
673
+ const trPr = stringifyTableRowProperties(opts.row);
674
+ if (trPr) children.push(trPr);
675
+ }
676
+ if (opts.cell) {
677
+ const tcPr = stringifyTableCellProperties(opts.cell);
678
+ if (tcPr) children.push(tcPr);
679
+ }
680
+ return `<w:tblStylePr w:type="${opts.type}">${children.join("")}</w:tblStylePr>`;
681
+ }
682
+ /** Build `<w:style type="table">` XML for a table style. */
683
+ function stringifyTableStyle(opts) {
684
+ const children = [stringifyStyleLevelChildren(opts)];
685
+ const pPr = stringifyParagraphProperties(opts.paragraph).xml;
686
+ if (pPr) children.push(pPr);
687
+ const rPr = stringifyRunProperties(opts.run);
688
+ if (rPr) children.push(rPr);
689
+ if (opts.table) {
690
+ const tblPr = stringifyTableProperties(opts.table);
691
+ if (tblPr) children.push(tblPr);
692
+ }
693
+ if (opts.row) {
694
+ const trPr = stringifyTableRowProperties(opts.row);
695
+ if (trPr) children.push(trPr);
696
+ }
697
+ if (opts.cell) {
698
+ const tcPr = stringifyTableCellProperties(opts.cell);
699
+ if (tcPr) children.push(tcPr);
700
+ }
701
+ for (const cf of opts.conditionalFormats ?? []) children.push(stringifyConditionalTableStyle(cf));
702
+ return `${styleOpenTag("table", opts)}${children.join("")}</w:style>`;
703
+ }
704
+ /** Build `<w:style type="numbering">` XML for a numbering style. */
705
+ function stringifyNumberingStyle(opts) {
706
+ const children = [stringifyStyleLevelChildren(opts)];
707
+ const pPr = stringifyParagraphProperties(opts.paragraph).xml;
708
+ if (pPr) children.push(pPr);
709
+ const rPr = stringifyRunProperties(opts.run);
710
+ if (rPr) children.push(rPr);
711
+ return `${styleOpenTag("numbering", opts)}${children.join("")}</w:style>`;
712
+ }
713
+ /** Resolve a user override for heading level N (1-9) from default styles options. */
714
+ function headingOverride(options, level) {
715
+ switch (level) {
716
+ case 1: return options.heading1;
717
+ case 2: return options.heading2;
718
+ case 3: return options.heading3;
719
+ case 4: return options.heading4;
720
+ case 5: return options.heading5;
721
+ case 6: return options.heading6;
722
+ case 7: return options.heading7;
723
+ case 8: return options.heading8;
724
+ case 9: return options.heading9;
725
+ default: return;
726
+ }
727
+ }
728
+ /** Build `<w:docDefaults>` XML matching Word's default settings. */
729
+ function stringifyDocDefaults(opts) {
730
+ const children = [];
731
+ const rPr = stringifyRunProperties(opts.run);
732
+ if (rPr) children.push(`<w:rPrDefault>${rPr}</w:rPrDefault>`);
733
+ else children.push("<w:rPrDefault><w:rPr><w:rFonts w:asciiTheme=\"minorHAnsi\" w:eastAsiaTheme=\"minorEastAsia\" w:hAnsiTheme=\"minorHAnsi\" w:cstheme=\"minorBidi\"/><w:kern w:val=\"2\"/><w:sz w:val=\"22\"/><w:szCs w:val=\"24\"/><w:lang w:val=\"en-US\" w:eastAsia=\"zh-CN\" w:bidi=\"ar-SA\"/><w14:ligatures w14:val=\"standardContextual\"/></w:rPr></w:rPrDefault>");
734
+ const pPr = stringifyParagraphProperties(opts.paragraph).xml;
735
+ if (pPr) children.push(`<w:pPrDefault>${pPr}</w:pPrDefault>`);
736
+ else children.push("<w:pPrDefault><w:pPr><w:widowControl/><w:spacing w:after=\"160\" w:line=\"278\" w:lineRule=\"auto\"/></w:pPr></w:pPrDefault>");
737
+ return `<w:docDefaults>${children.join("")}</w:docDefaults>`;
738
+ }
739
+ let cachedDefaultStyles = null;
740
+ /**
741
+ * Factory for creating default document styles.
742
+ *
743
+ * Creates styles matching Microsoft Word's default document template.
744
+ * Pure string generation — no XmlComponent inheritance.
745
+ */
746
+ var DefaultStylesFactory = class {
747
+ newInstance(options = {}) {
748
+ if (Object.keys(options).length === 0) {
749
+ if (!cachedDefaultStyles) cachedDefaultStyles = this.build({});
750
+ return cachedDefaultStyles;
751
+ }
752
+ return this.build(options);
753
+ }
754
+ build(options) {
755
+ const importedStyles = [];
756
+ const paragraphStyles = [];
757
+ const characterStyles = [];
758
+ const tableStyles = [];
759
+ const numberingStyles = [];
760
+ const initialAttributes = {
761
+ "xmlns:mc": "http://schemas.openxmlformats.org/markup-compatibility/2006",
762
+ "xmlns:r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
763
+ "xmlns:w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
764
+ "xmlns:w14": "http://schemas.microsoft.com/office/word/2010/wordml",
765
+ "xmlns:w15": "http://schemas.microsoft.com/office/word/2012/wordml",
766
+ "mc:Ignorable": "w14 w15"
767
+ };
768
+ importedStyles.push({ _raw: stringifyDocDefaults(options.document ?? {}) });
769
+ importedStyles.push({ _raw: "<w:latentStyles w:defLockedState=\"0\" w:defUIPriority=\"99\" w:defSemiHidden=\"0\" w:defUnhideWhenUsed=\"0\" w:defQFormat=\"0\" w:count=\"376\"><w:lsdException w:name=\"Normal\" w:uiPriority=\"0\" w:qFormat=\"1\"/><w:lsdException w:name=\"heading 1\" w:uiPriority=\"9\" w:qFormat=\"1\"/><w:lsdException w:name=\"heading 2\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/><w:lsdException w:name=\"heading 3\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/><w:lsdException w:name=\"heading 4\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/><w:lsdException w:name=\"heading 5\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/><w:lsdException w:name=\"heading 6\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/><w:lsdException w:name=\"heading 7\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/><w:lsdException w:name=\"heading 8\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/><w:lsdException w:name=\"heading 9\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/><w:lsdException w:name=\"Default Paragraph Font\" w:semiHidden=\"1\" w:uiPriority=\"1\" w:unhideWhenUsed=\"1\"/><w:lsdException w:name=\"Normal Table\" w:semiHidden=\"1\" w:uiPriority=\"99\" w:unhideWhenUsed=\"1\"/><w:lsdException w:name=\"No List\" w:semiHidden=\"1\" w:uiPriority=\"99\" w:unhideWhenUsed=\"1\"/><w:lsdException w:name=\"Subtitle\" w:uiPriority=\"11\" w:qFormat=\"1\"/><w:lsdException w:name=\"Strong\" w:uiPriority=\"22\" w:qFormat=\"1\"/><w:lsdException w:name=\"Emphasis\" w:uiPriority=\"20\" w:qFormat=\"1\"/><w:lsdException w:name=\"Hyperlink\" w:semiHidden=\"1\" w:unhideWhenUsed=\"1\"/><w:lsdException w:name=\"FollowedHyperlink\" w:semiHidden=\"1\" w:unhideWhenUsed=\"1\"/><w:lsdException w:name=\"No Spacing\" w:uiPriority=\"1\" w:qFormat=\"1\"/><w:lsdException w:name=\"Revision\" w:semiHidden=\"1\"/></w:latentStyles>" });
770
+ paragraphStyles.push({
771
+ id: "Normal",
772
+ name: "Normal",
773
+ default: true,
774
+ quickFormat: true
775
+ });
776
+ for (const [headingIdx, h] of [
777
+ {
778
+ id: "Heading1",
779
+ name: "heading 1",
780
+ link: "Heading1Char",
781
+ sz: 48,
782
+ before: 480,
783
+ after: 80,
784
+ outlineLvl: 0
785
+ },
786
+ {
787
+ id: "Heading2",
788
+ name: "heading 2",
789
+ link: "Heading2Char",
790
+ sz: 40,
791
+ before: 160,
792
+ after: 80,
793
+ outlineLvl: 1
794
+ },
795
+ {
796
+ id: "Heading3",
797
+ name: "heading 3",
798
+ link: "Heading3Char",
799
+ sz: 32,
800
+ before: 160,
801
+ after: 80,
802
+ outlineLvl: 2
803
+ },
804
+ {
805
+ id: "Heading4",
806
+ name: "heading 4",
807
+ link: "Heading4Char",
808
+ sz: 28,
809
+ before: 80,
810
+ after: 40,
811
+ outlineLvl: 3
812
+ },
813
+ {
814
+ id: "Heading5",
815
+ name: "heading 5",
816
+ link: "Heading5Char",
817
+ sz: 24,
818
+ before: 80,
819
+ after: 40,
820
+ outlineLvl: 4
821
+ },
822
+ {
823
+ id: "Heading6",
824
+ name: "heading 6",
825
+ link: "Heading6Char",
826
+ sz: void 0,
827
+ before: 40,
828
+ after: 0,
829
+ outlineLvl: 5
830
+ },
831
+ {
832
+ id: "Heading7",
833
+ name: "heading 7",
834
+ link: "Heading7Char",
835
+ sz: void 0,
836
+ before: 40,
837
+ after: 0,
838
+ outlineLvl: 6
839
+ },
840
+ {
841
+ id: "Heading8",
842
+ name: "heading 8",
843
+ link: "Heading8Char",
844
+ sz: void 0,
845
+ before: void 0,
846
+ after: 0,
847
+ outlineLvl: 7
848
+ },
849
+ {
850
+ id: "Heading9",
851
+ name: "heading 9",
852
+ link: "Heading9Char",
853
+ sz: void 0,
854
+ before: void 0,
855
+ after: 0,
856
+ outlineLvl: 8
857
+ }
858
+ ].entries()) {
859
+ const outlineLvl = h.outlineLvl;
860
+ const headingOverrideOpts = headingOverride(options, headingIdx + 1);
861
+ if (headingOverrideOpts) {
862
+ paragraphStyles.push({
863
+ id: h.id,
864
+ name: headingOverrideOpts.name ?? h.name,
865
+ basedOn: headingOverrideOpts.basedOn ?? "Normal",
866
+ next: headingOverrideOpts.next ?? "Normal",
867
+ link: headingOverrideOpts.link ?? h.link,
868
+ uiPriority: headingOverrideOpts.uiPriority ?? 9,
869
+ quickFormat: headingOverrideOpts.quickFormat ?? true,
870
+ semiHidden: headingOverrideOpts.semiHidden,
871
+ unhideWhenUsed: headingOverrideOpts.unhideWhenUsed,
872
+ paragraph: {
873
+ outlineLevel: headingIdx,
874
+ ...headingOverrideOpts.paragraph
875
+ },
876
+ run: headingOverrideOpts.run
877
+ });
878
+ characterStyles.push({
879
+ id: h.link,
880
+ name: `${h.name} Char`,
881
+ basedOn: "DefaultParagraphFont",
882
+ link: h.id,
883
+ run: headingOverrideOpts.run
884
+ });
885
+ continue;
886
+ }
887
+ const accentRange = outlineLvl < 6;
888
+ const runProps = {
889
+ font: accentRange ? {
890
+ asciiTheme: "majorHAnsi",
891
+ eastAsiaTheme: "majorEastAsia",
892
+ hAnsiTheme: "majorHAnsi",
893
+ cstheme: "majorBidi"
894
+ } : { cstheme: "majorBidi" },
895
+ color: accentRange ? {
896
+ val: "0F4761",
897
+ themeColor: "accent1",
898
+ themeShade: "BF"
899
+ } : {
900
+ val: "595959",
901
+ themeColor: "text1",
902
+ themeTint: "A6"
903
+ }
904
+ };
905
+ if (h.sz) {
906
+ const sizePt = h.sz / 2;
907
+ runProps.size = sizePt;
908
+ runProps.sizeComplexScript = sizePt;
909
+ }
910
+ if (outlineLvl >= 5) {
911
+ runProps.bold = true;
912
+ runProps.boldComplexScript = true;
913
+ }
914
+ paragraphStyles.push({
915
+ id: h.id,
916
+ name: h.name,
917
+ basedOn: "Normal",
918
+ next: "Normal",
919
+ link: h.link,
920
+ uiPriority: 9,
921
+ semiHidden: outlineLvl > 0,
922
+ unhideWhenUsed: outlineLvl > 0,
923
+ quickFormat: true,
924
+ paragraph: {
925
+ keepNext: true,
926
+ keepLines: true,
927
+ spacing: {
928
+ before: h.before,
929
+ after: h.after
930
+ },
931
+ outlineLevel: outlineLvl
932
+ },
933
+ run: runProps
934
+ });
935
+ characterStyles.push({
936
+ id: h.link,
937
+ name: `${h.name} Char`,
938
+ basedOn: "DefaultParagraphFont",
939
+ link: h.id,
940
+ uiPriority: 9,
941
+ semiHidden: outlineLvl > 0,
942
+ run: runProps
943
+ });
944
+ }
945
+ characterStyles.push({
946
+ id: "DefaultParagraphFont",
947
+ name: "Default Paragraph Font",
948
+ default: true,
949
+ uiPriority: 1,
950
+ semiHidden: true,
951
+ unhideWhenUsed: true
952
+ });
953
+ tableStyles.push({
954
+ id: "NormalTable",
955
+ name: "Normal Table",
956
+ default: true,
957
+ uiPriority: 99,
958
+ semiHidden: true,
959
+ unhideWhenUsed: true,
960
+ table: {
961
+ indent: {
962
+ size: 0,
963
+ type: WidthType.DXA
964
+ },
965
+ cellMargin: {
966
+ top: {
967
+ size: 0,
968
+ type: WidthType.DXA
969
+ },
970
+ left: {
971
+ size: 108,
972
+ type: WidthType.DXA
973
+ },
974
+ bottom: {
975
+ size: 0,
976
+ type: WidthType.DXA
977
+ },
978
+ right: {
979
+ size: 108,
980
+ type: WidthType.DXA
981
+ }
982
+ }
983
+ }
984
+ });
985
+ numberingStyles.push({
986
+ id: "NoList",
987
+ name: "No List",
988
+ default: true,
989
+ uiPriority: 99,
990
+ semiHidden: true,
991
+ unhideWhenUsed: true
992
+ });
993
+ if (options.title) {
994
+ paragraphStyles.push({
995
+ id: "Title",
996
+ name: options.title.name ?? "Title",
997
+ basedOn: options.title.basedOn ?? "Normal",
998
+ next: options.title.next ?? "Normal",
999
+ link: options.title.link ?? "TitleChar",
1000
+ uiPriority: options.title.uiPriority ?? 10,
1001
+ quickFormat: options.title.quickFormat ?? true,
1002
+ paragraph: options.title.paragraph,
1003
+ run: options.title.run
1004
+ });
1005
+ characterStyles.push({
1006
+ id: "TitleChar",
1007
+ name: "Title Char",
1008
+ basedOn: "DefaultParagraphFont",
1009
+ link: "Title",
1010
+ run: options.title.run
1011
+ });
1012
+ } else {
1013
+ const titleRun = {
1014
+ font: {
1015
+ asciiTheme: "majorHAnsi",
1016
+ eastAsiaTheme: "majorEastAsia",
1017
+ hAnsiTheme: "majorHAnsi",
1018
+ cstheme: "majorBidi"
1019
+ },
1020
+ characterSpacing: -10,
1021
+ kern: 28,
1022
+ size: 28,
1023
+ sizeComplexScript: 28
1024
+ };
1025
+ paragraphStyles.push({
1026
+ id: "Title",
1027
+ name: "Title",
1028
+ basedOn: "Normal",
1029
+ next: "Normal",
1030
+ link: "TitleChar",
1031
+ uiPriority: 10,
1032
+ quickFormat: true,
1033
+ paragraph: {
1034
+ spacing: {
1035
+ after: 80,
1036
+ line: 240,
1037
+ lineRule: "auto"
1038
+ },
1039
+ contextualSpacing: true,
1040
+ alignment: AlignmentType.CENTER
1041
+ },
1042
+ run: titleRun
1043
+ });
1044
+ characterStyles.push({
1045
+ id: "TitleChar",
1046
+ name: "Title Char",
1047
+ basedOn: "DefaultParagraphFont",
1048
+ link: "Title",
1049
+ uiPriority: 10,
1050
+ run: titleRun
1051
+ });
1052
+ }
1053
+ if (options.subtitle) {
1054
+ paragraphStyles.push({
1055
+ id: "Subtitle",
1056
+ name: options.subtitle.name ?? "Subtitle",
1057
+ basedOn: options.subtitle.basedOn ?? "Normal",
1058
+ next: options.subtitle.next ?? "Normal",
1059
+ link: options.subtitle.link ?? "SubtitleChar",
1060
+ uiPriority: options.subtitle.uiPriority ?? 11,
1061
+ quickFormat: options.subtitle.quickFormat ?? true,
1062
+ paragraph: options.subtitle.paragraph,
1063
+ run: options.subtitle.run
1064
+ });
1065
+ characterStyles.push({
1066
+ id: "SubtitleChar",
1067
+ name: "Subtitle Char",
1068
+ basedOn: "DefaultParagraphFont",
1069
+ link: "Subtitle",
1070
+ run: options.subtitle.run
1071
+ });
1072
+ } else {
1073
+ const subtitleRun = {
1074
+ font: {
1075
+ asciiTheme: "majorHAnsi",
1076
+ eastAsiaTheme: "majorEastAsia",
1077
+ hAnsiTheme: "majorHAnsi",
1078
+ cstheme: "majorBidi"
1079
+ },
1080
+ color: {
1081
+ val: "595959",
1082
+ themeColor: "text1",
1083
+ themeTint: "A6"
1084
+ },
1085
+ characterSpacing: 15,
1086
+ size: 14,
1087
+ sizeComplexScript: 14
1088
+ };
1089
+ paragraphStyles.push({
1090
+ id: "Subtitle",
1091
+ name: "Subtitle",
1092
+ basedOn: "Normal",
1093
+ next: "Normal",
1094
+ link: "SubtitleChar",
1095
+ uiPriority: 11,
1096
+ quickFormat: true,
1097
+ paragraph: { alignment: AlignmentType.CENTER },
1098
+ run: subtitleRun
1099
+ });
1100
+ characterStyles.push({
1101
+ id: "SubtitleChar",
1102
+ name: "Subtitle Char",
1103
+ basedOn: "DefaultParagraphFont",
1104
+ link: "Subtitle",
1105
+ uiPriority: 11,
1106
+ run: subtitleRun
1107
+ });
1108
+ }
1109
+ if (options.listParagraph) paragraphStyles.push({
1110
+ id: "ListParagraph",
1111
+ name: options.listParagraph.name ?? "List Paragraph",
1112
+ basedOn: options.listParagraph.basedOn ?? "Normal",
1113
+ uiPriority: options.listParagraph.uiPriority ?? 34,
1114
+ quickFormat: options.listParagraph.quickFormat ?? true,
1115
+ paragraph: options.listParagraph.paragraph,
1116
+ run: options.listParagraph.run
1117
+ });
1118
+ else paragraphStyles.push({
1119
+ id: "ListParagraph",
1120
+ name: "List Paragraph",
1121
+ basedOn: "Normal",
1122
+ uiPriority: 34,
1123
+ quickFormat: true,
1124
+ paragraph: {
1125
+ indent: { left: 720 },
1126
+ contextualSpacing: true
1127
+ }
1128
+ });
1129
+ if (options.strong) paragraphStyles.push({
1130
+ id: "Strong",
1131
+ name: options.strong.name ?? "Strong",
1132
+ basedOn: options.strong.basedOn ?? "Normal",
1133
+ next: options.strong.next ?? "Normal",
1134
+ quickFormat: options.strong.quickFormat ?? true,
1135
+ paragraph: options.strong.paragraph,
1136
+ run: options.strong.run
1137
+ });
1138
+ if (options.emphasis) paragraphStyles.push({
1139
+ id: "Emphasis",
1140
+ name: options.emphasis.name ?? "Emphasis",
1141
+ basedOn: options.emphasis.basedOn ?? "Normal",
1142
+ next: options.emphasis.next ?? "Normal",
1143
+ quickFormat: options.emphasis.quickFormat ?? true,
1144
+ paragraph: options.emphasis.paragraph,
1145
+ run: options.emphasis.run
1146
+ });
1147
+ const quoteRun = {
1148
+ italic: true,
1149
+ italicComplexScript: true,
1150
+ color: {
1151
+ val: "404040",
1152
+ themeColor: "text1",
1153
+ themeTint: "BF"
1154
+ }
1155
+ };
1156
+ if (options.quote) {
1157
+ paragraphStyles.push({
1158
+ id: "Quote",
1159
+ name: options.quote.name ?? "Quote",
1160
+ basedOn: options.quote.basedOn ?? "Normal",
1161
+ next: options.quote.next ?? "Normal",
1162
+ link: options.quote.link ?? "QuoteChar",
1163
+ uiPriority: options.quote.uiPriority ?? 29,
1164
+ quickFormat: options.quote.quickFormat ?? true,
1165
+ paragraph: options.quote.paragraph,
1166
+ run: options.quote.run
1167
+ });
1168
+ characterStyles.push({
1169
+ id: "QuoteChar",
1170
+ name: "Quote Char",
1171
+ basedOn: "DefaultParagraphFont",
1172
+ link: "Quote",
1173
+ run: options.quote.run
1174
+ });
1175
+ } else {
1176
+ paragraphStyles.push({
1177
+ id: "Quote",
1178
+ name: "Quote",
1179
+ basedOn: "Normal",
1180
+ next: "Normal",
1181
+ link: "QuoteChar",
1182
+ uiPriority: 29,
1183
+ quickFormat: true,
1184
+ paragraph: {
1185
+ spacing: { before: 160 },
1186
+ alignment: AlignmentType.CENTER
1187
+ },
1188
+ run: quoteRun
1189
+ });
1190
+ characterStyles.push({
1191
+ id: "QuoteChar",
1192
+ name: "Quote Char",
1193
+ basedOn: "DefaultParagraphFont",
1194
+ link: "Quote",
1195
+ uiPriority: 29,
1196
+ run: quoteRun
1197
+ });
1198
+ }
1199
+ const intenseQuoteRun = {
1200
+ italic: true,
1201
+ italicComplexScript: true,
1202
+ color: {
1203
+ val: "0F4761",
1204
+ themeColor: "accent1",
1205
+ themeShade: "BF"
1206
+ }
1207
+ };
1208
+ const intenseQuoteBorder = {
1209
+ style: BorderStyle.SINGLE,
1210
+ size: 4,
1211
+ space: 10,
1212
+ color: "0F4761",
1213
+ themeColor: "accent1",
1214
+ themeShade: "BF"
1215
+ };
1216
+ paragraphStyles.push({
1217
+ id: "IntenseQuote",
1218
+ name: "Intense Quote",
1219
+ basedOn: "Normal",
1220
+ next: "Normal",
1221
+ link: "IntenseQuoteChar",
1222
+ uiPriority: 30,
1223
+ quickFormat: true,
1224
+ paragraph: {
1225
+ border: {
1226
+ top: intenseQuoteBorder,
1227
+ bottom: intenseQuoteBorder
1228
+ },
1229
+ spacing: {
1230
+ before: 360,
1231
+ after: 360
1232
+ },
1233
+ indent: {
1234
+ left: 864,
1235
+ right: 864
1236
+ },
1237
+ alignment: AlignmentType.CENTER
1238
+ },
1239
+ run: intenseQuoteRun
1240
+ });
1241
+ characterStyles.push({
1242
+ id: "IntenseQuoteChar",
1243
+ name: "Intense Quote Char",
1244
+ basedOn: "DefaultParagraphFont",
1245
+ link: "IntenseQuote",
1246
+ uiPriority: 30,
1247
+ run: intenseQuoteRun
1248
+ });
1249
+ characterStyles.push({
1250
+ id: "Hyperlink",
1251
+ name: "Hyperlink",
1252
+ basedOn: "DefaultParagraphFont",
1253
+ semiHidden: true,
1254
+ unhideWhenUsed: true,
1255
+ run: {
1256
+ color: "0563C1",
1257
+ underline: { type: "single" }
1258
+ },
1259
+ ...options.hyperlink
1260
+ });
1261
+ characterStyles.push({
1262
+ id: "FootnoteReference",
1263
+ name: "footnote reference",
1264
+ basedOn: "DefaultParagraphFont",
1265
+ semiHidden: true,
1266
+ unhideWhenUsed: true,
1267
+ run: { superScript: true },
1268
+ ...options.footnoteReference
1269
+ });
1270
+ paragraphStyles.push({
1271
+ id: "FootnoteText",
1272
+ name: "footnote text",
1273
+ basedOn: "Normal",
1274
+ link: "FootnoteTextChar",
1275
+ semiHidden: true,
1276
+ uiPriority: 99,
1277
+ unhideWhenUsed: true,
1278
+ paragraph: { spacing: {
1279
+ after: 0,
1280
+ line: 240,
1281
+ lineRule: "auto"
1282
+ } },
1283
+ run: { size: 20 },
1284
+ ...options.footnoteText
1285
+ });
1286
+ characterStyles.push({
1287
+ id: "FootnoteTextChar",
1288
+ name: "Footnote Text Char",
1289
+ basedOn: "DefaultParagraphFont",
1290
+ link: "FootnoteText",
1291
+ semiHidden: true,
1292
+ run: { size: 20 },
1293
+ ...options.footnoteTextChar
1294
+ });
1295
+ characterStyles.push({
1296
+ id: "EndnoteReference",
1297
+ name: "endnote reference",
1298
+ basedOn: "DefaultParagraphFont",
1299
+ semiHidden: true,
1300
+ unhideWhenUsed: true,
1301
+ run: { superScript: true },
1302
+ ...options.endnoteReference
1303
+ });
1304
+ paragraphStyles.push({
1305
+ id: "EndnoteText",
1306
+ name: "endnote text",
1307
+ basedOn: "Normal",
1308
+ link: "EndnoteTextChar",
1309
+ semiHidden: true,
1310
+ uiPriority: 99,
1311
+ unhideWhenUsed: true,
1312
+ paragraph: { spacing: {
1313
+ after: 0,
1314
+ line: 240,
1315
+ lineRule: "auto"
1316
+ } },
1317
+ run: { size: 20 },
1318
+ ...options.endnoteText
1319
+ });
1320
+ characterStyles.push({
1321
+ id: "EndnoteTextChar",
1322
+ name: "Endnote Text Char",
1323
+ basedOn: "DefaultParagraphFont",
1324
+ link: "EndnoteText",
1325
+ semiHidden: true,
1326
+ run: { size: 20 },
1327
+ ...options.endnoteTextChar
1328
+ });
1329
+ characterStyles.push({
1330
+ id: "IntenseReference",
1331
+ name: "Intense Reference",
1332
+ basedOn: "DefaultParagraphFont",
1333
+ uiPriority: 32,
1334
+ quickFormat: true,
1335
+ run: {
1336
+ bold: true,
1337
+ boldComplexScript: true,
1338
+ smallCaps: true,
1339
+ color: {
1340
+ val: "0F4761",
1341
+ themeColor: "accent1",
1342
+ themeShade: "BF"
1343
+ },
1344
+ characterSpacing: 5
1345
+ }
1346
+ });
1347
+ return {
1348
+ importedStyles,
1349
+ paragraphStyles,
1350
+ characterStyles,
1351
+ tableStyles,
1352
+ numberingStyles,
1353
+ initialAttributes
1354
+ };
1355
+ }
1356
+ };
1357
+ //#endregion
1358
+ //#region src/parts/styles/styles.ts
1359
+ /**
1360
+ * Styles module for WordprocessingML documents.
1361
+ *
1362
+ * Pure collector — no XmlComponent inheritance.
1363
+ * Collects child elements as raw XML strings and serializes.
1364
+ *
1365
+ * Reference: http://officeopenxml.com/WPstyles.php
1366
+ *
1367
+ * @module
1368
+ */
1369
+ /**
1370
+ * Extract the `w:styleId` from a raw `<w:style>` XML string, if present.
1371
+ *
1372
+ * Returns `undefined` for non-style elements (docDefaults / latentStyles),
1373
+ * whose raw XML carries no `w:styleId` attribute.
1374
+ */
1375
+ function extractStyleId(raw) {
1376
+ const m = raw.match(/w:styleId="([^"]+)"/);
1377
+ return m ? m[1] : void 0;
1378
+ }
1379
+ /**
1380
+ * Represents the styles definitions in a WordprocessingML document.
1381
+ *
1382
+ * Pure collector — no XmlComponent inheritance.
1383
+ * Collects child elements as raw XML strings and serializes.
1384
+ */
1385
+ var Styles = class {
1386
+ attributes = {};
1387
+ parts = [];
1388
+ constructor(options) {
1389
+ if (options.initialAttributes) this.attributes = options.initialAttributes;
1390
+ const customStyleIds = /* @__PURE__ */ new Set();
1391
+ for (const s of options.paragraphStyles ?? []) customStyleIds.add(s.id);
1392
+ for (const s of options.characterStyles ?? []) customStyleIds.add(s.id);
1393
+ for (const s of options.tableStyles ?? []) customStyleIds.add(s.id);
1394
+ if (options.importedStyles) for (const style of options.importedStyles) {
1395
+ if (!style._raw) continue;
1396
+ if (customStyleIds.size > 0) {
1397
+ const id = extractStyleId(style._raw);
1398
+ if (id && customStyleIds.has(id)) continue;
1399
+ }
1400
+ this.parts.push(style._raw);
1401
+ }
1402
+ if (options.paragraphStyles) for (const style of options.paragraphStyles) this.parts.push(stringifyParagraphStyle(style));
1403
+ if (options.characterStyles) for (const style of options.characterStyles) this.parts.push(stringifyCharacterStyle(style));
1404
+ if (options.tableStyles) for (const style of options.tableStyles) this.parts.push(stringifyTableStyle(style));
1405
+ if (options.numberingStyles) for (const style of options.numberingStyles) this.parts.push(stringifyNumberingStyle(style));
1406
+ }
1407
+ /**
1408
+ * Serialize to word/styles.xml content (with XML declaration).
1409
+ */
1410
+ serialize() {
1411
+ const attrParts = [];
1412
+ for (const [k, v] of Object.entries(this.attributes)) if (v !== void 0 && v !== null) attrParts.push(` ${k}="${v}"`);
1413
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles${attrParts.join("")}>${this.parts.join("")}</w:styles>`;
1414
+ }
1415
+ };
1416
+ /**
1417
+ * Build a cache of style elements keyed by styleId.
1418
+ */
1419
+ function buildStyleCache(stylesEl) {
1420
+ const cache = /* @__PURE__ */ new Map();
1421
+ if (!stylesEl) return cache;
1422
+ for (const child of stylesEl.elements ?? []) {
1423
+ if (child.name !== "w:style") continue;
1424
+ const styleId = attr(child, "w:styleId");
1425
+ if (styleId) cache.set(styleId, child);
1426
+ }
1427
+ return cache;
1428
+ }
1429
+ /**
1430
+ * Build a cache of abstract numbering elements keyed by abstractNumId.
1431
+ */
1432
+ function buildNumberingCache(numberingEl) {
1433
+ const cache = /* @__PURE__ */ new Map();
1434
+ if (!numberingEl) return cache;
1435
+ for (const child of numberingEl.elements ?? []) {
1436
+ if (child.name !== "w:abstractNum") continue;
1437
+ const abstractNumId = attr(child, "w:abstractNumId");
1438
+ if (abstractNumId !== void 0) cache.set(abstractNumId, child);
1439
+ }
1440
+ return cache;
1441
+ }
1442
+ /**
1443
+ * Parse w:styles element into StylesOptions.
1444
+ *
1445
+ * Skips built-in styles that DefaultStylesFactory already generates,
1446
+ * keeping only user-defined custom styles for round-trip fidelity.
1447
+ */
1448
+ function parseStyleDefinitions(el, parseParagraphProperties, ctx) {
1449
+ const opts = {};
1450
+ const paragraphStyles = [];
1451
+ const characterStyles = [];
1452
+ const tableStyles = [];
1453
+ const numberingStyles = [];
1454
+ for (const child of el.elements ?? []) if (child.name === "w:docDefaults") {
1455
+ const defOpts = parseDocDefaults(child, parseParagraphProperties, ctx);
1456
+ if (defOpts) opts.default = defOpts;
1457
+ opts.docDefaultsXml = stringifyElement(child);
1458
+ } else if (child.name === "w:latentStyles") opts.latentStylesXml = stringifyElement(child);
1459
+ else if (child.name === "w:style") {
1460
+ const styleOpts = parseStyleElement(child, parseParagraphProperties, ctx);
1461
+ if (!styleOpts?._type || !styleOpts.id) continue;
1462
+ const type = styleOpts._type;
1463
+ delete styleOpts._type;
1464
+ if (type === "table") tableStyles.push(styleOpts);
1465
+ else if (type === "numbering") numberingStyles.push(styleOpts);
1466
+ else if (type === "paragraph") paragraphStyles.push(styleOpts);
1467
+ else if (type === "character") characterStyles.push(styleOpts);
1468
+ }
1469
+ if (paragraphStyles.length > 0) opts.paragraphStyles = paragraphStyles;
1470
+ if (characterStyles.length > 0) opts.characterStyles = characterStyles;
1471
+ if (tableStyles.length > 0) opts.tableStyles = tableStyles;
1472
+ if (numberingStyles.length > 0) opts.numberingStyles = numberingStyles;
1473
+ opts.roundTripped = true;
1474
+ return Object.keys(opts).length > 0 ? opts : void 0;
1475
+ }
1476
+ function parseDocDefaults(el, parseParagraphProperties, ctx) {
1477
+ const document = {};
1478
+ const rPrDefault = findChild(el, "w:rPrDefault");
1479
+ if (rPrDefault) {
1480
+ const rPr = findChild(rPrDefault, "w:rPr");
1481
+ if (rPr) {
1482
+ const runDefaults = parseRunProperties(rPr);
1483
+ if (Object.keys(runDefaults).length > 0) document.run = runDefaults;
1484
+ }
1485
+ }
1486
+ const pPrDefault = findChild(el, "w:pPrDefault");
1487
+ if (pPrDefault) {
1488
+ const pPr = findChild(pPrDefault, "w:pPr");
1489
+ if (pPr) {
1490
+ const paraDefaults = parseParagraphProperties(pPr, ctx);
1491
+ if (Object.keys(paraDefaults).length > 0) document.paragraph = paraDefaults;
1492
+ }
1493
+ }
1494
+ return Object.keys(document).length > 0 ? { document } : void 0;
1495
+ }
1496
+ function parseStyleElement(el, parseParagraphProperties, ctx) {
1497
+ const opts = {};
1498
+ const type = attr(el, "w:type");
1499
+ if (type) opts._type = type;
1500
+ const id = attr(el, "w:styleId");
1501
+ if (id) opts.id = id;
1502
+ if (attrBool(el, "w:default")) opts.default = true;
1503
+ if (attrBool(el, "w:customStyle")) opts.customStyle = true;
1504
+ const nameEl = findChild(el, "w:name");
1505
+ if (nameEl) {
1506
+ const name = attr(nameEl, "w:val");
1507
+ if (name) opts.name = name;
1508
+ }
1509
+ const basedOn = findChild(el, "w:basedOn");
1510
+ if (basedOn) {
1511
+ const val = attr(basedOn, "w:val");
1512
+ if (val) opts.basedOn = val;
1513
+ }
1514
+ const next = findChild(el, "w:next");
1515
+ if (next) {
1516
+ const val = attr(next, "w:val");
1517
+ if (val) opts.next = val;
1518
+ }
1519
+ const link = findChild(el, "w:link");
1520
+ if (link) {
1521
+ const val = attr(link, "w:val");
1522
+ if (val) opts.link = val;
1523
+ }
1524
+ const uiPriority = findChild(el, "w:uiPriority");
1525
+ if (uiPriority) {
1526
+ const val = attrNum(uiPriority, "w:val");
1527
+ if (val !== void 0) opts.uiPriority = val;
1528
+ }
1529
+ if (findChild(el, "w:qFormat")) opts.quickFormat = true;
1530
+ if (findChild(el, "w:semiHidden")) opts.semiHidden = true;
1531
+ if (findChild(el, "w:unhideWhenUsed")) opts.unhideWhenUsed = true;
1532
+ if (findChild(el, "w:autoRedefine")) opts.autoRedefine = true;
1533
+ if (findChild(el, "w:locked")) opts.locked = true;
1534
+ if (findChild(el, "w:personal")) opts.personal = true;
1535
+ if (findChild(el, "w:personalCompose")) opts.personalCompose = true;
1536
+ if (findChild(el, "w:personalReply")) opts.personalReply = true;
1537
+ if (findChild(el, "w:hidden")) opts.hidden = true;
1538
+ const rsidEl = findChild(el, "w:rsid");
1539
+ if (rsidEl) {
1540
+ const val = attr(rsidEl, "w:val");
1541
+ if (val) opts.rsid = val;
1542
+ }
1543
+ const aliases = findChild(el, "w:aliases");
1544
+ if (aliases) {
1545
+ const val = attr(aliases, "w:val");
1546
+ if (val) opts.aliases = val;
1547
+ }
1548
+ const pPr = findChild(el, "w:pPr");
1549
+ if (pPr) {
1550
+ const paraOpts = parseParagraphProperties(pPr, ctx);
1551
+ if (Object.keys(paraOpts).length > 0) opts.paragraph = paraOpts;
1552
+ }
1553
+ const rPr = findChild(el, "w:rPr");
1554
+ if (rPr) {
1555
+ const runOpts = parseRunProperties(rPr);
1556
+ if (Object.keys(runOpts).length > 0) opts.run = runOpts;
1557
+ }
1558
+ const tblPr = findChild(el, "w:tblPr");
1559
+ if (tblPr) {
1560
+ const tableOpts = parseTablePropertiesEl(tblPr);
1561
+ if (Object.keys(tableOpts).length > 0) opts.table = tableOpts;
1562
+ }
1563
+ const trPr = findChild(el, "w:trPr");
1564
+ if (trPr) {
1565
+ const rowOpts = parseTableRowPropertiesEl(trPr);
1566
+ if (Object.keys(rowOpts).length > 0) opts.row = rowOpts;
1567
+ }
1568
+ const tcPr = findChild(el, "w:tcPr");
1569
+ if (tcPr) {
1570
+ const cellOpts = parseTableCellPropertiesEl(tcPr);
1571
+ if (Object.keys(cellOpts).length > 0) opts.cell = cellOpts;
1572
+ }
1573
+ const conditionalFormats = [];
1574
+ for (const child of el.elements ?? []) {
1575
+ if (child.name !== "w:tblStylePr") continue;
1576
+ const type = attr(child, "w:type");
1577
+ if (!type) continue;
1578
+ const cf = { type };
1579
+ const cfPPr = findChild(child, "w:pPr");
1580
+ if (cfPPr) {
1581
+ const paraOpts = parseParagraphProperties(cfPPr, ctx);
1582
+ if (Object.keys(paraOpts).length > 0) cf.paragraph = paraOpts;
1583
+ }
1584
+ const cfRPr = findChild(child, "w:rPr");
1585
+ if (cfRPr) {
1586
+ const runOpts = parseRunProperties(cfRPr);
1587
+ if (Object.keys(runOpts).length > 0) cf.run = runOpts;
1588
+ }
1589
+ const cfTblPr = findChild(child, "w:tblPr");
1590
+ if (cfTblPr) {
1591
+ const tableOpts = parseTablePropertiesEl(cfTblPr);
1592
+ if (Object.keys(tableOpts).length > 0) cf.table = tableOpts;
1593
+ }
1594
+ const cfTrPr = findChild(child, "w:trPr");
1595
+ if (cfTrPr) {
1596
+ const rowOpts = parseTableRowPropertiesEl(cfTrPr);
1597
+ if (Object.keys(rowOpts).length > 0) cf.row = rowOpts;
1598
+ }
1599
+ const cfTcPr = findChild(child, "w:tcPr");
1600
+ if (cfTcPr) {
1601
+ const cellOpts = parseTableCellPropertiesEl(cfTcPr);
1602
+ if (Object.keys(cellOpts).length > 0) cf.cell = cellOpts;
1603
+ }
1604
+ conditionalFormats.push(cf);
1605
+ }
1606
+ if (conditionalFormats.length > 0) opts.conditionalFormats = conditionalFormats;
1607
+ return opts;
1608
+ }
1609
+ //#endregion
1610
+ //#region src/parts/settings/descriptor.ts
1611
+ /**
1612
+ * Settings descriptor — produces word/settings.xml.
1613
+ *
1614
+ * Stringifies pure JSON SettingsOptions into XML without creating
1615
+ * Settings/Compatibility/DocumentProtection/etc. class instances.
1616
+ * Zero XmlComponent allocation — pure string concatenation.
1617
+ *
1618
+ * @module
1619
+ */
1620
+ /** Derive the namespace-prefixed val attribute from the element tag. */
1621
+ function valAttr(tag) {
1622
+ return `${tag.split(":")[0]}:val`;
1623
+ }
1624
+ function onOff(tag, val) {
1625
+ return val !== void 0 ? `<${tag} ${valAttr(tag)}="${val ? 1 : 0}"/>` : "";
1626
+ }
1627
+ function numVal(tag, val) {
1628
+ return val !== void 0 ? `<${tag} ${valAttr(tag)}="${val}"/>` : "";
1629
+ }
1630
+ function strVal(tag, val) {
1631
+ return val !== void 0 ? `<${tag} ${valAttr(tag)}="${escapeXml(val)}"/>` : "";
1632
+ }
1633
+ /** Build attribute string from key-value pairs, skipping undefined. */
1634
+ function attrStr(attrs) {
1635
+ const parts = [];
1636
+ for (const [k, v] of Object.entries(attrs)) if (v !== void 0) parts.push(`${k}="${escapeXml(String(v))}"`);
1637
+ return parts.join(" ");
1638
+ }
1639
+ /** Self-closing element with attributes only. */
1640
+ function attrEl(tag, attrs) {
1641
+ const a = attrStr(attrs);
1642
+ return a ? `<${tag} ${a}/>` : `<${tag}/>`;
1643
+ }
1644
+ function compatSetting(name, val, uri) {
1645
+ const u = uri ?? "http://schemas.microsoft.com/office/word";
1646
+ return `<w:compatSetting w:name="${escapeXml(name)}" w:uri="${u}" w:val="${val}"/>`;
1647
+ }
1648
+ /** Read a CT_OnOff child as boolean (presence true unless val is explicitly false). */
1649
+ function readOnOff(el) {
1650
+ if (!el || !el.name) return void 0;
1651
+ const v = attr(el, valAttr(el.name));
1652
+ return v !== "false" && v !== "0" && v !== "off";
1653
+ }
1654
+ /** Read an attribute as a number, or undefined if absent/unparseable. */
1655
+ function readNum(el, name) {
1656
+ if (!el) return void 0;
1657
+ const v = attr(el, name);
1658
+ if (v === void 0 || v === "") return void 0;
1659
+ const n = parseInt(v, 10);
1660
+ return Number.isNaN(n) ? void 0 : n;
1661
+ }
1662
+ /** Read an attribute as a string, or undefined if absent. */
1663
+ function readStr(el, name) {
1664
+ if (!el) return void 0;
1665
+ const v = attr(el, name);
1666
+ return v === void 0 || v === "" ? void 0 : v;
1667
+ }
1668
+ /** Read an attribute constrained to an enum; undefined if absent or not allowed. */
1669
+ function readEnum(el, name, allowed) {
1670
+ const v = readStr(el, name);
1671
+ return v !== void 0 && allowed.includes(v) ? v : void 0;
1672
+ }
1673
+ /** Shared password/crypto attributes (AG_TransitionalPassword) → options keys. */
1674
+ const PASSWORD_ATTR_MAP = [
1675
+ [
1676
+ "hashValue",
1677
+ "w:hashValue",
1678
+ false
1679
+ ],
1680
+ [
1681
+ "saltValue",
1682
+ "w:saltValue",
1683
+ false
1684
+ ],
1685
+ [
1686
+ "hash",
1687
+ "w:hash",
1688
+ false
1689
+ ],
1690
+ [
1691
+ "salt",
1692
+ "w:salt",
1693
+ false
1694
+ ],
1695
+ [
1696
+ "spinCount",
1697
+ "w:spinCount",
1698
+ true
1699
+ ],
1700
+ [
1701
+ "algorithmName",
1702
+ "w:algorithmName",
1703
+ false
1704
+ ],
1705
+ [
1706
+ "cryptoAlgorithmClass",
1707
+ "w:cryptAlgorithmClass",
1708
+ false
1709
+ ],
1710
+ [
1711
+ "cryptoAlgorithmSid",
1712
+ "w:cryptAlgorithmSid",
1713
+ true
1714
+ ],
1715
+ [
1716
+ "cryptoAlgorithmType",
1717
+ "w:cryptAlgorithmType",
1718
+ false
1719
+ ],
1720
+ [
1721
+ "cryptoProvider",
1722
+ "w:cryptProvider",
1723
+ false
1724
+ ],
1725
+ [
1726
+ "cryptoProviderType",
1727
+ "w:cryptProviderType",
1728
+ false
1729
+ ],
1730
+ [
1731
+ "cryptoProviderTypeExtension",
1732
+ "w:cryptProviderTypeExt",
1733
+ true
1734
+ ],
1735
+ [
1736
+ "cryptoProviderTypeExtensionSource",
1737
+ "w:cryptProviderTypeExtSource",
1738
+ false
1739
+ ],
1740
+ [
1741
+ "algorithmExtensionId",
1742
+ "w:algIdExt",
1743
+ true
1744
+ ],
1745
+ [
1746
+ "algorithmExtensionSource",
1747
+ "w:algIdExtSource",
1748
+ false
1749
+ ],
1750
+ [
1751
+ "cryptoSpinCount",
1752
+ "w:cryptSpinCount",
1753
+ true
1754
+ ]
1755
+ ];
1756
+ /** Read shared password/crypto attributes into an options object. */
1757
+ function readPasswordAttrs(el) {
1758
+ const out = {};
1759
+ for (const [key, xmlAttr, isNum] of PASSWORD_ATTR_MAP) {
1760
+ const v = attr(el, xmlAttr);
1761
+ if (v === void 0 || v === "") continue;
1762
+ out[key] = isNum ? parseInt(v, 10) : v;
1763
+ }
1764
+ return out;
1765
+ }
1766
+ /**
1767
+ * CT_OnOff compat flag elements → CompatibilityOptions keys. The XML tag often
1768
+ * differs from the option key (e.g. wordPerfectJustification → w:wpJustification).
1769
+ * Order mirrors stringifyCompatibility so round-trip preserves element order.
1770
+ */
1771
+ const COMPAT_FLAG_MAP = [
1772
+ ["useSingleBorderforContiguousCells", "w:useSingleBorderforContiguousCells"],
1773
+ ["wordPerfectJustification", "w:wpJustification"],
1774
+ ["noTabStopForHangingIndent", "w:noTabHangInd"],
1775
+ ["noLeading", "w:noLeading"],
1776
+ ["spaceForUnderline", "w:spaceForUL"],
1777
+ ["noColumnBalance", "w:noColumnBalance"],
1778
+ ["balanceSingleByteDoubleByteWidth", "w:balanceSingleByteDoubleByteWidth"],
1779
+ ["noExtraLineSpacing", "w:noExtraLineSpacing"],
1780
+ ["doNotLeaveBackslashAlone", "w:doNotLeaveBackslashAlone"],
1781
+ ["underlineTrailingSpaces", "w:ulTrailSpace"],
1782
+ ["doNotExpandShiftReturn", "w:doNotExpandShiftReturn"],
1783
+ ["spacingInWholePoints", "w:spacingInWholePoints"],
1784
+ ["lineWrapLikeWord6", "w:lineWrapLikeWord6"],
1785
+ ["printBodyTextBeforeHeader", "w:printBodyTextBeforeHeader"],
1786
+ ["printColorsBlack", "w:printColBlack"],
1787
+ ["spaceWidth", "w:wpSpaceWidth"],
1788
+ ["showBreaksInFrames", "w:showBreaksInFrames"],
1789
+ ["subFontBySize", "w:subFontBySize"],
1790
+ ["suppressBottomSpacing", "w:suppressBottomSpacing"],
1791
+ ["suppressTopSpacing", "w:suppressTopSpacing"],
1792
+ ["suppressSpacingAtTopOfPage", "w:suppressSpacingAtTopOfPage"],
1793
+ ["suppressTopSpacingWP", "w:suppressTopSpacingWP"],
1794
+ ["suppressSpBfAfterPgBrk", "w:suppressSpBfAfterPgBrk"],
1795
+ ["swapBordersFacingPages", "w:swapBordersFacingPages"],
1796
+ ["convertMailMergeEsc", "w:convMailMergeEsc"],
1797
+ ["truncateFontHeightsLikeWP6", "w:truncateFontHeightsLikeWP6"],
1798
+ ["macWordSmallCaps", "w:mwSmallCaps"],
1799
+ ["usePrinterMetrics", "w:usePrinterMetrics"],
1800
+ ["doNotSuppressParagraphBorders", "w:doNotSuppressParagraphBorders"],
1801
+ ["wrapTrailSpaces", "w:wrapTrailSpaces"],
1802
+ ["footnoteLayoutLikeWW8", "w:footnoteLayoutLikeWW8"],
1803
+ ["shapeLayoutLikeWW8", "w:shapeLayoutLikeWW8"],
1804
+ ["alignTablesRowByRow", "w:alignTablesRowByRow"],
1805
+ ["forgetLastTabAlignment", "w:forgetLastTabAlignment"],
1806
+ ["adjustLineHeightInTable", "w:adjustLineHeightInTable"],
1807
+ ["autoSpaceLikeWord95", "w:autoSpaceLikeWord95"],
1808
+ ["noSpaceRaiseLower", "w:noSpaceRaiseLower"],
1809
+ ["doNotUseHTMLParagraphAutoSpacing", "w:doNotUseHTMLParagraphAutoSpacing"],
1810
+ ["layoutRawTableWidth", "w:layoutRawTableWidth"],
1811
+ ["layoutTableRowsApart", "w:layoutTableRowsApart"],
1812
+ ["useWord97LineBreakRules", "w:useWord97LineBreakRules"],
1813
+ ["doNotBreakWrappedTables", "w:doNotBreakWrappedTables"],
1814
+ ["doNotSnapToGridInCell", "w:doNotSnapToGridInCell"],
1815
+ ["selectFieldWithFirstOrLastCharacter", "w:selectFldWithFirstOrLastChar"],
1816
+ ["applyBreakingRules", "w:applyBreakingRules"],
1817
+ ["doNotWrapTextWithPunctuation", "w:doNotWrapTextWithPunct"],
1818
+ ["doNotUseEastAsianBreakRules", "w:doNotUseEastAsianBreakRules"],
1819
+ ["useWord2002TableStyleRules", "w:useWord2002TableStyleRules"],
1820
+ ["growAutofit", "w:growAutofit"],
1821
+ ["useFELayout", "w:useFELayout"],
1822
+ ["useNormalStyleForList", "w:useNormalStyleForList"],
1823
+ ["doNotUseIndentAsNumberingTabStop", "w:doNotUseIndentAsNumberingTabStop"],
1824
+ ["useAlternateEastAsianLineBreakRules", "w:useAltKinsokuLineBreakRules"],
1825
+ ["allowSpaceOfSameStyleInTable", "w:allowSpaceOfSameStyleInTable"],
1826
+ ["doNotSuppressIndentation", "w:doNotSuppressIndentation"],
1827
+ ["doNotAutofitConstrainedTables", "w:doNotAutofitConstrainedTables"],
1828
+ ["autofitToFirstFixedWidthCell", "w:autofitToFirstFixedWidthCell"],
1829
+ ["underlineTabInNumberingList", "w:underlineTabInNumList"],
1830
+ ["displayHangulFixedWidth", "w:displayHangulFixedWidth"],
1831
+ ["splitPgBreakAndParaMark", "w:splitPgBreakAndParaMark"],
1832
+ ["doNotVerticallyAlignCellWithSp", "w:doNotVertAlignCellWithSp"],
1833
+ ["doNotBreakConstrainedForcedTable", "w:doNotBreakConstrainedForcedTable"],
1834
+ ["ignoreVerticalAlignmentInTextboxes", "w:doNotVertAlignInTxbx"],
1835
+ ["useAnsiKerningPairs", "w:useAnsiKerningPairs"],
1836
+ ["cachedColumnBalance", "w:cachedColBalance"]
1837
+ ];
1838
+ /** compatSetting names that map to dedicated sugar fields (not into compatSettings[]). */
1839
+ const COMPAT_SETTING_SUGAR = {
1840
+ compatibilityMode: "version",
1841
+ overrideTableStyleFontSizeAndJustification: "overrideTableStyleFontSizeAndJustification",
1842
+ enableOpenTypeFeatures: "enableOpenTypeFeatures",
1843
+ doNotFlipMirrorIndents: "doNotFlipMirrorIndents"
1844
+ };
1845
+ /** Parse w:footnotePr / w:endnotePr (CT_FtnDocProps / CT_EdnDocProps). */
1846
+ function parseFtnEdnPr(el) {
1847
+ const o = {};
1848
+ const pos = readStr(findChild(el, "w:pos"), "w:val");
1849
+ if (pos) o.pos = pos;
1850
+ const numFmtEl = findChild(el, "w:numFmt");
1851
+ if (numFmtEl) {
1852
+ const v = readStr(numFmtEl, "w:val");
1853
+ if (v) o.numFmt = v;
1854
+ const format = readStr(numFmtEl, "w:format");
1855
+ if (format) o.format = format;
1856
+ }
1857
+ const numStart = readNum(findChild(el, "w:numStart"), "w:val");
1858
+ if (numStart !== void 0) o.numStart = numStart;
1859
+ const numRestart = readStr(findChild(el, "w:numRestart"), "w:val");
1860
+ if (numRestart) o.numRestart = numRestart;
1861
+ return Object.keys(o).length > 0 ? o : void 0;
1862
+ }
1863
+ /** Parse w:compat (CT_Compat): on/off flag elements + w:compatSetting entries. */
1864
+ function parseCompatibility(el) {
1865
+ const o = {};
1866
+ const flagMap = Object.fromEntries(COMPAT_FLAG_MAP.map(([key, tag]) => [tag, key]));
1867
+ const extras = [];
1868
+ for (const child of el.elements ?? []) {
1869
+ if (child.type !== "element" || !child.name) continue;
1870
+ const key = flagMap[child.name];
1871
+ if (key !== void 0) {
1872
+ o[key] = true;
1873
+ continue;
1874
+ }
1875
+ if (child.name === "w:compatSetting") {
1876
+ const name = attr(child, "w:name");
1877
+ const val = attr(child, "w:val");
1878
+ if (name === void 0 || val === void 0) continue;
1879
+ const sugar = COMPAT_SETTING_SUGAR[name];
1880
+ if (sugar === "version") {
1881
+ const n = parseInt(val, 10);
1882
+ if (!Number.isNaN(n)) o.version = n;
1883
+ } else if (sugar !== void 0) o[sugar] = val !== "0" && val !== "false";
1884
+ else extras.push({
1885
+ name,
1886
+ val,
1887
+ uri: attr(child, "w:uri")
1888
+ });
1889
+ }
1890
+ }
1891
+ if (extras.length > 0) o.compatSettings = extras;
1892
+ return Object.keys(o).length > 0 ? o : void 0;
1893
+ }
1894
+ /** Parse m:mathPr (CT_MathPr). */
1895
+ function parseMathPr(el) {
1896
+ const o = {};
1897
+ const mathFont = readStr(findChild(el, "m:mathFont"), "m:val");
1898
+ if (mathFont) o.mathFont = mathFont;
1899
+ const binaryOperatorBreak = readEnum(findChild(el, "m:brkBin"), "m:val", [
1900
+ "before",
1901
+ "after",
1902
+ "repeat"
1903
+ ]);
1904
+ if (binaryOperatorBreak) o.binaryOperatorBreak = binaryOperatorBreak;
1905
+ const binaryOperatorBreakSubtraction = readEnum(findChild(el, "m:brkBinSub"), "m:val", [
1906
+ "--",
1907
+ "-+",
1908
+ "+-"
1909
+ ]);
1910
+ if (binaryOperatorBreakSubtraction) o.binaryOperatorBreakSubtraction = binaryOperatorBreakSubtraction;
1911
+ const smallFractions = readOnOff(findChild(el, "m:smallFrac"));
1912
+ if (smallFractions !== void 0) o.smallFractions = smallFractions;
1913
+ const displayDefaults = readOnOff(findChild(el, "m:dispDef"));
1914
+ if (displayDefaults !== void 0) o.displayDefaults = displayDefaults;
1915
+ const leftMargin = readNum(findChild(el, "m:lMargin"), "m:val");
1916
+ if (leftMargin !== void 0) o.leftMargin = leftMargin;
1917
+ const rightMargin = readNum(findChild(el, "m:rMargin"), "m:val");
1918
+ if (rightMargin !== void 0) o.rightMargin = rightMargin;
1919
+ const defaultJustification = readEnum(findChild(el, "m:defJc"), "m:val", [
1920
+ "left",
1921
+ "right",
1922
+ "center",
1923
+ "centerGroup"
1924
+ ]);
1925
+ if (defaultJustification) o.defaultJustification = defaultJustification;
1926
+ const preSpacing = readNum(findChild(el, "m:preSp"), "m:val");
1927
+ if (preSpacing !== void 0) o.preSpacing = preSpacing;
1928
+ const postSpacing = readNum(findChild(el, "m:postSp"), "m:val");
1929
+ if (postSpacing !== void 0) o.postSpacing = postSpacing;
1930
+ const interSpacing = readNum(findChild(el, "m:interSp"), "m:val");
1931
+ if (interSpacing !== void 0) o.interSpacing = interSpacing;
1932
+ const intraSpacing = readNum(findChild(el, "m:intraSp"), "m:val");
1933
+ if (intraSpacing !== void 0) o.intraSpacing = intraSpacing;
1934
+ const wrapIndent = readNum(findChild(el, "m:wrapIndent"), "m:val");
1935
+ if (wrapIndent !== void 0) o.wrapIndent = wrapIndent;
1936
+ const wrapRight = readOnOff(findChild(el, "m:wrapRight"));
1937
+ if (wrapRight !== void 0) o.wrapRight = wrapRight;
1938
+ const integralLimitLocation = readEnum(findChild(el, "m:intLim"), "m:val", ["subSup", "undOvr"]);
1939
+ if (integralLimitLocation) o.integralLimitLocation = integralLimitLocation;
1940
+ const naryLimitLocation = readEnum(findChild(el, "m:naryLim"), "m:val", ["subSup", "undOvr"]);
1941
+ if (naryLimitLocation) o.naryLimitLocation = naryLimitLocation;
1942
+ return Object.keys(o).length > 0 ? o : void 0;
1943
+ }
1944
+ /** Parse w:captions (CT_Captions). */
1945
+ function parseCaptions(el) {
1946
+ const captions = [];
1947
+ const autoCaptions = [];
1948
+ for (const child of el.elements ?? []) {
1949
+ if (child.type !== "element") continue;
1950
+ if (child.name === "w:caption") {
1951
+ const c = { name: attr(child, "w:name") ?? "" };
1952
+ const pos = attr(child, "w:pos");
1953
+ if (pos) c.pos = pos;
1954
+ const chapNum = attr(child, "w:chapNum");
1955
+ if (chapNum !== void 0) c.chapNum = chapNum === "1";
1956
+ const heading = attr(child, "w:heading");
1957
+ if (heading !== void 0) c.heading = parseInt(heading, 10);
1958
+ const noLabel = attr(child, "w:noLabel");
1959
+ if (noLabel !== void 0) c.noLabel = noLabel === "1";
1960
+ const numFmt = attr(child, "w:numFmt");
1961
+ if (numFmt) c.numFmt = numFmt;
1962
+ const sep = attr(child, "w:sep");
1963
+ if (sep) c.sep = sep;
1964
+ captions.push(c);
1965
+ } else if (child.name === "w:autoCaptions") for (const ac of child.elements ?? []) {
1966
+ if (ac.name !== "w:autoCaption") continue;
1967
+ const name = attr(ac, "w:name");
1968
+ const caption = attr(ac, "w:caption");
1969
+ if (name && caption) autoCaptions.push({
1970
+ name,
1971
+ caption
1972
+ });
1973
+ }
1974
+ }
1975
+ if (captions.length === 0) return void 0;
1976
+ const o = { captions };
1977
+ if (autoCaptions.length > 0) o.autoCaptions = autoCaptions;
1978
+ return o;
1979
+ }
1980
+ /** Parse w:odso (CT_Odso). */
1981
+ function parseOdso(el) {
1982
+ const o = {};
1983
+ const udl = readStr(findChild(el, "w:udl"), "w:val");
1984
+ if (udl) o.udl = udl;
1985
+ const table = readStr(findChild(el, "w:table"), "w:val");
1986
+ if (table) o.table = table;
1987
+ const srcEl = findChild(el, "w:src");
1988
+ if (srcEl) {
1989
+ const rid = attr(srcEl, "r:id");
1990
+ if (rid) o.src = rid;
1991
+ }
1992
+ const colDelim = readNum(findChild(el, "w:colDelim"), "w:val");
1993
+ if (colDelim !== void 0) o.colDelim = colDelim;
1994
+ const type = readStr(findChild(el, "w:type"), "w:val");
1995
+ if (type) o.type = type;
1996
+ const fHdr = readOnOff(findChild(el, "w:fHdr"));
1997
+ if (fHdr !== void 0) o.fHdr = fHdr;
1998
+ const fieldMapData = [];
1999
+ for (const child of el.elements ?? []) {
2000
+ if (child.name !== "w:fieldMapData") continue;
2001
+ const fm = {};
2002
+ const t = readStr(findChild(child, "w:type"), "w:val");
2003
+ if (t) fm.type = t;
2004
+ const n = readStr(findChild(child, "w:name"), "w:val");
2005
+ if (n) fm.name = n;
2006
+ const mn = readStr(findChild(child, "w:mappedName"), "w:val");
2007
+ if (mn) fm.mappedName = mn;
2008
+ const col = readNum(findChild(child, "w:column"), "w:val");
2009
+ if (col !== void 0) fm.column = col;
2010
+ const lid = readStr(findChild(child, "w:lid"), "w:val");
2011
+ if (lid) fm.lid = lid;
2012
+ const dyn = readOnOff(findChild(child, "w:dynamicAddress"));
2013
+ if (dyn !== void 0) fm.dynamicAddress = dyn;
2014
+ if (Object.keys(fm).length > 0) fieldMapData.push(fm);
2015
+ }
2016
+ if (fieldMapData.length > 0) o.fieldMapData = fieldMapData;
2017
+ const recipientData = [];
2018
+ for (const child of el.elements ?? []) {
2019
+ if (child.name !== "w:recipientData") continue;
2020
+ const rid = attr(child, "r:id");
2021
+ if (rid) recipientData.push(rid);
2022
+ }
2023
+ if (recipientData.length > 0) o.recipientData = recipientData;
2024
+ const uniqueTag = readStr(findChild(el, "w:uniqueTag"), "w:val");
2025
+ if (uniqueTag) o.uniqueTag = uniqueTag;
2026
+ return Object.keys(o).length > 0 ? o : void 0;
2027
+ }
2028
+ /** Parse w:mailMerge (CT_MailMerge). */
2029
+ function parseMailMerge(el) {
2030
+ const o = {};
2031
+ const mdt = readStr(findChild(el, "w:mainDocumentType"), "w:val");
2032
+ if (mdt) o.mainDocumentType = mdt;
2033
+ const dataType = readStr(findChild(el, "w:dataType"), "w:val");
2034
+ if (dataType) o.dataType = dataType;
2035
+ const dest = readStr(findChild(el, "w:destination"), "w:val");
2036
+ if (dest) o.destination = dest;
2037
+ const connectString = readStr(findChild(el, "w:connectString"), "w:val");
2038
+ if (connectString) o.connectString = connectString;
2039
+ const query = readStr(findChild(el, "w:query"), "w:val");
2040
+ if (query) o.query = query;
2041
+ const dsEl = findChild(el, "w:dataSource");
2042
+ if (dsEl) {
2043
+ const rid = attr(dsEl, "r:id");
2044
+ if (rid) o.dataSource = rid;
2045
+ }
2046
+ const hsEl = findChild(el, "w:headerSource");
2047
+ if (hsEl) {
2048
+ const rid = attr(hsEl, "r:id");
2049
+ if (rid) o.headerSource = rid;
2050
+ }
2051
+ const linkToQuery = readOnOff(findChild(el, "w:linkToQuery"));
2052
+ if (linkToQuery !== void 0) o.linkToQuery = linkToQuery;
2053
+ const doNotSuppress = readOnOff(findChild(el, "w:doNotSuppressBlankLines"));
2054
+ if (doNotSuppress !== void 0) o.doNotSuppressBlankLines = doNotSuppress;
2055
+ const addressFieldName = readStr(findChild(el, "w:addressFieldName"), "w:val");
2056
+ if (addressFieldName) o.addressFieldName = addressFieldName;
2057
+ const mailSubject = readStr(findChild(el, "w:mailSubject"), "w:val");
2058
+ if (mailSubject) o.mailSubject = mailSubject;
2059
+ const mailAsAttachment = readOnOff(findChild(el, "w:mailAsAttachment"));
2060
+ if (mailAsAttachment !== void 0) o.mailAsAttachment = mailAsAttachment;
2061
+ const viewMergedData = readOnOff(findChild(el, "w:viewMergedData"));
2062
+ if (viewMergedData !== void 0) o.viewMergedData = viewMergedData;
2063
+ const activeRecord = readNum(findChild(el, "w:activeRecord"), "w:val");
2064
+ if (activeRecord !== void 0) o.activeRecord = activeRecord;
2065
+ const checkErrors = readNum(findChild(el, "w:checkErrors"), "w:val");
2066
+ if (checkErrors !== void 0) o.checkErrors = checkErrors;
2067
+ const active = readOnOff(findChild(el, "w:active"));
2068
+ if (active !== void 0) o.active = active;
2069
+ const recipientsEl = findChild(el, "w:recipients");
2070
+ if (recipientsEl) {
2071
+ const rid = attr(recipientsEl, "r:id");
2072
+ if (rid) o.recipients = rid;
2073
+ }
2074
+ const odsoEl = findChild(el, "w:odso");
2075
+ if (odsoEl) {
2076
+ const odso = parseOdso(odsoEl);
2077
+ if (odso) o.odso = odso;
2078
+ }
2079
+ if (Object.keys(o).length === 0) return void 0;
2080
+ return o;
2081
+ }
2082
+ function maybeDerive(password, hashValue) {
2083
+ return password !== void 0 && hashValue === void 0 ? derivePasswordHash(password) : void 0;
2084
+ }
2085
+ /** Valid w:documentProtection/@w:edit values (ST_DocProtect). */
2086
+ const DOC_PROTECT_EDITS = [
2087
+ "none",
2088
+ "readOnly",
2089
+ "comments",
2090
+ "trackedChanges",
2091
+ "forms"
2092
+ ];
2093
+ function stringifyDocProtect(opts) {
2094
+ const derived = maybeDerive(opts.password, opts.hashValue);
2095
+ const attrs = { "w:enforcement": "1" };
2096
+ if (opts.edit !== void 0) attrs["w:edit"] = opts.edit;
2097
+ if (opts.formatting !== void 0) attrs["w:formatting"] = opts.formatting ? "1" : "0";
2098
+ if (opts.algorithmName ?? derived?.algorithmName) attrs["w:algorithmName"] = opts.algorithmName ?? derived.algorithmName;
2099
+ if (opts.hashValue ?? derived?.hashValue) attrs["w:hashValue"] = opts.hashValue ?? derived.hashValue;
2100
+ if (opts.saltValue ?? derived?.saltValue) attrs["w:saltValue"] = opts.saltValue ?? derived.saltValue;
2101
+ if (opts.hash !== void 0) attrs["w:hash"] = opts.hash;
2102
+ if (opts.salt !== void 0) attrs["w:salt"] = opts.salt;
2103
+ if (opts.spinCount ?? derived?.spinCount) attrs["w:spinCount"] = opts.spinCount ?? derived.spinCount;
2104
+ if (opts.cryptoAlgorithmClass !== void 0) attrs["w:cryptAlgorithmClass"] = opts.cryptoAlgorithmClass;
2105
+ if (opts.cryptoAlgorithmSid !== void 0) attrs["w:cryptAlgorithmSid"] = opts.cryptoAlgorithmSid;
2106
+ if (opts.cryptoAlgorithmType !== void 0) attrs["w:cryptAlgorithmType"] = opts.cryptoAlgorithmType;
2107
+ if (opts.cryptoProvider !== void 0) attrs["w:cryptProvider"] = opts.cryptoProvider;
2108
+ if (opts.cryptoProviderType !== void 0) attrs["w:cryptProviderType"] = opts.cryptoProviderType;
2109
+ if (opts.cryptoProviderTypeExtension !== void 0) attrs["w:cryptProviderTypeExt"] = opts.cryptoProviderTypeExtension;
2110
+ if (opts.cryptoProviderTypeExtensionSource !== void 0) attrs["w:cryptProviderTypeExtSource"] = opts.cryptoProviderTypeExtensionSource;
2111
+ if (opts.algorithmExtensionId !== void 0) attrs["w:algIdExt"] = opts.algorithmExtensionId;
2112
+ if (opts.algorithmExtensionSource !== void 0) attrs["w:algIdExtSource"] = opts.algorithmExtensionSource;
2113
+ if (opts.cryptoSpinCount !== void 0) attrs["w:cryptSpinCount"] = opts.cryptoSpinCount;
2114
+ return attrEl("w:documentProtection", attrs);
2115
+ }
2116
+ function stringifyWriteProtect(opts) {
2117
+ const derived = maybeDerive(opts.password, opts.hashValue);
2118
+ const attrs = {};
2119
+ if (opts.recommended !== void 0) attrs["w:recommended"] = opts.recommended ? "1" : "0";
2120
+ if (opts.hashValue ?? derived?.hashValue) attrs["w:hashValue"] = opts.hashValue ?? derived.hashValue;
2121
+ if (opts.saltValue ?? derived?.saltValue) attrs["w:saltValue"] = opts.saltValue ?? derived.saltValue;
2122
+ if (opts.hash !== void 0) attrs["w:hash"] = opts.hash;
2123
+ if (opts.salt !== void 0) attrs["w:salt"] = opts.salt;
2124
+ if (opts.spinCount ?? derived?.spinCount) attrs["w:spinCount"] = opts.spinCount ?? derived.spinCount;
2125
+ if (opts.algorithmName ?? derived?.algorithmName) attrs["w:algorithmName"] = opts.algorithmName ?? derived.algorithmName;
2126
+ if (opts.cryptoAlgorithmClass !== void 0) attrs["w:cryptAlgorithmClass"] = opts.cryptoAlgorithmClass;
2127
+ if (opts.cryptoAlgorithmSid !== void 0) attrs["w:cryptAlgorithmSid"] = opts.cryptoAlgorithmSid;
2128
+ if (opts.cryptoAlgorithmType !== void 0) attrs["w:cryptAlgorithmType"] = opts.cryptoAlgorithmType;
2129
+ if (opts.cryptoProvider !== void 0) attrs["w:cryptProvider"] = opts.cryptoProvider;
2130
+ if (opts.cryptoProviderType !== void 0) attrs["w:cryptProviderType"] = opts.cryptoProviderType;
2131
+ if (opts.algorithmExtensionId !== void 0) attrs["w:algIdExt"] = opts.algorithmExtensionId;
2132
+ if (opts.algorithmExtensionSource !== void 0) attrs["w:algIdExtSource"] = opts.algorithmExtensionSource;
2133
+ if (opts.cryptoProviderTypeExtension !== void 0) attrs["w:cryptProviderTypeExt"] = opts.cryptoProviderTypeExtension;
2134
+ if (opts.cryptoProviderTypeExtensionSource !== void 0) attrs["w:cryptProviderTypeExtSource"] = opts.cryptoProviderTypeExtensionSource;
2135
+ if (opts.cryptoSpinCount !== void 0) attrs["w:cryptSpinCount"] = opts.cryptoSpinCount;
2136
+ return attrEl("w:writeProtection", attrs);
2137
+ }
2138
+ function stringifyRevisionView(opts) {
2139
+ const attrs = {};
2140
+ if (opts.markup !== void 0) attrs["w:markup"] = opts.markup ? "true" : "false";
2141
+ if (opts.comments !== void 0) attrs["w:comments"] = opts.comments ? "true" : "false";
2142
+ if (opts.insDel !== void 0) attrs["w:insDel"] = opts.insDel ? "true" : "false";
2143
+ if (opts.formatting !== void 0) attrs["w:formatting"] = opts.formatting ? "true" : "false";
2144
+ if (opts.inkAnnotations !== void 0) attrs["w:inkAnnotations"] = opts.inkAnnotations ? "true" : "false";
2145
+ return attrEl("w:revisionView", attrs);
2146
+ }
2147
+ function stringifyMailMerge(opts) {
2148
+ const p = [];
2149
+ p.push(strVal("w:mainDocumentType", opts.mainDocumentType));
2150
+ p.push(onOff("w:linkToQuery", opts.linkToQuery));
2151
+ p.push(strVal("w:dataType", opts.dataType));
2152
+ p.push(strVal("w:connectString", opts.connectString));
2153
+ p.push(strVal("w:query", opts.query));
2154
+ if (opts.dataSource !== void 0) p.push(attrEl("w:dataSource", { "r:id": opts.dataSource }));
2155
+ if (opts.headerSource !== void 0) p.push(attrEl("w:headerSource", { "r:id": opts.headerSource }));
2156
+ p.push(onOff("w:doNotSuppressBlankLines", opts.doNotSuppressBlankLines));
2157
+ p.push(strVal("w:destination", opts.destination));
2158
+ p.push(strVal("w:addressFieldName", opts.addressFieldName));
2159
+ p.push(strVal("w:mailSubject", opts.mailSubject));
2160
+ p.push(onOff("w:mailAsAttachment", opts.mailAsAttachment));
2161
+ p.push(onOff("w:viewMergedData", opts.viewMergedData));
2162
+ p.push(numVal("w:activeRecord", opts.activeRecord));
2163
+ p.push(numVal("w:checkErrors", opts.checkErrors));
2164
+ if (opts.odso !== void 0) p.push(stringifyOdso(opts.odso));
2165
+ p.push(onOff("w:active", opts.active));
2166
+ if (opts.recipients !== void 0) p.push(attrEl("w:recipients", { "r:id": opts.recipients }));
2167
+ return `<w:mailMerge>${p.join("")}</w:mailMerge>`;
2168
+ }
2169
+ function stringifyOdso(opts) {
2170
+ const p = [];
2171
+ p.push(strVal("w:udl", opts.udl));
2172
+ p.push(strVal("w:table", opts.table));
2173
+ if (opts.src !== void 0) p.push(attrEl("w:src", { "r:id": opts.src }));
2174
+ p.push(numVal("w:colDelim", opts.colDelim));
2175
+ p.push(strVal("w:type", opts.type));
2176
+ p.push(onOff("w:fHdr", opts.fHdr));
2177
+ if (opts.fieldMapData !== void 0) for (const fm of opts.fieldMapData) p.push(stringifyOdsoFieldMap(fm));
2178
+ if (opts.recipientData !== void 0) for (const rd of opts.recipientData) p.push(attrEl("w:recipientData", { "r:id": rd }));
2179
+ p.push(strVal("w:uniqueTag", opts.uniqueTag));
2180
+ return `<w:odso>${p.join("")}</w:odso>`;
2181
+ }
2182
+ function stringifyOdsoFieldMap(opts) {
2183
+ const p = [];
2184
+ p.push(strVal("w:type", opts.type));
2185
+ p.push(strVal("w:name", opts.name));
2186
+ p.push(strVal("w:mappedName", opts.mappedName));
2187
+ p.push(numVal("w:column", opts.column));
2188
+ p.push(strVal("w:lid", opts.lid));
2189
+ p.push(onOff("w:dynamicAddress", opts.dynamicAddress));
2190
+ return `<w:fieldMapData>${p.join("")}</w:fieldMapData>`;
2191
+ }
2192
+ function stringifyFootnotePr(opts) {
2193
+ const p = [];
2194
+ if (opts.pos !== void 0) p.push(attrEl("w:pos", { "w:val": opts.pos }));
2195
+ if (opts.numFmt !== void 0 || opts.format !== void 0) {
2196
+ const a = {};
2197
+ if (opts.numFmt !== void 0) a["w:val"] = opts.numFmt;
2198
+ if (opts.format !== void 0) a["w:format"] = opts.format;
2199
+ p.push(attrEl("w:numFmt", a));
2200
+ }
2201
+ p.push(numVal("w:numStart", opts.numStart));
2202
+ p.push(strVal("w:numRestart", opts.numRestart));
2203
+ return `<w:footnotePr>${p.join("")}</w:footnotePr>`;
2204
+ }
2205
+ function stringifyEndnotePr(opts) {
2206
+ const p = [];
2207
+ if (opts.pos !== void 0) p.push(attrEl("w:pos", { "w:val": opts.pos }));
2208
+ if (opts.numFmt !== void 0 || opts.format !== void 0) {
2209
+ const a = {};
2210
+ if (opts.numFmt !== void 0) a["w:val"] = opts.numFmt;
2211
+ if (opts.format !== void 0) a["w:format"] = opts.format;
2212
+ p.push(attrEl("w:numFmt", a));
2213
+ }
2214
+ p.push(numVal("w:numStart", opts.numStart));
2215
+ p.push(strVal("w:numRestart", opts.numRestart));
2216
+ return `<w:endnotePr>${p.join("")}</w:endnotePr>`;
2217
+ }
2218
+ function stringifyRsids(opts) {
2219
+ const p = [];
2220
+ if (opts.rsidRoot !== void 0) p.push(attrEl("w:rsidRoot", { "w:val": opts.rsidRoot }));
2221
+ if (opts.rsids !== void 0) for (const rsid of opts.rsids) p.push(attrEl("w:rsid", { "w:val": rsid }));
2222
+ return `<w:rsids>${p.join("")}</w:rsids>`;
2223
+ }
2224
+ function stringifyReadModeInkLockDown(opts) {
2225
+ return attrEl("w:readModeInkLockDown", {
2226
+ "w:actualPg": opts.actualPg === false ? "0" : "1",
2227
+ "w:w": opts.w,
2228
+ "w:h": opts.h,
2229
+ "w:fontSz": opts.fontSz
2230
+ });
2231
+ }
2232
+ function stringifyCaptions(opts) {
2233
+ const p = [];
2234
+ for (const cap of opts.captions) {
2235
+ const attrs = { "w:name": cap.name };
2236
+ if (cap.pos !== void 0) attrs["w:pos"] = cap.pos;
2237
+ if (cap.chapNum !== void 0) attrs["w:chapNum"] = cap.chapNum ? "1" : "0";
2238
+ if (cap.heading !== void 0) attrs["w:heading"] = cap.heading;
2239
+ if (cap.noLabel !== void 0) attrs["w:noLabel"] = cap.noLabel ? "1" : "0";
2240
+ if (cap.numFmt !== void 0) attrs["w:numFmt"] = cap.numFmt;
2241
+ if (cap.sep !== void 0) attrs["w:sep"] = cap.sep;
2242
+ p.push(attrEl("w:caption", attrs));
2243
+ }
2244
+ if (opts.autoCaptions?.length) {
2245
+ const acXml = opts.autoCaptions.map((ac) => attrEl("w:autoCaption", {
2246
+ "w:name": ac.name,
2247
+ "w:caption": ac.caption
2248
+ })).join("");
2249
+ p.push(`<w:autoCaptions>${acXml}</w:autoCaptions>`);
2250
+ }
2251
+ return `<w:captions>${p.join("")}</w:captions>`;
2252
+ }
2253
+ function stringifyMathPr(opts) {
2254
+ const p = [];
2255
+ if (opts.mathFont !== void 0) p.push(attrEl("m:mathFont", { "m:val": opts.mathFont }));
2256
+ if (opts.binaryOperatorBreak !== void 0) p.push(attrEl("m:brkBin", { "m:val": opts.binaryOperatorBreak }));
2257
+ if (opts.binaryOperatorBreakSubtraction !== void 0) p.push(attrEl("m:brkBinSub", { "m:val": opts.binaryOperatorBreakSubtraction }));
2258
+ p.push(onOff("m:smallFrac", opts.smallFractions));
2259
+ p.push(onOff("m:dispDef", opts.displayDefaults));
2260
+ p.push(numVal("m:lMargin", opts.leftMargin));
2261
+ p.push(numVal("m:rMargin", opts.rightMargin));
2262
+ if (opts.defaultJustification !== void 0) p.push(attrEl("m:defJc", { "m:val": opts.defaultJustification }));
2263
+ p.push(numVal("m:preSp", opts.preSpacing));
2264
+ p.push(numVal("m:postSp", opts.postSpacing));
2265
+ p.push(numVal("m:interSp", opts.interSpacing));
2266
+ p.push(numVal("m:intraSp", opts.intraSpacing));
2267
+ p.push(numVal("m:wrapIndent", opts.wrapIndent));
2268
+ p.push(onOff("m:wrapRight", opts.wrapRight));
2269
+ if (opts.integralLimitLocation !== void 0) p.push(attrEl("m:intLim", { "m:val": opts.integralLimitLocation }));
2270
+ if (opts.naryLimitLocation !== void 0) p.push(attrEl("m:naryLim", { "m:val": opts.naryLimitLocation }));
2271
+ return `<m:mathPr>${p.join("")}</m:mathPr>`;
2272
+ }
2273
+ function stringifyColorSchemeMapping(opts) {
2274
+ const attrs = {};
2275
+ if (opts.bg1 !== void 0) attrs["w:bg1"] = opts.bg1;
2276
+ if (opts.t1 !== void 0) attrs["w:t1"] = opts.t1;
2277
+ if (opts.bg2 !== void 0) attrs["w:bg2"] = opts.bg2;
2278
+ if (opts.t2 !== void 0) attrs["w:t2"] = opts.t2;
2279
+ if (opts.accent1 !== void 0) attrs["w:accent1"] = opts.accent1;
2280
+ if (opts.accent2 !== void 0) attrs["w:accent2"] = opts.accent2;
2281
+ if (opts.accent3 !== void 0) attrs["w:accent3"] = opts.accent3;
2282
+ if (opts.accent4 !== void 0) attrs["w:accent4"] = opts.accent4;
2283
+ if (opts.accent5 !== void 0) attrs["w:accent5"] = opts.accent5;
2284
+ if (opts.accent6 !== void 0) attrs["w:accent6"] = opts.accent6;
2285
+ if (opts.hyperlink !== void 0) attrs["w:hyperlink"] = opts.hyperlink;
2286
+ if (opts.followedHyperlink !== void 0) attrs["w:followedHyperlink"] = opts.followedHyperlink;
2287
+ return attrEl("w:clrSchemeMapping", attrs);
2288
+ }
2289
+ function stringifyCompatibility(opts) {
2290
+ const p = [];
2291
+ if (opts.useSingleBorderforContiguousCells) p.push(onOff("w:useSingleBorderforContiguousCells", true));
2292
+ if (opts.wordPerfectJustification) p.push(onOff("w:wpJustification", true));
2293
+ if (opts.noTabStopForHangingIndent) p.push(onOff("w:noTabHangInd", true));
2294
+ if (opts.noLeading) p.push(onOff("w:noLeading", true));
2295
+ if (opts.spaceForUnderline) p.push(onOff("w:spaceForUL", true));
2296
+ if (opts.noColumnBalance) p.push(onOff("w:noColumnBalance", true));
2297
+ if (opts.balanceSingleByteDoubleByteWidth) p.push(onOff("w:balanceSingleByteDoubleByteWidth", true));
2298
+ if (opts.noExtraLineSpacing) p.push(onOff("w:noExtraLineSpacing", true));
2299
+ if (opts.doNotLeaveBackslashAlone) p.push(onOff("w:doNotLeaveBackslashAlone", true));
2300
+ if (opts.underlineTrailingSpaces) p.push(onOff("w:ulTrailSpace", true));
2301
+ if (opts.doNotExpandShiftReturn) p.push(onOff("w:doNotExpandShiftReturn", true));
2302
+ if (opts.spacingInWholePoints) p.push(onOff("w:spacingInWholePoints", true));
2303
+ if (opts.lineWrapLikeWord6) p.push(onOff("w:lineWrapLikeWord6", true));
2304
+ if (opts.printBodyTextBeforeHeader) p.push(onOff("w:printBodyTextBeforeHeader", true));
2305
+ if (opts.printColorsBlack) p.push(onOff("w:printColBlack", true));
2306
+ if (opts.spaceWidth) p.push(onOff("w:wpSpaceWidth", true));
2307
+ if (opts.showBreaksInFrames) p.push(onOff("w:showBreaksInFrames", true));
2308
+ if (opts.subFontBySize) p.push(onOff("w:subFontBySize", true));
2309
+ if (opts.suppressBottomSpacing) p.push(onOff("w:suppressBottomSpacing", true));
2310
+ if (opts.suppressTopSpacing) p.push(onOff("w:suppressTopSpacing", true));
2311
+ if (opts.suppressSpacingAtTopOfPage) p.push(onOff("w:suppressSpacingAtTopOfPage", true));
2312
+ if (opts.suppressTopSpacingWP) p.push(onOff("w:suppressTopSpacingWP", true));
2313
+ if (opts.suppressSpBfAfterPgBrk) p.push(onOff("w:suppressSpBfAfterPgBrk", true));
2314
+ if (opts.swapBordersFacingPages) p.push(onOff("w:swapBordersFacingPages", true));
2315
+ if (opts.convertMailMergeEsc) p.push(onOff("w:convMailMergeEsc", true));
2316
+ if (opts.truncateFontHeightsLikeWP6) p.push(onOff("w:truncateFontHeightsLikeWP6", true));
2317
+ if (opts.macWordSmallCaps) p.push(onOff("w:mwSmallCaps", true));
2318
+ if (opts.usePrinterMetrics) p.push(onOff("w:usePrinterMetrics", true));
2319
+ if (opts.doNotSuppressParagraphBorders) p.push(onOff("w:doNotSuppressParagraphBorders", true));
2320
+ if (opts.wrapTrailSpaces) p.push(onOff("w:wrapTrailSpaces", true));
2321
+ if (opts.footnoteLayoutLikeWW8) p.push(onOff("w:footnoteLayoutLikeWW8", true));
2322
+ if (opts.shapeLayoutLikeWW8) p.push(onOff("w:shapeLayoutLikeWW8", true));
2323
+ if (opts.alignTablesRowByRow) p.push(onOff("w:alignTablesRowByRow", true));
2324
+ if (opts.forgetLastTabAlignment) p.push(onOff("w:forgetLastTabAlignment", true));
2325
+ if (opts.adjustLineHeightInTable) p.push(onOff("w:adjustLineHeightInTable", true));
2326
+ if (opts.autoSpaceLikeWord95) p.push(onOff("w:autoSpaceLikeWord95", true));
2327
+ if (opts.noSpaceRaiseLower) p.push(onOff("w:noSpaceRaiseLower", true));
2328
+ if (opts.doNotUseHTMLParagraphAutoSpacing) p.push(onOff("w:doNotUseHTMLParagraphAutoSpacing", true));
2329
+ if (opts.layoutRawTableWidth) p.push(onOff("w:layoutRawTableWidth", true));
2330
+ if (opts.layoutTableRowsApart) p.push(onOff("w:layoutTableRowsApart", true));
2331
+ if (opts.useWord97LineBreakRules) p.push(onOff("w:useWord97LineBreakRules", true));
2332
+ if (opts.doNotBreakWrappedTables) p.push(onOff("w:doNotBreakWrappedTables", true));
2333
+ if (opts.doNotSnapToGridInCell) p.push(onOff("w:doNotSnapToGridInCell", true));
2334
+ if (opts.selectFieldWithFirstOrLastCharacter) p.push(onOff("w:selectFldWithFirstOrLastChar", true));
2335
+ if (opts.applyBreakingRules) p.push(onOff("w:applyBreakingRules", true));
2336
+ if (opts.doNotWrapTextWithPunctuation) p.push(onOff("w:doNotWrapTextWithPunct", true));
2337
+ if (opts.doNotUseEastAsianBreakRules) p.push(onOff("w:doNotUseEastAsianBreakRules", true));
2338
+ if (opts.useWord2002TableStyleRules) p.push(onOff("w:useWord2002TableStyleRules", true));
2339
+ if (opts.growAutofit) p.push(onOff("w:growAutofit", true));
2340
+ if (opts.useFELayout) p.push(onOff("w:useFELayout", true));
2341
+ if (opts.useNormalStyleForList) p.push(onOff("w:useNormalStyleForList", true));
2342
+ if (opts.doNotUseIndentAsNumberingTabStop) p.push(onOff("w:doNotUseIndentAsNumberingTabStop", true));
2343
+ if (opts.useAlternateEastAsianLineBreakRules) p.push(onOff("w:useAltKinsokuLineBreakRules", true));
2344
+ if (opts.allowSpaceOfSameStyleInTable) p.push(onOff("w:allowSpaceOfSameStyleInTable", true));
2345
+ if (opts.doNotSuppressIndentation) p.push(onOff("w:doNotSuppressIndentation", true));
2346
+ if (opts.doNotAutofitConstrainedTables) p.push(onOff("w:doNotAutofitConstrainedTables", true));
2347
+ if (opts.autofitToFirstFixedWidthCell) p.push(onOff("w:autofitToFirstFixedWidthCell", true));
2348
+ if (opts.underlineTabInNumberingList) p.push(onOff("w:underlineTabInNumList", true));
2349
+ if (opts.displayHangulFixedWidth) p.push(onOff("w:displayHangulFixedWidth", true));
2350
+ if (opts.splitPgBreakAndParaMark) p.push(onOff("w:splitPgBreakAndParaMark", true));
2351
+ if (opts.doNotVerticallyAlignCellWithSp) p.push(onOff("w:doNotVertAlignCellWithSp", true));
2352
+ if (opts.doNotBreakConstrainedForcedTable) p.push(onOff("w:doNotBreakConstrainedForcedTable", true));
2353
+ if (opts.ignoreVerticalAlignmentInTextboxes) p.push(onOff("w:doNotVertAlignInTxbx", true));
2354
+ if (opts.useAnsiKerningPairs) p.push(onOff("w:useAnsiKerningPairs", true));
2355
+ if (opts.cachedColumnBalance) p.push(onOff("w:cachedColBalance", true));
2356
+ if (opts.version) p.push(compatSetting("compatibilityMode", opts.version));
2357
+ if (opts.overrideTableStyleFontSizeAndJustification) p.push(compatSetting("overrideTableStyleFontSizeAndJustification", 1));
2358
+ if (opts.enableOpenTypeFeatures) p.push(compatSetting("enableOpenTypeFeatures", 1));
2359
+ if (opts.doNotFlipMirrorIndents) p.push(compatSetting("doNotFlipMirrorIndents", 1));
2360
+ if (opts.compatSettings) {
2361
+ const emitted = /* @__PURE__ */ new Set();
2362
+ if (opts.version) emitted.add("compatibilityMode");
2363
+ if (opts.overrideTableStyleFontSizeAndJustification) emitted.add("overrideTableStyleFontSizeAndJustification");
2364
+ if (opts.enableOpenTypeFeatures) emitted.add("enableOpenTypeFeatures");
2365
+ if (opts.doNotFlipMirrorIndents) emitted.add("doNotFlipMirrorIndents");
2366
+ for (const cs of opts.compatSettings) {
2367
+ if (emitted.has(cs.name)) continue;
2368
+ p.push(compatSetting(cs.name, cs.val, cs.uri));
2369
+ emitted.add(cs.name);
2370
+ }
2371
+ }
2372
+ return p.length ? `<w:compat>${p.join("")}</w:compat>` : "";
2373
+ }
2374
+ const SETTINGS_NS = "xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:w10=\"urn:schemas-microsoft-com:office:word\" xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\" xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\" xmlns:wne=\"http://schemas.microsoft.com/office/word/2006/wordml\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" xmlns:wp14=\"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing\" xmlns:wpc=\"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas\" xmlns:wpg=\"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup\" xmlns:wpi=\"http://schemas.microsoft.com/office/word/2010/wordprocessingInk\" xmlns:wps=\"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\" mc:Ignorable=\"w14 w15 wp14\"";
2375
+ const settingsDesc = {
2376
+ kind: "custom",
2377
+ stringify(opts, _ctx) {
2378
+ if (opts.rawXml !== void 0) return `<w:settings ${opts.rootAttributes ? attrStr(opts.rootAttributes) : SETTINGS_NS}>${opts.rawXml}</w:settings>`;
2379
+ const p = [];
2380
+ if (opts.writeProtection !== void 0) p.push(stringifyWriteProtect(opts.writeProtection));
2381
+ if (opts.view !== void 0) p.push(attrEl("w:view", { "w:val": opts.view }));
2382
+ if (opts.zoom !== void 0) p.push(attrEl("w:zoom", {
2383
+ "w:percent": opts.zoom.percent ?? 100,
2384
+ "w:val": opts.zoom.val
2385
+ }));
2386
+ p.push(onOff("w:removePersonalInformation", opts.removePersonalInformation));
2387
+ p.push(onOff("w:removeDateAndTime", opts.removeDateAndTime));
2388
+ p.push(onOff("w:doNotDisplayPageBoundaries", opts.doNotDisplayPageBoundaries));
2389
+ p.push(onOff("w:displayBackgroundShape", opts.displayBackgroundShape));
2390
+ p.push(onOff("w:printPostScriptOverText", opts.printPostScriptOverText));
2391
+ p.push(onOff("w:printFractionalCharacterWidth", opts.printFractionalCharacterWidth));
2392
+ p.push(onOff("w:printFormsData", opts.printFormsData));
2393
+ p.push(onOff("w:embedTrueTypeFonts", opts.embedTrueTypeFonts));
2394
+ p.push(onOff("w:embedSystemFonts", opts.embedSystemFonts));
2395
+ p.push(onOff("w:saveSubsetFonts", opts.saveSubsetFonts));
2396
+ p.push(onOff("w:saveFormsData", opts.saveFormsData));
2397
+ p.push(onOff("w:mirrorMargins", opts.mirrorMargins));
2398
+ p.push(onOff("w:alignBordersAndEdges", opts.alignBordersAndEdges));
2399
+ p.push(onOff("w:bordersDoNotSurroundHeader", opts.bordersDoNotSurroundHeader));
2400
+ p.push(onOff("w:bordersDoNotSurroundFooter", opts.bordersDoNotSurroundFooter));
2401
+ p.push(onOff("w:gutterAtTop", opts.gutterAtTop));
2402
+ p.push(onOff("w:hideSpellingErrors", opts.hideSpellingErrors));
2403
+ p.push(onOff("w:hideGrammaticalErrors", opts.hideGrammaticalErrors));
2404
+ if (opts.activeWritingStyle !== void 0) for (const ws of opts.activeWritingStyle) {
2405
+ const attrs = {};
2406
+ if (ws.lang !== void 0) attrs["w:lang"] = ws.lang;
2407
+ if (ws.vendorID !== void 0) attrs["w:vendorID"] = ws.vendorID;
2408
+ if (ws.dllVersion !== void 0) attrs["w:dllVersion"] = ws.dllVersion;
2409
+ if (ws.nlCheck !== void 0) attrs["w:nlCheck"] = ws.nlCheck;
2410
+ if (ws.checkStyle !== void 0) attrs["w:checkStyle"] = ws.checkStyle;
2411
+ if (ws.appCheck !== void 0) attrs["w:appCheck"] = ws.appCheck;
2412
+ if (ws.appName !== void 0) attrs["w:appName"] = ws.appName;
2413
+ p.push(attrEl("w:activeWritingStyle", attrs));
2414
+ }
2415
+ if (opts.proofState !== void 0) {
2416
+ const attrs = {};
2417
+ if (opts.proofState.spelling !== void 0) attrs["w:spelling"] = opts.proofState.spelling;
2418
+ if (opts.proofState.grammar !== void 0) attrs["w:grammar"] = opts.proofState.grammar;
2419
+ p.push(attrEl("w:proofState", attrs));
2420
+ }
2421
+ p.push(onOff("w:formsDesign", opts.formsDesign));
2422
+ if (opts.attachedTemplate !== void 0) p.push(attrEl("w:attachedTemplate", { "r:id": opts.attachedTemplate }));
2423
+ p.push(onOff("w:linkStyles", opts.linkStyles));
2424
+ if (opts.stylePaneFormatFilter !== void 0) {
2425
+ const f = opts.stylePaneFormatFilter;
2426
+ const attrs = {};
2427
+ for (const [prop, xmlKey] of [
2428
+ ["allStyles", "w:allStyles"],
2429
+ ["customStyles", "w:customStyles"],
2430
+ ["stylesInUse", "w:stylesInUse"],
2431
+ ["headingStyles", "w:headingStyles"],
2432
+ ["numberingStyles", "w:numberingStyles"],
2433
+ ["tableStyles", "w:tableStyles"],
2434
+ ["directFormattingOnRuns", "w:directFormattingOnRuns"],
2435
+ ["directFormattingOnParagraphs", "w:directFormattingOnParagraphs"],
2436
+ ["directFormattingOnNumbering", "w:directFormattingOnNumbering"],
2437
+ ["directFormattingOnTables", "w:directFormattingOnTables"],
2438
+ ["clearFormatting", "w:clearFormatting"],
2439
+ ["top3HeadingStyles", "w:top3HeadingStyles"],
2440
+ ["visibleStyles", "w:visibleStyles"],
2441
+ ["alternateStyleNames", "w:alternateStyleNames"],
2442
+ ["latentStyles", "w:latentStyles"]
2443
+ ]) if (f[prop] !== void 0) attrs[xmlKey] = f[prop] ? "1" : "0";
2444
+ p.push(attrEl("w:stylePaneFormatFilter", attrs));
2445
+ }
2446
+ p.push(strVal("w:stylePaneSortMethod", opts.stylePaneSortMethod));
2447
+ p.push(strVal("w:documentType", opts.documentType));
2448
+ if (opts.revisionView !== void 0) p.push(stringifyRevisionView(opts.revisionView));
2449
+ p.push(onOff("w:trackRevisions", opts.trackRevisions));
2450
+ p.push(onOff("w:doNotTrackMoves", opts.doNotTrackMoves));
2451
+ p.push(onOff("w:doNotTrackFormatting", opts.doNotTrackFormatting));
2452
+ if (opts.mailMerge !== void 0) p.push(stringifyMailMerge(opts.mailMerge));
2453
+ if (opts.documentProtection !== void 0) p.push(stringifyDocProtect(opts.documentProtection));
2454
+ p.push(onOff("w:autoFormatOverride", opts.autoFormatOverride));
2455
+ p.push(onOff("w:styleLockTheme", opts.styleLockTheme));
2456
+ p.push(onOff("w:styleLockQFSet", opts.styleLockQFSet));
2457
+ if (opts.defaultTabStop !== void 0) p.push(numVal("w:defaultTabStop", opts.defaultTabStop));
2458
+ p.push(onOff("w:autoHyphenation", opts.hyphenation?.autoHyphenation));
2459
+ p.push(numVal("w:consecutiveHyphenLimit", opts.hyphenation?.consecutiveHyphenLimit));
2460
+ p.push(numVal("w:hyphenationZone", opts.hyphenation?.hyphenationZone));
2461
+ p.push(onOff("w:doNotHyphenateCaps", opts.hyphenation?.doNotHyphenateCaps));
2462
+ p.push(onOff("w:showEnvelope", opts.showEnvelope));
2463
+ p.push(numVal("w:summaryLength", opts.summaryLength));
2464
+ p.push(strVal("w:clickAndTypeStyle", opts.clickAndTypeStyle));
2465
+ p.push(strVal("w:defaultTableStyle", opts.defaultTableStyle));
2466
+ p.push(onOff("w:evenAndOddHeaders", opts.evenAndOddHeaders));
2467
+ p.push(onOff("w:bookFoldRevPrinting", opts.bookFoldRevPrinting));
2468
+ p.push(onOff("w:bookFoldPrinting", opts.bookFoldPrinting));
2469
+ p.push(numVal("w:bookFoldPrintingSheets", opts.bookFoldPrintingSheets));
2470
+ p.push(numVal("w:drawingGridHorizontalSpacing", opts.drawingGridHorizontalSpacing));
2471
+ p.push(numVal("w:drawingGridVerticalSpacing", opts.drawingGridVerticalSpacing));
2472
+ p.push(numVal("w:displayHorizontalDrawingGridEvery", opts.displayHorizontalDrawingGridEvery));
2473
+ p.push(numVal("w:displayVerticalDrawingGridEvery", opts.displayVerticalDrawingGridEvery));
2474
+ p.push(onOff("w:doNotUseMarginsForDrawingGridOrigin", opts.doNotUseMarginsForDrawingGridOrigin));
2475
+ p.push(numVal("w:drawingGridHorizontalOrigin", opts.drawingGridHorizontalOrigin));
2476
+ p.push(numVal("w:drawingGridVerticalOrigin", opts.drawingGridVerticalOrigin));
2477
+ p.push(onOff("w:doNotShadeFormData", opts.doNotShadeFormData));
2478
+ p.push(onOff("w:noPunctuationKerning", opts.noPunctuationKerning));
2479
+ if (opts.characterSpacingControl !== void 0) p.push(strVal("w:characterSpacingControl", opts.characterSpacingControl));
2480
+ p.push(onOff("w:printTwoOnOne", opts.printTwoOnOne));
2481
+ p.push(onOff("w:strictFirstAndLastChars", opts.strictFirstAndLastChars));
2482
+ if (opts.noLineBreaksAfter !== void 0) {
2483
+ const attrs = {};
2484
+ if (opts.noLineBreaksAfter.lang !== void 0) attrs["w:lang"] = opts.noLineBreaksAfter.lang;
2485
+ if (opts.noLineBreaksAfter.val !== void 0) attrs["w:val"] = opts.noLineBreaksAfter.val;
2486
+ p.push(attrEl("w:noLineBreaksAfter", attrs));
2487
+ }
2488
+ if (opts.noLineBreaksBefore !== void 0) {
2489
+ const attrs = {};
2490
+ if (opts.noLineBreaksBefore.lang !== void 0) attrs["w:lang"] = opts.noLineBreaksBefore.lang;
2491
+ if (opts.noLineBreaksBefore.val !== void 0) attrs["w:val"] = opts.noLineBreaksBefore.val;
2492
+ p.push(attrEl("w:noLineBreaksBefore", attrs));
2493
+ }
2494
+ p.push(onOff("w:savePreviewPicture", opts.savePreviewPicture));
2495
+ p.push(onOff("w:doNotValidateAgainstSchema", opts.doNotValidateAgainstSchema));
2496
+ p.push(onOff("w:saveInvalidXml", opts.saveInvalidXml));
2497
+ p.push(onOff("w:ignoreMixedContent", opts.ignoreMixedContent));
2498
+ p.push(onOff("w:alwaysShowPlaceholderText", opts.alwaysShowPlaceholderText));
2499
+ p.push(onOff("w:doNotDemarcateInvalidXml", opts.doNotDemarcateInvalidXml));
2500
+ p.push(onOff("w:saveXmlDataOnly", opts.saveXmlDataOnly));
2501
+ p.push(onOff("w:useXSLTWhenSaving", opts.useXSLTWhenSaving));
2502
+ if (opts.saveThroughXslt !== void 0) {
2503
+ const attrs = {};
2504
+ if (opts.saveThroughXslt.id !== void 0) attrs["r:id"] = opts.saveThroughXslt.id;
2505
+ if (opts.saveThroughXslt.val !== void 0) attrs["w:val"] = opts.saveThroughXslt.val;
2506
+ if (opts.saveThroughXslt.solutionID !== void 0) attrs["w:solutionID"] = opts.saveThroughXslt.solutionID;
2507
+ p.push(attrEl("w:saveThroughXslt", attrs));
2508
+ }
2509
+ p.push(onOff("w:showXMLTags", opts.showXMLTags));
2510
+ p.push(onOff("w:alwaysMergeEmptyNamespace", opts.alwaysMergeEmptyNamespace));
2511
+ p.push(onOff("w:updateFields", opts.updateFields));
2512
+ if (opts.hdrShapeDefaults !== void 0) p.push(`<w:hdrShapeDefaults>${opts.hdrShapeDefaults}</w:hdrShapeDefaults>`);
2513
+ if (opts.footnotePr !== void 0) p.push(stringifyFootnotePr(opts.footnotePr));
2514
+ if (opts.endnotePr !== void 0) p.push(stringifyEndnotePr(opts.endnotePr));
2515
+ const compatXml = stringifyCompatibility({
2516
+ ...opts.compatibility,
2517
+ version: opts.compatibility?.version ?? opts.compatibilityModeVersion
2518
+ });
2519
+ if (compatXml) p.push(compatXml);
2520
+ if (opts.docVars?.length) {
2521
+ const vars = opts.docVars.map((v) => attrEl("w:docVar", {
2522
+ "w:name": v.name,
2523
+ "w:val": v.val
2524
+ })).join("");
2525
+ p.push(`<w:docVars>${vars}</w:docVars>`);
2526
+ }
2527
+ if (opts.rsids !== void 0) p.push(stringifyRsids(opts.rsids));
2528
+ if (opts.mathPr !== void 0) p.push(stringifyMathPr(opts.mathPr));
2529
+ if (opts.attachedSchema !== void 0) for (const schema of opts.attachedSchema) p.push(strVal("w:attachedSchema", schema));
2530
+ if (opts.themeFontLang !== void 0) {
2531
+ const a = {};
2532
+ if (opts.themeFontLang.val !== void 0) a["w:val"] = opts.themeFontLang.val;
2533
+ if (opts.themeFontLang.eastAsia !== void 0) a["w:eastAsia"] = opts.themeFontLang.eastAsia;
2534
+ if (opts.themeFontLang.bidi !== void 0) a["w:bidi"] = opts.themeFontLang.bidi;
2535
+ p.push(attrEl("w:themeFontLang", a));
2536
+ }
2537
+ if (opts.colorSchemeMapping !== void 0) p.push(stringifyColorSchemeMapping(opts.colorSchemeMapping));
2538
+ p.push(onOff("w:doNotIncludeSubdocsInStats", opts.doNotIncludeSubdocsInStats));
2539
+ p.push(onOff("w:doNotAutoCompressPictures", opts.doNotAutoCompressPictures));
2540
+ if (opts.forceUpgrade !== void 0) p.push("<w:forceUpgrade/>");
2541
+ if (opts.captions !== void 0) p.push(stringifyCaptions(opts.captions));
2542
+ if (opts.readModeInkLockDown !== void 0) p.push(stringifyReadModeInkLockDown(opts.readModeInkLockDown));
2543
+ if (opts.smartTagType !== void 0) for (const st of opts.smartTagType) {
2544
+ const attrs = {};
2545
+ if (st.namespace !== void 0) attrs["w:namespace"] = st.namespace;
2546
+ if (st.namespaceuri !== void 0) attrs["w:namespaceuri"] = st.namespaceuri;
2547
+ if (st.name !== void 0) attrs["w:name"] = st.name;
2548
+ if (st.url !== void 0) attrs["w:url"] = st.url;
2549
+ p.push(attrEl("w:smartTagType", attrs));
2550
+ }
2551
+ if (opts.shapeDefaults !== void 0) p.push(`<w:shapeDefaults>${opts.shapeDefaults}</w:shapeDefaults>`);
2552
+ p.push(onOff("w:doNotEmbedSmartTags", opts.doNotEmbedSmartTags));
2553
+ p.push(strVal("w:decimalSymbol", opts.decimalSymbol));
2554
+ p.push(strVal("w:listSeparator", opts.listSeparator));
2555
+ return `<w:settings ${SETTINGS_NS}>${p.join("")}</w:settings>`;
2556
+ },
2557
+ parse(el, _ctx) {
2558
+ const opts = {};
2559
+ const wpEl = findChild(el, "w:writeProtection");
2560
+ if (wpEl) {
2561
+ const wp = readPasswordAttrs(wpEl);
2562
+ const recommended = attr(wpEl, "w:recommended");
2563
+ if (recommended !== void 0) wp.recommended = recommended === "1" || recommended === "true";
2564
+ if (Object.keys(wp).length > 0) opts.writeProtection = wp;
2565
+ }
2566
+ const viewVal = readStr(findChild(el, "w:view"), "w:val");
2567
+ if (viewVal) opts.view = viewVal;
2568
+ const zoomEl = findChild(el, "w:zoom");
2569
+ if (zoomEl) {
2570
+ const zoom = {};
2571
+ const percent = attr(zoomEl, "w:percent");
2572
+ if (percent) zoom.percent = parseInt(percent, 10);
2573
+ const zval = attr(zoomEl, "w:val");
2574
+ if (zval) zoom.val = zval;
2575
+ if (Object.keys(zoom).length > 0) opts.zoom = zoom;
2576
+ }
2577
+ for (const [key, tag] of [
2578
+ ["removePersonalInformation", "w:removePersonalInformation"],
2579
+ ["removeDateAndTime", "w:removeDateAndTime"],
2580
+ ["doNotDisplayPageBoundaries", "w:doNotDisplayPageBoundaries"],
2581
+ ["displayBackgroundShape", "w:displayBackgroundShape"],
2582
+ ["printPostScriptOverText", "w:printPostScriptOverText"],
2583
+ ["printFractionalCharacterWidth", "w:printFractionalCharacterWidth"],
2584
+ ["printFormsData", "w:printFormsData"],
2585
+ ["embedTrueTypeFonts", "w:embedTrueTypeFonts"],
2586
+ ["embedSystemFonts", "w:embedSystemFonts"],
2587
+ ["saveSubsetFonts", "w:saveSubsetFonts"],
2588
+ ["saveFormsData", "w:saveFormsData"],
2589
+ ["mirrorMargins", "w:mirrorMargins"],
2590
+ ["alignBordersAndEdges", "w:alignBordersAndEdges"],
2591
+ ["bordersDoNotSurroundHeader", "w:bordersDoNotSurroundHeader"],
2592
+ ["bordersDoNotSurroundFooter", "w:bordersDoNotSurroundFooter"],
2593
+ ["gutterAtTop", "w:gutterAtTop"],
2594
+ ["hideSpellingErrors", "w:hideSpellingErrors"],
2595
+ ["hideGrammaticalErrors", "w:hideGrammaticalErrors"],
2596
+ ["formsDesign", "w:formsDesign"],
2597
+ ["linkStyles", "w:linkStyles"],
2598
+ ["trackRevisions", "w:trackRevisions"],
2599
+ ["doNotTrackMoves", "w:doNotTrackMoves"],
2600
+ ["doNotTrackFormatting", "w:doNotTrackFormatting"],
2601
+ ["autoFormatOverride", "w:autoFormatOverride"],
2602
+ ["styleLockTheme", "w:styleLockTheme"],
2603
+ ["styleLockQFSet", "w:styleLockQFSet"],
2604
+ ["showEnvelope", "w:showEnvelope"],
2605
+ ["evenAndOddHeaders", "w:evenAndOddHeaders"],
2606
+ ["bookFoldRevPrinting", "w:bookFoldRevPrinting"],
2607
+ ["bookFoldPrinting", "w:bookFoldPrinting"],
2608
+ ["doNotUseMarginsForDrawingGridOrigin", "w:doNotUseMarginsForDrawingGridOrigin"],
2609
+ ["doNotShadeFormData", "w:doNotShadeFormData"],
2610
+ ["noPunctuationKerning", "w:noPunctuationKerning"],
2611
+ ["printTwoOnOne", "w:printTwoOnOne"],
2612
+ ["strictFirstAndLastChars", "w:strictFirstAndLastChars"],
2613
+ ["savePreviewPicture", "w:savePreviewPicture"],
2614
+ ["doNotValidateAgainstSchema", "w:doNotValidateAgainstSchema"],
2615
+ ["saveInvalidXml", "w:saveInvalidXml"],
2616
+ ["ignoreMixedContent", "w:ignoreMixedContent"],
2617
+ ["alwaysShowPlaceholderText", "w:alwaysShowPlaceholderText"],
2618
+ ["doNotDemarcateInvalidXml", "w:doNotDemarcateInvalidXml"],
2619
+ ["saveXmlDataOnly", "w:saveXmlDataOnly"],
2620
+ ["useXSLTWhenSaving", "w:useXSLTWhenSaving"],
2621
+ ["showXMLTags", "w:showXMLTags"],
2622
+ ["alwaysMergeEmptyNamespace", "w:alwaysMergeEmptyNamespace"],
2623
+ ["updateFields", "w:updateFields"],
2624
+ ["doNotIncludeSubdocsInStats", "w:doNotIncludeSubdocsInStats"],
2625
+ ["doNotAutoCompressPictures", "w:doNotAutoCompressPictures"],
2626
+ ["doNotEmbedSmartTags", "w:doNotEmbedSmartTags"]
2627
+ ]) {
2628
+ const v = readOnOff(findChild(el, tag));
2629
+ if (v !== void 0) opts[key] = v;
2630
+ }
2631
+ const awsList = [];
2632
+ for (const child of el.elements ?? []) {
2633
+ if (child.name !== "w:activeWritingStyle") continue;
2634
+ const entry = {};
2635
+ const lang = attr(child, "w:lang");
2636
+ if (lang) entry.lang = lang;
2637
+ const vendorID = attr(child, "w:vendorID");
2638
+ if (vendorID) entry.vendorID = vendorID;
2639
+ const dllVersion = attr(child, "w:dllVersion");
2640
+ if (dllVersion) entry.dllVersion = dllVersion;
2641
+ const nlCheck = attr(child, "w:nlCheck");
2642
+ if (nlCheck !== void 0) entry.nlCheck = nlCheck !== "0" && nlCheck !== "false";
2643
+ const checkStyle = attr(child, "w:checkStyle");
2644
+ if (checkStyle !== void 0) entry.checkStyle = checkStyle !== "0" && checkStyle !== "false";
2645
+ const appCheck = attr(child, "w:appCheck");
2646
+ if (appCheck) entry.appCheck = appCheck;
2647
+ const appName = attr(child, "w:appName");
2648
+ if (appName) entry.appName = appName;
2649
+ if (Object.keys(entry).length > 0) awsList.push(entry);
2650
+ }
2651
+ if (awsList.length > 0) opts.activeWritingStyle = awsList;
2652
+ const proofEl = findChild(el, "w:proofState");
2653
+ if (proofEl) {
2654
+ const proof = {};
2655
+ const spelling = attr(proofEl, "w:spelling");
2656
+ if (spelling) proof.spelling = spelling;
2657
+ const grammar = attr(proofEl, "w:grammar");
2658
+ if (grammar) proof.grammar = grammar;
2659
+ if (Object.keys(proof).length > 0) opts.proofState = proof;
2660
+ }
2661
+ const attachedTplEl = findChild(el, "w:attachedTemplate");
2662
+ if (attachedTplEl) {
2663
+ const rid = attr(attachedTplEl, "r:id");
2664
+ if (rid) opts.attachedTemplate = rid;
2665
+ }
2666
+ const spffEl = findChild(el, "w:stylePaneFormatFilter");
2667
+ if (spffEl) {
2668
+ const filter = {};
2669
+ for (const [prop, xmlKey] of [
2670
+ ["allStyles", "w:allStyles"],
2671
+ ["customStyles", "w:customStyles"],
2672
+ ["stylesInUse", "w:stylesInUse"],
2673
+ ["headingStyles", "w:headingStyles"],
2674
+ ["numberingStyles", "w:numberingStyles"],
2675
+ ["tableStyles", "w:tableStyles"],
2676
+ ["directFormattingOnRuns", "w:directFormattingOnRuns"],
2677
+ ["directFormattingOnParagraphs", "w:directFormattingOnParagraphs"],
2678
+ ["directFormattingOnNumbering", "w:directFormattingOnNumbering"],
2679
+ ["directFormattingOnTables", "w:directFormattingOnTables"],
2680
+ ["clearFormatting", "w:clearFormatting"],
2681
+ ["top3HeadingStyles", "w:top3HeadingStyles"],
2682
+ ["visibleStyles", "w:visibleStyles"],
2683
+ ["alternateStyleNames", "w:alternateStyleNames"],
2684
+ ["latentStyles", "w:latentStyles"]
2685
+ ]) {
2686
+ const v = attr(spffEl, xmlKey);
2687
+ if (v !== void 0) filter[prop] = v !== "0" && v !== "false" && v !== "off";
2688
+ }
2689
+ if (Object.keys(filter).length > 0) opts.stylePaneFormatFilter = filter;
2690
+ }
2691
+ const stylePaneSortMethod = readStr(findChild(el, "w:stylePaneSortMethod"), "w:val");
2692
+ if (stylePaneSortMethod) opts.stylePaneSortMethod = stylePaneSortMethod;
2693
+ const documentType = readStr(findChild(el, "w:documentType"), "w:val");
2694
+ if (documentType) opts.documentType = documentType;
2695
+ const clickAndTypeStyle = readStr(findChild(el, "w:clickAndTypeStyle"), "w:val");
2696
+ if (clickAndTypeStyle) opts.clickAndTypeStyle = clickAndTypeStyle;
2697
+ const defaultTableStyle = readStr(findChild(el, "w:defaultTableStyle"), "w:val");
2698
+ if (defaultTableStyle) opts.defaultTableStyle = defaultTableStyle;
2699
+ const mailMergeEl = findChild(el, "w:mailMerge");
2700
+ if (mailMergeEl) {
2701
+ const mm = parseMailMerge(mailMergeEl);
2702
+ if (mm) opts.mailMerge = mm;
2703
+ }
2704
+ const revViewEl = findChild(el, "w:revisionView");
2705
+ if (revViewEl) {
2706
+ const rv = {};
2707
+ for (const [k, a] of [
2708
+ ["markup", "w:markup"],
2709
+ ["comments", "w:comments"],
2710
+ ["insDel", "w:insDel"],
2711
+ ["formatting", "w:formatting"],
2712
+ ["inkAnnotations", "w:inkAnnotations"]
2713
+ ]) {
2714
+ const v = attr(revViewEl, a);
2715
+ if (v !== void 0) rv[k] = v !== "false" && v !== "0";
2716
+ }
2717
+ if (Object.keys(rv).length > 0) opts.revisionView = rv;
2718
+ }
2719
+ const docProtEl = findChild(el, "w:documentProtection");
2720
+ if (docProtEl) {
2721
+ const prot = {};
2722
+ const edit = attr(docProtEl, "w:edit");
2723
+ if (edit && DOC_PROTECT_EDITS.includes(edit)) prot.edit = edit;
2724
+ if (attr(docProtEl, "w:enforcement") !== void 0) {
2725
+ Object.assign(prot, readPasswordAttrs(docProtEl));
2726
+ const formatting = attr(docProtEl, "w:formatting");
2727
+ if (formatting !== void 0) prot.formatting = formatting === "1" || formatting === "true";
2728
+ }
2729
+ if (Object.keys(prot).length > 0) opts.documentProtection = prot;
2730
+ }
2731
+ const defaultTabStop = readNum(findChild(el, "w:defaultTabStop"), "w:val");
2732
+ if (defaultTabStop !== void 0) opts.defaultTabStop = defaultTabStop;
2733
+ if (findChild(el, "w:autoHyphenation") || findChild(el, "w:doNotHyphenateCaps") || findChild(el, "w:consecutiveHyphenLimit") || findChild(el, "w:hyphenationZone")) {
2734
+ const hyphenation = {};
2735
+ const autoHyph = readOnOff(findChild(el, "w:autoHyphenation"));
2736
+ if (autoHyph !== void 0) hyphenation.autoHyphenation = autoHyph;
2737
+ const noHyphCaps = readOnOff(findChild(el, "w:doNotHyphenateCaps"));
2738
+ if (noHyphCaps !== void 0) hyphenation.doNotHyphenateCaps = noHyphCaps;
2739
+ const consLimit = readNum(findChild(el, "w:consecutiveHyphenLimit"), "w:val");
2740
+ if (consLimit !== void 0) hyphenation.consecutiveHyphenLimit = consLimit;
2741
+ const zone = readNum(findChild(el, "w:hyphenationZone"), "w:val");
2742
+ if (zone !== void 0) hyphenation.hyphenationZone = zone;
2743
+ if (Object.keys(hyphenation).length > 0) opts.hyphenation = hyphenation;
2744
+ }
2745
+ const summaryLength = readNum(findChild(el, "w:summaryLength"), "w:val");
2746
+ if (summaryLength !== void 0) opts.summaryLength = summaryLength;
2747
+ const bookFoldSheets = readNum(findChild(el, "w:bookFoldPrintingSheets"), "w:val");
2748
+ if (bookFoldSheets !== void 0) opts.bookFoldPrintingSheets = bookFoldSheets;
2749
+ for (const [key, tag] of [
2750
+ ["drawingGridHorizontalSpacing", "w:drawingGridHorizontalSpacing"],
2751
+ ["drawingGridVerticalSpacing", "w:drawingGridVerticalSpacing"],
2752
+ ["displayHorizontalDrawingGridEvery", "w:displayHorizontalDrawingGridEvery"],
2753
+ ["displayVerticalDrawingGridEvery", "w:displayVerticalDrawingGridEvery"],
2754
+ ["drawingGridHorizontalOrigin", "w:drawingGridHorizontalOrigin"],
2755
+ ["drawingGridVerticalOrigin", "w:drawingGridVerticalOrigin"]
2756
+ ]) {
2757
+ const v = readNum(findChild(el, tag), "w:val");
2758
+ if (v !== void 0) opts[key] = v;
2759
+ }
2760
+ const characterSpacingControl = readStr(findChild(el, "w:characterSpacingControl"), "w:val");
2761
+ if (characterSpacingControl) opts.characterSpacingControl = characterSpacingControl;
2762
+ for (const [key, tag] of [["noLineBreaksAfter", "w:noLineBreaksAfter"], ["noLineBreaksBefore", "w:noLineBreaksBefore"]]) {
2763
+ const lbEl = findChild(el, tag);
2764
+ if (!lbEl) continue;
2765
+ const entry = {};
2766
+ const lang = attr(lbEl, "w:lang");
2767
+ if (lang) entry.lang = lang;
2768
+ const val = attr(lbEl, "w:val");
2769
+ if (val) entry.val = val;
2770
+ if (Object.keys(entry).length > 0) opts[key] = entry;
2771
+ }
2772
+ const stxEl = findChild(el, "w:saveThroughXslt");
2773
+ if (stxEl) {
2774
+ const stx = {};
2775
+ const id = attr(stxEl, "r:id");
2776
+ if (id) stx.id = id;
2777
+ const val = attr(stxEl, "w:val");
2778
+ if (val) stx.val = val;
2779
+ const solutionID = attr(stxEl, "w:solutionID");
2780
+ if (solutionID) stx.solutionID = solutionID;
2781
+ if (Object.keys(stx).length > 0) opts.saveThroughXslt = stx;
2782
+ }
2783
+ const hdrSdEl = findChild(el, "w:hdrShapeDefaults");
2784
+ if (hdrSdEl) opts.hdrShapeDefaults = stringify(hdrSdEl);
2785
+ const sdEl = findChild(el, "w:shapeDefaults");
2786
+ if (sdEl) opts.shapeDefaults = stringify(sdEl);
2787
+ const fnPrEl = findChild(el, "w:footnotePr");
2788
+ if (fnPrEl) {
2789
+ const fn = parseFtnEdnPr(fnPrEl);
2790
+ if (fn) opts.footnotePr = fn;
2791
+ }
2792
+ const enPrEl = findChild(el, "w:endnotePr");
2793
+ if (enPrEl) {
2794
+ const en = parseFtnEdnPr(enPrEl);
2795
+ if (en) opts.endnotePr = en;
2796
+ }
2797
+ const compatEl = findChild(el, "w:compat");
2798
+ if (compatEl) {
2799
+ const compat = parseCompatibility(compatEl);
2800
+ if (compat) opts.compatibility = compat;
2801
+ }
2802
+ const docVarsEl = findChild(el, "w:docVars");
2803
+ if (docVarsEl) {
2804
+ const vars = [];
2805
+ for (const child of docVarsEl.elements ?? []) {
2806
+ if (child.name !== "w:docVar") continue;
2807
+ const name = attr(child, "w:name");
2808
+ const val = attr(child, "w:val");
2809
+ if (name !== void 0 && val !== void 0) vars.push({
2810
+ name,
2811
+ val
2812
+ });
2813
+ }
2814
+ if (vars.length > 0) opts.docVars = vars;
2815
+ }
2816
+ const rsidsEl = findChild(el, "w:rsids");
2817
+ if (rsidsEl) {
2818
+ const rsids = {};
2819
+ const root = readStr(findChild(rsidsEl, "w:rsidRoot"), "w:val");
2820
+ if (root) rsids.rsidRoot = root;
2821
+ const list = [];
2822
+ for (const child of rsidsEl.elements ?? []) {
2823
+ if (child.name !== "w:rsid") continue;
2824
+ const val = attr(child, "w:val");
2825
+ if (val) list.push(val);
2826
+ }
2827
+ if (list.length > 0) rsids.rsids = list;
2828
+ if (Object.keys(rsids).length > 0) opts.rsids = rsids;
2829
+ }
2830
+ const mathPrEl = findChild(el, "m:mathPr");
2831
+ if (mathPrEl) {
2832
+ const mp = parseMathPr(mathPrEl);
2833
+ if (mp) opts.mathPr = mp;
2834
+ }
2835
+ const attachedSchemas = [];
2836
+ for (const child of el.elements ?? []) {
2837
+ if (child.name !== "w:attachedSchema") continue;
2838
+ const val = attr(child, "w:val");
2839
+ if (val) attachedSchemas.push(val);
2840
+ }
2841
+ if (attachedSchemas.length > 0) opts.attachedSchema = attachedSchemas;
2842
+ const tflEl = findChild(el, "w:themeFontLang");
2843
+ if (tflEl) {
2844
+ const tfl = {};
2845
+ const val = attr(tflEl, "w:val");
2846
+ if (val) tfl.val = val;
2847
+ const eastAsia = attr(tflEl, "w:eastAsia");
2848
+ if (eastAsia) tfl.eastAsia = eastAsia;
2849
+ const bidi = attr(tflEl, "w:bidi");
2850
+ if (bidi) tfl.bidi = bidi;
2851
+ if (Object.keys(tfl).length > 0) opts.themeFontLang = tfl;
2852
+ }
2853
+ const csmEl = findChild(el, "w:clrSchemeMapping");
2854
+ if (csmEl) {
2855
+ const csm = {};
2856
+ for (const [key, xmlAttr] of [
2857
+ ["bg1", "w:bg1"],
2858
+ ["t1", "w:t1"],
2859
+ ["bg2", "w:bg2"],
2860
+ ["t2", "w:t2"],
2861
+ ["accent1", "w:accent1"],
2862
+ ["accent2", "w:accent2"],
2863
+ ["accent3", "w:accent3"],
2864
+ ["accent4", "w:accent4"],
2865
+ ["accent5", "w:accent5"],
2866
+ ["accent6", "w:accent6"],
2867
+ ["hyperlink", "w:hyperlink"],
2868
+ ["followedHyperlink", "w:followedHyperlink"]
2869
+ ]) {
2870
+ const v = attr(csmEl, xmlAttr);
2871
+ if (v) csm[key] = v;
2872
+ }
2873
+ if (Object.keys(csm).length > 0) opts.colorSchemeMapping = csm;
2874
+ }
2875
+ if (findChild(el, "w:forceUpgrade")) opts.forceUpgrade = true;
2876
+ const captionsEl = findChild(el, "w:captions");
2877
+ if (captionsEl) {
2878
+ const captions = parseCaptions(captionsEl);
2879
+ if (captions) opts.captions = captions;
2880
+ }
2881
+ const rmilEl = findChild(el, "w:readModeInkLockDown");
2882
+ if (rmilEl) opts.readModeInkLockDown = {
2883
+ actualPg: attr(rmilEl, "w:actualPg") !== "0",
2884
+ w: parseInt(attr(rmilEl, "w:w") ?? "0", 10),
2885
+ h: parseInt(attr(rmilEl, "w:h") ?? "0", 10),
2886
+ fontSz: parseInt(attr(rmilEl, "w:fontSz") ?? "0", 10)
2887
+ };
2888
+ const smartTags = [];
2889
+ for (const child of el.elements ?? []) {
2890
+ if (child.name !== "w:smartTagType") continue;
2891
+ const entry = {};
2892
+ const ns = attr(child, "w:namespace");
2893
+ if (ns) entry.namespace = ns;
2894
+ const nsuri = attr(child, "w:namespaceuri");
2895
+ if (nsuri) entry.namespaceuri = nsuri;
2896
+ const name = attr(child, "w:name");
2897
+ if (name) entry.name = name;
2898
+ const url = attr(child, "w:url");
2899
+ if (url) entry.url = url;
2900
+ if (Object.keys(entry).length > 0) smartTags.push(entry);
2901
+ }
2902
+ if (smartTags.length > 0) opts.smartTagType = smartTags;
2903
+ const decimalSymbol = readStr(findChild(el, "w:decimalSymbol"), "w:val");
2904
+ if (decimalSymbol) opts.decimalSymbol = decimalSymbol;
2905
+ const listSeparator = readStr(findChild(el, "w:listSeparator"), "w:val");
2906
+ if (listSeparator) opts.listSeparator = listSeparator;
2907
+ return opts;
2908
+ }
2909
+ };
2910
+ //#endregion
2911
+ //#region src/parts/footnotes/descriptor.ts
2912
+ const NS$2 = "xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:w10=\"urn:schemas-microsoft-com:office:word\" xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\" xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\" xmlns:wne=\"http://schemas.openxmlformats.org/office/word/2006/wordml\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" xmlns:wp14=\"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing\" xmlns:wpc=\"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas\" xmlns:wpg=\"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup\" xmlns:wpi=\"http://schemas.microsoft.com/office/word/2010/wordprocessingInk\" xmlns:wps=\"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\"";
2913
+ /** XML for the footnoteRef run — auto-injected at start of first paragraph. */
2914
+ const FOOTNOTE_REF_RUN = "<w:r><w:rPr><w:rStyle w:val=\"FootnoteReference\"/></w:rPr><w:footnoteRef/></w:r>";
2915
+ /** Default separator footnote (id=-1) for freshly generated documents. */
2916
+ const SEPARATOR_FOOTNOTE = "<w:footnote w:type=\"separator\" w:id=\"-1\"><w:p><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr><w:r><w:separator/></w:r></w:p></w:footnote>";
2917
+ /** Default continuation separator footnote (id=0) for freshly generated documents. */
2918
+ const CONTINUATION_SEPARATOR_FOOTNOTE = "<w:footnote w:type=\"continuationSeparator\" w:id=\"0\"><w:p><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr><w:r><w:continuationSeparator/></w:r></w:p></w:footnote>";
2919
+ /** Render a system footnote from round-tripped id + content, or the spec default. */
2920
+ function footnoteSystemNote(type, sep, fallback, ctx) {
2921
+ if (!sep) return fallback;
2922
+ const inner = sep.paragraphs.map((p) => stringifyParagraphInline(p, ctx)).join("");
2923
+ return `<w:footnote w:type="${type}" w:id="${sep.id}">${inner}</w:footnote>`;
2924
+ }
2925
+ const footnotesDesc = {
2926
+ kind: "custom",
2927
+ stringify(data, ctx) {
2928
+ const parts = [`<w:footnotes ${NS$2} mc:Ignorable="w14 w15 wp14">`];
2929
+ parts.push(footnoteSystemNote("separator", data.separator, SEPARATOR_FOOTNOTE, ctx));
2930
+ parts.push(footnoteSystemNote("continuationSeparator", data.continuationSeparator, CONTINUATION_SEPARATOR_FOOTNOTE, ctx));
2931
+ for (const [id, paragraphs] of data.notes) {
2932
+ parts.push(`<w:footnote w:id="${id}">`);
2933
+ for (const [i, para] of paragraphs.entries()) {
2934
+ const pXml = stringifyParagraphInline(para, ctx);
2935
+ if (i === 0) {
2936
+ const openIdx = pXml.indexOf(">");
2937
+ if (openIdx !== -1) parts.push(pXml.slice(0, openIdx + 1) + FOOTNOTE_REF_RUN + pXml.slice(openIdx + 1));
2938
+ else parts.push(pXml);
2939
+ } else parts.push(pXml);
2940
+ }
2941
+ parts.push("</w:footnote>");
2942
+ }
2943
+ parts.push("</w:footnotes>");
2944
+ return parts.join("");
2945
+ },
2946
+ parse(el, ctx) {
2947
+ const notes = /* @__PURE__ */ new Map();
2948
+ let separator;
2949
+ let continuationSeparator;
2950
+ for (const child of el.elements ?? []) {
2951
+ if (child.name !== "w:footnote") continue;
2952
+ const id = attrNum(child, "w:id");
2953
+ if (id === void 0) continue;
2954
+ const type = attr(child, "w:type");
2955
+ const paragraphs = [];
2956
+ for (const sub of child.elements ?? []) if (sub.name === "w:p") paragraphs.push(parseParagraph(sub, ctx));
2957
+ if (type === "separator") separator = {
2958
+ id,
2959
+ paragraphs
2960
+ };
2961
+ else if (type === "continuationSeparator") continuationSeparator = {
2962
+ id,
2963
+ paragraphs
2964
+ };
2965
+ else notes.set(id, paragraphs);
2966
+ }
2967
+ return {
2968
+ notes,
2969
+ separator,
2970
+ continuationSeparator
2971
+ };
2972
+ }
2973
+ };
2974
+ //#endregion
2975
+ //#region src/parts/endnotes/descriptor.ts
2976
+ const NS$1 = "xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:w10=\"urn:schemas-microsoft-com:office:word\" xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\" xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\" xmlns:wne=\"http://schemas.openxmlformats.org/office/word/2006/wordml\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" xmlns:wp14=\"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing\" xmlns:wpc=\"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas\" xmlns:wpg=\"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup\" xmlns:wpi=\"http://schemas.microsoft.com/office/word/2010/wordprocessingInk\" xmlns:wps=\"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\"";
2977
+ /** XML for the endnoteRef run — auto-injected at start of first paragraph. */
2978
+ const ENDNOTE_REF_RUN = "<w:r><w:rPr><w:rStyle w:val=\"EndnoteReference\"/></w:rPr><w:endnoteRef/></w:r>";
2979
+ /** Default separator endnote (id=-1) for freshly generated documents. */
2980
+ const SEPARATOR_ENDNOTE = "<w:endnote w:type=\"separator\" w:id=\"-1\"><w:p><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr><w:r><w:separator/></w:r></w:p></w:endnote>";
2981
+ /** Default continuation separator endnote (id=0) for freshly generated documents. */
2982
+ const CONTINUATION_SEPARATOR_ENDNOTE = "<w:endnote w:type=\"continuationSeparator\" w:id=\"0\"><w:p><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr><w:r><w:continuationSeparator/></w:r></w:p></w:endnote>";
2983
+ /** Render a system endnote from round-tripped id + content, or the spec default. */
2984
+ function endnoteSystemNote(type, sep, fallback, ctx) {
2985
+ if (!sep) return fallback;
2986
+ const inner = sep.paragraphs.map((p) => stringifyParagraphInline(p, ctx)).join("");
2987
+ return `<w:endnote w:type="${type}" w:id="${sep.id}">${inner}</w:endnote>`;
2988
+ }
2989
+ const endnotesDesc = {
2990
+ kind: "custom",
2991
+ stringify(data, ctx) {
2992
+ const parts = [`<w:endnotes ${NS$1} mc:Ignorable="w14 w15 wp14">`];
2993
+ parts.push(endnoteSystemNote("separator", data.separator, SEPARATOR_ENDNOTE, ctx));
2994
+ parts.push(endnoteSystemNote("continuationSeparator", data.continuationSeparator, CONTINUATION_SEPARATOR_ENDNOTE, ctx));
2995
+ for (const [id, paragraphs] of data.notes) {
2996
+ parts.push(`<w:endnote w:id="${id}">`);
2997
+ for (const [i, para] of paragraphs.entries()) {
2998
+ const pXml = stringifyParagraphInline(para, ctx);
2999
+ if (i === 0) {
3000
+ const openIdx = pXml.indexOf(">");
3001
+ if (openIdx !== -1) parts.push(pXml.slice(0, openIdx + 1) + ENDNOTE_REF_RUN + pXml.slice(openIdx + 1));
3002
+ else parts.push(pXml);
3003
+ } else parts.push(pXml);
3004
+ }
3005
+ parts.push("</w:endnote>");
3006
+ }
3007
+ parts.push("</w:endnotes>");
3008
+ return parts.join("");
3009
+ },
3010
+ parse(el, ctx) {
3011
+ const notes = /* @__PURE__ */ new Map();
3012
+ let separator;
3013
+ let continuationSeparator;
3014
+ for (const child of el.elements ?? []) {
3015
+ if (child.name !== "w:endnote") continue;
3016
+ const id = attrNum(child, "w:id");
3017
+ if (id === void 0) continue;
3018
+ const type = attr(child, "w:type");
3019
+ const paragraphs = [];
3020
+ for (const sub of child.elements ?? []) if (sub.name === "w:p") paragraphs.push(parseParagraph(sub, ctx));
3021
+ if (type === "separator") separator = {
3022
+ id,
3023
+ paragraphs
3024
+ };
3025
+ else if (type === "continuationSeparator") continuationSeparator = {
3026
+ id,
3027
+ paragraphs
3028
+ };
3029
+ else notes.set(id, paragraphs);
3030
+ }
3031
+ return {
3032
+ notes,
3033
+ separator,
3034
+ continuationSeparator
3035
+ };
3036
+ }
3037
+ };
3038
+ //#endregion
3039
+ //#region src/parts/alt-chunk/alt-chunk-collection.ts
3040
+ /**
3041
+ * Manages alternative format chunk parts in a document.
3042
+ *
3043
+ * Stores external content (HTML, RTF, plain text) that will be
3044
+ * serialized into separate parts in the DOCX package.
3045
+ */
3046
+ var AltChunkCollection = class {
3047
+ map;
3048
+ constructor() {
3049
+ this.map = /* @__PURE__ */ new Map();
3050
+ }
3051
+ addAltChunk(key, data) {
3052
+ this.map.set(key, data);
3053
+ }
3054
+ get array() {
3055
+ return [...this.map.values()];
3056
+ }
3057
+ };
3058
+ //#endregion
3059
+ //#region src/parts/sub-doc/sub-doc-collection.ts
3060
+ /**
3061
+ * Manages sub-document parts in a document.
3062
+ */
3063
+ var SubDocCollection = class {
3064
+ map;
3065
+ constructor() {
3066
+ this.map = /* @__PURE__ */ new Map();
3067
+ }
3068
+ addSubDoc(key, data) {
3069
+ this.map.set(key, data);
3070
+ }
3071
+ get array() {
3072
+ return [...this.map.values()];
3073
+ }
3074
+ };
3075
+ //#endregion
3076
+ //#region src/parts/fonts/descriptor.ts
3077
+ const NS = "xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\" xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\" xmlns:w16=\"http://schemas.microsoft.com/office/word/2018/wordml\" xmlns:w16cex=\"http://schemas.microsoft.com/office/word/2018/wordml/cex\" xmlns:w16cid=\"http://schemas.microsoft.com/office/word/2016/wordml/cid\" xmlns:w16sdtdh=\"http://schemas.microsoft.com/office/word/2020/wordml/sdtdatahash\" xmlns:w16se=\"http://schemas.microsoft.com/office/word/2015/wordml/symex\"";
3078
+ /** Default font signature for regular embedded fonts. */
3079
+ const DEFAULT_SIG = {
3080
+ usb0: "E0002AFF",
3081
+ usb1: "C000247B",
3082
+ usb2: "00000009",
3083
+ usb3: "00000000",
3084
+ csb0: "000001FF",
3085
+ csb1: "00000000"
3086
+ };
3087
+ function fontXml(font) {
3088
+ const parts = [`<w:font w:name="${escapeXml(font.name)}">`];
3089
+ if (font.altName) parts.push(`<w:altName w:val="${escapeXml(font.altName)}"/>`);
3090
+ if (font.panose1) parts.push(`<w:panose1 w:val="${escapeXml(font.panose1)}"/>`);
3091
+ if (font.characterSet || font.characterSetName) {
3092
+ const valAttr = font.characterSet ? ` w:val="${escapeXml(font.characterSet)}"` : "";
3093
+ const csAttr = font.characterSetName ? ` w:characterSet="${escapeXml(font.characterSetName)}"` : "";
3094
+ parts.push(`<w:charset${valAttr}${csAttr}/>`);
3095
+ }
3096
+ const family = font.family ?? (font.embedRid ? "auto" : void 0);
3097
+ if (family) parts.push(`<w:family w:val="${escapeXml(family)}"/>`);
3098
+ const pitch = font.pitch ?? (font.embedRid ? "variable" : void 0);
3099
+ if (pitch) parts.push(`<w:pitch w:val="${escapeXml(pitch)}"/>`);
3100
+ const sig = font.sig ?? (font.embedRid ? DEFAULT_SIG : void 0);
3101
+ if (sig) parts.push(`<w:sig w:usb0="${sig.usb0}" w:usb1="${sig.usb1}" w:usb2="${sig.usb2}" w:usb3="${sig.usb3}" w:csb0="${sig.csb0}" w:csb1="${sig.csb1}"/>`);
3102
+ if (font.embedRid) {
3103
+ const embedAttrs = [`r:id="${font.embedRid}"`, `w:fontKey="{${font.fontKey}}"`];
3104
+ if (font.subsetted !== void 0) embedAttrs.push(`w:subsetted="${font.subsetted ? 1 : 0}"`);
3105
+ parts.push(`<w:embedRegular ${embedAttrs.join(" ")}/>`);
3106
+ }
3107
+ parts.push("</w:font>");
3108
+ return parts.join("");
3109
+ }
3110
+ const fontTableDesc = {
3111
+ kind: "custom",
3112
+ stringify(opts, _ctx) {
3113
+ const parts = [`<w:fonts ${NS} mc:Ignorable="w14 w15 w16se w16cid w16 w16cex w16sdtdh">`];
3114
+ for (const font of opts.fonts) parts.push(fontXml(font));
3115
+ parts.push("</w:fonts>");
3116
+ return parts.join("");
3117
+ },
3118
+ parse(el, _ctx) {
3119
+ const fonts = [];
3120
+ for (const child of el.elements ?? []) {
3121
+ if (child.name !== "w:font") continue;
3122
+ const font = { fontKey: "" };
3123
+ const name = child.attributes?.["w:name"];
3124
+ if (name) font.name = String(name);
3125
+ const altNameEl = findChild(child, "w:altName");
3126
+ if (altNameEl) {
3127
+ const val = attr(altNameEl, "w:val");
3128
+ if (val) font.altName = val;
3129
+ }
3130
+ const panose1El = findChild(child, "w:panose1");
3131
+ if (panose1El) {
3132
+ const val = attr(panose1El, "w:val");
3133
+ if (val) font.panose1 = val;
3134
+ }
3135
+ const charsetEl = findChild(child, "w:charset");
3136
+ if (charsetEl) {
3137
+ const val = attr(charsetEl, "w:val");
3138
+ if (val) font.characterSet = val;
3139
+ const csName = attr(charsetEl, "w:characterSet");
3140
+ if (csName) font.characterSetName = csName;
3141
+ }
3142
+ const familyEl = findChild(child, "w:family");
3143
+ if (familyEl) {
3144
+ const val = attr(familyEl, "w:val");
3145
+ if (val) font.family = val;
3146
+ }
3147
+ const pitchEl = findChild(child, "w:pitch");
3148
+ if (pitchEl) {
3149
+ const val = attr(pitchEl, "w:val");
3150
+ if (val) font.pitch = val;
3151
+ }
3152
+ const sigEl = findChild(child, "w:sig");
3153
+ if (sigEl) {
3154
+ const sig = {
3155
+ usb0: "",
3156
+ usb1: "",
3157
+ usb2: "",
3158
+ usb3: "",
3159
+ csb0: "",
3160
+ csb1: ""
3161
+ };
3162
+ for (const key of [
3163
+ "usb0",
3164
+ "usb1",
3165
+ "usb2",
3166
+ "usb3",
3167
+ "csb0",
3168
+ "csb1"
3169
+ ]) {
3170
+ const val = attr(sigEl, `w:${key}`);
3171
+ if (val) sig[key] = val;
3172
+ }
3173
+ if (Object.values(sig).some(Boolean)) font.sig = sig;
3174
+ }
3175
+ const embedEl = findChild(child, "w:embedRegular");
3176
+ if (embedEl) {
3177
+ const rawKey = attr(embedEl, "w:fontKey");
3178
+ if (rawKey) font.fontKey = rawKey.replace(/^\{\{|\}\}$/g, "").replace(/^\{|\}$/g, "");
3179
+ const rid = attr(embedEl, "r:id");
3180
+ if (rid) font.embedRid = rid;
3181
+ const subsetted = attrBool(embedEl, "w:subsetted");
3182
+ if (subsetted !== void 0) font.subsetted = subsetted;
3183
+ }
3184
+ fonts.push(font);
3185
+ }
3186
+ return { fonts };
3187
+ }
3188
+ };
3189
+ //#endregion
3190
+ //#region src/parts/bibliography.ts
3191
+ const SOURCE_FIELDS = [
3192
+ ["SourceType", "type"],
3193
+ ["Title", "title"],
3194
+ ["Author", "author"],
3195
+ ["Year", "year"],
3196
+ ["Month", "month"],
3197
+ ["Day", "day"],
3198
+ ["BookTitle", "bookTitle"],
3199
+ ["JournalName", "journal"],
3200
+ ["Volume", "volume"],
3201
+ ["Issue", "issue"],
3202
+ ["Pages", "pages"],
3203
+ ["Publisher", "publisher"],
3204
+ ["City", "city"],
3205
+ ["URL", "url"],
3206
+ ["Edition", "edition"],
3207
+ ["Institution", "institution"]
3208
+ ];
3209
+ const bibliographyDesc = {
3210
+ kind: "custom",
3211
+ stringify(opts, _ctx) {
3212
+ const attrParts = ["xmlns:b=\"http://schemas.openxmlformats.org/officeDocument/2006/bibliography\""];
3213
+ if (opts.styleName !== void 0) attrParts.push(`StyleName="${escapeXml(opts.styleName)}"`);
3214
+ const parts = [`<b:Sources ${attrParts.join(" ")}>`];
3215
+ for (const source of opts.sources) {
3216
+ const sourceParts = [];
3217
+ for (const [tagName, key] of SOURCE_FIELDS) {
3218
+ const value = source[key];
3219
+ if (value !== void 0) sourceParts.push(`<b:${tagName}>${escapeXml(value)}</b:${tagName}>`);
3220
+ }
3221
+ parts.push(`<b:Source>${sourceParts.join("")}</b:Source>`);
3222
+ }
3223
+ parts.push("</b:Sources>");
3224
+ return parts.join("");
3225
+ },
3226
+ parse(el, _ctx) {
3227
+ const opts = {};
3228
+ const styleName = el.attributes?.["StyleName"];
3229
+ if (styleName) opts.styleName = styleName;
3230
+ const sources = [];
3231
+ for (const child of el.elements ?? []) {
3232
+ if (child.name !== "b:Source") continue;
3233
+ const source = {};
3234
+ for (const [, key] of SOURCE_FIELDS) {
3235
+ const xmlChild = findChild(child, `b:${SOURCE_FIELDS.find((f) => f[1] === key)[0]}`);
3236
+ if (xmlChild) {
3237
+ const val = textOf(xmlChild);
3238
+ if (val) source[key] = val;
3239
+ }
3240
+ }
3241
+ sources.push(source);
3242
+ }
3243
+ opts.sources = sources;
3244
+ return opts;
3245
+ }
3246
+ };
3247
+ //#endregion
3248
+ //#region src/parts/glossary-document.ts
3249
+ /** Gallery type for building blocks (ST_DocPartGallery) */
3250
+ const DocPartGallery = {
3251
+ PLACEHOLDER: "placeholder",
3252
+ DEFAULT: "default",
3253
+ DOC_PARTS: "docParts",
3254
+ COVER_PAGE: "coverPg",
3255
+ EQUATIONS: "eq",
3256
+ FOOTERS: "ftrs",
3257
+ HEADERS: "hdrs",
3258
+ PAGE_NUMBERS: "pgNum",
3259
+ TABLES: "tbls",
3260
+ WATERMARKS: "watermarks",
3261
+ AUTO_TEXT: "autoTxt",
3262
+ TEXT_BOX: "txtBox",
3263
+ PAGE_NUMBERS_TOP: "pgNumT",
3264
+ PAGE_NUMBERS_BOTTOM: "pgNumB",
3265
+ PAGE_NUMBERS_MARGIN: "pgNumMargins",
3266
+ TABLE_OF_CONTENTS: "tblOfContents",
3267
+ BIBLIOGRAPHY: "bib",
3268
+ CUSTOM_QUICK_PARTS: "custQuickParts",
3269
+ CUSTOM_COVER_PAGE: "custCoverPg",
3270
+ CUSTOM_EQUATIONS: "custEq",
3271
+ CUSTOM_FOOTERS: "custFtrs",
3272
+ CUSTOM_HEADERS: "custHdrs",
3273
+ CUSTOM_PAGE_NUMBERS: "custPgNum",
3274
+ CUSTOM_TABLES: "custTbls",
3275
+ CUSTOM_WATERMARKS: "custWatermarks",
3276
+ CUSTOM_AUTO_TEXT: "custAutoTxt",
3277
+ CUSTOM_TEXT_BOX: "custTxtBox",
3278
+ CUSTOM_PAGE_NUMBERS_TOP: "custPgNumT",
3279
+ CUSTOM_PAGE_NUMBERS_BOTTOM: "custPgNumB",
3280
+ CUSTOM_PAGE_NUMBERS_MARGIN: "custPgNumMargins",
3281
+ CUSTOM_TABLE_OF_CONTENTS: "custTblOfContents",
3282
+ CUSTOM_BIBLIOGRAPHY: "custBib",
3283
+ CUSTOM1: "custom1",
3284
+ CUSTOM2: "custom2",
3285
+ CUSTOM3: "custom3",
3286
+ CUSTOM4: "custom4",
3287
+ CUSTOM5: "custom5"
3288
+ };
3289
+ /** Building block type (ST_DocPartType) */
3290
+ const DocPartType = {
3291
+ NONE: "none",
3292
+ NORMAL: "normal",
3293
+ AUTO_EXPAND: "autoExp",
3294
+ TOOLBAR: "toolbar",
3295
+ SPELLER: "speller",
3296
+ FORM_FIELD: "formFld",
3297
+ BUILDING_BLOCK_PLACEHOLDER: "bbPlcHdr"
3298
+ };
3299
+ /** Building block behavior (ST_DocPartBehavior) */
3300
+ const DocPartBehavior = {
3301
+ CONTENT: "content",
3302
+ PARAGRAPH: "p",
3303
+ PAGE: "pg"
3304
+ };
3305
+ const GLOSSARY_NS = "xmlns:wpc=\"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" xmlns:w10=\"urn:schemas-microsoft-com:office:word\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\" xmlns:wpg=\"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup\" xmlns:wpi=\"http://schemas.microsoft.com/office/word/2010/wordprocessingInk\" xmlns:wne=\"http://schemas.microsoft.com/office/word/2006/wordml\" xmlns:wps=\"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\"";
3306
+ function docPartPrXml(part) {
3307
+ const prParts = [];
3308
+ prParts.push(`<w:name w:val="${escapeXml(part.name)}"${part.decorated ? " w:decorated=\"1\"" : ""}/>`);
3309
+ if (part.category || part.gallery) {
3310
+ const catParts = [];
3311
+ if (part.category) catParts.push(`<w:name w:val="${escapeXml(part.category)}"/>`);
3312
+ catParts.push(`<w:gallery w:val="${part.gallery}"/>`);
3313
+ prParts.push(`<w:category>${catParts.join("")}</w:category>`);
3314
+ }
3315
+ if (part.types && part.types.length > 0) {
3316
+ const typeXml = part.types.map((t) => `<w:type w:val="${t}"/>`).join("");
3317
+ const allAttr = part.allTypes ? " w:all=\"1\"" : "";
3318
+ prParts.push(`<w:types${allAttr}>${typeXml}</w:types>`);
3319
+ }
3320
+ if (part.behaviors && part.behaviors.length > 0) {
3321
+ const behaviorXml = part.behaviors.map((b) => `<w:behavior w:val="${b}"/>`).join("");
3322
+ prParts.push(`<w:behaviors>${behaviorXml}</w:behaviors>`);
3323
+ }
3324
+ if (part.description) prParts.push(`<w:description w:val="${escapeXml(part.description)}"/>`);
3325
+ if (part.guid) prParts.push(`<w:guid w:val="${escapeXml(part.guid)}"/>`);
3326
+ return `<w:docPartPr>${prParts.join("")}</w:docPartPr>`;
3327
+ }
3328
+ const glossaryDesc = {
3329
+ kind: "custom",
3330
+ stringify(opts, ctx) {
3331
+ return `<w:glossaryDocument ${GLOSSARY_NS}><w:docParts>${opts.parts.map((part) => {
3332
+ const bodyContent = (part.children ?? []).map((child) => ctx.stringifyChild(child, ctx)).join("");
3333
+ return `<w:docPart>${docPartPrXml(part)}<w:docPartBody>${bodyContent}</w:docPartBody></w:docPart>`;
3334
+ }).join("")}</w:docParts></w:glossaryDocument>`;
3335
+ },
3336
+ parse(el, ctx) {
3337
+ const dctx = ctx;
3338
+ const parts = [];
3339
+ const docPartsEl = findChild(el, "w:docParts");
3340
+ if (!docPartsEl) return { parts };
3341
+ for (const docPart of docPartsEl.elements ?? []) {
3342
+ if (docPart.name !== "w:docPart") continue;
3343
+ const part = {};
3344
+ const pr = findChild(docPart, "w:docPartPr");
3345
+ if (pr) {
3346
+ const name = findChild(pr, "w:name");
3347
+ if (name) {
3348
+ part.name = attr(name, "w:val") ?? "";
3349
+ if (attr(name, "w:decorated") === "1") part.decorated = true;
3350
+ }
3351
+ const category = findChild(pr, "w:category");
3352
+ if (category) {
3353
+ const catName = findChild(category, "w:name");
3354
+ if (catName) part.category = attr(catName, "w:val");
3355
+ const gallery = findChild(category, "w:gallery");
3356
+ if (gallery) part.gallery = attr(gallery, "w:val");
3357
+ }
3358
+ const types = findChild(pr, "w:types");
3359
+ if (types) {
3360
+ const typeList = [];
3361
+ for (const t of types.elements ?? []) if (t.name === "w:type") {
3362
+ const val = attr(t, "w:val");
3363
+ if (val) typeList.push(val);
3364
+ }
3365
+ if (typeList.length > 0) part.types = typeList;
3366
+ if (attr(types, "w:all") === "1") part.allTypes = true;
3367
+ }
3368
+ const behaviors = findChild(pr, "w:behaviors");
3369
+ if (behaviors) {
3370
+ const behaviorList = [];
3371
+ for (const b of behaviors.elements ?? []) if (b.name === "w:behavior") {
3372
+ const val = attr(b, "w:val");
3373
+ if (val) behaviorList.push(val);
3374
+ }
3375
+ if (behaviorList.length > 0) part.behaviors = behaviorList;
3376
+ }
3377
+ const desc = findChild(pr, "w:description");
3378
+ if (desc) {
3379
+ const val = attr(desc, "w:val");
3380
+ if (val) part.description = val;
3381
+ }
3382
+ const guid = findChild(pr, "w:guid");
3383
+ if (guid) {
3384
+ const val = attr(guid, "w:val");
3385
+ if (val) part.guid = val;
3386
+ }
3387
+ }
3388
+ const body = findChild(docPart, "w:docPartBody");
3389
+ if (body) {
3390
+ const childList = [];
3391
+ for (const sub of body.elements ?? []) if (sub.name === "w:p") childList.push({ paragraph: parseParagraph(sub, dctx) });
3392
+ if (childList.length > 0) part.children = childList;
3393
+ }
3394
+ parts.push(part);
3395
+ }
3396
+ return { parts };
3397
+ }
3398
+ };
3399
+ //#endregion
3400
+ //#region src/parts/contenttypes.ts
3401
+ /**
3402
+ * Content types descriptor — produces [Content_Types].xml.
3403
+ *
3404
+ * Reference: OPC, Content_Types.xsd
3405
+ *
3406
+ * @module
3407
+ */
3408
+ function defaultXml(ext, ct) {
3409
+ return `<Default Extension="${ext}" ContentType="${ct}"/>`;
3410
+ }
3411
+ function overrideXml(partName, ct) {
3412
+ return `<Override PartName="${partName}" ContentType="${ct}"/>`;
3413
+ }
3414
+ const contentTypesDesc = {
3415
+ kind: "custom",
3416
+ stringify(opts, _ctx) {
3417
+ const p = ["<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">"];
3418
+ const seenDefault = /* @__PURE__ */ new Set();
3419
+ for (const d of opts.defaults) {
3420
+ const key = d.extension.toLowerCase();
3421
+ if (seenDefault.has(key)) continue;
3422
+ seenDefault.add(key);
3423
+ p.push(defaultXml(d.extension, d.contentType));
3424
+ }
3425
+ const seenOverride = /* @__PURE__ */ new Set();
3426
+ for (const o of opts.overrides) {
3427
+ const key = o.partName.toLowerCase();
3428
+ if (seenOverride.has(key)) continue;
3429
+ seenOverride.add(key);
3430
+ p.push(overrideXml(o.partName, o.contentType));
3431
+ }
3432
+ p.push("</Types>");
3433
+ return p.join("");
3434
+ },
3435
+ parse(el, _ctx) {
3436
+ const defaults = [];
3437
+ const overrides = [];
3438
+ for (const child of el.elements ?? []) if (child.name === "Default") {
3439
+ const ext = child.attributes?.["Extension"];
3440
+ const ct = child.attributes?.["ContentType"];
3441
+ if (ext && ct) defaults.push({
3442
+ extension: String(ext),
3443
+ contentType: String(ct)
3444
+ });
3445
+ } else if (child.name === "Override") {
3446
+ const pn = child.attributes?.["PartName"];
3447
+ const ct = child.attributes?.["ContentType"];
3448
+ if (pn && ct) overrides.push({
3449
+ partName: String(pn),
3450
+ contentType: String(ct)
3451
+ });
3452
+ }
3453
+ return {
3454
+ defaults,
3455
+ overrides
3456
+ };
3457
+ }
3458
+ };
3459
+ /** Standard extension → content-type defaults covering every media type emitted. */
3460
+ const STANDARD_DEFAULTS = [
3461
+ {
3462
+ extension: "png",
3463
+ contentType: "image/png"
3464
+ },
3465
+ {
3466
+ extension: "jpeg",
3467
+ contentType: "image/jpeg"
3468
+ },
3469
+ {
3470
+ extension: "jpg",
3471
+ contentType: "image/jpeg"
3472
+ },
3473
+ {
3474
+ extension: "bmp",
3475
+ contentType: "image/bmp"
3476
+ },
3477
+ {
3478
+ extension: "gif",
3479
+ contentType: "image/gif"
3480
+ },
3481
+ {
3482
+ extension: "tif",
3483
+ contentType: "image/tiff"
3484
+ },
3485
+ {
3486
+ extension: "tiff",
3487
+ contentType: "image/tiff"
3488
+ },
3489
+ {
3490
+ extension: "emf",
3491
+ contentType: "image/x-emf"
3492
+ },
3493
+ {
3494
+ extension: "wmf",
3495
+ contentType: "image/x-wmf"
3496
+ },
3497
+ {
3498
+ extension: "ico",
3499
+ contentType: "image/x-icon"
3500
+ },
3501
+ {
3502
+ extension: "svg",
3503
+ contentType: "image/svg+xml"
3504
+ },
3505
+ {
3506
+ extension: "rels",
3507
+ contentType: "application/vnd.openxmlformats-package.relationships+xml"
3508
+ },
3509
+ {
3510
+ extension: "xml",
3511
+ contentType: "application/xml"
3512
+ },
3513
+ {
3514
+ extension: "odttf",
3515
+ contentType: "application/vnd.openxmlformats-officedocument.obfuscatedFont"
3516
+ },
3517
+ {
3518
+ extension: "bin",
3519
+ contentType: "application/vnd.openxmlformats-officedocument.oleObject"
3520
+ }
3521
+ ];
3522
+ /**
3523
+ * Ensure every media part in the package has a resolvable content-type Default.
3524
+ *
3525
+ * Round-tripped packages pass through the source's [Content_Types], which may
3526
+ * declare an uppercase extension (e.g. `JPG`) while the media is named `.jpg`.
3527
+ * OPC extension matching is **case-insensitive** (ECMA-376-2 §10.1.2), so `JPG`
3528
+ * and `jpg` are one key — emitting both yields a duplicate default that Word
3529
+ * rejects as unreadable content. Match existing defaults case-insensitively so
3530
+ * we never add a colliding extension; the media then resolves through the
3531
+ * source's already-declared default.
3532
+ */
3533
+ function withMediaDefaults(input, mediaFileNames) {
3534
+ const have = new Set(input.defaults.map((d) => d.extension.toLowerCase()));
3535
+ const standard = new Map(STANDARD_DEFAULTS.map((d) => [d.extension, d.contentType]));
3536
+ const defaults = [...input.defaults];
3537
+ for (const fileName of mediaFileNames) {
3538
+ const ext = fileName.slice(fileName.lastIndexOf(".") + 1);
3539
+ const key = ext.toLowerCase();
3540
+ if (!ext || have.has(key)) continue;
3541
+ const contentType = standard.get(key);
3542
+ if (contentType) {
3543
+ defaults.push({
3544
+ extension: ext,
3545
+ contentType
3546
+ });
3547
+ have.add(key);
3548
+ }
3549
+ }
3550
+ return {
3551
+ defaults,
3552
+ overrides: input.overrides
3553
+ };
3554
+ }
3555
+ /** Default content types for altChunk part extensions. */
3556
+ const ALTCHUNK_DEFAULTS = {
3557
+ html: "text/html",
3558
+ rtf: "application/rtf",
3559
+ txt: "text/plain"
3560
+ };
3561
+ /**
3562
+ * Realign [Content_Types] Overrides for altChunk parts on a round-tripped
3563
+ * package. The pass-through content types carry Override PartNames from the
3564
+ * source, but the compiler regenerates altChunk part paths (uniqueId), so the
3565
+ * Override and the written part drift apart (O5/O6). This drops the stale
3566
+ * afchunk Overrides and appends ones matching the freshly generated paths,
3567
+ * backfilling the extension Default so the part is resolvable either way.
3568
+ */
3569
+ function withAltChunkOverrides(input, altChunks) {
3570
+ const defaults = [...input.defaults];
3571
+ const haveExt = new Set(defaults.map((d) => d.extension.toLowerCase()));
3572
+ for (const ac of altChunks) {
3573
+ const ext = (ac.path.split(".").pop() ?? "").toLowerCase();
3574
+ if (ext && !haveExt.has(ext) && ALTCHUNK_DEFAULTS[ext]) {
3575
+ defaults.push({
3576
+ extension: ext,
3577
+ contentType: ALTCHUNK_DEFAULTS[ext]
3578
+ });
3579
+ haveExt.add(ext);
3580
+ }
3581
+ }
3582
+ const overrides = input.overrides.filter((o) => !o.partName.startsWith("/word/afchunks/"));
3583
+ for (const ac of altChunks) {
3584
+ const partName = ac.path.startsWith("/") ? ac.path : `/${ac.path}`;
3585
+ overrides.push({
3586
+ partName,
3587
+ contentType: ac.contentType
3588
+ });
3589
+ }
3590
+ return {
3591
+ defaults,
3592
+ overrides
3593
+ };
3594
+ }
3595
+ /**
3596
+ * Build [Content_Types].xml for a fresh DOCX compile, driven by the part
3597
+ * registry. Static parts (document/styles/…/comments/headers/…) come from
3598
+ * {@link buildContentTypeOverrides} over {@link DOCX_PARTS}; dynamic parts whose
3599
+ * path or count is runtime-determined (altChunks, sub-documents) are appended
3600
+ * here — they are not enumerable in the registry.
3601
+ *
3602
+ * `facts` keys mirror the registry's `flag` / `countFrom` tokens. The Override
3603
+ * set (order-independent) matches the former hand-written builder, so the OPC
3604
+ * consistency validator stays green.
3605
+ */
3606
+ function buildContentTypesFromRegistry(facts, dynamic = {}) {
3607
+ const overrides = buildContentTypeOverrides(DOCX_PARTS, facts);
3608
+ for (const ac of dynamic.altChunks ?? []) overrides.push({
3609
+ partName: ac.path.startsWith("/") ? ac.path : `/${ac.path}`,
3610
+ contentType: ac.contentType
3611
+ });
3612
+ for (const sd of dynamic.subDocs ?? []) overrides.push({
3613
+ partName: sd.path.startsWith("/") ? sd.path : `/${sd.path}`,
3614
+ contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
3615
+ });
3616
+ const defaults = [{
3617
+ extension: "rels",
3618
+ contentType: "application/vnd.openxmlformats-package.relationships+xml"
3619
+ }, {
3620
+ extension: "xml",
3621
+ contentType: "application/xml"
3622
+ }];
3623
+ const haveExt = new Set(["rels", "xml"]);
3624
+ for (const ac of dynamic.altChunks ?? []) {
3625
+ const ext = (ac.path.split(".").pop() ?? "").toLowerCase();
3626
+ if (ext && !haveExt.has(ext) && ALTCHUNK_DEFAULTS[ext]) {
3627
+ defaults.push({
3628
+ extension: ext,
3629
+ contentType: ALTCHUNK_DEFAULTS[ext]
3630
+ });
3631
+ haveExt.add(ext);
3632
+ }
3633
+ }
3634
+ return {
3635
+ defaults,
3636
+ overrides
3637
+ };
3638
+ }
3639
+ //#endregion
3640
+ //#region src/parts/core-properties.ts
3641
+ const corePropertiesDesc = {
3642
+ kind: "custom",
3643
+ stringify(opts, _ctx) {
3644
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3645
+ const p = ["<cp:coreProperties xmlns:cp=\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:dcmitype=\"http://purl.org/dc/dcmitype/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"];
3646
+ p.push(`<dcterms:created xsi:type="dcterms:W3CDTF">${opts.created ?? now}</dcterms:created>`);
3647
+ if (opts.creator) p.push(`<dc:creator>${escapeXml(opts.creator)}</dc:creator>`);
3648
+ if (opts.description) p.push(`<dc:description>${escapeXml(opts.description)}</dc:description>`);
3649
+ if (opts.keywords) p.push(`<cp:keywords>${escapeXml(opts.keywords)}</cp:keywords>`);
3650
+ if (opts.lastModifiedBy) p.push(`<cp:lastModifiedBy>${escapeXml(opts.lastModifiedBy)}</cp:lastModifiedBy>`);
3651
+ if (opts.lastPrinted) p.push(`<cp:lastPrinted>${escapeXml(opts.lastPrinted)}</cp:lastPrinted>`);
3652
+ p.push(`<dcterms:modified xsi:type="dcterms:W3CDTF">${opts.modified ?? now}</dcterms:modified>`);
3653
+ if (opts.revision !== void 0) p.push(`<cp:revision>${opts.revision}</cp:revision>`);
3654
+ if (opts.subject) p.push(`<dc:subject>${escapeXml(opts.subject)}</dc:subject>`);
3655
+ if (opts.title) p.push(`<dc:title>${escapeXml(opts.title)}</dc:title>`);
3656
+ p.push("</cp:coreProperties>");
3657
+ return p.join("");
3658
+ },
3659
+ parse(el, _ctx) {
3660
+ const result = {};
3661
+ for (const child of el.elements ?? []) {
3662
+ if (typeof child.name !== "string") continue;
3663
+ const text = child.elements?.[0]?.text;
3664
+ if (typeof text !== "string") continue;
3665
+ switch (child.name) {
3666
+ case "dc:title":
3667
+ result.title = text;
3668
+ break;
3669
+ case "dc:subject":
3670
+ result.subject = text;
3671
+ break;
3672
+ case "dc:creator":
3673
+ result.creator = text;
3674
+ break;
3675
+ case "cp:keywords":
3676
+ result.keywords = text;
3677
+ break;
3678
+ case "dc:description":
3679
+ result.description = text;
3680
+ break;
3681
+ case "cp:lastModifiedBy":
3682
+ result.lastModifiedBy = text;
3683
+ break;
3684
+ case "cp:revision":
3685
+ result.revision = Number(text);
3686
+ break;
3687
+ case "cp:lastPrinted":
3688
+ result.lastPrinted = text;
3689
+ break;
3690
+ case "dcterms:created":
3691
+ result.created = text;
3692
+ break;
3693
+ case "dcterms:modified":
3694
+ result.modified = text;
3695
+ break;
3696
+ }
3697
+ }
3698
+ return result;
3699
+ }
3700
+ };
3701
+ //#endregion
3702
+ //#region src/parts/web-settings.ts
3703
+ /**
3704
+ * Screen size types for web settings target.
3705
+ */
3706
+ const TargetScreenSize = {
3707
+ SIZE_544X376: "544x376",
3708
+ SIZE_640X480: "640x480",
3709
+ SIZE_720X512: "720x512",
3710
+ SIZE_800X600: "800x600",
3711
+ SIZE_1024X768: "1024x768",
3712
+ SIZE_1152X882: "1152x882",
3713
+ SIZE_1152X900: "1152x900",
3714
+ SIZE_1280X1024: "1280x1024",
3715
+ SIZE_1600X1200: "1600x1200",
3716
+ SIZE_1800X1440: "1800x1440",
3717
+ SIZE_1920X1200: "1920x1200"
3718
+ };
3719
+ const WS_NS = "xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\"";
3720
+ function wsOnOff(tag, val) {
3721
+ return `<${tag} w:val="${val ? "true" : "false"}"/>`;
3722
+ }
3723
+ function wsStringVal(tag, val) {
3724
+ return `<${tag} w:val="${escapeXml(val)}"/>`;
3725
+ }
3726
+ function wsNumVal(tag, val) {
3727
+ return `<${tag} w:val="${val}"/>`;
3728
+ }
3729
+ function parseFramesetEl(el) {
3730
+ const opts = {};
3731
+ const sz = findChild(el, "w:sz");
3732
+ if (sz) {
3733
+ const val = attr(sz, "w:val");
3734
+ if (val) opts.size = val;
3735
+ }
3736
+ const splitbar = findChild(el, "w:framesetSplitbar");
3737
+ if (splitbar) opts.splitbar = parseSplitbarEl(splitbar);
3738
+ const layout = findChild(el, "w:frameLayout");
3739
+ if (layout) {
3740
+ const val = attr(layout, "w:val");
3741
+ if (val === "rows" || val === "cols") opts.layout = val;
3742
+ }
3743
+ const title = findChild(el, "w:title");
3744
+ if (title) {
3745
+ const val = attr(title, "w:val");
3746
+ if (val) opts.title = val;
3747
+ }
3748
+ const children = [];
3749
+ for (const child of el.elements ?? []) if (child.name === "w:frameset") children.push(parseFramesetEl(child));
3750
+ else if (child.name === "w:frame") children.push(parseFrameEl(child));
3751
+ if (children.length > 0) opts.children = children;
3752
+ return opts;
3753
+ }
3754
+ function parseSplitbarEl(el) {
3755
+ const opts = {};
3756
+ const w = findChild(el, "w:w");
3757
+ if (w) {
3758
+ const val = attrNum(w, "w:w");
3759
+ if (val !== void 0) opts.width = val;
3760
+ }
3761
+ const color = findChild(el, "w:color");
3762
+ if (color) {
3763
+ const val = attr(color, "w:val");
3764
+ if (val) opts.color = val;
3765
+ }
3766
+ if (findChild(el, "w:noBorder")) opts.noBorder = true;
3767
+ if (findChild(el, "w:flatBorders")) opts.flatBorders = true;
3768
+ return opts;
3769
+ }
3770
+ function parseFrameEl(el) {
3771
+ const opts = {};
3772
+ const sz = findChild(el, "w:sz");
3773
+ if (sz) {
3774
+ const val = attr(sz, "w:val");
3775
+ if (val) opts.size = val;
3776
+ }
3777
+ const name = findChild(el, "w:name");
3778
+ if (name) {
3779
+ const val = attr(name, "w:val");
3780
+ if (val) opts.name = val;
3781
+ }
3782
+ const title = findChild(el, "w:title");
3783
+ if (title) {
3784
+ const val = attr(title, "w:val");
3785
+ if (val) opts.title = val;
3786
+ }
3787
+ const source = findChild(el, "w:sourceFileName");
3788
+ if (source) {
3789
+ const val = attr(source, "r:id");
3790
+ if (val) opts.sourceRId = val;
3791
+ }
3792
+ const marW = findChild(el, "w:marW");
3793
+ if (marW) {
3794
+ const val = attrNum(marW, "w:val");
3795
+ if (val !== void 0) opts.marginWidth = val;
3796
+ }
3797
+ const marH = findChild(el, "w:marH");
3798
+ if (marH) {
3799
+ const val = attrNum(marH, "w:val");
3800
+ if (val !== void 0) opts.marginHeight = val;
3801
+ }
3802
+ const scrollbar = findChild(el, "w:scrollbar");
3803
+ if (scrollbar) {
3804
+ const val = attr(scrollbar, "w:val");
3805
+ if (val === "on" || val === "off" || val === "auto") opts.scrollbar = val;
3806
+ }
3807
+ if (findChild(el, "w:noResizeAllowed")) opts.noResizeAllowed = true;
3808
+ if (findChild(el, "w:linkedToFile")) opts.linkedToFile = true;
3809
+ const longDesc = findChild(el, "w:longDesc");
3810
+ if (longDesc) {
3811
+ const val = attr(longDesc, "r:id");
3812
+ if (val) opts.longDescRId = val;
3813
+ }
3814
+ return opts;
3815
+ }
3816
+ function parseDivsEl(el) {
3817
+ const result = [];
3818
+ for (const child of el.elements ?? []) if (child.name === "w:div") result.push(parseDivEl(child));
3819
+ return result;
3820
+ }
3821
+ function parseDivEl(el) {
3822
+ const opts = { id: attrNum(el, "w:id") ?? 0 };
3823
+ const marLeft = findChild(el, "w:marLeft");
3824
+ if (marLeft) {
3825
+ const val = attrMeasure(marLeft, "w:val");
3826
+ if (val !== void 0) opts.marginLeft = val;
3827
+ }
3828
+ const marRight = findChild(el, "w:marRight");
3829
+ if (marRight) {
3830
+ const val = attrMeasure(marRight, "w:val");
3831
+ if (val !== void 0) opts.marginRight = val;
3832
+ }
3833
+ const marTop = findChild(el, "w:marTop");
3834
+ if (marTop) {
3835
+ const val = attrMeasure(marTop, "w:val");
3836
+ if (val !== void 0) opts.marginTop = val;
3837
+ }
3838
+ const marBottom = findChild(el, "w:marBottom");
3839
+ if (marBottom) {
3840
+ const val = attrMeasure(marBottom, "w:val");
3841
+ if (val !== void 0) opts.marginBottom = val;
3842
+ }
3843
+ const blockQuote = findChild(el, "w:blockQuote");
3844
+ if (blockQuote) opts.blockQuote = attr(blockQuote, "w:val") !== "off";
3845
+ const bodyDiv = findChild(el, "w:bodyDiv");
3846
+ if (bodyDiv) opts.bodyDiv = attr(bodyDiv, "w:val") !== "off";
3847
+ const divBdr = findChild(el, "w:divBdr");
3848
+ if (divBdr) opts.border = parseDivBorderEl(divBdr);
3849
+ const divsChild = findChild(el, "w:divsChild");
3850
+ if (divsChild) {
3851
+ const children = parseDivsEl(divsChild);
3852
+ if (children.length > 0) opts.children = children;
3853
+ }
3854
+ return opts;
3855
+ }
3856
+ function parseDivBorderEl(el) {
3857
+ const opts = {};
3858
+ for (const side of [
3859
+ "top",
3860
+ "left",
3861
+ "bottom",
3862
+ "right"
3863
+ ]) {
3864
+ const sideEl = findChild(el, `w:${side}`);
3865
+ if (sideEl) {
3866
+ const b = {};
3867
+ const val = attr(sideEl, "w:val");
3868
+ if (val) b.style = val;
3869
+ const color = attr(sideEl, "w:color");
3870
+ if (color) b.color = color;
3871
+ const sz = attrNum(sideEl, "w:sz");
3872
+ if (sz !== void 0) b.size = sz;
3873
+ opts[side] = b;
3874
+ }
3875
+ }
3876
+ return opts;
3877
+ }
3878
+ function wsDivBorderXml(b) {
3879
+ const parts = ["<w:divBdr>"];
3880
+ const sides = [
3881
+ ["w:top", b.top],
3882
+ ["w:left", b.left],
3883
+ ["w:bottom", b.bottom],
3884
+ ["w:right", b.right]
3885
+ ];
3886
+ for (const [tag, side] of sides) {
3887
+ if (!side) continue;
3888
+ const attrParts = [`w:val="${escapeXml(side.style)}"`];
3889
+ if (side.color) attrParts.push(`w:color="${escapeXml(side.color)}"`);
3890
+ if (side.size !== void 0) attrParts.push(`w:sz="${side.size}"`);
3891
+ parts.push(`<${tag} ${attrParts.join(" ")}/>`);
3892
+ }
3893
+ parts.push("</w:divBdr>");
3894
+ return parts.join("");
3895
+ }
3896
+ function wsDivXml(d) {
3897
+ const parts = [`<w:div w:id="${d.id}">`];
3898
+ if (d.blockQuote !== void 0) parts.push(wsStringVal("w:blockQuote", d.blockQuote ? "on" : "off"));
3899
+ if (d.bodyDiv !== void 0) parts.push(wsStringVal("w:bodyDiv", d.bodyDiv ? "on" : "off"));
3900
+ parts.push(wsNumVal("w:marLeft", d.marginLeft));
3901
+ parts.push(wsNumVal("w:marRight", d.marginRight));
3902
+ parts.push(wsNumVal("w:marTop", d.marginTop));
3903
+ parts.push(wsNumVal("w:marBottom", d.marginBottom));
3904
+ if (d.border) parts.push(wsDivBorderXml(d.border));
3905
+ if (d.children?.length) {
3906
+ parts.push("<w:divsChild>");
3907
+ for (const child of d.children) parts.push(wsDivXml(child));
3908
+ parts.push("</w:divsChild>");
3909
+ }
3910
+ parts.push("</w:div>");
3911
+ return parts.join("");
3912
+ }
3913
+ function framesetXml(fs) {
3914
+ const parts = ["<w:frameset>"];
3915
+ if (fs.size !== void 0) parts.push(wsStringVal("w:sz", fs.size));
3916
+ if (fs.splitbar) {
3917
+ parts.push("<w:framesetSplitbar>");
3918
+ if (fs.splitbar.width !== void 0) parts.push(`<w:w w:w="${fs.splitbar.width}" w:type="dxa"/>`);
3919
+ if (fs.splitbar.color !== void 0) parts.push(wsStringVal("w:color", fs.splitbar.color));
3920
+ if (fs.splitbar.noBorder) parts.push("<w:noBorder/>");
3921
+ if (fs.splitbar.flatBorders) parts.push("<w:flatBorders/>");
3922
+ parts.push("</w:framesetSplitbar>");
3923
+ }
3924
+ if (fs.layout !== void 0) parts.push(`<w:frameLayout w:val="${fs.layout}"/>`);
3925
+ if (fs.title !== void 0) parts.push(wsStringVal("w:title", fs.title));
3926
+ if (fs.children) for (const child of fs.children) if ("children" in child || "layout" in child || "splitbar" in child) parts.push(framesetXml(child));
3927
+ else parts.push(frameXml(child));
3928
+ parts.push("</w:frameset>");
3929
+ return parts.join("");
3930
+ }
3931
+ function frameXml(f) {
3932
+ const parts = ["<w:frame>"];
3933
+ if (f.size !== void 0) parts.push(wsStringVal("w:sz", f.size));
3934
+ if (f.name !== void 0) parts.push(wsStringVal("w:name", f.name));
3935
+ if (f.title !== void 0) parts.push(wsStringVal("w:title", f.title));
3936
+ if (f.sourceRId !== void 0) parts.push(`<w:sourceFileName r:id="${escapeXml(f.sourceRId)}"/>`);
3937
+ if (f.marginWidth !== void 0) parts.push(wsNumVal("w:marW", f.marginWidth));
3938
+ if (f.marginHeight !== void 0) parts.push(wsNumVal("w:marH", f.marginHeight));
3939
+ if (f.scrollbar !== void 0) parts.push(`<w:scrollbar w:val="${f.scrollbar}"/>`);
3940
+ if (f.noResizeAllowed) parts.push("<w:noResizeAllowed/>");
3941
+ if (f.linkedToFile) parts.push("<w:linkedToFile/>");
3942
+ if (f.longDescRId !== void 0) parts.push(`<w:longDesc r:id="${escapeXml(f.longDescRId)}"/>`);
3943
+ parts.push("</w:frame>");
3944
+ return parts.join("");
3945
+ }
3946
+ const webSettingsDesc = {
3947
+ kind: "custom",
3948
+ stringify(opts, _ctx) {
3949
+ const p = [`<w:webSettings ${WS_NS}>`];
3950
+ if (opts.frameset !== void 0) p.push(framesetXml(opts.frameset));
3951
+ if (opts.divs?.length) {
3952
+ p.push("<w:divs>");
3953
+ for (const d of opts.divs) p.push(wsDivXml(d));
3954
+ p.push("</w:divs>");
3955
+ }
3956
+ if (opts.encoding !== void 0) p.push(wsStringVal("w:encoding", opts.encoding));
3957
+ if (opts.optimizeForBrowser !== void 0) {
3958
+ const ob = opts.optimizeForBrowser;
3959
+ if (typeof ob === "boolean") p.push(wsOnOff("w:optimizeForBrowser", ob));
3960
+ else {
3961
+ const valAttr = ob.value === false ? " w:val=\"false\"" : "";
3962
+ const targetAttr = ob.target ? ` w:target="${escapeXml(ob.target)}"` : "";
3963
+ p.push(`<w:optimizeForBrowser${valAttr}${targetAttr}/>`);
3964
+ }
3965
+ }
3966
+ if (opts.relyOnVML !== void 0) p.push(wsOnOff("w:relyOnVML", opts.relyOnVML));
3967
+ if (opts.allowPNG !== void 0) p.push(wsOnOff("w:allowPNG", opts.allowPNG));
3968
+ if (opts.doNotRelyOnCSS !== void 0) p.push(wsOnOff("w:doNotRelyOnCSS", opts.doNotRelyOnCSS));
3969
+ if (opts.doNotSaveAsSingleFile !== void 0) p.push(wsOnOff("w:doNotSaveAsSingleFile", opts.doNotSaveAsSingleFile));
3970
+ if (opts.doNotOrganizeInFolder !== void 0) p.push(wsOnOff("w:doNotOrganizeInFolder", opts.doNotOrganizeInFolder));
3971
+ if (opts.doNotUseLongFileNames !== void 0) p.push(wsOnOff("w:doNotUseLongFileNames", opts.doNotUseLongFileNames));
3972
+ if (opts.pixelsPerInch !== void 0) p.push(wsNumVal("w:pixelsPerInch", opts.pixelsPerInch));
3973
+ if (opts.targetScreenSize !== void 0) p.push(wsStringVal("w:targetScreenSz", opts.targetScreenSize));
3974
+ if (opts.saveSmartTagsAsXml !== void 0) p.push(wsOnOff("w:saveSmartTagsAsXml", opts.saveSmartTagsAsXml));
3975
+ p.push("</w:webSettings>");
3976
+ return p.join("");
3977
+ },
3978
+ parse(el, _ctx) {
3979
+ const opts = {};
3980
+ const frameset = findChild(el, "w:frameset");
3981
+ if (frameset) opts.frameset = parseFramesetEl(frameset);
3982
+ const divs = findChild(el, "w:divs");
3983
+ if (divs) {
3984
+ const parsed = parseDivsEl(divs);
3985
+ if (parsed.length > 0) opts.divs = parsed;
3986
+ }
3987
+ const encoding = findChild(el, "w:encoding");
3988
+ if (encoding) {
3989
+ const val = attr(encoding, "w:val");
3990
+ if (val) opts.encoding = val;
3991
+ }
3992
+ for (const [name, optKey] of [
3993
+ ["w:relyOnVML", "relyOnVML"],
3994
+ ["w:allowPNG", "allowPNG"],
3995
+ ["w:doNotRelyOnCSS", "doNotRelyOnCSS"],
3996
+ ["w:doNotSaveAsSingleFile", "doNotSaveAsSingleFile"],
3997
+ ["w:doNotOrganizeInFolder", "doNotOrganizeInFolder"],
3998
+ ["w:doNotUseLongFileNames", "doNotUseLongFileNames"],
3999
+ ["w:saveSmartTagsAsXml", "saveSmartTagsAsXml"]
4000
+ ]) {
4001
+ const child = findChild(el, name);
4002
+ if (child) opts[optKey] = attrBool(child, "w:val") ?? true;
4003
+ }
4004
+ const obEl = findChild(el, "w:optimizeForBrowser");
4005
+ if (obEl) {
4006
+ const target = attr(obEl, "w:target");
4007
+ if (target) opts.optimizeForBrowser = {
4008
+ value: attrBool(obEl, "w:val") ?? true,
4009
+ target
4010
+ };
4011
+ else opts.optimizeForBrowser = attrBool(obEl, "w:val") ?? true;
4012
+ }
4013
+ const ppi = findChild(el, "w:pixelsPerInch");
4014
+ if (ppi) {
4015
+ const val = attrNum(ppi, "w:val");
4016
+ if (val !== void 0) opts.pixelsPerInch = val;
4017
+ }
4018
+ const targetScreenSize = findChild(el, "w:targetScreenSz");
4019
+ if (targetScreenSize) {
4020
+ const val = attr(targetScreenSize, "w:val");
4021
+ if (val) opts.targetScreenSize = val;
4022
+ }
4023
+ return opts;
4024
+ }
4025
+ };
4026
+ //#endregion
4027
+ //#region src/parts/styles/external-styles-factory.ts
4028
+ /**
4029
+ * External styles factory module for WordprocessingML documents.
4030
+ *
4031
+ * Parses styles from external XML and returns raw XML strings.
4032
+ * No XmlComponent dependency.
4033
+ *
4034
+ * Reference: http://officeopenxml.com/WPstyles.php
4035
+ *
4036
+ * @module
4037
+ */
4038
+ /**
4039
+ * Factory for creating styles from external XML sources.
4040
+ *
4041
+ * Parses styles from XML (typically from a styles.xml file)
4042
+ * and returns raw XML strings for each style element.
4043
+ */
4044
+ var ExternalStylesFactory = class {
4045
+ /**
4046
+ * Creates new Styles based on the given XML data.
4047
+ *
4048
+ * Parses the styles XML and converts each child to a raw XML string.
4049
+ */
4050
+ newInstance(xmlData) {
4051
+ const xmlObj = xml2js(xmlData, { compact: false });
4052
+ let stylesXmlElement;
4053
+ for (const xmlElm of xmlObj.elements || []) if (xmlElm.name === "w:styles") stylesXmlElement = xmlElm;
4054
+ if (stylesXmlElement === void 0) return {
4055
+ importedStyles: [],
4056
+ initialAttributes: {}
4057
+ };
4058
+ return {
4059
+ importedStyles: (stylesXmlElement.elements || []).map((childElm) => ({ _raw: js2xml({ elements: [childElm] }) })),
4060
+ initialAttributes: stylesXmlElement.attributes ?? {}
4061
+ };
4062
+ }
4063
+ };
4064
+ //#endregion
4065
+ //#region src/shared/embeddings/embeddings.ts
4066
+ /**
4067
+ * Collects OLE embeddings allocated during document generation. Each embedding
4068
+ * is stored under a sequential `oleObjectN.bin` name in word/embeddings/,
4069
+ * mirroring MS Office's numbering so output is deterministic and diffable.
4070
+ */
4071
+ var EmbeddingCollection = class {
4072
+ map = /* @__PURE__ */ new Map();
4073
+ counter = 0;
4074
+ /** Allocate the next sequential embedding file name (oleObject1.bin, …). */
4075
+ nextEmbeddingName() {
4076
+ return `oleObject${++this.counter}.bin`;
4077
+ }
4078
+ /** Register an embedding under a unique key. */
4079
+ addEmbedding(key, data) {
4080
+ this.map.set(key, data);
4081
+ }
4082
+ /** All registered embeddings in insertion order. */
4083
+ get array() {
4084
+ return [...this.map.values()];
4085
+ }
4086
+ };
4087
+ //#endregion
4088
+ //#region src/context.ts
4089
+ /**
4090
+ * DOCX compilation context.
4091
+ *
4092
+ * DocxWriteContext holds all mutable state needed during document compilation.
4093
+ * generateDocument() creates a DocxWriteContext internally.
4094
+ *
4095
+ * @module
4096
+ */
4097
+ /** User styles override factory defaults with the same styleId; keep the rest. */
4098
+ function mergeById(factoryStyles, userStyles) {
4099
+ const factory = factoryStyles ?? [];
4100
+ if (!userStyles || userStyles.length === 0) return factory;
4101
+ const userIds = new Set(userStyles.map((s) => s.id));
4102
+ return [...factory.filter((s) => !userIds.has(s.id)), ...userStyles];
4103
+ }
4104
+ /**
4105
+ * Highest comment id in an explicit comments list, or -1 when there are none.
4106
+ * Seeds the comment id allocator so auto-allocated ids never collide with ids
4107
+ * the caller already assigned (e.g. round-tripped from an existing document).
4108
+ */
4109
+ function maxCommentId(comments) {
4110
+ let max = -1;
4111
+ if (comments) {
4112
+ for (const c of comments) if (c.id > max) max = c.id;
4113
+ }
4114
+ return max;
4115
+ }
4116
+ /** Narrows an object to a `{ id: number }` marker without an `as` cast. */
4117
+ function isNumericIdMarker(value) {
4118
+ return typeof value === "object" && value !== null && "id" in value && typeof value.id === "number";
4119
+ }
4120
+ /**
4121
+ * Highest w:id among explicit bookmark + move-range start markers (`range`) and
4122
+ * explicit movedFrom/movedTo runs (`moveRun`) anywhere in the body tree
4123
+ * (paragraphs, tables, textboxes, SDTs, headers/footers nested in sections).
4124
+ * Seeds the markup id allocators so `{ bookmark }` / `{ moveFrom }` / `{ moveTo }`
4125
+ * sugars never collide with ids the caller already assigned. Comment ids live in
4126
+ * their own namespace (comments.nextId) and are intentionally excluded.
4127
+ */
4128
+ function collectMaxMarkupIds(value, acc) {
4129
+ if (value === null || value === void 0 || typeof value !== "object") return;
4130
+ if (value instanceof Uint8Array || value instanceof Date) return;
4131
+ if (Array.isArray(value)) {
4132
+ for (const item of value) collectMaxMarkupIds(item, acc);
4133
+ return;
4134
+ }
4135
+ const obj = value;
4136
+ const rangeMarker = obj.bookmarkStart ?? obj.moveFromRangeStart ?? obj.moveToRangeStart;
4137
+ if (isNumericIdMarker(rangeMarker) && rangeMarker.id > acc.range) acc.range = rangeMarker.id;
4138
+ const moveRun = obj.movedFrom ?? obj.movedTo;
4139
+ if (isNumericIdMarker(moveRun) && moveRun.id > acc.moveRun) acc.moveRun = moveRun.id;
4140
+ for (const key of Object.keys(obj)) collectMaxMarkupIds(obj[key], acc);
4141
+ }
4142
+ /**
4143
+ * Whether any `{ comment }` sugar child appears anywhere in the body tree
4144
+ * (paragraphs, tables, textboxes, SDTs, headers/footers nested in sections).
4145
+ * The document→comments relationship must exist whenever comments.xml will be
4146
+ * generated; since sugar entries are registered during stringify — after the
4147
+ * constructor wires relationships — this pre-scan predicts them so the part and
4148
+ * its relationship stay in sync (OPC consistency). Every `{ comment }` always
4149
+ * stringifies, so the prediction matches the entries actually registered.
4150
+ */
4151
+ function bodyContainsCommentSugar(value) {
4152
+ if (value === null || value === void 0) return false;
4153
+ if (typeof value !== "object") return false;
4154
+ if (value instanceof Uint8Array || value instanceof Date) return false;
4155
+ if (Array.isArray(value)) {
4156
+ for (const item of value) if (bodyContainsCommentSugar(item)) return true;
4157
+ return false;
4158
+ }
4159
+ const obj = value;
4160
+ if (typeof obj.comment === "object" && obj.comment !== null) return true;
4161
+ for (const key of Object.keys(obj)) if (bodyContainsCommentSugar(obj[key])) return true;
4162
+ return false;
4163
+ }
4164
+ var DocxWriteContext = class {
4165
+ _currentRelationshipId = 1;
4166
+ _sectionProperties = [];
4167
+ get sectionProperties() {
4168
+ return this._sectionProperties;
4169
+ }
4170
+ _hasFootnotes;
4171
+ _hasEndnotes;
4172
+ _hasNumbering;
4173
+ get hasFootnotes() {
4174
+ return this._hasFootnotes;
4175
+ }
4176
+ get hasEndnotes() {
4177
+ return this._hasEndnotes;
4178
+ }
4179
+ get hasNumbering() {
4180
+ return this._hasNumbering;
4181
+ }
4182
+ addRelationship(_type, _target, _mode) {
4183
+ return `rId${this._currentRelationshipId++}`;
4184
+ }
4185
+ addMedia(data, type) {
4186
+ return `{${this.media.addMedia(data, type, (fileName) => ({
4187
+ data,
4188
+ fileName,
4189
+ type,
4190
+ transformation: {
4191
+ pixels: {
4192
+ x: 0,
4193
+ y: 0
4194
+ },
4195
+ emus: {
4196
+ x: 0,
4197
+ y: 0
4198
+ }
4199
+ }
4200
+ })).fileName}}`;
4201
+ }
4202
+ _headers = [];
4203
+ _footers = [];
4204
+ constructor(options) {
4205
+ this._options = options;
4206
+ this.numbering = new Numbering(options.numbering ? options.numbering : { config: [] });
4207
+ this.comments = {
4208
+ relationships: new Relationships(),
4209
+ entries: [],
4210
+ nextId: maxCommentId(options.comments?.children) + 1
4211
+ };
4212
+ const markupSeed = {
4213
+ range: -1,
4214
+ moveRun: -1
4215
+ };
4216
+ collectMaxMarkupIds(options.sections, markupSeed);
4217
+ this.markupIds = {
4218
+ rangeNext: markupSeed.range + 1,
4219
+ moveRunNext: markupSeed.moveRun + 1
4220
+ };
4221
+ this.fileRelationships = new Relationships();
4222
+ this.footNotes = {
4223
+ relationships: new Relationships(),
4224
+ notes: /* @__PURE__ */ new Map()
4225
+ };
4226
+ this.endnotes = {
4227
+ relationships: new Relationships(),
4228
+ notes: /* @__PURE__ */ new Map()
4229
+ };
4230
+ this.document = { relationships: new Relationships() };
4231
+ this._settingsOptions = {
4232
+ compatibility: options.compatibility,
4233
+ compatibilityModeVersion: options.compatabilityModeVersion,
4234
+ defaultTabStop: options.defaultTabStop,
4235
+ evenAndOddHeaders: options.evenAndOddHeaderAndFooters ? true : false,
4236
+ characterSpacingControl: options.characterSpacingControl,
4237
+ hyphenation: {
4238
+ autoHyphenation: options.hyphenation?.autoHyphenation,
4239
+ consecutiveHyphenLimit: options.hyphenation?.consecutiveHyphenLimit,
4240
+ doNotHyphenateCaps: options.hyphenation?.doNotHyphenateCaps,
4241
+ hyphenationZone: options.hyphenation?.hyphenationZone
4242
+ },
4243
+ trackRevisions: options.features?.trackRevisions,
4244
+ updateFields: options.features?.updateFields,
4245
+ documentProtection: options.features?.documentProtection,
4246
+ view: options.view,
4247
+ zoom: options.zoom,
4248
+ writeProtection: options.writeProtection,
4249
+ displayBackgroundShape: options.displayBackgroundShape ?? (options.background?.image ? true : void 0),
4250
+ embedTrueTypeFonts: options.embedTrueTypeFonts,
4251
+ embedSystemFonts: options.embedSystemFonts,
4252
+ saveSubsetFonts: options.saveSubsetFonts,
4253
+ docVars: options.docVars,
4254
+ colorSchemeMapping: options.colorSchemeMapping,
4255
+ mailMerge: options.mailMerge,
4256
+ ...options.settings
4257
+ };
4258
+ this.media = new Media();
4259
+ this.charts = new ChartCollection();
4260
+ this.smartArts = new SmartArtCollection();
4261
+ this.embeddings = new EmbeddingCollection();
4262
+ this.altChunks = new AltChunkCollection();
4263
+ this.subDocs = new SubDocCollection();
4264
+ if (options.externalStyles !== void 0) {
4265
+ const externalStyles = new ExternalStylesFactory().newInstance(options.externalStyles);
4266
+ const defaultStyles = new DefaultStylesFactory().newInstance(options.styles?.default ?? {});
4267
+ const externalIds = /* @__PURE__ */ new Set();
4268
+ for (const s of externalStyles.importedStyles ?? []) {
4269
+ const id = extractStyleId(s._raw);
4270
+ if (id) externalIds.add(id);
4271
+ }
4272
+ const notInExternal = (arr) => (arr ?? []).filter((s) => !externalIds.has(s.id));
4273
+ this.styles = new Styles({
4274
+ importedStyles: externalStyles.importedStyles,
4275
+ initialAttributes: externalStyles.initialAttributes ?? defaultStyles.initialAttributes,
4276
+ paragraphStyles: notInExternal(defaultStyles.paragraphStyles),
4277
+ characterStyles: notInExternal(defaultStyles.characterStyles),
4278
+ tableStyles: notInExternal(defaultStyles.tableStyles),
4279
+ numberingStyles: notInExternal(defaultStyles.numberingStyles)
4280
+ });
4281
+ } else if (options.styles) {
4282
+ const s = options.styles;
4283
+ if (s.roundTripped) {
4284
+ const f = new DefaultStylesFactory().newInstance({});
4285
+ const docDefaults = s.docDefaultsXml ?? f.importedStyles?.[0]?._raw ?? "";
4286
+ const latentStyles = s.latentStylesXml ?? f.importedStyles?.[1]?._raw ?? "";
4287
+ this.styles = new Styles({
4288
+ importedStyles: [{ _raw: docDefaults }, { _raw: latentStyles }],
4289
+ initialAttributes: s.initialAttributes ?? f.initialAttributes,
4290
+ paragraphStyles: s.paragraphStyles,
4291
+ characterStyles: s.characterStyles,
4292
+ tableStyles: s.tableStyles,
4293
+ numberingStyles: s.numberingStyles
4294
+ });
4295
+ } else {
4296
+ const f = new DefaultStylesFactory().newInstance(s.default);
4297
+ this.styles = new Styles({
4298
+ importedStyles: f.importedStyles,
4299
+ initialAttributes: s.initialAttributes ?? f.initialAttributes,
4300
+ paragraphStyles: mergeById(f.paragraphStyles, s.paragraphStyles),
4301
+ characterStyles: mergeById(f.characterStyles, s.characterStyles),
4302
+ tableStyles: mergeById(f.tableStyles, s.tableStyles),
4303
+ numberingStyles: mergeById(f.numberingStyles, s.numberingStyles)
4304
+ });
4305
+ }
4306
+ } else {
4307
+ const stylesFactory = new DefaultStylesFactory();
4308
+ this.styles = new Styles(stylesFactory.newInstance());
4309
+ }
4310
+ if (options.styles?.paragraphStyles) for (const style of options.styles.paragraphStyles) {
4311
+ const num = style.paragraph?.numbering;
4312
+ if (num) this.numbering.createConcreteNumberingInstance(num.reference, num.instance ?? 0);
4313
+ }
4314
+ const sourceOverrides = options.contentTypes?.overrides ?? [];
4315
+ this._hasFootnotes = !options.contentTypes || sourceOverrides.some((o) => o.partName === "/word/footnotes.xml");
4316
+ this._hasEndnotes = !options.contentTypes || sourceOverrides.some((o) => o.partName === "/word/endnotes.xml");
4317
+ this._hasNumbering = !options.contentTypes || sourceOverrides.some((o) => o.partName === "/word/numbering.xml");
4318
+ this.addDefaultRelationships();
4319
+ for (const section of options.sections) this.addSection(section);
4320
+ if (options.footnotes) {
4321
+ for (const key in options.footnotes) {
4322
+ if (key === "separator" || key === "continuationSeparator") continue;
4323
+ const note = options.footnotes[key];
4324
+ if (!note) continue;
4325
+ this.footNotes.notes.set(parseFloat(key), note.children);
4326
+ }
4327
+ this.footNotes.separator = options.footnotes.separator;
4328
+ this.footNotes.continuationSeparator = options.footnotes.continuationSeparator;
4329
+ }
4330
+ if (options.endnotes) {
4331
+ for (const key in options.endnotes) {
4332
+ if (key === "separator" || key === "continuationSeparator") continue;
4333
+ const note = options.endnotes[key];
4334
+ if (!note) continue;
4335
+ this.endnotes.notes.set(parseFloat(key), note.children);
4336
+ }
4337
+ this.endnotes.separator = options.endnotes.separator;
4338
+ this.endnotes.continuationSeparator = options.endnotes.continuationSeparator;
4339
+ }
4340
+ this.fontTable = new FontWrapper(options.fonts ?? []);
4341
+ this.glossaryOptions = options.glossary;
4342
+ this.webSettings = options.webSettings ?? void 0;
4343
+ if (options.glossary) this.document.relationships.addRelationship(this._currentRelationshipId++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/glossaryDocument", "glossary/document.xml");
4344
+ if (this.webSettings) this.document.relationships.addRelationship(this._currentRelationshipId++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings", "webSettings.xml");
4345
+ }
4346
+ get headers() {
4347
+ return this._headers;
4348
+ }
4349
+ get footers() {
4350
+ return this._footers;
4351
+ }
4352
+ addSection({ headers = {}, footers = {}, properties }) {
4353
+ const sectPrOptions = {
4354
+ ...properties,
4355
+ footerWrapperGroup: {
4356
+ default: footers.default ? this.createFooter(footers.default) : void 0,
4357
+ even: footers.even ? this.createFooter(footers.even) : void 0,
4358
+ first: footers.first ? this.createFooter(footers.first) : void 0
4359
+ },
4360
+ headerWrapperGroup: {
4361
+ default: headers.default ? this.createHeader(headers.default) : void 0,
4362
+ even: headers.even ? this.createHeader(headers.even) : void 0,
4363
+ first: headers.first ? this.createHeader(headers.first) : void 0
4364
+ }
4365
+ };
4366
+ this._sectionProperties.push(sectPrOptions);
4367
+ }
4368
+ createHeader(header) {
4369
+ const referenceId = this._currentRelationshipId++;
4370
+ const entry = {
4371
+ children: header,
4372
+ relationships: new Relationships(),
4373
+ referenceId
4374
+ };
4375
+ this.addHeaderToDocument(entry);
4376
+ return entry;
4377
+ }
4378
+ createFooter(footer) {
4379
+ const referenceId = this._currentRelationshipId++;
4380
+ const entry = {
4381
+ children: footer,
4382
+ relationships: new Relationships(),
4383
+ referenceId
4384
+ };
4385
+ this.addFooterToDocument(entry);
4386
+ return entry;
4387
+ }
4388
+ addHeaderToDocument(header) {
4389
+ this._headers.push(header);
4390
+ this.document.relationships.addRelationship(header.referenceId, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header", `header${this._headers.length}.xml`);
4391
+ }
4392
+ addFooterToDocument(footer) {
4393
+ this._footers.push(footer);
4394
+ this.document.relationships.addRelationship(footer.referenceId, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer", `footer${this._footers.length}.xml`);
4395
+ }
4396
+ addDefaultRelationships() {
4397
+ this.fileRelationships.addRelationship(1, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "word/document.xml");
4398
+ this.fileRelationships.addRelationship(2, "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", "docProps/core.xml");
4399
+ this.fileRelationships.addRelationship(3, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties", "docProps/app.xml");
4400
+ this.fileRelationships.addRelationship(4, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties", "docProps/custom.xml");
4401
+ this.document.relationships.addRelationship(this._currentRelationshipId++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles", "styles.xml");
4402
+ if (this._hasNumbering) this.document.relationships.addRelationship(this._currentRelationshipId++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering", "numbering.xml");
4403
+ if (this._hasFootnotes) this.document.relationships.addRelationship(this._currentRelationshipId++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes", "footnotes.xml");
4404
+ if (this._hasEndnotes) this.document.relationships.addRelationship(this._currentRelationshipId++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes", "endnotes.xml");
4405
+ this.document.relationships.addRelationship(this._currentRelationshipId++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings", "settings.xml");
4406
+ if (this._options.comments?.children?.length || bodyContainsCommentSugar(this._options.sections)) this.document.relationships.addRelationship(this._currentRelationshipId++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments", "comments.xml");
4407
+ if (this._options.bibliography) this.document.relationships.addRelationship(this._currentRelationshipId++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/bibliography", "bibliography.xml");
4408
+ const themePart = this._options.rawParts?.find((p) => p.path.startsWith("word/theme/"));
4409
+ this.document.relationships.addRelationship(this._currentRelationshipId++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme", themePart ? themePart.path.replace(/^word\//, "") : "theme/theme1.xml");
4410
+ for (const part of this._options.rawParts ?? []) if (part.path.startsWith("customXml/") && part.path.endsWith(".xml") && !part.path.includes("/_rels/") && !part.path.includes("itemProps")) this.document.relationships.addRelationship(this._currentRelationshipId++, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml", `../${part.path}`);
4411
+ }
4412
+ };
4413
+ /**
4414
+ * DOCX-specific read context.
4415
+ *
4416
+ * Holds references to the parsed DocxDocument and cached style/numbering data
4417
+ * used throughout the DOCX parsing pipeline. Implements ReadContext for
4418
+ * descriptor pipeline compatibility.
4419
+ */
4420
+ var DocxReadContext = class {
4421
+ docx;
4422
+ styleCache;
4423
+ numberingCache;
4424
+ /**
4425
+ * Path of the part currently being parsed. Each part carries its own .rels
4426
+ * with independent rId numbering, so drawings inside a part must resolve
4427
+ * image relationships against that part's rels. Defaults to the document body.
4428
+ */
4429
+ currentPart = "word/document.xml";
4430
+ constructor(docx, styleCache, numberingCache) {
4431
+ this.docx = docx;
4432
+ this.styleCache = styleCache;
4433
+ this.numberingCache = numberingCache;
4434
+ }
4435
+ resolveRelationship(rId) {
4436
+ const partMedia = this.docx.partRefs.partMedia.get(this.currentPart);
4437
+ if (partMedia) {
4438
+ const media = partMedia.get(rId);
4439
+ if (media) return media;
4440
+ }
4441
+ return this.docx.partRefs.headers.get(rId) ?? this.docx.partRefs.footers.get(rId) ?? this.docx.partRefs.media.get(rId) ?? this.docx.partRefs.charts.get(rId) ?? this.docx.partRefs.diagramData.get(rId) ?? this.docx.partRefs.afChunks.get(rId) ?? this.docx.partRefs.subDocs.get(rId) ?? this.docx.partRefs.hyperlinks.get(rId);
4442
+ }
4443
+ /**
4444
+ * Run `fn` with `currentPart` temporarily set to `partPath`, restoring the
4445
+ * previous value afterwards. Use when parsing a sub-document part (header,
4446
+ * footer, footnotes, …) so its drawings resolve images from its own rels.
4447
+ */
4448
+ withPart(partPath, fn) {
4449
+ const prev = this.currentPart;
4450
+ this.currentPart = partPath;
4451
+ try {
4452
+ return fn();
4453
+ } finally {
4454
+ this.currentPart = prev;
4455
+ }
4456
+ }
4457
+ getPart(path) {
4458
+ return this.docx.doc.get(path);
4459
+ }
4460
+ getRaw(path) {
4461
+ return this.docx.doc.getRaw(path);
4462
+ }
4463
+ };
4464
+ //#endregion
4465
+ export { DefaultStylesFactory as A, AlignmentType as B, footnotesDesc as C, buildStyleCache as D, buildNumberingCache as E, stringifyTableStyle as F, Numbering as I, parseNumberingDefinitions as L, stringifyConditionalTableStyle as M, stringifyNumberingStyle as N, extractStyleId as O, stringifyParagraphStyle as P, LevelFormat as R, endnotesDesc as S, Styles as T, glossaryDesc as _, framesetXml as a, SubDocCollection as b, customPropertiesDesc as c, contentTypesDesc as d, withAltChunkOverrides as f, DocPartType as g, DocPartGallery as h, frameXml as i, stringifyCharacterStyle as j, parseStyleDefinitions as k, corePropertiesDesc as l, DocPartBehavior as m, DocxWriteContext as n, webSettingsDesc as o, withMediaDefaults as p, TargetScreenSize as r, appPropertiesDesc as s, DocxReadContext as t, buildContentTypesFromRegistry as u, bibliographyDesc as v, settingsDesc as w, AltChunkCollection as x, fontTableDesc as y, LevelSuffix as z };
4466
+
4467
+ //# sourceMappingURL=context-B4Ffx12w.mjs.map