@viveeditor/docx 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1301 @@
1
+ import { isAllowedUrl } from "@viveeditor/core";
2
+ import { normalizeColor } from "@viveeditor/ext-format";
3
+ import { DEFAULT_SOURCE_POLICY, imageSize, normalizeImageSrc, sniffImageType } from "@viveeditor/ext-image";
4
+ import { Inflate, zipSync } from "fflate";
5
+ // src/errors.ts
6
+ var DocxError = class extends Error {
7
+ code;
8
+ constructor(code, message) {
9
+ super(message);
10
+ this.name = "DocxError";
11
+ this.code = code;
12
+ }
13
+ };
14
+ function throwIfAborted(signal) {
15
+ if (signal?.aborted) throw new DocxError("ABORTED", "The import was cancelled.");
16
+ }
17
+ // src/xml.ts
18
+ const NS = {
19
+ w: "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
20
+ r: "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
21
+ a: "http://schemas.openxmlformats.org/drawingml/2006/main",
22
+ wp: "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
23
+ pic: "http://schemas.openxmlformats.org/drawingml/2006/picture",
24
+ mc: "http://schemas.openxmlformats.org/markup-compatibility/2006",
25
+ rel: "http://schemas.openxmlformats.org/package/2006/relationships"
26
+ };
27
+ const FORBIDDEN = /<!(?:DOCTYPE|ENTITY)/i;
28
+ function decode(bytes) {
29
+ const encoding = bytes.length >= 2 && (bytes[0] === 255 && bytes[1] === 254 || bytes[0] === 254 && bytes[1] === 255) ? bytes[0] === 255 ? "utf-16le" : "utf-16be" : "utf-8";
30
+ try {
31
+ return new TextDecoder(encoding, { fatal: true }).decode(bytes);
32
+ } catch {
33
+ throw new DocxError("DAMAGED", "The Word document is damaged.");
34
+ }
35
+ }
36
+ function parseXml(bytes) {
37
+ const source = decode(bytes);
38
+ if (FORBIDDEN.test(source)) throw new DocxError("UNSUPPORTED", "The Word document contains a document type declaration.");
39
+ const doc = new DOMParser().parseFromString(source, "application/xml");
40
+ if (doc.getElementsByTagName("parsererror").length > 0) throw new DocxError("DAMAGED", "The Word document is damaged.");
41
+ return doc;
42
+ }
43
+ const is = (node, ns, name) => node?.nodeType === Node.ELEMENT_NODE && node.namespaceURI === ns && node.localName === name;
44
+ function child(element, ns, name) {
45
+ if (!element) return null;
46
+ for (const node of element.children) if (is(node, ns, name)) return node;
47
+ return null;
48
+ }
49
+ function children(element, ns, name) {
50
+ return element ? [...element.children].filter((node) => is(node, ns, name)) : [];
51
+ }
52
+ function descendant(element, path) {
53
+ let current = element;
54
+ for (const [ns, name] of path) current = child(current, ns, name);
55
+ return current;
56
+ }
57
+ const wAttr = (element, name) => element?.getAttributeNS(NS.w, name) ?? null;
58
+ function onOff(element) {
59
+ if (!element) return false;
60
+ const value = wAttr(element, "val");
61
+ return value === null || ![
62
+ "0",
63
+ "false",
64
+ "off",
65
+ "none"
66
+ ].includes(value);
67
+ }
68
+ // src/zip.ts
69
+ const CENTRAL_SIGNATURE = 33639248;
70
+ const END_SIGNATURE = 101010256;
71
+ const LOCAL_SIGNATURE = 67324752;
72
+ const CHUNK = 4096;
73
+ function findEnd(view) {
74
+ const lowest = Math.max(0, view.byteLength - 22 - 65535);
75
+ for (let offset = view.byteLength - 22; offset >= lowest; offset--) if (view.getUint32(offset, true) === END_SIGNATURE) return offset;
76
+ throw new DocxError("NOT_DOCX", "The file is not a Word document.");
77
+ }
78
+ function readEntries(bytes) {
79
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
80
+ const end = findEnd(view);
81
+ const count = view.getUint16(end + 10, true);
82
+ let offset = view.getUint32(end + 16, true);
83
+ const decoder = new TextDecoder("utf-8", { fatal: true });
84
+ const entries = [];
85
+ for (let index = 0; index < count; index++) {
86
+ if (offset + 46 > bytes.length || view.getUint32(offset, true) !== CENTRAL_SIGNATURE) throw new DocxError("DAMAGED", "The Word document is damaged.");
87
+ const flags = view.getUint16(offset + 8, true);
88
+ const nameLength = view.getUint16(offset + 28, true);
89
+ const extraLength = view.getUint16(offset + 30, true);
90
+ const commentLength = view.getUint16(offset + 32, true);
91
+ if (flags & 1) throw new DocxError("ENCRYPTED", "The Word document is password protected.");
92
+ if (offset + 46 + nameLength > bytes.length) throw new DocxError("DAMAGED", "The Word document is damaged.");
93
+ let name;
94
+ try {
95
+ name = decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength));
96
+ } catch {
97
+ throw new DocxError("DAMAGED", "The Word document is damaged.");
98
+ }
99
+ entries.push({
100
+ name,
101
+ method: view.getUint16(offset + 10, true),
102
+ compressedSize: view.getUint32(offset + 20, true),
103
+ localOffset: view.getUint32(offset + 42, true)
104
+ });
105
+ offset += 46 + nameLength + extraLength + commentLength;
106
+ }
107
+ return entries;
108
+ }
109
+ function dataStart(bytes, entry) {
110
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
111
+ const offset = entry.localOffset;
112
+ if (offset + 30 > bytes.length || view.getUint32(offset, true) !== LOCAL_SIGNATURE) throw new DocxError("DAMAGED", "The Word document is damaged.");
113
+ const start = offset + 30 + view.getUint16(offset + 26, true) + view.getUint16(offset + 28, true);
114
+ if (start + entry.compressedSize > bytes.length) throw new DocxError("DAMAGED", "The Word document is damaged.");
115
+ return start;
116
+ }
117
+ function inflateLimited(data, limit, onBytes) {
118
+ const chunks = [];
119
+ let size = 0;
120
+ let finished = false;
121
+ const inflate = new Inflate((chunk, final) => {
122
+ size += chunk.length;
123
+ onBytes(chunk.length);
124
+ if (size > limit) throw new DocxError("TOO_LARGE", "A part of the Word document is too large.");
125
+ chunks.push(chunk);
126
+ if (final) finished = true;
127
+ });
128
+ try {
129
+ for (let offset = 0; offset < data.length; offset += CHUNK) {
130
+ const end = Math.min(offset + CHUNK, data.length);
131
+ inflate.push(data.subarray(offset, end), end === data.length);
132
+ }
133
+ } catch (error) {
134
+ if (error instanceof DocxError) throw error;
135
+ throw new DocxError("DAMAGED", "The Word document is damaged.");
136
+ }
137
+ if (!finished && data.length > 0) throw new DocxError("DAMAGED", "The Word document is damaged.");
138
+ const output = new Uint8Array(size);
139
+ let position = 0;
140
+ for (const chunk of chunks) {
141
+ output.set(chunk, position);
142
+ position += chunk.length;
143
+ }
144
+ return output;
145
+ }
146
+ function readZip(bytes, wanted, limits) {
147
+ const entries = readEntries(bytes);
148
+ const seen = /* @__PURE__ */ new Set();
149
+ for (const entry of entries) {
150
+ if (seen.has(entry.name)) throw new DocxError("DAMAGED", "The Word document is damaged.");
151
+ seen.add(entry.name);
152
+ }
153
+ const parts = /* @__PURE__ */ new Map();
154
+ let total = 0;
155
+ const count = (size) => {
156
+ total += size;
157
+ if (total > limits.totalBytes) throw new DocxError("TOO_LARGE", "The Word document expands to too much data.");
158
+ };
159
+ for (const entry of entries) {
160
+ if (!wanted(entry.name)) continue;
161
+ if (entry.method !== 0 && entry.method !== 8) throw new DocxError("UNSUPPORTED", "The Word document uses an unsupported compression.");
162
+ const start = dataStart(bytes, entry);
163
+ const data = bytes.subarray(start, start + entry.compressedSize);
164
+ const limit = limits.partBytes(entry.name);
165
+ if (entry.method === 0) {
166
+ if (data.length > limit) throw new DocxError("TOO_LARGE", "A part of the Word document is too large.");
167
+ count(data.length);
168
+ parts.set(entry.name, data.slice());
169
+ } else parts.set(entry.name, inflateLimited(data, limit, count));
170
+ }
171
+ return parts;
172
+ }
173
+ // src/read.ts
174
+ const DEFAULT_IMPORT_LIMITS = Object.freeze({
175
+ fileBytes: 20971520,
176
+ totalBytes: 104857600,
177
+ documentBytes: 31457280,
178
+ partBytes: 5242880,
179
+ imageBytes: 10485760,
180
+ images: 200,
181
+ imagePixels: 5e7,
182
+ elements: 1e5,
183
+ cells: 1e4
184
+ });
185
+ const REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
186
+ const REL_OFFICE_DOCUMENT = `${REL}/officeDocument`;
187
+ const REL_HYPERLINK = `${REL}/hyperlink`;
188
+ const REL_IMAGE = `${REL}/image`;
189
+ const MAX_DEPTH = 64;
190
+ const MAX_TABLE_DEPTH = 3;
191
+ const MAX_COLUMNS = 100;
192
+ const MAX_DIMENSION$1 = 1e4;
193
+ const MAX_TEXT = 1e3;
194
+ const MAX_LINK = 2048;
195
+ const EMU_PER_PIXEL$1 = 9525;
196
+ const isControl = (code) => code <= 31 && code !== 9 && code !== 10 && code !== 13 || code === 127;
197
+ const isInvisible = (code) => code <= 32 || code >= 127 && code <= 160 || code === 173 || code >= 8203 && code <= 8207 || code >= 8232 && code <= 8238 || code >= 8288 && code <= 8303 || code === 65279;
198
+ function without(value, drop) {
199
+ let result = "";
200
+ for (const character of value) if (!drop(character.codePointAt(0) ?? 0)) result += character;
201
+ return result;
202
+ }
203
+ const LINK_PROTOCOLS = /* @__PURE__ */ new Set([
204
+ "http:",
205
+ "https:",
206
+ "mailto:"
207
+ ]);
208
+ const HIGHLIGHTS = {
209
+ yellow: "#ffff00",
210
+ green: "#00ff00",
211
+ cyan: "#00ffff",
212
+ magenta: "#ff00ff",
213
+ blue: "#0000ff",
214
+ red: "#ff0000",
215
+ darkBlue: "#000080",
216
+ darkCyan: "#008080",
217
+ darkGreen: "#008000",
218
+ darkMagenta: "#800080",
219
+ darkRed: "#800000",
220
+ darkYellow: "#808000",
221
+ darkGray: "#808080",
222
+ lightGray: "#c0c0c0",
223
+ black: "#000000"
224
+ };
225
+ const CODE_CHARACTER_STYLES = /* @__PURE__ */ new Set([
226
+ "code char",
227
+ "html code",
228
+ "verbatim char",
229
+ "source text"
230
+ ]);
231
+ const ALIGNMENTS$1 = {
232
+ center: "center",
233
+ right: "right",
234
+ end: "right",
235
+ both: "justify",
236
+ distribute: "justify"
237
+ };
238
+ function cleanLimits$1(input) {
239
+ const limits = { ...DEFAULT_IMPORT_LIMITS };
240
+ for (const key of Object.keys(limits)) {
241
+ const value = input?.[key];
242
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) limits[key] = value;
243
+ }
244
+ return limits;
245
+ }
246
+ function clampInt(value, min, max, fallback) {
247
+ const number = Number.parseInt(value ?? "", 10);
248
+ return Number.isFinite(number) ? Math.min(max, Math.max(min, number)) : fallback;
249
+ }
250
+ function cleanText(value, max = MAX_TEXT) {
251
+ return without(value ?? "", isControl).trim().slice(0, max);
252
+ }
253
+ function cleanLink(target) {
254
+ const value = without(target, isInvisible);
255
+ if (value === "" || value.length > MAX_LINK) return null;
256
+ let url;
257
+ try {
258
+ url = new URL(value);
259
+ } catch {
260
+ return null;
261
+ }
262
+ if (!LINK_PROTOCOLS.has(url.protocol)) return null;
263
+ return isAllowedUrl(url.href) ? url.href : null;
264
+ }
265
+ function resolvePart(base, target) {
266
+ const segments = (target.startsWith("/") ? target.slice(1) : base + target).split("/");
267
+ const resolved = [];
268
+ for (const segment of segments) if (segment === "..") {
269
+ if (resolved.length === 0) return null;
270
+ resolved.pop();
271
+ } else if (segment !== "." && segment !== "") resolved.push(segment);
272
+ return resolved.join("/");
273
+ }
274
+ function readRelationships(doc) {
275
+ const relationships = /* @__PURE__ */ new Map();
276
+ if (!doc) return relationships;
277
+ for (const element of children(doc.documentElement, NS.rel, "Relationship")) {
278
+ const id = element.getAttribute("Id");
279
+ if (!id || relationships.has(id)) continue;
280
+ relationships.set(id, {
281
+ type: element.getAttribute("Type") ?? "",
282
+ target: element.getAttribute("Target") ?? "",
283
+ external: element.getAttribute("TargetMode") === "External"
284
+ });
285
+ }
286
+ return relationships;
287
+ }
288
+ function readStyles(doc) {
289
+ const paragraphs = /* @__PURE__ */ new Map();
290
+ const runs = /* @__PURE__ */ new Map();
291
+ if (!doc) return {
292
+ paragraphs,
293
+ runs
294
+ };
295
+ for (const style of children(doc.documentElement, NS.w, "style")) {
296
+ const id = wAttr(style, "styleId");
297
+ if (!id) continue;
298
+ const type = wAttr(style, "type");
299
+ const name = (wAttr(child(style, NS.w, "name"), "val") ?? "").toLowerCase();
300
+ if (type === "character") {
301
+ runs.set(id, name === "hyperlink" ? {} : CODE_CHARACTER_STYLES.has(name) ? { code: true } : readRunFormat(child(style, NS.w, "rPr")));
302
+ continue;
303
+ }
304
+ if (type !== "paragraph") continue;
305
+ const pPr = child(style, NS.w, "pPr");
306
+ const numPr = child(pPr, NS.w, "numPr");
307
+ const outline = wAttr(child(pPr, NS.w, "outlineLvl"), "val");
308
+ const headingMatch = /^heading ([1-9])$/.exec(name);
309
+ const heading = name === "title" ? 1 : headingMatch ? Math.min(6, Number(headingMatch[1])) : outline !== null && /^[0-5]$/.test(outline) ? Number(outline) + 1 : null;
310
+ paragraphs.set(id, {
311
+ heading,
312
+ quote: name === "quote" || name === "intense quote",
313
+ code: name === "html preformatted" || name === "code" || name.includes("source code"),
314
+ listParagraph: name === "list paragraph",
315
+ numId: wAttr(child(numPr, NS.w, "numId"), "val"),
316
+ ilvl: clampInt(wAttr(child(numPr, NS.w, "ilvl"), "val"), 0, 8, 0),
317
+ basedOn: wAttr(child(style, NS.w, "basedOn"), "val")
318
+ });
319
+ }
320
+ return {
321
+ paragraphs,
322
+ runs
323
+ };
324
+ }
325
+ function resolveStyle(styles, id) {
326
+ let current = id ? styles.get(id) : void 0;
327
+ const result = current ? { ...current } : null;
328
+ for (let step = 0; current?.basedOn && result && step < 10; step++) {
329
+ current = styles.get(current.basedOn);
330
+ if (!current) break;
331
+ result.heading ??= current.heading;
332
+ result.quote ||= current.quote;
333
+ result.code ||= current.code;
334
+ result.listParagraph ||= current.listParagraph;
335
+ if (result.numId === null) {
336
+ result.numId = current.numId;
337
+ result.ilvl = current.ilvl;
338
+ }
339
+ }
340
+ return result;
341
+ }
342
+ function readNumbering(doc) {
343
+ const abstracts = /* @__PURE__ */ new Map();
344
+ const instances = /* @__PURE__ */ new Map();
345
+ if (doc) {
346
+ for (const abstract of children(doc.documentElement, NS.w, "abstractNum")) {
347
+ const levels = /* @__PURE__ */ new Map();
348
+ for (const level of children(abstract, NS.w, "lvl")) {
349
+ const format = wAttr(child(level, NS.w, "numFmt"), "val") ?? "decimal";
350
+ levels.set(clampInt(wAttr(level, "ilvl"), 0, 8, 0), {
351
+ ordered: format !== "bullet" && format !== "none",
352
+ start: clampInt(wAttr(child(level, NS.w, "start"), "val"), 1, 9999, 1)
353
+ });
354
+ }
355
+ const id = wAttr(abstract, "abstractNumId");
356
+ if (id !== null) abstracts.set(id, levels);
357
+ }
358
+ for (const num of children(doc.documentElement, NS.w, "num")) {
359
+ const id = wAttr(num, "numId");
360
+ const abstractId = wAttr(child(num, NS.w, "abstractNumId"), "val");
361
+ if (id === null || abstractId === null) continue;
362
+ const starts = /* @__PURE__ */ new Map();
363
+ for (const override of children(num, NS.w, "lvlOverride")) {
364
+ const start = wAttr(child(override, NS.w, "startOverride"), "val");
365
+ if (start !== null) starts.set(clampInt(wAttr(override, "ilvl"), 0, 8, 0), clampInt(start, 1, 9999, 1));
366
+ }
367
+ instances.set(id, {
368
+ abstractId,
369
+ starts
370
+ });
371
+ }
372
+ }
373
+ return (numId, ilvl) => {
374
+ const instance = instances.get(numId);
375
+ const level = instance ? abstracts.get(instance.abstractId)?.get(ilvl) : void 0;
376
+ return {
377
+ ordered: level?.ordered ?? false,
378
+ start: instance?.starts.get(ilvl) ?? level?.start ?? 1
379
+ };
380
+ };
381
+ }
382
+ function readRunFormat(rPr) {
383
+ if (!rPr) return {};
384
+ const format = {};
385
+ const flag = (name, key) => {
386
+ const element = child(rPr, NS.w, name);
387
+ if (element) format[key] = onOff(element);
388
+ };
389
+ flag("b", "bold");
390
+ flag("i", "italic");
391
+ flag("strike", "strike");
392
+ if (child(rPr, NS.w, "dstrike")) format.strike = onOff(child(rPr, NS.w, "dstrike"));
393
+ const underline = child(rPr, NS.w, "u");
394
+ if (underline) format.underline = (wAttr(underline, "val") ?? "single") !== "none";
395
+ const color = wAttr(child(rPr, NS.w, "color"), "val");
396
+ if (color && /^[0-9A-Fa-f]{6}$/.test(color)) format.color = normalizeColor(`#${color}`);
397
+ const highlight = wAttr(child(rPr, NS.w, "highlight"), "val");
398
+ if (highlight && Object.hasOwn(HIGHLIGHTS, highlight)) format.highlight = HIGHLIGHTS[highlight] ?? null;
399
+ if ([
400
+ "vanish",
401
+ "specVanish",
402
+ "webHidden"
403
+ ].some((name) => child(rPr, NS.w, name))) format.hidden = [
404
+ "vanish",
405
+ "specVanish",
406
+ "webHidden"
407
+ ].some((name) => onOff(child(rPr, NS.w, name)));
408
+ const fill = wAttr(child(rPr, NS.w, "shd"), "fill");
409
+ if (!format.highlight && fill && /^[0-9A-Fa-f]{6}$/.test(fill) && fill.toLowerCase() !== "ffffff") format.highlight = normalizeColor(`#${fill}`);
410
+ return format;
411
+ }
412
+ var Reader = class {
413
+ limits;
414
+ relationships;
415
+ media;
416
+ paragraphStyles;
417
+ runStyles;
418
+ listLevel;
419
+ doc = document.implementation.createHTMLDocument("");
420
+ images = [];
421
+ warnings = /* @__PURE__ */ new Map();
422
+ elements = 0;
423
+ cells = 0;
424
+ fieldStack = [];
425
+ instructions = 0;
426
+ constructor(limits, relationships, media, paragraphStyles, runStyles, listLevel) {
427
+ this.limits = limits;
428
+ this.relationships = relationships;
429
+ this.media = media;
430
+ this.paragraphStyles = paragraphStyles;
431
+ this.runStyles = runStyles;
432
+ this.listLevel = listLevel;
433
+ }
434
+ warn(code) {
435
+ this.warnings.set(code, (this.warnings.get(code) ?? 0) + 1);
436
+ }
437
+ warningList() {
438
+ return [...this.warnings].slice(0, 100).map(([code, count]) => ({
439
+ code,
440
+ count
441
+ }));
442
+ }
443
+ visit(depth) {
444
+ this.elements += 1;
445
+ if (this.elements > this.limits.elements) throw new DocxError("TOO_COMPLEX", "The Word document has too many elements.");
446
+ return depth <= MAX_DEPTH;
447
+ }
448
+ blocks(container, target, depth, tableDepth) {
449
+ for (const node of container.children) {
450
+ if (!this.visit(depth)) return;
451
+ if (is(node, NS.w, "p")) this.paragraph(node, target, depth + 1);
452
+ else if (is(node, NS.w, "tbl")) this.table(node, target, depth + 1, tableDepth + 1);
453
+ else if (is(node, NS.w, "sdt")) {
454
+ const content = child(node, NS.w, "sdtContent");
455
+ if (content) this.blocks(content, target, depth + 1, tableDepth);
456
+ } else if (is(node, NS.w, "customXml") || is(node, NS.w, "ins") || is(node, NS.w, "moveTo")) this.blocks(node, target, depth + 1, tableDepth);
457
+ else if (is(node, NS.mc, "AlternateContent")) {
458
+ const fallback = child(node, NS.mc, "Fallback");
459
+ if (fallback) this.blocks(fallback, target, depth + 1, tableDepth);
460
+ } else if (is(node, NS.w, "altChunk")) this.warn("OBJECT_DROPPED");
461
+ }
462
+ }
463
+ paragraph(paragraph, target, depth) {
464
+ const pPr = child(paragraph, NS.w, "pPr");
465
+ const style = resolveStyle(this.paragraphStyles, wAttr(child(pPr, NS.w, "pStyle"), "val"));
466
+ const numPr = child(pPr, NS.w, "numPr");
467
+ const numId = numPr ? wAttr(child(numPr, NS.w, "numId"), "val") : style?.numId ?? null;
468
+ const ilvl = numPr ? clampInt(wAttr(child(numPr, NS.w, "ilvl"), "val"), 0, 8, 0) : style?.ilvl ?? 0;
469
+ const content = this.doc.createElement("span");
470
+ this.inline(paragraph, content, {}, depth);
471
+ if (style?.code) {
472
+ target.code(content.textContent ?? "");
473
+ return;
474
+ }
475
+ const heading = style?.heading ?? null;
476
+ const block = this.doc.createElement(heading ? `h${heading}` : "p");
477
+ block.append(...content.childNodes);
478
+ const jc = wAttr(child(pPr, NS.w, "jc"), "val") ?? "";
479
+ const align = Object.hasOwn(ALIGNMENTS$1, jc) ? ALIGNMENTS$1[jc] : void 0;
480
+ if (align) block.style.setProperty("text-align", align);
481
+ if (numId && numId !== "0" && !heading) target.listItem(block, numId, ilvl, this.listLevel(numId, ilvl));
482
+ else if (style?.listParagraph && !heading && target.continueItem(block)) return;
483
+ else if (style?.quote) target.quote(block);
484
+ else target.block(block);
485
+ }
486
+ inline(container, target, inherited, depth) {
487
+ for (const node of container.children) {
488
+ if (!this.visit(depth)) return;
489
+ if (is(node, NS.w, "r")) this.run(node, target, inherited, depth + 1);
490
+ else if (is(node, NS.w, "hyperlink")) this.hyperlink(node, target, inherited, depth + 1);
491
+ else if (is(node, NS.w, "ins") || is(node, NS.w, "moveTo") || is(node, NS.w, "smartTag") || is(node, NS.w, "customXml") || is(node, NS.w, "fldSimple")) this.inline(node, target, inherited, depth + 1);
492
+ else if (is(node, NS.w, "sdt")) {
493
+ const content = child(node, NS.w, "sdtContent");
494
+ if (content) this.inline(content, target, inherited, depth + 1);
495
+ } else if (is(node, NS.mc, "AlternateContent")) {
496
+ const fallback = child(node, NS.mc, "Fallback");
497
+ if (fallback) this.inline(fallback, target, inherited, depth + 1);
498
+ } else if (node.namespaceURI === "http://schemas.openxmlformats.org/officeDocument/2006/math") this.warn("OBJECT_DROPPED");
499
+ }
500
+ }
501
+ hyperlink(link, target, inherited, depth) {
502
+ const id = link.getAttributeNS(NS.r, "id");
503
+ const relationship = id ? this.relationships.get(id) : void 0;
504
+ const href = relationship?.type === REL_HYPERLINK && relationship.external ? cleanLink(relationship.target) : null;
505
+ if (id && !href) this.warn("LINK_DROPPED");
506
+ if (!href) {
507
+ this.inline(link, target, inherited, depth);
508
+ return;
509
+ }
510
+ const anchor = this.doc.createElement("a");
511
+ anchor.setAttribute("href", href);
512
+ this.inline(link, anchor, inherited, depth);
513
+ target.append(anchor);
514
+ }
515
+ run(run, target, inherited, depth) {
516
+ const rPr = child(run, NS.w, "rPr");
517
+ const style = this.runStyles.get(wAttr(child(rPr, NS.w, "rStyle"), "val") ?? "") ?? {};
518
+ const format = {
519
+ ...inherited,
520
+ ...style,
521
+ ...readRunFormat(rPr)
522
+ };
523
+ if (format.hidden) {
524
+ if (run.textContent) this.warn("HIDDEN_TEXT");
525
+ return;
526
+ }
527
+ for (const node of run.children) {
528
+ if (!this.visit(depth)) return;
529
+ if (is(node, NS.w, "fldChar")) {
530
+ const type = wAttr(node, "fldCharType");
531
+ if (type === "begin") {
532
+ this.fieldStack.push("instruction");
533
+ this.instructions += 1;
534
+ } else if (type === "separate" && this.fieldStack.at(-1) === "instruction") {
535
+ this.fieldStack[this.fieldStack.length - 1] = "result";
536
+ this.instructions -= 1;
537
+ } else if (type === "end" && this.fieldStack.pop() === "instruction") this.instructions -= 1;
538
+ continue;
539
+ }
540
+ if (this.instructions > 0) continue;
541
+ if (is(node, NS.w, "t")) this.text(node.textContent ?? "", format, target);
542
+ else if (is(node, NS.w, "tab")) this.text(" ", format, target);
543
+ else if (is(node, NS.w, "noBreakHyphen")) this.text("‑", format, target);
544
+ else if (is(node, NS.w, "br") || is(node, NS.w, "cr")) {
545
+ const type = wAttr(node, "type");
546
+ if (type !== "page" && type !== "column") target.append(this.doc.createElement("br"));
547
+ } else if (is(node, NS.w, "drawing")) this.drawing(node, target);
548
+ else if (is(node, NS.w, "pict") || is(node, NS.w, "object")) this.warn("OBJECT_DROPPED");
549
+ else if (is(node, NS.mc, "AlternateContent")) {
550
+ const fallback = child(node, NS.mc, "Fallback");
551
+ if (fallback && child(fallback, NS.w, "drawing")) this.drawing(child(fallback, NS.w, "drawing"), target);
552
+ else this.warn("OBJECT_DROPPED");
553
+ }
554
+ }
555
+ }
556
+ text(value, format, target) {
557
+ const text = without(value, isControl);
558
+ if (!text) return;
559
+ let node = this.doc.createTextNode(text);
560
+ const wrap = (tag, style) => {
561
+ const element = this.doc.createElement(tag);
562
+ if (style) element.style.setProperty(style[0], style[1]);
563
+ element.append(node);
564
+ node = element;
565
+ };
566
+ if (format.highlight) wrap("mark", ["background-color", format.highlight]);
567
+ if (format.color) wrap("span", ["color", format.color]);
568
+ if (format.strike) wrap("s");
569
+ if (format.underline) wrap("u");
570
+ if (format.italic) wrap("em");
571
+ if (format.code) wrap("code");
572
+ if (format.bold) wrap("strong");
573
+ target.append(node);
574
+ }
575
+ drawing(drawing, target) {
576
+ const frame = child(drawing, NS.wp, "inline") ?? child(drawing, NS.wp, "anchor");
577
+ const id = descendant(frame, [
578
+ [NS.a, "graphic"],
579
+ [NS.a, "graphicData"],
580
+ [NS.pic, "pic"],
581
+ [NS.pic, "blipFill"],
582
+ [NS.a, "blip"]
583
+ ])?.getAttributeNS(NS.r, "embed");
584
+ const relationship = id ? this.relationships.get(id) : void 0;
585
+ const path = relationship && relationship.type === REL_IMAGE && !relationship.external ? resolvePart("word/", relationship.target) : null;
586
+ const bytes = path ? this.media.get(path) : void 0;
587
+ if (!bytes || this.images.length >= this.limits.images) {
588
+ this.warn("IMAGE_DROPPED");
589
+ return;
590
+ }
591
+ const image = this.doc.createElement("img");
592
+ const docPr = child(frame, NS.wp, "docPr");
593
+ const alt = cleanText(docPr?.getAttribute("descr") || docPr?.getAttribute("title"));
594
+ if (alt) image.setAttribute("alt", alt);
595
+ const extent = child(frame, NS.wp, "extent");
596
+ const width = Math.round(Number(extent?.getAttribute("cx")) / EMU_PER_PIXEL$1);
597
+ const height = Math.round(Number(extent?.getAttribute("cy")) / EMU_PER_PIXEL$1);
598
+ if (width >= 1 && height >= 1 && width <= MAX_DIMENSION$1 && height <= MAX_DIMENSION$1) {
599
+ image.setAttribute("width", String(width));
600
+ image.setAttribute("height", String(height));
601
+ }
602
+ this.images.push({
603
+ element: image,
604
+ bytes
605
+ });
606
+ target.append(image);
607
+ }
608
+ table(table, target, depth, tableDepth) {
609
+ if (tableDepth > MAX_TABLE_DEPTH) {
610
+ this.warn("NESTING_FLATTENED");
611
+ this.flatten(table, target, depth);
612
+ return;
613
+ }
614
+ const widths = children(child(table, NS.w, "tblGrid"), NS.w, "gridCol").map((column) => Math.max(0, Math.round(clampInt(wAttr(column, "w"), 0, 1e5, 0) / 15)));
615
+ const element = this.doc.createElement("table");
616
+ const body = this.doc.createElement("tbody");
617
+ element.append(body);
618
+ const origins = /* @__PURE__ */ new Map();
619
+ const rows = children(table, NS.w, "tr").filter((row) => child(row, NS.w, "tc"));
620
+ let widest = 0;
621
+ rows.forEach((row, rowIndex) => {
622
+ if (!this.visit(depth)) return;
623
+ const header = onOff(child(child(row, NS.w, "trPr"), NS.w, "tblHeader"));
624
+ const tableRow = this.doc.createElement("tr");
625
+ let column = 0;
626
+ for (const cell of children(row, NS.w, "tc")) {
627
+ const tcPr = child(cell, NS.w, "tcPr");
628
+ const span = clampInt(wAttr(child(tcPr, NS.w, "gridSpan"), "val"), 1, 63, 1);
629
+ const merge = child(tcPr, NS.w, "vMerge");
630
+ const continues = merge !== null && wAttr(merge, "val") !== "restart";
631
+ if (column + span > MAX_COLUMNS) throw new DocxError("TOO_COMPLEX", "The Word document has a table that is too wide.");
632
+ const origin = origins.get(column);
633
+ if (continues && origin) {
634
+ const rowspan = Math.min(rows.length - rowIndex + 1, (origin.rowSpan || 1) + 1);
635
+ origin.setAttribute("rowspan", String(rowspan));
636
+ column += span;
637
+ continue;
638
+ }
639
+ this.cells += 1;
640
+ if (this.cells > this.limits.cells) throw new DocxError("TOO_COMPLEX", "The Word document has too many table cells.");
641
+ const tableCell = this.doc.createElement(header ? "th" : "td");
642
+ if (span > 1) tableCell.setAttribute("colspan", String(span));
643
+ const cellWidths = widths.slice(column, column + span);
644
+ if (clampInt(wAttr(child(tcPr, NS.w, "tcW"), "w"), 0, 1e5, 0) > 0 && cellWidths.length === span && cellWidths.every((width) => width > 0)) tableCell.setAttribute("data-colwidth", cellWidths.join(","));
645
+ for (let offset = 0; offset < span; offset++) if (merge) origins.set(column + offset, tableCell);
646
+ else origins.delete(column + offset);
647
+ this.blocks(cell, new BlockWriter(this.doc, tableCell), depth + 1, tableDepth);
648
+ if (!tableCell.firstChild) tableCell.append(this.doc.createElement("p"));
649
+ tableRow.append(tableCell);
650
+ column += span;
651
+ }
652
+ widest = Math.max(widest, column);
653
+ if (widest * (rowIndex + 1) > this.limits.cells) throw new DocxError("TOO_COMPLEX", "The Word document has too many table cells.");
654
+ body.append(tableRow);
655
+ });
656
+ target.block(element);
657
+ }
658
+ flatten(container, target, depth) {
659
+ for (const node of container.children) {
660
+ if (!this.visit(depth)) return;
661
+ if (is(node, NS.w, "p")) this.paragraph(node, target, depth + 1);
662
+ else if ([
663
+ "tbl",
664
+ "tr",
665
+ "tc",
666
+ "sdt",
667
+ "sdtContent",
668
+ "ins",
669
+ "moveTo",
670
+ "customXml"
671
+ ].some((name) => is(node, NS.w, name))) this.flatten(node, target, depth + 1);
672
+ else if (is(node, NS.mc, "AlternateContent")) {
673
+ const fallback = child(node, NS.mc, "Fallback");
674
+ if (fallback) this.flatten(fallback, target, depth + 1);
675
+ }
676
+ }
677
+ }
678
+ };
679
+ var BlockWriter = class {
680
+ doc;
681
+ parent;
682
+ lists = [];
683
+ quoteElement = null;
684
+ codeElement = null;
685
+ constructor(doc, parent) {
686
+ this.doc = doc;
687
+ this.parent = parent;
688
+ }
689
+ reset(keep) {
690
+ if (keep !== "list") this.lists = [];
691
+ if (keep !== "quote") this.quoteElement = null;
692
+ if (keep !== "code") this.codeElement = null;
693
+ }
694
+ block(element) {
695
+ this.reset(null);
696
+ this.parent.append(element);
697
+ }
698
+ quote(element) {
699
+ this.reset("quote");
700
+ if (!this.quoteElement) {
701
+ this.quoteElement = this.doc.createElement("blockquote");
702
+ this.parent.append(this.quoteElement);
703
+ }
704
+ this.quoteElement.append(element);
705
+ }
706
+ code(text) {
707
+ this.reset("code");
708
+ if (this.codeElement) {
709
+ this.codeElement.append(`\n${text}`);
710
+ return;
711
+ }
712
+ const pre = this.doc.createElement("pre");
713
+ this.codeElement = this.doc.createElement("code");
714
+ this.codeElement.append(text);
715
+ pre.append(this.codeElement);
716
+ this.parent.append(pre);
717
+ }
718
+ continueItem(element) {
719
+ const item = this.lists.at(-1)?.lastItem;
720
+ if (!item) return false;
721
+ item.append(element);
722
+ return true;
723
+ }
724
+ listItem(element, numId, ilvl, level) {
725
+ this.reset("list");
726
+ while (this.lists.length > 0 && (this.lists.at(-1)?.ilvl ?? 0) > ilvl) this.lists.pop();
727
+ let top = this.lists.at(-1);
728
+ if (top && top.ilvl === ilvl && (top.numId !== numId || top.ordered !== level.ordered)) {
729
+ this.lists.pop();
730
+ top = this.lists.at(-1);
731
+ }
732
+ if (!top || top.ilvl < ilvl) {
733
+ const list = this.doc.createElement(level.ordered ? "ol" : "ul");
734
+ if (level.ordered && level.start !== 1) list.setAttribute("start", String(level.start));
735
+ (top?.lastItem ?? this.parent).append(list);
736
+ top = {
737
+ ilvl,
738
+ numId,
739
+ ordered: level.ordered,
740
+ element: list,
741
+ lastItem: null
742
+ };
743
+ this.lists.push(top);
744
+ }
745
+ const item = this.doc.createElement("li");
746
+ item.append(element);
747
+ top.element.append(item);
748
+ top.lastItem = item;
749
+ }
750
+ };
751
+ function base64(bytes) {
752
+ let binary = "";
753
+ for (let offset = 0; offset < bytes.length; offset += 32768) binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768));
754
+ return btoa(binary);
755
+ }
756
+ const EXTENSIONS = {
757
+ "image/png": "png",
758
+ "image/jpeg": "jpg",
759
+ "image/gif": "gif",
760
+ "image/webp": "webp",
761
+ "image/avif": "avif"
762
+ };
763
+ async function resolveImages(reader, options, limits) {
764
+ const policy = {
765
+ ...DEFAULT_SOURCE_POLICY,
766
+ ...options.imagePolicy,
767
+ allowBase64: options.allowBase64 === true
768
+ };
769
+ let index = 0;
770
+ for (const { element, bytes } of reader.images) {
771
+ throwIfAborted(options.signal);
772
+ if (!reader.doc.body.contains(element)) continue;
773
+ index += 1;
774
+ const type = sniffImageType(bytes);
775
+ const size = imageSize(bytes);
776
+ const tooBig = bytes.length > limits.imageBytes || size === null || size.width * size.height > limits.imagePixels;
777
+ let src = null;
778
+ if (type && !tooBig && options.upload) try {
779
+ const file = new File([bytes], `image-${index}.${EXTENSIONS[type] ?? "bin"}`, { type });
780
+ const result = await options.upload(file, {
781
+ signal: options.signal ?? new AbortController().signal,
782
+ onProgress: () => void 0
783
+ });
784
+ src = normalizeImageSrc(typeof result === "string" ? result : result.src, policy);
785
+ const width = typeof result === "string" ? 0 : Math.round(Number(result.width));
786
+ const height = typeof result === "string" ? 0 : Math.round(Number(result.height));
787
+ if (src && width >= 1 && height >= 1 && width <= MAX_DIMENSION$1 && height <= MAX_DIMENSION$1) {
788
+ element.setAttribute("width", String(width));
789
+ element.setAttribute("height", String(height));
790
+ }
791
+ } catch {
792
+ throwIfAborted(options.signal);
793
+ }
794
+ else if (type && !tooBig && policy.allowBase64) src = normalizeImageSrc(`data:${type};base64,${base64(bytes)}`, policy);
795
+ if (src) element.setAttribute("src", src);
796
+ else {
797
+ element.remove();
798
+ reader.warn("IMAGE_DROPPED");
799
+ }
800
+ }
801
+ }
802
+ async function importDocx(file, options = {}) {
803
+ const limits = cleanLimits$1(options.limits);
804
+ if (file.size > limits.fileBytes) throw new DocxError("TOO_LARGE", "The Word document is too large.");
805
+ throwIfAborted(options.signal);
806
+ const bytes = new Uint8Array(await file.arrayBuffer());
807
+ throwIfAborted(options.signal);
808
+ const root = readZip(bytes, (name) => name === "_rels/.rels", {
809
+ totalBytes: limits.totalBytes,
810
+ partBytes: () => limits.partBytes
811
+ }).get("_rels/.rels");
812
+ const office = [...readRelationships(root ? parseXml(root) : null).values()].find((relationship) => relationship.type === REL_OFFICE_DOCUMENT);
813
+ const documentPath = office ? resolvePart("", office.target) : null;
814
+ if (!documentPath || !/^word\/[^/]+\.xml$/.test(documentPath)) throw new DocxError("NOT_DOCX", "The file is not a Word document.");
815
+ const relsPath = documentPath.replace(/^word\/(.+)$/, "word/_rels/$1.rels");
816
+ let mediaCount = 0;
817
+ const parts = readZip(bytes, (name) => {
818
+ if ([
819
+ documentPath,
820
+ relsPath,
821
+ "word/styles.xml",
822
+ "word/numbering.xml"
823
+ ].includes(name)) return true;
824
+ if (!/^word\/media\/[^/]+$/.test(name) || mediaCount >= limits.images) return false;
825
+ mediaCount += 1;
826
+ return true;
827
+ }, {
828
+ totalBytes: limits.totalBytes,
829
+ partBytes: (name) => name === documentPath ? limits.documentBytes : name.startsWith("word/media/") ? limits.imageBytes : limits.partBytes
830
+ });
831
+ const part = (name) => {
832
+ const data = parts.get(name);
833
+ return data ? parseXml(data) : null;
834
+ };
835
+ const body = child(part(documentPath)?.documentElement, NS.w, "body");
836
+ if (!body) throw new DocxError("UNSUPPORTED", "This kind of Word document is not supported.");
837
+ const styles = readStyles(part("word/styles.xml"));
838
+ const media = new Map([...parts].filter(([name]) => name.startsWith("word/media/")));
839
+ const reader = new Reader(limits, readRelationships(part(relsPath)), media, styles.paragraphs, styles.runs, readNumbering(part("word/numbering.xml")));
840
+ reader.blocks(body, new BlockWriter(reader.doc, reader.doc.body), 0, 0);
841
+ await resolveImages(reader, options, limits);
842
+ throwIfAborted(options.signal);
843
+ return {
844
+ html: reader.doc.body.innerHTML,
845
+ warnings: reader.warningList()
846
+ };
847
+ }
848
+ // src/write.ts
849
+ const DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
850
+ const DEFAULT_EXPORT_LIMITS = Object.freeze({
851
+ imageBytes: 10485760,
852
+ images: 200,
853
+ timeout: 15e3
854
+ });
855
+ const W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
856
+ const R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
857
+ const PACKAGE_REL = "http://schemas.openxmlformats.org/package/2006/relationships";
858
+ const DECLARATION = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
859
+ const PAGE_WIDTH_TWIPS = 9360;
860
+ const MAX_IMAGE_PIXELS = 624;
861
+ const EMU_PER_PIXEL = 9525;
862
+ const TWIPS_PER_PIXEL = 15;
863
+ const MAX_LEVEL = 8;
864
+ const WATCH_URLS = {
865
+ youtube: (id) => `https://www.youtube.com/watch?v=${id}`,
866
+ vimeo: (id) => `https://vimeo.com/${id}`,
867
+ spotify: (id) => `https://open.spotify.com/${id.replace(":", "/")}`
868
+ };
869
+ const IMAGE_EXTENSIONS = {
870
+ "image/png": "png",
871
+ "image/jpeg": "jpeg",
872
+ "image/gif": "gif"
873
+ };
874
+ const MAX_DIMENSION = 1e4;
875
+ const ALIGNMENTS = {
876
+ center: "center",
877
+ right: "right",
878
+ justify: "both"
879
+ };
880
+ const MAX_CONVERT_PIXELS = 5e7;
881
+ const EMBEDDABLE = new Set(Object.keys(IMAGE_EXTENSIONS));
882
+ const CONVERTIBLE = /* @__PURE__ */ new Set(["image/webp", "image/avif"]);
883
+ function validXmlCharacter(code) {
884
+ return code === 9 || code === 10 || code === 13 || code >= 32 && code <= 55295 || code >= 57344 && code <= 65533 || code >= 65536;
885
+ }
886
+ function escapeXml(value) {
887
+ let result = "";
888
+ for (const character of String(value ?? "")) {
889
+ if (!validXmlCharacter(character.codePointAt(0) ?? 0)) continue;
890
+ if (character === "&") result += "&amp;";
891
+ else if (character === "<") result += "&lt;";
892
+ else if (character === ">") result += "&gt;";
893
+ else if (character === "\"") result += "&quot;";
894
+ else if (character === "'") result += "&apos;";
895
+ else result += character;
896
+ }
897
+ return result;
898
+ }
899
+ function cleanLimits(input) {
900
+ const limits = { ...DEFAULT_EXPORT_LIMITS };
901
+ for (const key of Object.keys(limits)) {
902
+ const value = input?.[key];
903
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) limits[key] = value;
904
+ }
905
+ return limits;
906
+ }
907
+ const hexColor = (value) => {
908
+ const match = typeof value === "string" ? /^#([0-9a-f]{6})(?:[0-9a-f]{2})?$/i.exec(value) : null;
909
+ return match?.[1] ? match[1].toUpperCase() : null;
910
+ };
911
+ const positiveInt = (value) => {
912
+ const number = Number(value);
913
+ return Number.isFinite(number) && number >= 1 ? Math.min(MAX_DIMENSION, Math.round(number)) : null;
914
+ };
915
+ function combinedSignal(signal, timeout) {
916
+ const timer = AbortSignal.timeout(timeout);
917
+ if (!signal) return timer;
918
+ const controller = new AbortController();
919
+ const abort = () => controller.abort();
920
+ if (signal.aborted || timer.aborted) abort();
921
+ signal.addEventListener("abort", abort, { once: true });
922
+ timer.addEventListener("abort", abort, { once: true });
923
+ return controller.signal;
924
+ }
925
+ function decodeDataUrl(src) {
926
+ const match = /^data:image\/[a-z0-9.+-]+;base64,([a-z0-9+/=\s]+)$/i.exec(src);
927
+ if (!match?.[1]) return null;
928
+ try {
929
+ const binary = atob(match[1].replace(/\s+/g, ""));
930
+ const bytes = new Uint8Array(binary.length);
931
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
932
+ return bytes;
933
+ } catch {
934
+ return null;
935
+ }
936
+ }
937
+ async function readLimited(response, max) {
938
+ const declared = Number(response.headers.get("content-length"));
939
+ if (Number.isFinite(declared) && declared > max) return null;
940
+ const reader = response.body?.getReader();
941
+ if (!reader) return null;
942
+ const chunks = [];
943
+ let total = 0;
944
+ for (;;) {
945
+ const { done, value } = await reader.read();
946
+ if (done) break;
947
+ total += value.length;
948
+ if (total > max) {
949
+ await reader.cancel();
950
+ return null;
951
+ }
952
+ chunks.push(value);
953
+ }
954
+ const bytes = new Uint8Array(total);
955
+ let offset = 0;
956
+ for (const chunk of chunks) {
957
+ bytes.set(chunk, offset);
958
+ offset += chunk.length;
959
+ }
960
+ return bytes;
961
+ }
962
+ async function toPng(bytes, type) {
963
+ if (typeof createImageBitmap !== "function" || typeof document === "undefined") return null;
964
+ try {
965
+ const bitmap = await createImageBitmap(new Blob([bytes], { type }));
966
+ const canvas = document.createElement("canvas");
967
+ canvas.width = bitmap.width;
968
+ canvas.height = bitmap.height;
969
+ const context = canvas.getContext("2d");
970
+ if (!context) return null;
971
+ context.drawImage(bitmap, 0, 0);
972
+ bitmap.close();
973
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
974
+ return blob ? new Uint8Array(await blob.arrayBuffer()) : null;
975
+ } catch {
976
+ return null;
977
+ }
978
+ }
979
+ var Writer = class {
980
+ options;
981
+ limits;
982
+ relationships = [];
983
+ numbering = [];
984
+ media = {};
985
+ relationshipCount = 2;
986
+ numCount = 0;
987
+ imageCount = 0;
988
+ imageAttempts = 0;
989
+ drawingCount = 0;
990
+ notes = [];
991
+ constructor(options, limits) {
992
+ this.options = options;
993
+ this.limits = limits;
994
+ }
995
+ relationship(type, target, external = false) {
996
+ this.relationshipCount += 1;
997
+ const id = `rId${this.relationshipCount}`;
998
+ this.relationships.push(`<Relationship Id="${id}" Type="${R}/${type}" Target="${escapeXml(target)}"${external ? " TargetMode=\"External\"" : ""}/>`);
999
+ return id;
1000
+ }
1001
+ relationshipsXml() {
1002
+ return `${DECLARATION}<Relationships xmlns="${PACKAGE_REL}"><Relationship Id="rId1" Type="${R}/styles" Target="styles.xml"/><Relationship Id="rId2" Type="${R}/numbering" Target="numbering.xml"/>${this.relationships.join("")}</Relationships>`;
1003
+ }
1004
+ notesXml() {
1005
+ if (this.notes.length === 0) return "";
1006
+ return "<w:p><w:pPr><w:pBdr><w:bottom w:val=\"single\" w:sz=\"6\" w:space=\"1\" w:color=\"auto\"/></w:pBdr></w:pPr></w:p>" + this.notes.map((note, index) => `<w:p>${this.textRun(`${index + 1}. `, "")}${this.inline(note)}</w:p>`).join("");
1007
+ }
1008
+ numberingXml() {
1009
+ const levels = (ordered) => Array.from({ length: 9 }, (_, level) => {
1010
+ return `<w:lvl w:ilvl="${level}"><w:start w:val="1"/><w:numFmt w:val="${ordered ? "decimal" : "bullet"}"/><w:lvlText w:val="${ordered ? `%${level + 1}.` : [
1011
+ "•",
1012
+ "◦",
1013
+ "▪"
1014
+ ][level % 3]}"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="${720 * (level + 1)}" w:hanging="360"/></w:pPr></w:lvl>`;
1015
+ }).join("");
1016
+ return `${DECLARATION}<w:numbering xmlns:w="${W}"><w:abstractNum w:abstractNumId="0"><w:multiLevelType w:val="hybridMultilevel"/>${levels(false)}</w:abstractNum><w:abstractNum w:abstractNumId="1"><w:multiLevelType w:val="hybridMultilevel"/>${levels(true)}</w:abstractNum>${this.numbering.join("")}</w:numbering>`;
1017
+ }
1018
+ newList(ordered, level, start) {
1019
+ this.numCount += 1;
1020
+ const override = ordered ? `<w:lvlOverride w:ilvl="${level}"><w:startOverride w:val="${Math.min(9999, Math.max(1, start))}"/></w:lvlOverride>` : "";
1021
+ this.numbering.push(`<w:num w:numId="${this.numCount}"><w:abstractNumId w:val="${ordered ? 1 : 0}"/>${override}</w:num>`);
1022
+ return this.numCount;
1023
+ }
1024
+ async blocks(parent, level, quote) {
1025
+ let xml = "";
1026
+ for (let index = 0; index < parent.childCount; index++) {
1027
+ const node = parent.child(index);
1028
+ xml += await this.block(node, level, quote);
1029
+ const next = index + 1 < parent.childCount ? parent.child(index + 1) : null;
1030
+ if (node.type.name === "table" && (!next || next.type.name === "table")) xml += "<w:p/>";
1031
+ }
1032
+ return xml;
1033
+ }
1034
+ async block(node, level, quote) {
1035
+ switch (node.type.name) {
1036
+ case "paragraph": return this.paragraph(node, quote ? "Quote" : null);
1037
+ case "heading": return this.paragraph(node, `Heading${Math.min(6, Math.max(1, Number(node.attrs.level) || 1))}`);
1038
+ case "blockquote": return this.blocks(node, level, true);
1039
+ case "bulletList":
1040
+ case "orderedList":
1041
+ case "taskList": return this.list(node, level);
1042
+ case "codeBlock": return node.textContent.split("\n").map((line) => `<w:p><w:pPr><w:pStyle w:val="Code"/></w:pPr>${this.textRun(line, "")}</w:p>`).join("");
1043
+ case "horizontalRule": return "<w:p><w:pPr><w:pBdr><w:bottom w:val=\"single\" w:sz=\"6\" w:space=\"1\" w:color=\"auto\"/></w:pBdr></w:pPr></w:p>";
1044
+ case "table": return this.table(node);
1045
+ case "image": return `<w:p>${await this.image(node)}</w:p>`;
1046
+ case "embed": return `<w:p>${this.embed(node)}</w:p>`;
1047
+ case "mathBlock": return String(node.attrs.latex ?? "").split("\n").map((line) => `<w:p><w:pPr><w:pStyle w:val="Code"/></w:pPr>${this.textRun(line, "")}</w:p>`).join("");
1048
+ default: return node.isTextblock ? this.paragraph(node, null) : node.childCount > 0 ? this.blocks(node, level, quote) : "";
1049
+ }
1050
+ }
1051
+ paragraphProperties(node, style, list) {
1052
+ let properties = style ? `<w:pStyle w:val="${style}"/>` : "";
1053
+ if (list) properties += `<w:numPr><w:ilvl w:val="${list[1]}"/><w:numId w:val="${list[0]}"/></w:numPr>`;
1054
+ const textAlign = String(node.attrs.textAlign);
1055
+ const align = Object.hasOwn(ALIGNMENTS, textAlign) ? ALIGNMENTS[textAlign] : void 0;
1056
+ if (align) properties += `<w:jc w:val="${align}"/>`;
1057
+ return properties ? `<w:pPr>${properties}</w:pPr>` : "";
1058
+ }
1059
+ paragraph(node, style, list, prefix = "") {
1060
+ return `<w:p>${this.paragraphProperties(node, style, list)}${prefix ? this.textRun(prefix, "") : ""}${this.inline(node)}</w:p>`;
1061
+ }
1062
+ async list(node, level) {
1063
+ const ordered = node.type.name === "orderedList";
1064
+ const depth = Math.min(MAX_LEVEL, level);
1065
+ const numId = this.newList(ordered, depth, Number(node.attrs.start) || 1);
1066
+ let xml = "";
1067
+ for (let index = 0; index < node.childCount; index++) {
1068
+ const item = node.child(index);
1069
+ const prefix = item.type.name === "taskItem" ? item.attrs.checked ? "☑ " : "☐ " : "";
1070
+ let first = true;
1071
+ for (let offset = 0; offset < item.childCount; offset++) {
1072
+ const content = item.child(offset);
1073
+ if (first && content.isTextblock && content.type.name !== "codeBlock") xml += this.paragraph(content, null, [numId, depth], prefix);
1074
+ else if (content.isTextblock && content.type.name === "paragraph") xml += this.paragraph(content, "ListParagraph");
1075
+ else xml += await this.block(content, level + 1, false);
1076
+ first = false;
1077
+ }
1078
+ if (first) xml += this.paragraph(item, null, [numId, depth], prefix);
1079
+ }
1080
+ return xml;
1081
+ }
1082
+ inline(node) {
1083
+ let xml = "";
1084
+ let link = null;
1085
+ let linkRuns = "";
1086
+ const flush = () => {
1087
+ if (link) xml += `<w:hyperlink r:id="${link.id}">${linkRuns}</w:hyperlink>`;
1088
+ link = null;
1089
+ linkRuns = "";
1090
+ };
1091
+ node.forEach((child) => {
1092
+ const linkMark = child.marks.find((mark) => mark.type.name === "link");
1093
+ const href = linkMark ? cleanLink(String(linkMark.attrs.href ?? "")) : null;
1094
+ if (link?.href !== href) {
1095
+ flush();
1096
+ if (href) link = {
1097
+ href,
1098
+ id: this.relationship("hyperlink", href, true)
1099
+ };
1100
+ }
1101
+ const properties = this.runProperties(child.marks, href !== null);
1102
+ const run = child.isText ? this.textRun(child.text ?? "", properties) : this.inlineNode(child, properties);
1103
+ if (link) linkRuns += run;
1104
+ else xml += run;
1105
+ });
1106
+ flush();
1107
+ return xml;
1108
+ }
1109
+ inlineNode(node, properties) {
1110
+ switch (node.type.name) {
1111
+ case "hardBreak": return "<w:r><w:br/></w:r>";
1112
+ case "mention": return this.textRun(String(node.type.spec.leafText?.(node) ?? ""), properties);
1113
+ case "mathInline": return this.textRun(String(node.attrs.latex ?? ""), "<w:rStyle w:val=\"CodeChar\"/>");
1114
+ case "footnote":
1115
+ this.notes.push(node);
1116
+ return this.textRun(String(this.notes.length), "<w:vertAlign w:val=\"superscript\"/>");
1117
+ default: return "";
1118
+ }
1119
+ }
1120
+ runProperties(marks, linked) {
1121
+ let properties = linked ? "<w:rStyle w:val=\"Hyperlink\"/>" : "";
1122
+ const names = new Set(marks.map((mark) => mark.type.name));
1123
+ if (names.has("code") && !linked) properties += "<w:rStyle w:val=\"CodeChar\"/>";
1124
+ if (names.has("bold")) properties += "<w:b/>";
1125
+ if (names.has("italic")) properties += "<w:i/>";
1126
+ if (names.has("strike")) properties += "<w:strike/>";
1127
+ const color = hexColor(marks.find((mark) => mark.type.name === "textColor")?.attrs.color);
1128
+ if (color) properties += `<w:color w:val="${color}"/>`;
1129
+ if (names.has("underline")) properties += "<w:u w:val=\"single\"/>";
1130
+ const fill = hexColor(marks.find((mark) => mark.type.name === "highlight")?.attrs.color);
1131
+ if (names.has("highlight")) properties += `<w:shd w:val="clear" w:color="auto" w:fill="${fill ?? "FFFF00"}"/>`;
1132
+ return properties;
1133
+ }
1134
+ textRun(text, properties) {
1135
+ const body = text.split(" ").map((part) => part ? `<w:t xml:space="preserve">${escapeXml(part)}</w:t>` : "").join("<w:tab/>");
1136
+ return body ? `<w:r>${properties ? `<w:rPr>${properties}</w:rPr>` : ""}${body}</w:r>` : "";
1137
+ }
1138
+ linkParagraphContent(href, text) {
1139
+ const label = text || href || "";
1140
+ if (!href) return this.textRun(label, "");
1141
+ return `<w:hyperlink r:id="${this.relationship("hyperlink", href, true)}">${this.textRun(label, "<w:rStyle w:val=\"Hyperlink\"/>")}</w:hyperlink>`;
1142
+ }
1143
+ embed(node) {
1144
+ const provider = String(node.attrs.provider);
1145
+ const watch = Object.hasOwn(WATCH_URLS, provider) ? WATCH_URLS[provider] : void 0;
1146
+ const href = watch && typeof node.attrs.id === "string" ? cleanLink(watch(node.attrs.id)) : null;
1147
+ return this.linkParagraphContent(href, String(node.attrs.title ?? ""));
1148
+ }
1149
+ async loadImage(src) {
1150
+ if (src.startsWith("data:")) return decodeDataUrl(src);
1151
+ if (!this.options.fetchImages || !/^https:\/\//i.test(src)) return null;
1152
+ const signal = combinedSignal(this.options.signal, this.limits.timeout);
1153
+ try {
1154
+ const response = await fetch(src, {
1155
+ credentials: "omit",
1156
+ referrerPolicy: "no-referrer",
1157
+ mode: "cors",
1158
+ redirect: "follow",
1159
+ signal
1160
+ });
1161
+ if (!response.ok || !/^https:\/\//i.test(response.url || src)) return null;
1162
+ return await readLimited(response, this.limits.imageBytes);
1163
+ } catch {
1164
+ if (this.options.signal?.aborted) throw this.options.signal.reason;
1165
+ return null;
1166
+ }
1167
+ }
1168
+ async embedImage(node) {
1169
+ if (this.imageAttempts >= this.limits.images) return null;
1170
+ this.imageAttempts += 1;
1171
+ const src = typeof node.attrs.src === "string" ? node.attrs.src : "";
1172
+ let bytes = await this.loadImage(src);
1173
+ if (!bytes || bytes.length > this.limits.imageBytes) return null;
1174
+ let type = sniffImageType(bytes);
1175
+ const measured = imageSize(bytes);
1176
+ if (type && CONVERTIBLE.has(type) && measured && measured.width * measured.height <= MAX_CONVERT_PIXELS) {
1177
+ bytes = await toPng(bytes, type);
1178
+ type = bytes ? "image/png" : null;
1179
+ }
1180
+ if (!bytes || !type || !EMBEDDABLE.has(type)) return null;
1181
+ const natural = imageSize(bytes);
1182
+ let width = positiveInt(node.attrs.width) ?? natural?.width ?? MAX_IMAGE_PIXELS;
1183
+ let height = positiveInt(node.attrs.height) ?? (natural ? Math.round(natural.height * width / natural.width) : Math.round(width * .75));
1184
+ if (width > MAX_IMAGE_PIXELS) {
1185
+ height = Math.max(1, Math.round(height * MAX_IMAGE_PIXELS / width));
1186
+ width = MAX_IMAGE_PIXELS;
1187
+ }
1188
+ this.imageCount += 1;
1189
+ return {
1190
+ bytes,
1191
+ type,
1192
+ width,
1193
+ height: Math.min(MAX_DIMENSION, Math.max(1, height))
1194
+ };
1195
+ }
1196
+ async image(node) {
1197
+ const image = await this.embedImage(node);
1198
+ const alt = String(node.attrs.alt ?? "");
1199
+ if (!image) {
1200
+ const src = typeof node.attrs.src === "string" ? cleanLink(node.attrs.src) : null;
1201
+ return this.linkParagraphContent(src, alt);
1202
+ }
1203
+ const name = `image${this.imageCount}.${IMAGE_EXTENSIONS[image.type]}`;
1204
+ this.media[`word/media/${name}`] = [image.bytes, { level: 0 }];
1205
+ const id = this.relationship("image", `media/${name}`);
1206
+ this.drawingCount += 1;
1207
+ const cx = image.width * EMU_PER_PIXEL;
1208
+ const cy = image.height * EMU_PER_PIXEL;
1209
+ const number = this.drawingCount;
1210
+ return `<w:r><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="${cx}" cy="${cy}"/><wp:docPr id="${number}" name="Picture ${number}" descr="${escapeXml(alt)}"/><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="${number}" name="${name}" descr="${escapeXml(alt)}"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="${id}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>`;
1211
+ }
1212
+ async table(node) {
1213
+ const rows = [];
1214
+ node.forEach((row) => {
1215
+ rows.push(row);
1216
+ });
1217
+ const pending = /* @__PURE__ */ new Map();
1218
+ const firstWidths = [];
1219
+ rows[0]?.forEach((cell) => {
1220
+ const span = positiveInt(cell.attrs.colspan) ?? 1;
1221
+ const widths = cell.attrs.colwidth;
1222
+ for (let index = 0; index < span; index++) firstWidths.push(Array.isArray(widths) ? positiveInt(widths[index]) : null);
1223
+ });
1224
+ let rowXml = "";
1225
+ let gridColumns = 0;
1226
+ for (const row of rows) {
1227
+ let column = 0;
1228
+ let cellIndex = 0;
1229
+ let cells = "";
1230
+ let header = row.childCount > 0;
1231
+ const continuation = () => {
1232
+ const merge = pending.get(column);
1233
+ if (!merge) return false;
1234
+ cells += `<w:tc><w:tcPr>${merge.span > 1 ? `<w:gridSpan w:val="${merge.span}"/>` : ""}<w:vMerge/></w:tcPr><w:p/></w:tc>`;
1235
+ merge.left -= 1;
1236
+ if (merge.left <= 0) pending.delete(column);
1237
+ column += merge.span;
1238
+ return true;
1239
+ };
1240
+ while (cellIndex < row.childCount) {
1241
+ if (continuation()) continue;
1242
+ const cell = row.child(cellIndex);
1243
+ cellIndex += 1;
1244
+ if (cell.type.name !== "tableHeader") header = false;
1245
+ const span = Math.min(63, positiveInt(cell.attrs.colspan) ?? 1);
1246
+ const rowspan = positiveInt(cell.attrs.rowspan) ?? 1;
1247
+ const widths = cell.attrs.colwidth;
1248
+ const width = Array.isArray(widths) ? widths.reduce((sum, value) => sum + (positiveInt(value) ?? 0), 0) * TWIPS_PER_PIXEL : 0;
1249
+ let properties = width > 0 ? `<w:tcW w:w="${width}" w:type="dxa"/>` : "";
1250
+ if (span > 1) properties += `<w:gridSpan w:val="${span}"/>`;
1251
+ if (rowspan > 1) {
1252
+ properties += "<w:vMerge w:val=\"restart\"/>";
1253
+ pending.set(column, {
1254
+ left: rowspan - 1,
1255
+ span
1256
+ });
1257
+ }
1258
+ let content = await this.blocks(cell, 0, false);
1259
+ if (!content.endsWith("</w:p>")) content += "<w:p/>";
1260
+ cells += `<w:tc>${properties ? `<w:tcPr>${properties}</w:tcPr>` : ""}${content}</w:tc>`;
1261
+ column += span;
1262
+ }
1263
+ while (pending.has(column)) continuation();
1264
+ gridColumns = Math.max(gridColumns, column);
1265
+ rowXml += `<w:tr>${header ? "<w:trPr><w:tblHeader/></w:trPr>" : ""}${cells}</w:tr>`;
1266
+ }
1267
+ gridColumns = Math.max(1, gridColumns);
1268
+ const fallback = Math.round(PAGE_WIDTH_TWIPS / gridColumns);
1269
+ return `<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="0" w:type="auto"/><w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="1" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/></w:tblPr><w:tblGrid>${Array.from({ length: gridColumns }, (_, index) => {
1270
+ const width = firstWidths[index];
1271
+ return `<w:gridCol w:w="${width ? width * TWIPS_PER_PIXEL : fallback}"/>`;
1272
+ }).join("")}</w:tblGrid>${rowXml}</w:tbl>`;
1273
+ }
1274
+ };
1275
+ function stylesXml() {
1276
+ const heading = (level, size) => `<w:style w:type="paragraph" w:styleId="Heading${level}"><w:name w:val="heading ${level}"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="240" w:after="80"/><w:outlineLvl w:val="${level - 1}"/></w:pPr><w:rPr><w:b/><w:sz w:val="${size}"/></w:rPr></w:style>`;
1277
+ return `${DECLARATION}<w:styles xmlns:w="${W}"><w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:eastAsia="Calibri" w:cs="Calibri"/><w:sz w:val="22"/><w:lang w:val="en-US"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="120" w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style><w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/><w:qFormat/><w:rPr><w:sz w:val="56"/></w:rPr></w:style>${heading(1, 40)}${heading(2, 32)}${heading(3, 28)}${heading(4, 24)}${heading(5, 22)}${heading(6, 22)}<w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:qFormat/><w:pPr><w:pBdr><w:left w:val="single" w:sz="18" w:space="8" w:color="BFBFBF"/></w:pBdr><w:ind w:left="567"/></w:pPr><w:rPr><w:i/><w:color w:val="404040"/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="Code"><w:name w:val="Code"/><w:basedOn w:val="Normal"/><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="F2F2F2"/><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:rPr><w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/><w:sz w:val="20"/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/><w:qFormat/><w:pPr><w:ind w:left="720"/></w:pPr></w:style><w:style w:type="character" w:default="1" w:styleId="DefaultParagraphFont"><w:name w:val="Default Paragraph Font"/><w:uiPriority w:val="1"/><w:semiHidden/></w:style><w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/><w:basedOn w:val="DefaultParagraphFont"/><w:rPr><w:color w:val="0563C1"/><w:u w:val="single"/></w:rPr></w:style><w:style w:type="character" w:styleId="CodeChar"><w:name w:val="Code Char"/><w:basedOn w:val="DefaultParagraphFont"/><w:rPr><w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/><w:shd w:val="clear" w:color="auto" w:fill="F2F2F2"/></w:rPr></w:style><w:style w:type="table" w:default="1" w:styleId="TableNormal"><w:name w:val="Normal Table"/><w:tblPr><w:tblInd w:w="0" w:type="dxa"/><w:tblCellMar><w:left w:w="108" w:type="dxa"/><w:right w:w="108" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style><w:style w:type="table" w:styleId="TableGrid"><w:name w:val="Table Grid"/><w:basedOn w:val="TableNormal"/><w:pPr><w:spacing w:after="0"/></w:pPr><w:tblPr><w:tblBorders><w:top w:val="single" w:sz="4" w:space="0" w:color="auto"/><w:left w:val="single" w:sz="4" w:space="0" w:color="auto"/><w:bottom w:val="single" w:sz="4" w:space="0" w:color="auto"/><w:right w:val="single" w:sz="4" w:space="0" w:color="auto"/><w:insideH w:val="single" w:sz="4" w:space="0" w:color="auto"/><w:insideV w:val="single" w:sz="4" w:space="0" w:color="auto"/></w:tblBorders></w:tblPr></w:style></w:styles>`;
1278
+ }
1279
+ const encoder = new TextEncoder();
1280
+ async function exportDocx(source, options = {}) {
1281
+ const doc = source.schema.nodeFromJSON(source.getJSON());
1282
+ doc.check();
1283
+ const writer = new Writer(options, cleanLimits(options.limits));
1284
+ const body = await writer.blocks(doc, 0, false) + writer.notesXml();
1285
+ options.signal?.throwIfAborted();
1286
+ const title = escapeXml((options.title ?? "").trim().slice(0, 255));
1287
+ const files = {
1288
+ "[Content_Types].xml": encoder.encode(`${DECLARATION}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="png" ContentType="image/png"/><Default Extension="jpeg" ContentType="image/jpeg"/><Default Extension="gif" ContentType="image/gif"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/><Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/></Types>`),
1289
+ "_rels/.rels": encoder.encode(`${DECLARATION}<Relationships xmlns="${PACKAGE_REL}"><Relationship Id="rId1" Type="${R}/officeDocument" Target="word/document.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/></Relationships>`),
1290
+ "docProps/core.xml": encoder.encode(`${DECLARATION}<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/">${title ? `<dc:title>${title}</dc:title>` : ""}</cp:coreProperties>`),
1291
+ "word/document.xml": encoder.encode(`${DECLARATION}<w:document xmlns:w="${W}" xmlns:r="${R}" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"><w:body>${body}<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1273" w:bottom="1440" w:left="1273" w:header="708" w:footer="708" w:gutter="0"/></w:sectPr></w:body></w:document>`),
1292
+ "word/styles.xml": encoder.encode(stylesXml()),
1293
+ "word/numbering.xml": encoder.encode(writer.numberingXml()),
1294
+ "word/_rels/document.xml.rels": encoder.encode(writer.relationshipsXml()),
1295
+ ...writer.media
1296
+ };
1297
+ return new Blob([zipSync(files)], { type: DOCX_MIME });
1298
+ }
1299
+ export { DEFAULT_IMPORT_LIMITS, DOCX_MIME, DocxError, exportDocx, importDocx };
1300
+
1301
+ //# sourceMappingURL=index.js.map