@office-open/docx 0.10.14 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,535 +0,0 @@
1
- import { C as endnotesDesc, T as settingsDesc, b as fontTableDesc, c as customPropertiesDesc, d as contentTypesDesc, f as ensureCustomPropertiesOverride, l as corePropertiesDesc, m as withMediaDefaults, n as DocxWriteContext, o as webSettingsDesc, p as withAltChunkOverrides, s as appPropertiesDesc, u as buildContentTypesFromRegistry, v as glossaryDesc, w as footnotesDesc, y as bibliographyDesc } from "./context-B5k1UabT.mjs";
2
- import { _ as stringifyBodyChild, t as commentsDesc, v as stringifyDocumentXml } from "./comments-Cn9Q0iT6.mjs";
3
- import { t as DocumentAttributeNamespaces } from "./document-attributes-C6PDT-ap.mjs";
4
- import { OoxmlMimeType, addSmartArtRelationships, createPacker, createThemeXml, findAndReplaceImagePlaceholders, formatId, hasPlaceholders, levelForMediaName, optionalRelsPart, replaceAllPlaceholders, replaceNumberingPlaceholders } from "@office-open/core";
5
- import { escapeXml } from "@office-open/xml";
6
- import { DEFAULT_DRAWING_XML, getColorXml, getLayoutXml, getStyleXml } from "@office-open/core/smartart";
7
- //#region src/parts/fonts/obfuscate-ttf-to-odttf.ts
8
- /**
9
- * Font obfuscation module for embedding fonts in WordprocessingML documents.
10
- *
11
- * This module implements the OOXML font obfuscation algorithm used to embed
12
- * fonts in DOCX documents. Obfuscation is required by the OOXML specification
13
- * to prevent simple extraction of embedded font files.
14
- *
15
- * Reference: ECMA-376 Part 2, Section 11.1 (Font Embedding)
16
- *
17
- * @module
18
- */
19
- /** Start offset for obfuscation in the font file */
20
- const obfuscatedStartOffset = 0;
21
- /** End offset for obfuscation (first 32 bytes are obfuscated) */
22
- const obfuscatedEndOffset = 32;
23
- /** Expected GUID size (32 hex characters without dashes) */
24
- const guidSize = 32;
25
- /**
26
- * Obfuscates a TrueType font file for embedding in OOXML documents.
27
- *
28
- * The obfuscation algorithm XORs the first 32 bytes of the font file
29
- * with a reversed byte sequence derived from the font's GUID key.
30
- * This prevents simple extraction while maintaining font functionality.
31
- *
32
- * @param buf - The original font file as a byte array
33
- * @param fontKey - The GUID key for the font (with or without dashes)
34
- * @returns The obfuscated font data
35
- * @throws Error if the fontKey is not a valid 32-character GUID
36
- *
37
- * @example
38
- * ```typescript
39
- * const fontData = readFileSync("font.ttf");
40
- * const fontKey = "00000000-0000-0000-0000-000000000000";
41
- * const obfuscatedData = obfuscate(fontData, fontKey);
42
- * ```
43
- *
44
- * @internal
45
- */
46
- const obfuscate = (buf, fontKey) => {
47
- const guid = fontKey.replace(/-/g, "");
48
- if (guid.length !== guidSize) throw new Error(`Error: Cannot extract GUID from font filename: ${fontKey}`);
49
- const hexNumbers = guid.replace(/(..)/g, "$1 ").trim().split(" ").map((hexString) => parseInt(hexString, 16));
50
- hexNumbers.reverse();
51
- const obfuscatedBytes = buf.slice(obfuscatedStartOffset, obfuscatedEndOffset).map((byte, i) => byte ^ hexNumbers[i % hexNumbers.length]);
52
- const out = new Uint8Array(obfuscatedStartOffset + obfuscatedBytes.length + Math.max(0, buf.length - obfuscatedEndOffset));
53
- out.set(buf.slice(0, obfuscatedStartOffset));
54
- out.set(obfuscatedBytes, obfuscatedStartOffset);
55
- out.set(buf.slice(obfuscatedEndOffset), obfuscatedStartOffset + obfuscatedBytes.length);
56
- return out;
57
- };
58
- //#endregion
59
- //#region src/parts/header-footer.ts
60
- /**
61
- * Namespace keys used by header elements.
62
- * @internal
63
- */
64
- const HEADER_NAMESPACES = [
65
- "cx",
66
- "cx1",
67
- "cx2",
68
- "cx3",
69
- "cx4",
70
- "cx5",
71
- "cx6",
72
- "cx7",
73
- "cx8",
74
- "m",
75
- "mc",
76
- "o",
77
- "r",
78
- "v",
79
- "w",
80
- "w10",
81
- "w14",
82
- "w15",
83
- "w16cid",
84
- "w16se",
85
- "wne",
86
- "wp",
87
- "wp14",
88
- "wpc",
89
- "wpg",
90
- "wpi",
91
- "wps"
92
- ];
93
- /**
94
- * Namespace keys used by footer elements.
95
- * @internal
96
- */
97
- const FOOTER_NAMESPACES = [
98
- "m",
99
- "mc",
100
- "o",
101
- "r",
102
- "v",
103
- "w",
104
- "w10",
105
- "w14",
106
- "w15",
107
- "wne",
108
- "wp",
109
- "wp14",
110
- "wpc",
111
- "wpg",
112
- "wpi",
113
- "wps"
114
- ];
115
- /**
116
- * Serialize a header or footer to XML.
117
- *
118
- * Builds the `<w:hdr>` or `<w:ftr>` element with namespace declarations,
119
- * then serializes each child element via `stringifyBodyChild()`.
120
- *
121
- * @param tag - Element tag name ("w:hdr" or "w:ftr")
122
- * @param namespaces - Namespace keys to declare on the root element
123
- * @param children - Block-level child elements (raw SectionChild objects)
124
- * @param ctx - Body context for stringification
125
- */
126
- function stringifyHeaderFooter(tag, namespaces, children, ctx) {
127
- const attrParts = [];
128
- for (const ns of namespaces) attrParts.push(`xmlns:${ns}="${escapeXml(DocumentAttributeNamespaces[ns])}"`);
129
- attrParts.push("mc:Ignorable=\"w14 w15 wp14\"");
130
- const attrStr = attrParts.join(" ");
131
- const childParts = [];
132
- for (const child of children) childParts.push(stringifyBodyChild(child, ctx));
133
- const body = childParts.join("");
134
- return body.length === 0 ? `<${tag} ${attrStr}/>` : `<${tag} ${attrStr}>${body}</${tag}>`;
135
- }
136
- //#endregion
137
- //#region src/compiler.ts
138
- /**
139
- * DOCX document compiler — pure function entry point.
140
- *
141
- * compileDocument() accepts DocumentOptions directly,
142
- * creates a DocxWriteContext internally, and produces a Zippable result.
143
- * All XML parts are produced via descriptors or serialize() —
144
- * no Formatter dependency.
145
- *
146
- * @module
147
- */
148
- /** Reusable TextEncoder (stateless, safe to share). */
149
- const encoder = new TextEncoder();
150
- /** XML declaration prepended to every OOXML part. */
151
- const XML_DECL = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
152
- /**
153
- * Compile document options into a flat file map suitable for fflate zipSync.
154
- *
155
- * This is the primary entry point for DOCX generation — accepts DocumentOptions
156
- * directly.
157
- */
158
- function compileDocument(options, overrides = [], mediaLevel = 0) {
159
- const ctx = new DocxWriteContext(options);
160
- const files = {};
161
- const xmlifiedFileMapping = xmlifyContext(ctx, /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map());
162
- const map = new Map(Object.entries(xmlifiedFileMapping));
163
- for (const [, obj] of map) {
164
- if (obj === void 0) continue;
165
- if (Array.isArray(obj)) for (const subFile of obj) files[subFile.path] = typeof subFile.data === "string" ? encoder.encode(subFile.data) : subFile.data;
166
- else files[obj.path] = typeof obj.data === "string" ? encoder.encode(obj.data) : obj.data;
167
- }
168
- for (const subFile of overrides) files[subFile.path] = typeof subFile.data === "string" ? encoder.encode(subFile.data) : subFile.data;
169
- const mediaArray = ctx.media.array;
170
- for (const mediaData of mediaArray) {
171
- files[`word/media/${mediaData.fileName}`] = [mediaData.data, { level: levelForMediaName(mediaData.fileName, mediaLevel) }];
172
- if (mediaData.type === "svg") files[`word/media/${mediaData.fallback.fileName}`] = [mediaData.fallback.data, { level: levelForMediaName(mediaData.fallback.fileName, mediaLevel) }];
173
- }
174
- for (const embedding of ctx.embeddings.array) files[`word/embeddings/${embedding.fileName}`] = [embedding.data, { level: levelForMediaName(embedding.fileName, mediaLevel) }];
175
- for (const font of ctx.fontTable.fontOptionsWithKey) {
176
- if (font.data === void 0) continue;
177
- const [nameWithoutExtension] = font.name.split(".");
178
- const filePath = font.odttfPath ?? `word/fonts/${nameWithoutExtension}.odttf`;
179
- files[filePath] = font.rawOdttf ? font.data : obfuscate(font.data, font.fontKey);
180
- }
181
- for (const part of ctx._options.rawParts ?? []) files[part.path] = part.data;
182
- files["[Content_Types].xml"] = encoder.encode(buildContentTypesData(ctx, files));
183
- return files;
184
- }
185
- /**
186
- * Comments carried by the document: those the caller listed explicitly
187
- * (`options.comments`) plus entries registered by `{ comment }` sugar children
188
- * during body stringification. Drives both word/comments.xml generation and the
189
- * [Content_Types] comments Override, which must stay in sync (OPC consistency).
190
- */
191
- function mergedCommentChildren(ctx) {
192
- return [...ctx._options.comments?.children ?? [], ...ctx.comments.entries];
193
- }
194
- /**
195
- * Serialize [Content_Types].xml from the part registry, then backfill media/
196
- * font/embedding `<Default>` entries from the parts actually written.
197
- *
198
- * Must run after every part has been stringified (parts call `ctx.addMedia`
199
- * during stringify), so call this once `xmlifyContext` has finished — not from
200
- * inside its object literal, where ContentTypes would evaluate before the
201
- * later-defined header/footer/font parts have registered their media.
202
- */
203
- function buildContentTypesData(ctx, files) {
204
- const altChunks = ctx.altChunks.array.map((ac) => ({
205
- path: `/word/${ac.path}`,
206
- contentType: ac.contentType ?? "application/xhtml+xml"
207
- }));
208
- const withMedia = withMediaDefaults(ctx._options.contentTypes ? ensureCustomPropertiesOverride(withAltChunkOverrides(ctx._options.contentTypes, altChunks)) : buildContentTypesFromRegistry(new Map([
209
- ["freshCompile", true],
210
- ["hasComments", mergedCommentChildren(ctx).length > 0],
211
- ["hasBibliography", !!ctx._options.bibliography],
212
- ["hasGlossary", !!ctx.glossaryOptions],
213
- ["hasWebSettings", !!ctx.webSettings],
214
- ["headerCount", ctx.headers.length],
215
- ["footerCount", ctx.footers.length],
216
- ["chartCount", ctx.charts.array.length],
217
- ["smartArtCount", ctx.smartArts.array.length]
218
- ]), {
219
- altChunks,
220
- subDocs: ctx.subDocs.array.map((sd) => ({ path: `/word/${sd.path}` }))
221
- }), Object.keys(files));
222
- return XML_DECL + (contentTypesDesc.stringify(withMedia, ctx) ?? "");
223
- }
224
- function xmlifyContext(ctx, headerFormattedViews, footerFormattedViews) {
225
- const mkCtx = (viewWrapper = ctx.document) => ({
226
- fileData: ctx,
227
- file: ctx,
228
- viewWrapper,
229
- stringifyChild: stringifyBodyChild,
230
- addRelationship: (type, target, mode) => ctx.addRelationship(type, target, mode),
231
- addMedia: (data, type) => ctx.addMedia(data, type)
232
- });
233
- const documentRelationshipCount = ctx.document.relationships.relationshipCount + 1;
234
- const footerMediaResults = /* @__PURE__ */ new Map();
235
- const headerMediaResults = /* @__PURE__ */ new Map();
236
- const documentXmlData = XML_DECL + stringifyDocumentXml(ctx, mkCtx(ctx.document));
237
- const mergedCommentChildrenList = mergedCommentChildren(ctx);
238
- const hasComments = mergedCommentChildrenList.length > 0;
239
- const commentRelationshipCount = hasComments ? ctx.comments.relationships.relationshipCount + 1 : 0;
240
- const commentCtx = hasComments ? mkCtx({ relationships: ctx.comments.relationships }) : null;
241
- const commentXmlData = commentCtx ? XML_DECL + commentsDesc.stringify({ children: mergedCommentChildrenList }, commentCtx) : "";
242
- const footnoteRelationshipCount = ctx.footNotes.relationships.relationshipCount + 1;
243
- const footnoteCtx = mkCtx({ relationships: ctx.footNotes.relationships });
244
- const footnoteXmlData = XML_DECL + (footnotesDesc.stringify({
245
- notes: ctx.footNotes.notes,
246
- separator: ctx.footNotes.separator,
247
- continuationSeparator: ctx.footNotes.continuationSeparator
248
- }, footnoteCtx) ?? "");
249
- const documentMedia = findAndReplaceImagePlaceholders(documentXmlData, ctx.media.array, documentRelationshipCount);
250
- const documentEmbeddingOffset = documentRelationshipCount + documentMedia.referenced.length;
251
- const documentEmbeddings = findAndReplaceImagePlaceholders(documentMedia.xml, ctx.embeddings.array, documentEmbeddingOffset);
252
- const commentMedia = hasComments ? findAndReplaceImagePlaceholders(commentXmlData, ctx.media.array, commentRelationshipCount) : {
253
- xml: "",
254
- referenced: []
255
- };
256
- const footnoteMedia = findAndReplaceImagePlaceholders(footnoteXmlData, ctx.media.array, footnoteRelationshipCount);
257
- for (const [i, ref] of footnoteMedia.referenced.entries()) ctx.footNotes.relationships.addRelationship(footnoteRelationshipCount + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", `media/${ref.fileName}`);
258
- return {
259
- AppProperties: {
260
- data: XML_DECL + (appPropertiesDesc.stringify(ctx._options.appProperties ?? {}, ctx) ?? ""),
261
- path: "docProps/app.xml"
262
- },
263
- ...hasComments ? {
264
- Comments: {
265
- data: (() => {
266
- return replaceNumberingPlaceholders(commentMedia.referenced.length > 0 ? commentMedia.xml : commentXmlData, ctx.numbering.concreteNumbering);
267
- })(),
268
- path: "word/comments.xml"
269
- },
270
- CommentsRelationships: (() => {
271
- for (const [i, ref] of commentMedia.referenced.entries()) ctx.comments.relationships.addRelationship(commentRelationshipCount + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", `media/${ref.fileName}`);
272
- return optionalRelsPart(ctx.comments.relationships, XML_DECL, "word/_rels/comments.xml.rels");
273
- })()
274
- } : {},
275
- CustomProperties: {
276
- data: XML_DECL + (customPropertiesDesc.stringify({ properties: ctx._options.customProperties ?? [] }, ctx) ?? ""),
277
- path: "docProps/custom.xml"
278
- },
279
- Document: {
280
- data: (() => {
281
- let xmlData = documentEmbeddings.xml;
282
- if (hasPlaceholders(xmlData)) {
283
- const mediaCount = documentMedia.referenced.length;
284
- const embeddingCount = documentEmbeddings.referenced.length;
285
- const chartKeys = ctx.charts.array.map((c) => c.key);
286
- const smartArtKeys = ctx.smartArts.array.map((s) => s.key);
287
- const chartOffset = documentRelationshipCount + mediaCount + embeddingCount;
288
- const smartArtOffset = chartOffset + chartKeys.length;
289
- const entries = [];
290
- for (const [i, key] of chartKeys.entries()) entries.push({
291
- prefix: "chart:",
292
- key,
293
- value: formatId(chartOffset, i, "rId")
294
- });
295
- const saPrefixes = [
296
- "smartart:",
297
- "smartart-lo:",
298
- "smartart-qs:",
299
- "smartart-cs:"
300
- ];
301
- for (const [i, key] of smartArtKeys.entries()) for (let p = 0; p < saPrefixes.length; p++) entries.push({
302
- prefix: saPrefixes[p],
303
- key,
304
- value: formatId(smartArtOffset + p * smartArtKeys.length, i, "rId")
305
- });
306
- for (const { reference, instance, numId } of ctx.numbering.concreteNumbering) entries.push({
307
- key: `${reference}-${instance}`,
308
- value: numId.toString()
309
- });
310
- xmlData = replaceAllPlaceholders(xmlData, entries);
311
- } else xmlData = replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);
312
- return xmlData;
313
- })(),
314
- path: "word/document.xml"
315
- },
316
- ...ctx._options.rawParts?.some((part) => part.path.startsWith("word/theme/")) ? {} : { Theme: {
317
- data: XML_DECL + createThemeXml(),
318
- path: "word/theme/theme1.xml"
319
- } },
320
- ...ctx.hasEndnotes ? {
321
- Endnotes: {
322
- data: (() => {
323
- const endnoteCtx = mkCtx({ relationships: ctx.endnotes.relationships });
324
- const xmlData = XML_DECL + (endnotesDesc.stringify({
325
- notes: ctx.endnotes.notes,
326
- separator: ctx.endnotes.separator,
327
- continuationSeparator: ctx.endnotes.continuationSeparator
328
- }, endnoteCtx) ?? "");
329
- const endnoteRelCount = ctx.endnotes.relationships.relationshipCount + 1;
330
- const endnoteMedia = findAndReplaceImagePlaceholders(xmlData, ctx.media.array, endnoteRelCount);
331
- if (endnoteMedia.referenced.length > 0) {
332
- for (const [i, ref] of endnoteMedia.referenced.entries()) ctx.endnotes.relationships.addRelationship(endnoteRelCount + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", `media/${ref.fileName}`);
333
- return replaceNumberingPlaceholders(endnoteMedia.xml, ctx.numbering.concreteNumbering);
334
- }
335
- return replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);
336
- })(),
337
- path: "word/endnotes.xml"
338
- },
339
- EndnotesRelationships: ctx.endnotes.relationships.relationshipCount > 0 ? {
340
- data: XML_DECL + ctx.endnotes.relationships.serialize(),
341
- path: "word/_rels/endnotes.xml.rels"
342
- } : void 0
343
- } : {},
344
- FileRelationships: {
345
- data: XML_DECL + ctx.fileRelationships.serialize(),
346
- path: "_rels/.rels"
347
- },
348
- FontTable: {
349
- data: XML_DECL + (fontTableDesc.stringify({ fonts: ctx.fontTable.fontOptionsWithKey }, ctx) ?? ""),
350
- path: "word/fontTable.xml"
351
- },
352
- FontTableRelationships: optionalRelsPart(ctx.fontTable.relationships, XML_DECL, "word/_rels/fontTable.xml.rels"),
353
- ...ctx.hasFootnotes ? {
354
- FootNotes: {
355
- data: (() => {
356
- return replaceNumberingPlaceholders(footnoteMedia.referenced.length > 0 ? footnoteMedia.xml : footnoteXmlData, ctx.numbering.concreteNumbering);
357
- })(),
358
- path: "word/footnotes.xml"
359
- },
360
- FootNotesRelationships: ctx.footNotes.relationships.relationshipCount > 0 ? {
361
- data: XML_DECL + ctx.footNotes.relationships.serialize(),
362
- path: "word/_rels/footnotes.xml.rels"
363
- } : void 0
364
- } : {},
365
- FooterRelationships: ctx.footers.map((entry, index) => {
366
- const footerCtx = mkCtx({ relationships: entry.relationships });
367
- const xmlData = XML_DECL + stringifyHeaderFooter("w:ftr", FOOTER_NAMESPACES, entry.children, footerCtx);
368
- footerFormattedViews.set(index, xmlData);
369
- const footerRelCount = entry.relationships.relationshipCount + 1;
370
- const footerMedia = findAndReplaceImagePlaceholders(xmlData, ctx.media.array, footerRelCount);
371
- footerMediaResults.set(index, footerMedia);
372
- for (const [i, ref] of footerMedia.referenced.entries()) entry.relationships.addRelationship(footerRelCount + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", `media/${ref.fileName}`);
373
- return optionalRelsPart(entry.relationships, XML_DECL, `word/_rels/footer${index + 1}.xml.rels`);
374
- }).filter((r) => r !== void 0),
375
- Footers: ctx.footers.map((_entry, index) => {
376
- const footerMedia = footerMediaResults.get(index);
377
- const tempXmlData = footerFormattedViews.get(index);
378
- return {
379
- data: replaceNumberingPlaceholders(footerMedia.referenced.length > 0 ? footerMedia.xml : tempXmlData, ctx.numbering.concreteNumbering),
380
- path: `word/footer${index + 1}.xml`
381
- };
382
- }),
383
- HeaderRelationships: ctx.headers.map((entry, index) => {
384
- const headerCtx = mkCtx({ relationships: entry.relationships });
385
- const xmlData = XML_DECL + stringifyHeaderFooter("w:hdr", HEADER_NAMESPACES, entry.children, headerCtx);
386
- headerFormattedViews.set(index, xmlData);
387
- const headerRelCount = entry.relationships.relationshipCount + 1;
388
- const headerMedia = findAndReplaceImagePlaceholders(xmlData, ctx.media.array, headerRelCount);
389
- headerMediaResults.set(index, headerMedia);
390
- for (const [i, ref] of headerMedia.referenced.entries()) entry.relationships.addRelationship(headerRelCount + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", `media/${ref.fileName}`);
391
- return optionalRelsPart(entry.relationships, XML_DECL, `word/_rels/header${index + 1}.xml.rels`);
392
- }).filter((r) => r !== void 0),
393
- Headers: ctx.headers.map((_entry, index) => {
394
- const headerMedia = headerMediaResults.get(index);
395
- const tempXmlData = headerFormattedViews.get(index);
396
- return {
397
- data: replaceNumberingPlaceholders(headerMedia.referenced.length > 0 ? headerMedia.xml : tempXmlData, ctx.numbering.concreteNumbering),
398
- path: `word/header${index + 1}.xml`
399
- };
400
- }),
401
- ...ctx.hasNumbering ? { Numbering: {
402
- data: ctx.numbering.serialize(),
403
- path: "word/numbering.xml"
404
- } } : {},
405
- Properties: {
406
- data: XML_DECL + (corePropertiesDesc.stringify(ctx._options, ctx) ?? ""),
407
- path: "docProps/core.xml"
408
- },
409
- Relationships: {
410
- data: (() => {
411
- for (const [i, ref] of documentMedia.referenced.entries()) ctx.document.relationships.addRelationship(documentRelationshipCount + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", `media/${ref.fileName}`);
412
- for (const [i, ref] of documentEmbeddings.referenced.entries()) ctx.document.relationships.addRelationship(documentEmbeddingOffset + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject", `embeddings/${ref.fileName}`);
413
- const chartOffset = documentRelationshipCount + documentMedia.referenced.length + documentEmbeddings.referenced.length;
414
- for (let i = 0; i < ctx.charts.array.length; i++) ctx.document.relationships.addRelationship(chartOffset + i, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart", `charts/chart${i + 1}.xml`);
415
- addSmartArtRelationships(ctx.smartArts.array.map((s) => s.key), (id, type, target) => {
416
- ctx.document.relationships.addRelationship(id, type, target);
417
- }, documentRelationshipCount + documentMedia.referenced.length + documentEmbeddings.referenced.length + ctx.charts.array.length, 0, {
418
- pathPrefix: "",
419
- styleRelType: "http://schemas.microsoft.com/office/2007/relationships/diagramStyle"
420
- });
421
- ctx.document.relationships.addRelationship(ctx.document.relationships.relationshipCount + 1, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable", "fontTable.xml");
422
- return XML_DECL + ctx.document.relationships.serialize();
423
- })(),
424
- path: "word/_rels/document.xml.rels"
425
- },
426
- Settings: {
427
- data: XML_DECL + (settingsDesc.stringify(ctx._settingsOptions, ctx) ?? ""),
428
- path: "word/settings.xml"
429
- },
430
- Styles: {
431
- data: (() => {
432
- return replaceNumberingPlaceholders(ctx.styles.serialize(), ctx.numbering.concreteNumbering);
433
- })(),
434
- path: "word/styles.xml"
435
- },
436
- ...ctx._options.bibliography ? { Bibliography: {
437
- data: XML_DECL + (bibliographyDesc.stringify(ctx._options.bibliography, ctx) ?? ""),
438
- path: "word/bibliography.xml"
439
- } } : {},
440
- ...ctx.charts.array.length > 0 ? { Charts: ctx.charts.array.map((chartData, i) => ({
441
- data: XML_DECL + chartData.chartSpaceXml,
442
- path: `word/charts/chart${i + 1}.xml`
443
- })) } : {},
444
- ...ctx.smartArts.array.length > 0 ? {
445
- DiagramData: ctx.smartArts.array.map((smartArtData, i) => ({
446
- data: XML_DECL + smartArtData.dataModelXml,
447
- path: `word/diagrams/data${i + 1}.xml`
448
- })),
449
- DiagramLayout: ctx.smartArts.array.map((smartArtData, i) => ({
450
- data: getLayoutXml(smartArtData.layout),
451
- path: `word/diagrams/layout${i + 1}.xml`
452
- })),
453
- DiagramStyle: ctx.smartArts.array.map((smartArtData, i) => ({
454
- data: getStyleXml(smartArtData.style),
455
- path: `word/diagrams/quickStyle${i + 1}.xml`
456
- })),
457
- DiagramColors: ctx.smartArts.array.map((smartArtData, i) => ({
458
- data: getColorXml(smartArtData.color),
459
- path: `word/diagrams/colors${i + 1}.xml`
460
- })),
461
- DiagramDrawing: ctx.smartArts.array.map((_, i) => ({
462
- data: DEFAULT_DRAWING_XML,
463
- path: `word/diagrams/drawing${i + 1}.xml`
464
- }))
465
- } : {},
466
- ...ctx.altChunks.array.length > 0 ? { AltChunks: ctx.altChunks.array.map((altChunkData) => ({
467
- data: altChunkData.data,
468
- path: `word/${altChunkData.path}`
469
- })) } : {},
470
- ...ctx.subDocs.array.length > 0 ? { SubDocs: ctx.subDocs.array.map((subDocData) => ({
471
- data: subDocData.data,
472
- path: `word/${subDocData.path}`
473
- })) } : {},
474
- ...ctx.glossaryOptions ? { Glossary: {
475
- data: (() => {
476
- const glossaryCtx = mkCtx(void 0);
477
- return XML_DECL + (glossaryDesc.stringify(ctx.glossaryOptions, glossaryCtx) ?? "");
478
- })(),
479
- path: "word/glossary/document.xml"
480
- } } : {},
481
- ...ctx.webSettings ? { WebSettings: {
482
- data: XML_DECL + (webSettingsDesc.stringify(ctx._options.webSettings ?? {}, ctx) ?? ""),
483
- path: "word/webSettings.xml"
484
- } } : {}
485
- };
486
- }
487
- //#endregion
488
- //#region src/generate.ts
489
- /**
490
- * Pure function API for generating DOCX files.
491
- *
492
- * @module
493
- */
494
- /** @internal Packer instance for DOCX generation. */
495
- const Packer = createPacker({
496
- compile: (options, overrides, mediaLevel) => compileDocument(options, overrides, mediaLevel),
497
- mimeType: OoxmlMimeType.DOCX
498
- });
499
- /**
500
- * Generate a DOCX file from pure JSON options.
501
- *
502
- * The output format is controlled by `packerOptions.type` (default: `"nodebuffer"` → Buffer).
503
- * For synchronous generation, use {@link generateDocumentSync}. For streaming, use {@link generateDocumentStream}.
504
- *
505
- * @param options - Document options (sections, styles, numbering, etc.)
506
- * @param packerOptions - Optional packer configuration (type, compression, overrides, etc.)
507
- *
508
- * @example
509
- * ```typescript
510
- * import { generateDocument } from "@office-open/docx";
511
- *
512
- * const buffer = await generateDocument({ sections: [...] });
513
- * const bytes = await generateDocument({ sections: [...] }, { type: "uint8array" });
514
- * const blob = await generateDocument({ sections: [...] }, { type: "blob" });
515
- * ```
516
- */
517
- function generateDocument(options, packerOptions) {
518
- return Packer.pack(options, packerOptions);
519
- }
520
- /**
521
- * Synchronously generate a DOCX file from pure JSON options.
522
- */
523
- function generateDocumentSync(options, packerOptions) {
524
- return Packer.packSync(options, packerOptions);
525
- }
526
- /**
527
- * Generate a DOCX file as a `ReadableStream<Uint8Array>`.
528
- */
529
- function generateDocumentStream(options, packerOptions) {
530
- return Packer.toStream(options, packerOptions);
531
- }
532
- //#endregion
533
- export { compileDocument as i, generateDocumentStream as n, generateDocumentSync as r, generateDocument as t };
534
-
535
- //# sourceMappingURL=generate-BxIo24VV.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate-BxIo24VV.mjs","names":[],"sources":["../src/parts/fonts/obfuscate-ttf-to-odttf.ts","../src/parts/header-footer.ts","../src/compiler.ts","../src/generate.ts"],"sourcesContent":["/**\n * Font obfuscation module for embedding fonts in WordprocessingML documents.\n *\n * This module implements the OOXML font obfuscation algorithm used to embed\n * fonts in DOCX documents. Obfuscation is required by the OOXML specification\n * to prevent simple extraction of embedded font files.\n *\n * Reference: ECMA-376 Part 2, Section 11.1 (Font Embedding)\n *\n * @module\n */\n\n/** Start offset for obfuscation in the font file */\nconst obfuscatedStartOffset = 0;\n/** End offset for obfuscation (first 32 bytes are obfuscated) */\nconst obfuscatedEndOffset = 32;\n/** Expected GUID size (32 hex characters without dashes) */\nconst guidSize = 32;\n\n/**\n * Obfuscates a TrueType font file for embedding in OOXML documents.\n *\n * The obfuscation algorithm XORs the first 32 bytes of the font file\n * with a reversed byte sequence derived from the font's GUID key.\n * This prevents simple extraction while maintaining font functionality.\n *\n * @param buf - The original font file as a byte array\n * @param fontKey - The GUID key for the font (with or without dashes)\n * @returns The obfuscated font data\n * @throws Error if the fontKey is not a valid 32-character GUID\n *\n * @example\n * ```typescript\n * const fontData = readFileSync(\"font.ttf\");\n * const fontKey = \"00000000-0000-0000-0000-000000000000\";\n * const obfuscatedData = obfuscate(fontData, fontKey);\n * ```\n *\n * @internal\n */\nexport const obfuscate = (buf: Uint8Array, fontKey: string): Uint8Array => {\n const guid = fontKey.replace(/-/g, \"\");\n if (guid.length !== guidSize) {\n throw new Error(`Error: Cannot extract GUID from font filename: ${fontKey}`);\n }\n\n const hexStrings = guid.replace(/(..)/g, \"$1 \").trim().split(\" \");\n const hexNumbers = hexStrings.map((hexString) => parseInt(hexString, 16));\n hexNumbers.reverse();\n\n const bytesToObfuscate = buf.slice(obfuscatedStartOffset, obfuscatedEndOffset);\n const obfuscatedBytes = bytesToObfuscate.map(\n (byte, i) => byte ^ hexNumbers[i % hexNumbers.length]!,\n );\n\n const out = new Uint8Array(\n obfuscatedStartOffset + obfuscatedBytes.length + Math.max(0, buf.length - obfuscatedEndOffset),\n );\n out.set(buf.slice(0, obfuscatedStartOffset));\n out.set(obfuscatedBytes, obfuscatedStartOffset);\n out.set(buf.slice(obfuscatedEndOffset), obfuscatedStartOffset + obfuscatedBytes.length);\n return out;\n};\n","/**\n * Header/Footer entry module for WordprocessingML documents.\n *\n * Replaces the former HeaderWrapper/FooterWrapper/Header/Footer/HeaderFooterBase\n * class hierarchy with a simple data structure + pure serialization function.\n *\n * Reference: ISO/IEC 29500-4, wml.xsd, CT_HdrFtr\n *\n * @module\n */\n\nimport type { Relationships } from \"@office-open/core\";\nimport { escapeXml } from \"@office-open/xml\";\nimport type { SectionChild } from \"@shared/section\";\n\nimport { stringifyBodyChild } from \"../body\";\nimport type { BodyContext } from \"../context\";\nimport { DocumentAttributeNamespaces } from \"./document/document-attributes\";\nimport type { DocumentAttributeNamespace } from \"./document/document-attributes\";\n\n/**\n * Simple data structure for a header or footer entry.\n *\n * Replaces HeaderWrapper/FooterWrapper — holds children, relationships,\n * and the reference ID needed for section property references.\n *\n * Children are raw SectionChild objects (plain JSON or class instances).\n */\nexport interface HeaderFooterEntry {\n children: SectionChild[];\n relationships: Relationships;\n referenceId: number;\n}\n\n/**\n * Namespace keys used by header elements.\n * @internal\n */\nexport const HEADER_NAMESPACES: DocumentAttributeNamespace[] = [\n \"cx\",\n \"cx1\",\n \"cx2\",\n \"cx3\",\n \"cx4\",\n \"cx5\",\n \"cx6\",\n \"cx7\",\n \"cx8\",\n \"m\",\n \"mc\",\n \"o\",\n \"r\",\n \"v\",\n \"w\",\n \"w10\",\n \"w14\",\n \"w15\",\n \"w16cid\",\n \"w16se\",\n \"wne\",\n \"wp\",\n \"wp14\",\n \"wpc\",\n \"wpg\",\n \"wpi\",\n \"wps\",\n];\n\n/**\n * Namespace keys used by footer elements.\n * @internal\n */\nexport const FOOTER_NAMESPACES: DocumentAttributeNamespace[] = [\n \"m\",\n \"mc\",\n \"o\",\n \"r\",\n \"v\",\n \"w\",\n \"w10\",\n \"w14\",\n \"w15\",\n \"wne\",\n \"wp\",\n \"wp14\",\n \"wpc\",\n \"wpg\",\n \"wpi\",\n \"wps\",\n];\n\n/**\n * Serialize a header or footer to XML.\n *\n * Builds the `<w:hdr>` or `<w:ftr>` element with namespace declarations,\n * then serializes each child element via `stringifyBodyChild()`.\n *\n * @param tag - Element tag name (\"w:hdr\" or \"w:ftr\")\n * @param namespaces - Namespace keys to declare on the root element\n * @param children - Block-level child elements (raw SectionChild objects)\n * @param ctx - Body context for stringification\n */\nexport function stringifyHeaderFooter(\n tag: string,\n namespaces: DocumentAttributeNamespace[],\n children: SectionChild[],\n ctx: BodyContext,\n): string {\n const attrParts: string[] = [];\n for (const ns of namespaces) {\n attrParts.push(`xmlns:${ns}=\"${escapeXml(DocumentAttributeNamespaces[ns])}\"`);\n }\n // mc:Ignorable must declare the ignorable namespaces (w14/w15/wp14) that\n // header/footer content uses (e.g. w14:paraId). Without it, Word in\n // compatibility mode 14 rejects the part as unreadable content.\n attrParts.push('mc:Ignorable=\"w14 w15 wp14\"');\n const attrStr = attrParts.join(\" \");\n\n const childParts: string[] = [];\n for (const child of children) {\n childParts.push(stringifyBodyChild(child, ctx));\n }\n\n const body = childParts.join(\"\");\n return body.length === 0 ? `<${tag} ${attrStr}/>` : `<${tag} ${attrStr}>${body}</${tag}>`;\n}\n","/**\n * DOCX document compiler — pure function entry point.\n *\n * compileDocument() accepts DocumentOptions directly,\n * creates a DocxWriteContext internally, and produces a Zippable result.\n * All XML parts are produced via descriptors or serialize() —\n * no Formatter dependency.\n *\n * @module\n */\n\nimport {\n addSmartArtRelationships,\n createThemeXml,\n findAndReplaceImagePlaceholders,\n formatId,\n hasPlaceholders,\n levelForMediaName,\n optionalRelsPart,\n replaceAllPlaceholders,\n replaceNumberingPlaceholders,\n} from \"@office-open/core\";\nimport type { XmlifyedFile, ZipOptions, Zippable } from \"@office-open/core\";\nimport {\n DEFAULT_DRAWING_XML,\n getColorXml,\n getLayoutXml,\n getStyleXml,\n} from \"@office-open/core/smartart\";\nimport type { DocumentOptions } from \"@parts/core-properties\";\nimport { obfuscate } from \"@parts/fonts/obfuscate-ttf-to-odttf\";\nimport { HEADER_NAMESPACES, FOOTER_NAMESPACES, stringifyHeaderFooter } from \"@parts/header-footer\";\nimport type { CommentOptions } from \"@parts/paragraph/run/comment-run\";\n\nimport { stringifyDocumentXml, stringifyBodyChild, type BodyContext } from \"./body\";\nimport { DocxWriteContext } from \"./context\";\nimport {\n corePropertiesDesc,\n customPropertiesDesc,\n appPropertiesDesc,\n contentTypesDesc,\n buildContentTypesFromRegistry,\n withAltChunkOverrides,\n withMediaDefaults,\n ensureCustomPropertiesOverride,\n fontTableDesc,\n webSettingsDesc,\n commentsDesc,\n bibliographyDesc,\n settingsDesc,\n footnotesDesc,\n endnotesDesc,\n glossaryDesc,\n} from \"./parts\";\n\n/** Reusable TextEncoder (stateless, safe to share). */\nconst encoder = new TextEncoder();\n\n/** XML declaration prepended to every OOXML part. */\nconst XML_DECL = '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>';\n\n/** Extended context for header/footer formatted view caching. */\ntype DocxContext = BodyContext & {\n headerFormattedViews?: Map<number, string>;\n footerFormattedViews?: Map<number, string>;\n};\n\n// ── Public API ──\n\n/**\n * Compile document options into a flat file map suitable for fflate zipSync.\n *\n * This is the primary entry point for DOCX generation — accepts DocumentOptions\n * directly.\n */\nexport function compileDocument(\n options: DocumentOptions,\n overrides: XmlifyedFile[] = [],\n mediaLevel: number = 0,\n): Zippable {\n const ctx = new DocxWriteContext(options);\n const files: Zippable = {};\n\n const headerFormattedViews = new Map<number, string>();\n const footerFormattedViews = new Map<number, string>();\n\n const xmlifiedFileMapping = xmlifyContext(ctx, headerFormattedViews, footerFormattedViews);\n const map = new Map<string, XmlifyedFile | XmlifyedFile[]>(Object.entries(xmlifiedFileMapping));\n\n for (const [, obj] of map) {\n if (obj === undefined) continue;\n if (Array.isArray(obj)) {\n for (const subFile of obj) {\n files[subFile.path] =\n typeof subFile.data === \"string\" ? encoder.encode(subFile.data) : subFile.data;\n }\n } else {\n files[obj.path] = typeof obj.data === \"string\" ? encoder.encode(obj.data) : obj.data;\n }\n }\n\n for (const subFile of overrides) {\n files[subFile.path] =\n typeof subFile.data === \"string\" ? encoder.encode(subFile.data) : subFile.data;\n }\n\n // Media files\n const mediaArray = ctx.media.array;\n for (const mediaData of mediaArray) {\n files[`word/media/${mediaData.fileName}`] = [\n mediaData.data as Uint8Array,\n { level: levelForMediaName(mediaData.fileName, mediaLevel) as ZipOptions[\"level\"] },\n ];\n if (mediaData.type === \"svg\") {\n files[`word/media/${mediaData.fallback.fileName}`] = [\n mediaData.fallback.data as Uint8Array,\n {\n level: levelForMediaName(mediaData.fallback.fileName, mediaLevel) as ZipOptions[\"level\"],\n },\n ];\n }\n }\n\n // OLE embedding binaries (word/embeddings/oleObjectN.bin)\n for (const embedding of ctx.embeddings.array) {\n files[`word/embeddings/${embedding.fileName}`] = [\n embedding.data as Uint8Array,\n { level: levelForMediaName(embedding.fileName, mediaLevel) as ZipOptions[\"level\"] },\n ];\n }\n\n // Font files — only fonts carrying binary data produce a .odttf part.\n // Round-tripped fonts (rawOdttf) keep their original obfuscated bytes.\n for (const font of ctx.fontTable.fontOptionsWithKey) {\n if (font.data === undefined) continue;\n const [nameWithoutExtension] = font.name.split(\".\");\n const filePath = font.odttfPath ?? `word/fonts/${nameWithoutExtension}.odttf`;\n files[filePath] = font.rawOdttf ? font.data : obfuscate(font.data, font.fontKey);\n }\n\n // Raw passthrough parts (word/theme/*, customXml/*, …) — generate doesn't\n // rebuild these, so copy their original bytes verbatim to keep [Content_Types]\n // declarations valid and the package openable in Word.\n for (const part of ctx._options.rawParts ?? []) {\n files[part.path] = part.data;\n }\n\n // [Content_Types].xml is serialized last: parts register their media/fonts\n // during stringify (run by xmlifyContext above), so backfilling <Default>\n // extensions from `ctx` now sees the complete set. Building it inside\n // xmlifyContext's object literal evaluated it before header/footer/font media\n // was registered, leaving jpg/gif/odttf without a covering Default.\n files[\"[Content_Types].xml\"] = encoder.encode(buildContentTypesData(ctx, files));\n\n return files;\n}\n\n// ── Internal ──\n\n/**\n * Complete mapping of all XML files in an OOXML document package.\n */\ninterface XmlifyedFileMapping {\n Document: XmlifyedFile;\n Styles: XmlifyedFile;\n Properties: XmlifyedFile;\n Numbering?: XmlifyedFile;\n Relationships: XmlifyedFile;\n FileRelationships: XmlifyedFile;\n Headers: XmlifyedFile[];\n Footers: XmlifyedFile[];\n HeaderRelationships: XmlifyedFile[];\n FooterRelationships: XmlifyedFile[];\n CustomProperties: XmlifyedFile;\n AppProperties: XmlifyedFile;\n FootNotes?: XmlifyedFile;\n FootNotesRelationships?: XmlifyedFile;\n Endnotes?: XmlifyedFile;\n EndnotesRelationships?: XmlifyedFile;\n Settings: XmlifyedFile;\n Comments?: XmlifyedFile;\n CommentsRelationships?: XmlifyedFile;\n FontTable?: XmlifyedFile;\n FontTableRelationships?: XmlifyedFile;\n Bibliography?: XmlifyedFile;\n Charts?: XmlifyedFile[];\n DiagramData?: XmlifyedFile[];\n DiagramLayout?: XmlifyedFile[];\n DiagramStyle?: XmlifyedFile[];\n DiagramColors?: XmlifyedFile[];\n DiagramDrawing?: XmlifyedFile[];\n AltChunks?: XmlifyedFile[];\n SubDocs?: XmlifyedFile[];\n Glossary?: XmlifyedFile;\n WebSettings?: XmlifyedFile;\n}\n\n/**\n * Comments carried by the document: those the caller listed explicitly\n * (`options.comments`) plus entries registered by `{ comment }` sugar children\n * during body stringification. Drives both word/comments.xml generation and the\n * [Content_Types] comments Override, which must stay in sync (OPC consistency).\n */\nfunction mergedCommentChildren(ctx: DocxWriteContext): CommentOptions[] {\n return [...(ctx._options.comments?.children ?? []), ...ctx.comments.entries];\n}\n\n/**\n * Serialize [Content_Types].xml from the part registry, then backfill media/\n * font/embedding `<Default>` entries from the parts actually written.\n *\n * Must run after every part has been stringified (parts call `ctx.addMedia`\n * during stringify), so call this once `xmlifyContext` has finished — not from\n * inside its object literal, where ContentTypes would evaluate before the\n * later-defined header/footer/font parts have registered their media.\n */\nfunction buildContentTypesData(ctx: DocxWriteContext, files: Zippable): string {\n const altChunks = ctx.altChunks.array.map((ac) => ({\n path: `/word/${ac.path}`,\n contentType: ac.contentType ?? \"application/xhtml+xml\",\n }));\n // Round-trip passes the source [Content_Types] through, but the compiler\n // regenerates altChunk part paths — realign the afchunk Overrides to the\n // freshly written parts (else O5/O6).\n const base = ctx._options.contentTypes\n ? ensureCustomPropertiesOverride(withAltChunkOverrides(ctx._options.contentTypes, altChunks))\n : buildContentTypesFromRegistry(\n new Map<string, boolean | number>([\n [\"freshCompile\", true],\n [\"hasComments\", mergedCommentChildren(ctx).length > 0],\n [\"hasBibliography\", !!ctx._options.bibliography],\n [\"hasGlossary\", !!ctx.glossaryOptions],\n [\"hasWebSettings\", !!ctx.webSettings],\n [\"headerCount\", ctx.headers.length],\n [\"footerCount\", ctx.footers.length],\n [\"chartCount\", ctx.charts.array.length],\n [\"smartArtCount\", ctx.smartArts.array.length],\n ]),\n {\n altChunks,\n subDocs: ctx.subDocs.array.map((sd) => ({ path: `/word/${sd.path}` })),\n },\n );\n // Backfill <Default> extensions from every part actually written to the\n // package — the parts on disk are the single source of truth, so media/font/\n // embedding defaults can never drift from what the package contains (e.g. a\n // font written via the fallback path when `odttfPath` is unset).\n const withMedia = withMediaDefaults(base, Object.keys(files));\n return XML_DECL + (contentTypesDesc.stringify(withMedia, ctx) ?? \"\");\n}\n\nfunction xmlifyContext(\n ctx: DocxWriteContext,\n headerFormattedViews: Map<number, string>,\n footerFormattedViews: Map<number, string>,\n): XmlifyedFileMapping {\n const mkCtx = (viewWrapper: DocxContext[\"viewWrapper\"] = ctx.document): DocxContext => ({\n fileData: ctx,\n file: ctx,\n viewWrapper,\n stringifyChild: stringifyBodyChild,\n addRelationship: (type: string, target: string, mode?: string) =>\n ctx.addRelationship(type, target, mode),\n addMedia: (data: Uint8Array, type: string) => ctx.addMedia(data, type),\n });\n\n const documentRelationshipCount = ctx.document.relationships.relationshipCount + 1;\n // Per-part media-replacement results shared between the .rels pass and the\n // body-XML pass so both use identical rId offsets. Each header/footer part\n // has its own relationship numbering (independent of the document part).\n const footerMediaResults = new Map<number, { xml: string; referenced: { fileName: string }[] }>();\n const headerMediaResults = new Map<number, { xml: string; referenced: { fileName: string }[] }>();\n const docCtx = mkCtx(ctx.document);\n const documentXmlData = XML_DECL + stringifyDocumentXml(ctx, docCtx);\n\n // Comments is an optional part — skip it entirely (no comments.xml, no\n // comments rels, no [Content_Types] Override) when the document carries none.\n // Emitting an empty comments.xml with a dangling relationship is the OPC\n // violation that makes Word reject the package on open.\n const mergedCommentChildrenList = mergedCommentChildren(ctx);\n const hasComments = mergedCommentChildrenList.length > 0;\n const commentRelationshipCount = hasComments\n ? ctx.comments.relationships.relationshipCount + 1\n : 0;\n const commentCtx = hasComments ? mkCtx({ relationships: ctx.comments.relationships }) : null;\n const commentXmlData = commentCtx\n ? XML_DECL + commentsDesc.stringify({ children: mergedCommentChildrenList }, commentCtx)\n : \"\";\n\n const footnoteRelationshipCount = ctx.footNotes.relationships.relationshipCount + 1;\n const footnoteCtx = mkCtx({\n relationships: ctx.footNotes.relationships,\n });\n const footnoteXmlData =\n XML_DECL +\n (footnotesDesc.stringify(\n {\n notes: ctx.footNotes.notes,\n separator: ctx.footNotes.separator,\n continuationSeparator: ctx.footNotes.continuationSeparator,\n },\n footnoteCtx,\n ) ?? \"\");\n\n const documentMedia = findAndReplaceImagePlaceholders(\n documentXmlData,\n ctx.media.array,\n documentRelationshipCount,\n );\n // OLE embeddings reuse the same {fileName} placeholder bridge as images; run\n // after media so {oleObjectN.bin} placeholders resolve against the embedding array.\n const documentEmbeddingOffset = documentRelationshipCount + documentMedia.referenced.length;\n const documentEmbeddings = findAndReplaceImagePlaceholders(\n documentMedia.xml,\n ctx.embeddings.array,\n documentEmbeddingOffset,\n );\n const commentMedia = hasComments\n ? findAndReplaceImagePlaceholders(commentXmlData, ctx.media.array, commentRelationshipCount)\n : { xml: \"\", referenced: [] as { fileName: string }[] };\n const footnoteMedia = findAndReplaceImagePlaceholders(\n footnoteXmlData,\n ctx.media.array,\n footnoteRelationshipCount,\n );\n // Register footnote media relationships eagerly so the relationshipCount used\n // to gate footnotes.xml.rels reflects the final state (see FootNotesRelationships).\n for (const [i, ref] of footnoteMedia.referenced.entries()) {\n ctx.footNotes.relationships.addRelationship(\n footnoteRelationshipCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${ref.fileName}`,\n );\n }\n\n return {\n AppProperties: {\n data: XML_DECL + (appPropertiesDesc.stringify(ctx._options.appProperties ?? {}, ctx) ?? \"\"),\n path: \"docProps/app.xml\",\n },\n ...(hasComments\n ? {\n Comments: {\n data: (() => {\n const xmlData =\n commentMedia.referenced.length > 0 ? commentMedia.xml : commentXmlData;\n return replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/comments.xml\",\n },\n CommentsRelationships: (() => {\n for (const [i, ref] of commentMedia.referenced.entries()) {\n ctx.comments.relationships.addRelationship(\n commentRelationshipCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${ref.fileName}`,\n );\n }\n return optionalRelsPart(\n ctx.comments.relationships,\n XML_DECL,\n \"word/_rels/comments.xml.rels\",\n );\n })(),\n }\n : {}),\n CustomProperties: {\n data:\n XML_DECL +\n (customPropertiesDesc.stringify({ properties: ctx._options.customProperties ?? [] }, ctx) ??\n \"\"),\n path: \"docProps/custom.xml\",\n },\n Document: {\n data: (() => {\n let xmlData = documentEmbeddings.xml;\n if (hasPlaceholders(xmlData)) {\n const mediaCount = documentMedia.referenced.length;\n const embeddingCount = documentEmbeddings.referenced.length;\n const chartKeys = ctx.charts.array.map((c) => c.key);\n const smartArtKeys = ctx.smartArts.array.map((s) => s.key);\n const chartOffset = documentRelationshipCount + mediaCount + embeddingCount;\n const smartArtOffset = chartOffset + chartKeys.length;\n\n // Build combined replacement entries for charts, smartart, and numbering\n const entries: Array<{ prefix?: string; key: string; value: string }> = [];\n for (const [i, key] of chartKeys.entries()) {\n entries.push({\n prefix: \"chart:\",\n key,\n value: formatId(chartOffset, i, \"rId\"),\n });\n }\n const saPrefixes = [\"smartart:\", \"smartart-lo:\", \"smartart-qs:\", \"smartart-cs:\"];\n for (const [i, key] of smartArtKeys.entries()) {\n for (let p = 0; p < saPrefixes.length; p++) {\n entries.push({\n prefix: saPrefixes[p],\n key,\n value: formatId(smartArtOffset + p * smartArtKeys.length, i, \"rId\"),\n });\n }\n }\n for (const { reference, instance, numId } of ctx.numbering.concreteNumbering) {\n entries.push({ key: `${reference}-${instance}`, value: numId.toString() });\n }\n xmlData = replaceAllPlaceholders(xmlData, entries);\n } else {\n xmlData = replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n }\n return xmlData;\n })(),\n path: \"word/document.xml\",\n },\n // Theme — fresh-compile emits a language-neutral default theme\n // (createThemeXml). Round-trip carries the source theme in rawParts,\n // already copied verbatim above, so skip emitting here to avoid a duplicate.\n ...(ctx._options.rawParts?.some((part) => part.path.startsWith(\"word/theme/\"))\n ? {}\n : {\n Theme: {\n data: XML_DECL + createThemeXml(),\n path: \"word/theme/theme1.xml\",\n },\n }),\n ...(ctx.hasEndnotes\n ? {\n Endnotes: {\n data: (() => {\n const endnoteCtx = mkCtx({\n relationships: ctx.endnotes.relationships,\n });\n const xmlData =\n XML_DECL +\n (endnotesDesc.stringify(\n {\n notes: ctx.endnotes.notes,\n separator: ctx.endnotes.separator,\n continuationSeparator: ctx.endnotes.continuationSeparator,\n },\n endnoteCtx,\n ) ?? \"\");\n const endnoteRelCount = ctx.endnotes.relationships.relationshipCount + 1;\n const endnoteMedia = findAndReplaceImagePlaceholders(\n xmlData,\n ctx.media.array,\n endnoteRelCount,\n );\n if (endnoteMedia.referenced.length > 0) {\n for (const [i, ref] of endnoteMedia.referenced.entries()) {\n ctx.endnotes.relationships.addRelationship(\n endnoteRelCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${ref.fileName}`,\n );\n }\n return replaceNumberingPlaceholders(\n endnoteMedia.xml,\n ctx.numbering.concreteNumbering,\n );\n }\n return replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/endnotes.xml\",\n },\n EndnotesRelationships:\n ctx.endnotes.relationships.relationshipCount > 0\n ? {\n data: XML_DECL + ctx.endnotes.relationships.serialize(),\n path: \"word/_rels/endnotes.xml.rels\",\n }\n : undefined,\n }\n : {}),\n FileRelationships: {\n data: XML_DECL + ctx.fileRelationships.serialize(),\n path: \"_rels/.rels\",\n },\n FontTable: {\n data:\n XML_DECL +\n (fontTableDesc.stringify({ fonts: ctx.fontTable.fontOptionsWithKey }, ctx) ?? \"\"),\n path: \"word/fontTable.xml\",\n },\n FontTableRelationships: optionalRelsPart(\n ctx.fontTable.relationships,\n XML_DECL,\n \"word/_rels/fontTable.xml.rels\",\n ),\n ...(ctx.hasFootnotes\n ? {\n FootNotes: {\n data: (() => {\n const xmlData =\n footnoteMedia.referenced.length > 0 ? footnoteMedia.xml : footnoteXmlData;\n return replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/footnotes.xml\",\n },\n FootNotesRelationships:\n ctx.footNotes.relationships.relationshipCount > 0\n ? {\n data: XML_DECL + ctx.footNotes.relationships.serialize(),\n path: \"word/_rels/footnotes.xml.rels\",\n }\n : undefined,\n }\n : {}),\n FooterRelationships: ctx.footers\n .map((entry, index) => {\n const footerCtx = mkCtx({ relationships: entry.relationships });\n const xmlData =\n XML_DECL + stringifyHeaderFooter(\"w:ftr\", FOOTER_NAMESPACES, entry.children, footerCtx);\n footerFormattedViews.set(index, xmlData);\n // Footer images get per-part relationship IDs starting at\n // relationshipCount+1, mirroring the document part. The placeholder pass\n // uses referenced-local positions, so body r:embed and .rels stay aligned.\n const footerRelCount = entry.relationships.relationshipCount + 1;\n const footerMedia = findAndReplaceImagePlaceholders(\n xmlData,\n ctx.media.array,\n footerRelCount,\n );\n footerMediaResults.set(index, footerMedia);\n\n for (const [i, ref] of footerMedia.referenced.entries()) {\n entry.relationships.addRelationship(\n footerRelCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${ref.fileName}`,\n );\n }\n\n return optionalRelsPart(\n entry.relationships,\n XML_DECL,\n `word/_rels/footer${index + 1}.xml.rels`,\n );\n })\n .filter((r): r is XmlifyedFile => r !== undefined),\n Footers: ctx.footers.map((_entry, index) => {\n const footerMedia = footerMediaResults.get(index)!;\n const tempXmlData = footerFormattedViews.get(index)!;\n const xmlData = footerMedia.referenced.length > 0 ? footerMedia.xml : tempXmlData;\n\n return {\n data: replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering),\n path: `word/footer${index + 1}.xml`,\n };\n }),\n HeaderRelationships: ctx.headers\n .map((entry, index) => {\n const headerCtx = mkCtx({ relationships: entry.relationships });\n const xmlData =\n XML_DECL + stringifyHeaderFooter(\"w:hdr\", HEADER_NAMESPACES, entry.children, headerCtx);\n headerFormattedViews.set(index, xmlData);\n // Header images get per-part relationship IDs starting at\n // relationshipCount+1, mirroring the document part. The placeholder pass\n // uses referenced-local positions, so body r:embed and .rels stay aligned.\n const headerRelCount = entry.relationships.relationshipCount + 1;\n const headerMedia = findAndReplaceImagePlaceholders(\n xmlData,\n ctx.media.array,\n headerRelCount,\n );\n headerMediaResults.set(index, headerMedia);\n\n for (const [i, ref] of headerMedia.referenced.entries()) {\n entry.relationships.addRelationship(\n headerRelCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${ref.fileName}`,\n );\n }\n\n return optionalRelsPart(\n entry.relationships,\n XML_DECL,\n `word/_rels/header${index + 1}.xml.rels`,\n );\n })\n .filter((r): r is XmlifyedFile => r !== undefined),\n Headers: ctx.headers.map((_entry, index) => {\n const headerMedia = headerMediaResults.get(index)!;\n const tempXmlData = headerFormattedViews.get(index)!;\n const xmlData = headerMedia.referenced.length > 0 ? headerMedia.xml : tempXmlData;\n\n return {\n data: replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering),\n path: `word/header${index + 1}.xml`,\n };\n }),\n ...(ctx.hasNumbering\n ? {\n Numbering: {\n data: ctx.numbering.serialize(),\n path: \"word/numbering.xml\",\n },\n }\n : {}),\n Properties: {\n data: XML_DECL + (corePropertiesDesc.stringify(ctx._options, ctx) ?? \"\"),\n path: \"docProps/core.xml\",\n },\n Relationships: {\n data: (() => {\n for (const [i, ref] of documentMedia.referenced.entries()) {\n ctx.document.relationships.addRelationship(\n documentRelationshipCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${ref.fileName}`,\n );\n }\n for (const [i, ref] of documentEmbeddings.referenced.entries()) {\n ctx.document.relationships.addRelationship(\n documentEmbeddingOffset + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject\",\n `embeddings/${ref.fileName}`,\n );\n }\n\n const chartOffset =\n documentRelationshipCount +\n documentMedia.referenced.length +\n documentEmbeddings.referenced.length;\n for (let i = 0; i < ctx.charts.array.length; i++) {\n ctx.document.relationships.addRelationship(\n chartOffset + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart\",\n `charts/chart${i + 1}.xml`,\n );\n }\n\n addSmartArtRelationships(\n ctx.smartArts.array.map((s) => s.key),\n (id, type, target) => {\n ctx.document.relationships.addRelationship(id, type, target);\n },\n documentRelationshipCount +\n documentMedia.referenced.length +\n documentEmbeddings.referenced.length +\n ctx.charts.array.length,\n 0,\n {\n pathPrefix: \"\",\n styleRelType: \"http://schemas.microsoft.com/office/2007/relationships/diagramStyle\",\n },\n );\n\n ctx.document.relationships.addRelationship(\n ctx.document.relationships.relationshipCount + 1,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable\",\n \"fontTable.xml\",\n );\n\n return XML_DECL + ctx.document.relationships.serialize();\n })(),\n path: \"word/_rels/document.xml.rels\",\n },\n Settings: {\n data: XML_DECL + (settingsDesc.stringify(ctx._settingsOptions, ctx) ?? \"\"),\n path: \"word/settings.xml\",\n },\n Styles: {\n data: (() => {\n const xmlStyles = ctx.styles.serialize();\n return replaceNumberingPlaceholders(xmlStyles, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/styles.xml\",\n },\n ...(ctx._options.bibliography\n ? {\n Bibliography: {\n data: XML_DECL + (bibliographyDesc.stringify(ctx._options.bibliography, ctx) ?? \"\"),\n path: \"word/bibliography.xml\",\n },\n }\n : {}),\n ...(ctx.charts.array.length > 0\n ? {\n Charts: ctx.charts.array.map((chartData, i) => ({\n data: XML_DECL + chartData.chartSpaceXml,\n path: `word/charts/chart${i + 1}.xml`,\n })),\n }\n : {}),\n ...(ctx.smartArts.array.length > 0\n ? {\n DiagramData: ctx.smartArts.array.map((smartArtData, i) => ({\n data: XML_DECL + smartArtData.dataModelXml,\n path: `word/diagrams/data${i + 1}.xml`,\n })),\n DiagramLayout: ctx.smartArts.array.map((smartArtData, i) => ({\n data: getLayoutXml(smartArtData.layout),\n path: `word/diagrams/layout${i + 1}.xml`,\n })),\n DiagramStyle: ctx.smartArts.array.map((smartArtData, i) => ({\n data: getStyleXml(smartArtData.style),\n path: `word/diagrams/quickStyle${i + 1}.xml`,\n })),\n DiagramColors: ctx.smartArts.array.map((smartArtData, i) => ({\n data: getColorXml(smartArtData.color),\n path: `word/diagrams/colors${i + 1}.xml`,\n })),\n DiagramDrawing: ctx.smartArts.array.map((_, i) => ({\n data: DEFAULT_DRAWING_XML,\n path: `word/diagrams/drawing${i + 1}.xml`,\n })),\n }\n : {}),\n ...(ctx.altChunks.array.length > 0\n ? {\n AltChunks: ctx.altChunks.array.map((altChunkData) => ({\n data: altChunkData.data,\n path: `word/${altChunkData.path}`,\n })),\n }\n : {}),\n ...(ctx.subDocs.array.length > 0\n ? {\n SubDocs: ctx.subDocs.array.map((subDocData) => ({\n data: subDocData.data,\n path: `word/${subDocData.path}`,\n })),\n }\n : {}),\n ...(ctx.glossaryOptions\n ? {\n Glossary: {\n data: (() => {\n const glossaryCtx = mkCtx(undefined);\n return XML_DECL + (glossaryDesc.stringify(ctx.glossaryOptions!, glossaryCtx) ?? \"\");\n })(),\n path: \"word/glossary/document.xml\",\n },\n }\n : {}),\n ...(ctx.webSettings\n ? {\n WebSettings: {\n data: XML_DECL + (webSettingsDesc.stringify(ctx._options.webSettings ?? {}, ctx) ?? \"\"),\n path: \"word/webSettings.xml\",\n },\n }\n : {}),\n };\n}\n","/**\n * Pure function API for generating DOCX files.\n *\n * @module\n */\n\nimport { createPacker, OoxmlMimeType } from \"@office-open/core\";\nimport type { OutputByType, OutputType, PackerOptions } from \"@office-open/core\";\nimport type { DocumentOptions } from \"@parts/core-properties\";\n\nimport { compileDocument } from \"./compiler\";\n\n/** @internal Packer instance for DOCX generation. */\nconst Packer = createPacker<DocumentOptions>({\n compile: (options, overrides, mediaLevel) => compileDocument(options, overrides, mediaLevel),\n mimeType: OoxmlMimeType.DOCX,\n});\n\n/**\n * Generate a DOCX file from pure JSON options.\n *\n * The output format is controlled by `packerOptions.type` (default: `\"nodebuffer\"` → Buffer).\n * For synchronous generation, use {@link generateDocumentSync}. For streaming, use {@link generateDocumentStream}.\n *\n * @param options - Document options (sections, styles, numbering, etc.)\n * @param packerOptions - Optional packer configuration (type, compression, overrides, etc.)\n *\n * @example\n * ```typescript\n * import { generateDocument } from \"@office-open/docx\";\n *\n * const buffer = await generateDocument({ sections: [...] });\n * const bytes = await generateDocument({ sections: [...] }, { type: \"uint8array\" });\n * const blob = await generateDocument({ sections: [...] }, { type: \"blob\" });\n * ```\n */\nexport function generateDocument<T extends OutputType = \"nodebuffer\">(\n options: DocumentOptions,\n packerOptions?: PackerOptions<T>,\n): Promise<OutputByType[T]> {\n return Packer.pack(options, packerOptions) as Promise<OutputByType[T]>;\n}\n\n/**\n * Synchronously generate a DOCX file from pure JSON options.\n */\nexport function generateDocumentSync<T extends OutputType = \"nodebuffer\">(\n options: DocumentOptions,\n packerOptions?: PackerOptions<T>,\n): OutputByType[T] {\n return Packer.packSync(options, packerOptions) as OutputByType[T];\n}\n\n/**\n * Generate a DOCX file as a `ReadableStream<Uint8Array>`.\n */\nexport function generateDocumentStream(\n options: DocumentOptions,\n packerOptions?: PackerOptions,\n): ReadableStream<Uint8Array> {\n return Packer.toStream(options, packerOptions);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAaA,MAAM,wBAAwB;;AAE9B,MAAM,sBAAsB;;AAE5B,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;AAuBjB,MAAa,aAAa,KAAiB,YAAgC;CACzE,MAAM,OAAO,QAAQ,QAAQ,MAAM,EAAE;CACrC,IAAI,KAAK,WAAW,UAClB,MAAM,IAAI,MAAM,kDAAkD,SAAS;CAI7E,MAAM,aADa,KAAK,QAAQ,SAAS,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,MAAM,GACjC,CAAC,CAAC,KAAK,cAAc,SAAS,WAAW,EAAE,CAAC;CACxE,WAAW,QAAQ;CAGnB,MAAM,kBADmB,IAAI,MAAM,uBAAuB,mBACnB,CAAC,CAAC,KACtC,MAAM,MAAM,OAAO,WAAW,IAAI,WAAW,OAChD;CAEA,MAAM,MAAM,IAAI,WACd,wBAAwB,gBAAgB,SAAS,KAAK,IAAI,GAAG,IAAI,SAAS,mBAAmB,CAC/F;CACA,IAAI,IAAI,IAAI,MAAM,GAAG,qBA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