@viveeditor/docx 0.0.0-stage → 1.0.0-rc.1

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,1986 @@
1
+ import { cleanUrl, repairContent } from "@viveeditor/core";
2
+ import { DEFAULT_FONT_FAMILIES, 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
+ function cellStyleOf(tcPr) {
190
+ const fill = wAttr(child(tcPr, NS.w, "shd"), "fill") ?? "";
191
+ const vertical = wAttr(child(tcPr, NS.w, "vAlign"), "val");
192
+ return [/^[0-9a-f]{6}$/i.test(fill) && !/^f{6}$/i.test(fill) ? `background-color: #${fill}` : "", vertical === "center" || vertical === "bottom" ? `vertical-align: ${vertical === "center" ? "middle" : vertical}` : ""].filter(Boolean).join("; ");
193
+ }
194
+ const W15$1 = "http://schemas.microsoft.com/office/word/2012/wordml";
195
+ const W14$1 = "http://schemas.microsoft.com/office/word/2010/wordml";
196
+ const WORD_ID = /^\d{1,9}$/;
197
+ const WORD_DATE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?Z?$/;
198
+ const MAX_COMMENT_BODY = 5e3;
199
+ const MAX_COMMENT_AUTHOR = 100;
200
+ const MAX_THREADS = 1e3;
201
+ const MAX_THREAD_COMMENTS = 200;
202
+ const MAX_OPEN_COMMENTS = 16;
203
+ const MAX_DEPTH = 64;
204
+ const MAX_TABLE_DEPTH = 3;
205
+ const MAX_COLUMNS = 100;
206
+ const MAX_DIMENSION$1 = 1e4;
207
+ const MAX_TEXT = 1e3;
208
+ const MAX_LINK = 2048;
209
+ const EMU_PER_PIXEL$1 = 9525;
210
+ const MIN_ROW_HEIGHT = 24;
211
+ const MAX_ROW_HEIGHT$1 = 2e3;
212
+ const isControl = (code) => code <= 31 && code !== 9 && code !== 10 && code !== 13 || code === 127;
213
+ 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;
214
+ function without(value, drop) {
215
+ let result = "";
216
+ for (const character of value) if (!drop(character.codePointAt(0) ?? 0)) result += character;
217
+ return result;
218
+ }
219
+ const LINK_PROTOCOLS = /* @__PURE__ */ new Set([
220
+ "http:",
221
+ "https:",
222
+ "mailto:"
223
+ ]);
224
+ const HIGHLIGHTS = {
225
+ yellow: "#ffff00",
226
+ green: "#00ff00",
227
+ cyan: "#00ffff",
228
+ magenta: "#ff00ff",
229
+ blue: "#0000ff",
230
+ red: "#ff0000",
231
+ darkBlue: "#000080",
232
+ darkCyan: "#008080",
233
+ darkGreen: "#008000",
234
+ darkMagenta: "#800080",
235
+ darkRed: "#800000",
236
+ darkYellow: "#808000",
237
+ darkGray: "#808080",
238
+ lightGray: "#c0c0c0",
239
+ black: "#000000"
240
+ };
241
+ const CODE_CHARACTER_STYLES = /* @__PURE__ */ new Set([
242
+ "code char",
243
+ "html code",
244
+ "verbatim char",
245
+ "source text"
246
+ ]);
247
+ const MIN_HALF_POINTS = 12;
248
+ const MAX_HALF_POINTS = 192;
249
+ const INDENT_TWIPS$1 = 720;
250
+ const MAX_INDENT$1 = 8;
251
+ const ALIGNMENTS$1 = {
252
+ center: "center",
253
+ right: "right",
254
+ end: "right",
255
+ both: "justify",
256
+ distribute: "justify"
257
+ };
258
+ const STRIPE_FILL$1 = "F2F2F2";
259
+ const LINE_HEIGHTS = /* @__PURE__ */ new Map([
260
+ ["240", "1"],
261
+ ["276", "1.15"],
262
+ ["360", "1.5"],
263
+ ["480", "2"]
264
+ ]);
265
+ const GENERIC_FAMILIES = /* @__PURE__ */ new Map([
266
+ ["times new roman", "serif"],
267
+ ["arial", "sans-serif"],
268
+ ["courier new", "monospace"]
269
+ ]);
270
+ const NUMBER_FORMATS = /* @__PURE__ */ new Map([
271
+ ["lowerLetter", "a"],
272
+ ["upperLetter", "A"],
273
+ ["lowerRoman", "i"],
274
+ ["upperRoman", "I"]
275
+ ]);
276
+ const BULLET_STYLES = /* @__PURE__ */ new Map([
277
+ ["•", "disc"],
278
+ ["◦", "circle"],
279
+ ["▪", "square"]
280
+ ]);
281
+ const BORDER_EDGES = [
282
+ ["top"],
283
+ ["left", "start"],
284
+ ["bottom"],
285
+ ["right", "end"],
286
+ ["insideH"],
287
+ ["insideV"]
288
+ ];
289
+ function cleanLimits$1(input) {
290
+ const limits = { ...DEFAULT_IMPORT_LIMITS };
291
+ for (const key of Object.keys(limits)) {
292
+ const value = input?.[key];
293
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) limits[key] = value;
294
+ }
295
+ return limits;
296
+ }
297
+ function rowHeightOf(trHeight) {
298
+ if (!trHeight || wAttr(trHeight, "hRule") === "auto") return null;
299
+ const twips = clampInt(wAttr(trHeight, "val"), 0, 1e5, 0);
300
+ return twips > 0 ? Math.min(MAX_ROW_HEIGHT$1, Math.max(MIN_ROW_HEIGHT, Math.round(twips / 15))) : null;
301
+ }
302
+ function clampInt(value, min, max, fallback) {
303
+ const number = Number.parseInt(value ?? "", 10);
304
+ return Number.isFinite(number) ? Math.min(max, Math.max(min, number)) : fallback;
305
+ }
306
+ function cleanText(value, max = MAX_TEXT) {
307
+ return without(value ?? "", isControl).trim().slice(0, max);
308
+ }
309
+ function cleanLink(target) {
310
+ const value = without(target, isInvisible);
311
+ if (value === "" || value.length > MAX_LINK) return null;
312
+ let url;
313
+ try {
314
+ url = new URL(value);
315
+ } catch {
316
+ return null;
317
+ }
318
+ if (!LINK_PROTOCOLS.has(url.protocol)) return null;
319
+ return cleanUrl(url.href);
320
+ }
321
+ function resolvePart(base, target) {
322
+ const segments = (target.startsWith("/") ? target.slice(1) : base + target).split("/");
323
+ const resolved = [];
324
+ for (const segment of segments) if (segment === "..") {
325
+ if (resolved.length === 0) return null;
326
+ resolved.pop();
327
+ } else if (segment !== "." && segment !== "") resolved.push(segment);
328
+ return resolved.join("/");
329
+ }
330
+ function readRelationships(doc) {
331
+ const relationships = /* @__PURE__ */ new Map();
332
+ if (!doc) return relationships;
333
+ for (const element of children(doc.documentElement, NS.rel, "Relationship")) {
334
+ const id = element.getAttribute("Id");
335
+ if (!id || relationships.has(id)) continue;
336
+ relationships.set(id, {
337
+ type: element.getAttribute("Type") ?? "",
338
+ target: element.getAttribute("Target") ?? "",
339
+ external: element.getAttribute("TargetMode") === "External"
340
+ });
341
+ }
342
+ return relationships;
343
+ }
344
+ function readSize(rPr) {
345
+ const complex = onOff(child(rPr, NS.w, "rtl")) || onOff(child(rPr, NS.w, "cs"));
346
+ const value = wAttr(child(rPr, NS.w, "sz"), "val") ?? (complex ? wAttr(child(rPr, NS.w, "szCs"), "val") : null);
347
+ return value !== null && /^[0-9]{1,4}$/.test(value) ? Number(value) : null;
348
+ }
349
+ function readStyles(doc) {
350
+ const paragraphs = /* @__PURE__ */ new Map();
351
+ const runs = /* @__PURE__ */ new Map();
352
+ const sheet = {
353
+ paragraphs,
354
+ runs,
355
+ defaultParagraph: null,
356
+ defaultSize: null,
357
+ defaultFont: null
358
+ };
359
+ if (!doc) return sheet;
360
+ const defaults = descendant(doc.documentElement, [
361
+ [NS.w, "docDefaults"],
362
+ [NS.w, "rPrDefault"],
363
+ [NS.w, "rPr"]
364
+ ]);
365
+ sheet.defaultSize = readSize(defaults);
366
+ sheet.defaultFont = wAttr(child(defaults, NS.w, "rFonts"), "ascii");
367
+ for (const style of children(doc.documentElement, NS.w, "style")) {
368
+ const id = wAttr(style, "styleId");
369
+ if (!id) continue;
370
+ const type = wAttr(style, "type");
371
+ const name = (wAttr(child(style, NS.w, "name"), "val") ?? "").toLowerCase();
372
+ if (type === "character") {
373
+ runs.set(id, name === "hyperlink" ? {} : CODE_CHARACTER_STYLES.has(name) ? { code: true } : readRunFormat(child(style, NS.w, "rPr")));
374
+ continue;
375
+ }
376
+ if (type !== "paragraph") continue;
377
+ if (sheet.defaultParagraph === null && [
378
+ "1",
379
+ "true",
380
+ "on"
381
+ ].includes(wAttr(style, "default") ?? "")) sheet.defaultParagraph = id;
382
+ const pPr = child(style, NS.w, "pPr");
383
+ const numPr = child(pPr, NS.w, "numPr");
384
+ const outline = wAttr(child(pPr, NS.w, "outlineLvl"), "val");
385
+ const headingMatch = /^heading ([1-9])$/.exec(name);
386
+ const heading = name === "title" ? 1 : headingMatch ? Math.min(6, Number(headingMatch[1])) : outline !== null && /^[0-5]$/.test(outline) ? Number(outline) + 1 : null;
387
+ paragraphs.set(id, {
388
+ heading,
389
+ quote: name === "quote" || name === "intense quote",
390
+ code: name === "html preformatted" || name === "code" || name.includes("source code"),
391
+ caption: name === "caption",
392
+ listParagraph: name === "list paragraph",
393
+ numId: wAttr(child(numPr, NS.w, "numId"), "val"),
394
+ ilvl: clampInt(wAttr(child(numPr, NS.w, "ilvl"), "val"), 0, 8, 0),
395
+ size: readSize(child(style, NS.w, "rPr")),
396
+ basedOn: wAttr(child(style, NS.w, "basedOn"), "val")
397
+ });
398
+ }
399
+ return sheet;
400
+ }
401
+ function resolveStyle(styles, id) {
402
+ let current = id ? styles.get(id) : void 0;
403
+ const result = current ? { ...current } : null;
404
+ for (let step = 0; current?.basedOn && result && step < 10; step++) {
405
+ current = styles.get(current.basedOn);
406
+ if (!current) break;
407
+ result.heading ??= current.heading;
408
+ result.quote ||= current.quote;
409
+ result.code ||= current.code;
410
+ result.caption ||= current.caption;
411
+ result.listParagraph ||= current.listParagraph;
412
+ result.size ??= current.size;
413
+ if (result.numId === null) {
414
+ result.numId = current.numId;
415
+ result.ilvl = current.ilvl;
416
+ }
417
+ }
418
+ return result;
419
+ }
420
+ function readNumbering(doc) {
421
+ const abstracts = /* @__PURE__ */ new Map();
422
+ const instances = /* @__PURE__ */ new Map();
423
+ if (doc) {
424
+ for (const abstract of children(doc.documentElement, NS.w, "abstractNum")) {
425
+ const levels = /* @__PURE__ */ new Map();
426
+ const texts = /* @__PURE__ */ new Set();
427
+ for (const level of children(abstract, NS.w, "lvl")) {
428
+ const format = wAttr(child(level, NS.w, "numFmt"), "val") ?? "decimal";
429
+ const text = wAttr(child(level, NS.w, "lvlText"), "val") ?? "";
430
+ texts.add(text);
431
+ const ordered = format !== "bullet" && format !== "none";
432
+ levels.set(clampInt(wAttr(level, "ilvl"), 0, 8, 0), {
433
+ ordered,
434
+ start: clampInt(wAttr(child(level, NS.w, "start"), "val"), 0, 9999, 1),
435
+ type: ordered ? NUMBER_FORMATS.get(format) ?? null : null,
436
+ bullet: ordered ? null : BULLET_STYLES.get(text) ?? null
437
+ });
438
+ }
439
+ if (texts.size > 1) for (const level of levels.values()) level.bullet = null;
440
+ const id = wAttr(abstract, "abstractNumId");
441
+ if (id !== null) abstracts.set(id, levels);
442
+ }
443
+ for (const num of children(doc.documentElement, NS.w, "num")) {
444
+ const id = wAttr(num, "numId");
445
+ const abstractId = wAttr(child(num, NS.w, "abstractNumId"), "val");
446
+ if (id === null || abstractId === null) continue;
447
+ const starts = /* @__PURE__ */ new Map();
448
+ for (const override of children(num, NS.w, "lvlOverride")) {
449
+ const start = wAttr(child(override, NS.w, "startOverride"), "val");
450
+ if (start !== null) starts.set(clampInt(wAttr(override, "ilvl"), 0, 8, 0), clampInt(start, 0, 9999, 1));
451
+ }
452
+ instances.set(id, {
453
+ abstractId,
454
+ starts
455
+ });
456
+ }
457
+ }
458
+ return (numId, ilvl) => {
459
+ const instance = instances.get(numId);
460
+ const level = instance ? abstracts.get(instance.abstractId)?.get(ilvl) : void 0;
461
+ return {
462
+ ordered: level?.ordered ?? false,
463
+ start: instance?.starts.get(ilvl) ?? level?.start ?? 1,
464
+ type: level?.type ?? null,
465
+ bullet: level?.bullet ?? null
466
+ };
467
+ };
468
+ }
469
+ const firstFamily = (entry) => (entry.split(",")[0] ?? "").trim().replace(/^(['"])(.*)\1$/, "$2").toLowerCase();
470
+ function fontLookup(list) {
471
+ const named = /* @__PURE__ */ new Map();
472
+ for (const entry of list) {
473
+ if (typeof entry !== "string") continue;
474
+ const key = firstFamily(entry);
475
+ if (key && !named.has(key)) named.set(key, entry);
476
+ }
477
+ return (font) => {
478
+ const key = (font ?? "").trim().toLowerCase();
479
+ if (!key) return null;
480
+ const generic = GENERIC_FAMILIES.get(key);
481
+ return named.get(key) ?? (generic ? named.get(generic) : void 0) ?? null;
482
+ };
483
+ }
484
+ function readBorders(borders) {
485
+ if (!borders) return {
486
+ border: null,
487
+ color: null
488
+ };
489
+ const edges = BORDER_EDGES.map((names) => names.reduce((found, name) => found ?? child(borders, NS.w, name), null));
490
+ const off = (edge) => !!edge && ["nil", "none"].includes(wAttr(edge, "val") ?? "");
491
+ const on = (edge) => !!edge && !off(edge);
492
+ const [top, left, bottom, right, insideH, insideV] = edges;
493
+ const border = edges.every(off) ? "none" : off(left) && off(right) && off(insideV) && on(top) && on(bottom) && on(insideH) ? "rows" : null;
494
+ const colors = new Set(edges.filter(on).map((edge) => (wAttr(edge, "color") ?? "auto").toLowerCase()));
495
+ const [only] = colors;
496
+ return {
497
+ border,
498
+ color: colors.size === 1 && only && /^[0-9a-f]{6}$/.test(only) ? normalizeColor(`#${only}`) : null
499
+ };
500
+ }
501
+ function pointsOf(size, base) {
502
+ if (size === null || size === void 0 || size === base) return null;
503
+ if (size < MIN_HALF_POINTS || size > MAX_HALF_POINTS) return null;
504
+ return `${Math.floor(size / 2)}${size % 2 === 1 ? ".5" : ""}pt`;
505
+ }
506
+ function readRunFormat(rPr) {
507
+ if (!rPr) return {};
508
+ const format = {};
509
+ const flag = (name, key) => {
510
+ const element = child(rPr, NS.w, name);
511
+ if (element) format[key] = onOff(element);
512
+ };
513
+ flag("b", "bold");
514
+ flag("i", "italic");
515
+ flag("strike", "strike");
516
+ if (child(rPr, NS.w, "dstrike")) format.strike = onOff(child(rPr, NS.w, "dstrike"));
517
+ const underline = child(rPr, NS.w, "u");
518
+ if (underline) format.underline = (wAttr(underline, "val") ?? "single") !== "none";
519
+ const color = wAttr(child(rPr, NS.w, "color"), "val");
520
+ if (color && /^[0-9A-Fa-f]{6}$/.test(color)) format.color = normalizeColor(`#${color}`);
521
+ const highlight = wAttr(child(rPr, NS.w, "highlight"), "val");
522
+ if (highlight && Object.hasOwn(HIGHLIGHTS, highlight)) format.highlight = HIGHLIGHTS[highlight] ?? null;
523
+ if ([
524
+ "vanish",
525
+ "specVanish",
526
+ "webHidden"
527
+ ].some((name) => child(rPr, NS.w, name))) format.hidden = [
528
+ "vanish",
529
+ "specVanish",
530
+ "webHidden"
531
+ ].some((name) => onOff(child(rPr, NS.w, name)));
532
+ const vertical = wAttr(child(rPr, NS.w, "vertAlign"), "val");
533
+ if (vertical) format.script = vertical === "superscript" ? "sup" : vertical === "subscript" ? "sub" : null;
534
+ const size = readSize(rPr);
535
+ if (size !== null) format.size = size;
536
+ const font = wAttr(child(rPr, NS.w, "rFonts"), "ascii");
537
+ if (font) format.font = font;
538
+ const fill = wAttr(child(rPr, NS.w, "shd"), "fill");
539
+ if (!format.highlight && fill && /^[0-9A-Fa-f]{6}$/.test(fill) && fill.toLowerCase() !== "ffffff") format.highlight = normalizeColor(`#${fill}`);
540
+ return format;
541
+ }
542
+ const NO_COMMENTS = {
543
+ comments: /* @__PURE__ */ new Map(),
544
+ parentOf: /* @__PURE__ */ new Map(),
545
+ resolved: /* @__PURE__ */ new Set()
546
+ };
547
+ function codePointSlice(value, max) {
548
+ return [...value].slice(0, max).join("");
549
+ }
550
+ function wordAuthor(value) {
551
+ return codePointSlice(cleanText(value).replace(/[\t\n\r]+/g, " ").replace(/[\u202A-\u202E\u2066-\u2069]/g, ""), MAX_COMMENT_AUTHOR).trim() || "Word";
552
+ }
553
+ function randomPrefix() {
554
+ return [...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(6))].map((byte) => (byte % 36).toString(36)).join("");
555
+ }
556
+ function wordTime(value, fallback) {
557
+ const match = value ? WORD_DATE.exec(value) : null;
558
+ if (!match) return fallback;
559
+ const [year, month, day, hour, minute, second] = match.slice(1).map(Number);
560
+ const date = new Date(Date.UTC(year ?? 0, (month ?? 1) - 1, day ?? 1, hour ?? 0, minute ?? 0, second ?? 0));
561
+ return date.getUTCFullYear() === year && date.getUTCMonth() === (month ?? 0) - 1 && date.getUTCDate() === day && date.getUTCHours() === hour && date.getUTCMinutes() === minute && date.getUTCSeconds() === second ? date.toISOString() : fallback;
562
+ }
563
+ function commentBody(comment) {
564
+ const lines = [];
565
+ for (const paragraph of children(comment, NS.w, "p")) {
566
+ let line = "";
567
+ for (const node of paragraph.getElementsByTagNameNS(NS.w, "*")) if (node.localName === "t") line += node.textContent ?? "";
568
+ else if (node.localName === "tab") line += " ";
569
+ else if (node.localName === "br" || node.localName === "cr") line += "\n";
570
+ lines.push(without(line, isControl).replace(/\r\n?/g, "\n"));
571
+ }
572
+ return codePointSlice(lines.join("\n").replace(/^\n+|\n+$/g, ""), MAX_COMMENT_BODY);
573
+ }
574
+ function readComments(comments, extended) {
575
+ if (!comments) return NO_COMMENTS;
576
+ const now = (/* @__PURE__ */ new Date()).toISOString();
577
+ const prefix = randomPrefix();
578
+ const result = /* @__PURE__ */ new Map();
579
+ const byParagraph = /* @__PURE__ */ new Map();
580
+ for (const comment of children(comments.documentElement, NS.w, "comment")) {
581
+ if (result.size >= MAX_THREADS * MAX_THREAD_COMMENTS) break;
582
+ const id = wAttr(comment, "id") ?? "";
583
+ if (!WORD_ID.test(id) || result.has(id)) continue;
584
+ const body = commentBody(comment);
585
+ if (!body.trim()) continue;
586
+ const name = wordAuthor(wAttr(comment, "author"));
587
+ result.set(id, {
588
+ id: `word-${prefix}-${id}`,
589
+ author: {
590
+ id: codePointSlice(`word:${name}`, 128),
591
+ name
592
+ },
593
+ body,
594
+ created: wordTime(wAttr(comment, "date"), now)
595
+ });
596
+ const last = children(comment, NS.w, "p").at(-1)?.getAttributeNS(W14$1, "paraId");
597
+ if (last) byParagraph.set(last.toUpperCase(), id);
598
+ }
599
+ const parentOf = /* @__PURE__ */ new Map();
600
+ const resolved = /* @__PURE__ */ new Set();
601
+ for (const entry of children(extended?.documentElement, W15$1, "commentEx")) {
602
+ const id = byParagraph.get((entry.getAttributeNS(W15$1, "paraId") ?? "").toUpperCase());
603
+ if (!id) continue;
604
+ const parent = byParagraph.get((entry.getAttributeNS(W15$1, "paraIdParent") ?? "").toUpperCase());
605
+ if (parent && parent !== id) parentOf.set(id, parent);
606
+ if (onOffValue(entry.getAttributeNS(W15$1, "done"))) resolved.add(id);
607
+ }
608
+ return {
609
+ comments: result,
610
+ parentOf,
611
+ resolved
612
+ };
613
+ }
614
+ const onOffValue = (value) => value === "1" || value === "true";
615
+ function revisionKind(node) {
616
+ if (is(node, NS.w, "ins") || is(node, NS.w, "moveTo")) return "insert";
617
+ if (is(node, NS.w, "del") || is(node, NS.w, "moveFrom")) return "delete";
618
+ return null;
619
+ }
620
+ function setChange(element, change) {
621
+ element.setAttribute("data-vive-change", change.id);
622
+ element.setAttribute("data-author", change.author);
623
+ element.setAttribute("data-name", change.name);
624
+ element.setAttribute("data-time", change.time);
625
+ }
626
+ var Reader = class {
627
+ limits;
628
+ relationships;
629
+ media;
630
+ styles;
631
+ listLevel;
632
+ fonts;
633
+ wordComments;
634
+ keepChanges;
635
+ doc = document.implementation.createHTMLDocument("");
636
+ images = [];
637
+ warnings = /* @__PURE__ */ new Map();
638
+ elements = 0;
639
+ cells = 0;
640
+ fieldStack = [];
641
+ instructions = 0;
642
+ paragraphSize = null;
643
+ paragraphStyles;
644
+ runStyles;
645
+ openComments = /* @__PURE__ */ new Set();
646
+ anchored = /* @__PURE__ */ new Set();
647
+ changePrefix = randomPrefix();
648
+ now = (/* @__PURE__ */ new Date()).toISOString();
649
+ changeCount = 0;
650
+ insertion = null;
651
+ deletion = null;
652
+ pendingBreak = null;
653
+ constructor(limits, relationships, media, styles, listLevel, fonts, wordComments = NO_COMMENTS, keepChanges = false) {
654
+ this.limits = limits;
655
+ this.relationships = relationships;
656
+ this.media = media;
657
+ this.styles = styles;
658
+ this.listLevel = listLevel;
659
+ this.fonts = fonts;
660
+ this.wordComments = wordComments;
661
+ this.keepChanges = keepChanges;
662
+ this.paragraphStyles = styles.paragraphs;
663
+ this.runStyles = styles.runs;
664
+ }
665
+ warn(code) {
666
+ this.warnings.set(code, (this.warnings.get(code) ?? 0) + 1);
667
+ }
668
+ rootComment(id) {
669
+ if (!id || !this.wordComments.comments.has(id)) return null;
670
+ let root = id;
671
+ for (let step = 0; step < MAX_THREAD_COMMENTS; step++) {
672
+ const parent = this.wordComments.parentOf.get(root);
673
+ if (!parent || !this.wordComments.comments.has(parent)) break;
674
+ root = parent;
675
+ }
676
+ return root;
677
+ }
678
+ commentRange(node) {
679
+ const start = is(node, NS.w, "commentRangeStart");
680
+ if (!start && !is(node, NS.w, "commentRangeEnd")) return false;
681
+ const id = wAttr(node, "id");
682
+ const root = this.rootComment(id);
683
+ if (!root || root !== id) return true;
684
+ if (!start) this.openComments.delete(root);
685
+ else if (this.openComments.size < MAX_OPEN_COMMENTS) this.openComments.add(root);
686
+ else this.warn("NESTING_FLATTENED");
687
+ return true;
688
+ }
689
+ threads() {
690
+ const { comments, resolved } = this.wordComments;
691
+ const threads = /* @__PURE__ */ new Map();
692
+ for (const root of this.anchored) {
693
+ const comment = comments.get(root);
694
+ if (comment && threads.size < MAX_THREADS) threads.set(root, {
695
+ id: comment.id,
696
+ resolved: resolved.has(root),
697
+ comments: [comment]
698
+ });
699
+ }
700
+ for (const [id, comment] of comments) {
701
+ const root = this.rootComment(id);
702
+ const thread = root && root !== id ? threads.get(root) : void 0;
703
+ if (thread && thread.comments.length < MAX_THREAD_COMMENTS) thread.comments.push(comment);
704
+ }
705
+ return [...threads.values()];
706
+ }
707
+ warningList() {
708
+ return [...this.warnings].slice(0, 100).map(([code, count]) => ({
709
+ code,
710
+ count
711
+ }));
712
+ }
713
+ change(element) {
714
+ this.changeCount += 1;
715
+ const name = wordAuthor(wAttr(element, "author"));
716
+ return {
717
+ id: `word-${this.changePrefix}-${this.changeCount}`,
718
+ author: codePointSlice(`word:${name}`, 128),
719
+ name,
720
+ time: wordTime(wAttr(element, "date"), this.now)
721
+ };
722
+ }
723
+ revision(node, walk) {
724
+ const kind = revisionKind(node);
725
+ if (!kind) return false;
726
+ if (!this.keepChanges) {
727
+ if (kind === "insert") walk();
728
+ return true;
729
+ }
730
+ const key = kind === "insert" ? "insertion" : "deletion";
731
+ const saved = this[key];
732
+ this[key] = this.change(node);
733
+ walk();
734
+ this[key] = saved;
735
+ return true;
736
+ }
737
+ paragraphBreak(pPr) {
738
+ if (!this.keepChanges) return null;
739
+ for (const node of child(pPr, NS.w, "rPr")?.children ?? []) {
740
+ const kind = revisionKind(node);
741
+ if (kind) return {
742
+ kind,
743
+ ...this.change(node)
744
+ };
745
+ }
746
+ return null;
747
+ }
748
+ tracked(node) {
749
+ let result = node;
750
+ for (const [tag, change] of [["del", this.deletion], ["ins", this.insertion]]) {
751
+ if (!change) continue;
752
+ this.visit(0);
753
+ const element = this.doc.createElement(tag);
754
+ setChange(element, change);
755
+ element.append(result);
756
+ result = element;
757
+ }
758
+ return result;
759
+ }
760
+ visit(depth) {
761
+ this.elements += 1;
762
+ if (this.elements > this.limits.elements) throw new DocxError("TOO_COMPLEX", "The Word document has too many elements.");
763
+ return depth <= MAX_DEPTH;
764
+ }
765
+ blocks(container, target, depth, tableDepth) {
766
+ for (const node of container.children) {
767
+ if (!this.visit(depth)) return;
768
+ if (this.commentRange(node)) continue;
769
+ if (is(node, NS.w, "p")) this.paragraph(node, target, depth + 1);
770
+ else if (is(node, NS.w, "tbl")) this.table(node, target, depth + 1, tableDepth + 1);
771
+ else if (is(node, NS.w, "sdt")) {
772
+ const content = child(node, NS.w, "sdtContent");
773
+ if (content) this.blocks(content, target, depth + 1, tableDepth);
774
+ } else if (this.revision(node, () => this.blocks(node, target, depth + 1, tableDepth))) {} else if (is(node, NS.w, "customXml")) this.blocks(node, target, depth + 1, tableDepth);
775
+ else if (is(node, NS.mc, "AlternateContent")) {
776
+ const fallback = child(node, NS.mc, "Fallback");
777
+ if (fallback) this.blocks(fallback, target, depth + 1, tableDepth);
778
+ } else if (is(node, NS.w, "altChunk")) this.warn("OBJECT_DROPPED");
779
+ }
780
+ }
781
+ paragraph(paragraph, target, depth) {
782
+ const pPr = child(paragraph, NS.w, "pPr");
783
+ const style = resolveStyle(this.paragraphStyles, wAttr(child(pPr, NS.w, "pStyle"), "val"));
784
+ const numPr = child(pPr, NS.w, "numPr");
785
+ const numId = numPr ? wAttr(child(numPr, NS.w, "numId"), "val") : style?.numId ?? null;
786
+ const ilvl = numPr ? clampInt(wAttr(child(numPr, NS.w, "ilvl"), "val"), 0, 8, 0) : style?.ilvl ?? 0;
787
+ const incoming = this.pendingBreak;
788
+ this.pendingBreak = this.paragraphBreak(pPr);
789
+ const content = this.doc.createElement("span");
790
+ const sized = style ?? resolveStyle(this.paragraphStyles, this.styles.defaultParagraph);
791
+ this.paragraphSize = sized?.size ?? this.styles.defaultSize;
792
+ this.inline(paragraph, content, {}, depth);
793
+ if (style?.code) {
794
+ target.code(content.textContent ?? "");
795
+ return;
796
+ }
797
+ if (style?.caption && !incoming && !content.querySelector("img")) {
798
+ const caption = (content.textContent ?? "").trim();
799
+ if (caption && target.caption(caption)) return;
800
+ }
801
+ const heading = style?.heading ?? null;
802
+ const jc = wAttr(child(pPr, NS.w, "jc"), "val") ?? "";
803
+ const align = Object.hasOwn(ALIGNMENTS$1, jc) ? ALIGNMENTS$1[jc] : void 0;
804
+ const spacing = child(pPr, NS.w, "spacing");
805
+ const rule = wAttr(spacing, "lineRule");
806
+ const lineHeight = rule === null || rule === "auto" ? LINE_HEIGHTS.get(wAttr(spacing, "line") ?? "") : void 0;
807
+ const ind = child(pPr, NS.w, "ind");
808
+ const twips = Number(wAttr(ind, "start") ?? wAttr(ind, "left"));
809
+ const listed = numId && numId !== "0" && !heading;
810
+ const indent = listed || style?.listParagraph || !(twips > 0) ? 0 : Math.min(MAX_INDENT$1, Math.round(twips / INDENT_TWIPS$1));
811
+ let change = incoming;
812
+ const text = () => {
813
+ const block = this.doc.createElement(heading ? `h${heading}` : "p");
814
+ if (align) block.style.setProperty("text-align", align);
815
+ if (lineHeight) block.style.setProperty("line-height", lineHeight);
816
+ if (indent) block.style.setProperty("margin-inline-start", `${indent * 2}em`);
817
+ if (change) {
818
+ block.setAttribute("data-vive-break", change.kind);
819
+ setChange(block, change);
820
+ change = null;
821
+ }
822
+ return block;
823
+ };
824
+ if (listed) {
825
+ const block = text();
826
+ block.append(...content.childNodes);
827
+ target.listItem(block, numId, ilvl, this.listLevel(numId, ilvl));
828
+ return;
829
+ }
830
+ let blocks = [];
831
+ let open = null;
832
+ for (const node of [...content.childNodes]) if (isImage(node)) {
833
+ const figure = this.doc.createElement("figure");
834
+ if (align === "center" || align === "right") figure.setAttribute("data-align", align);
835
+ figure.append(node);
836
+ blocks.push(figure);
837
+ open = null;
838
+ } else {
839
+ if (!open) {
840
+ open = text();
841
+ blocks.push(open);
842
+ }
843
+ open.append(node);
844
+ }
845
+ if (blocks.length === 0) blocks.push(text());
846
+ else if (blocks.some((block) => block.localName === "figure")) blocks = blocks.filter((block) => block.localName === "figure" || (block.textContent ?? "").trim());
847
+ for (const block of blocks) {
848
+ if (style?.listParagraph && !heading && target.continueItem(block)) continue;
849
+ if (style?.quote) target.quote(block);
850
+ else target.block(block);
851
+ }
852
+ }
853
+ inline(container, target, inherited, depth) {
854
+ for (const node of container.children) {
855
+ if (!this.visit(depth)) return;
856
+ if (this.commentRange(node)) continue;
857
+ if (is(node, NS.w, "r")) this.run(node, target, inherited, depth + 1);
858
+ else if (is(node, NS.w, "hyperlink")) this.hyperlink(node, target, inherited, depth + 1);
859
+ else if (this.revision(node, () => this.inline(node, target, inherited, depth + 1))) {} else if (is(node, NS.w, "smartTag") || is(node, NS.w, "customXml") || is(node, NS.w, "fldSimple")) this.inline(node, target, inherited, depth + 1);
860
+ else if (is(node, NS.w, "sdt")) {
861
+ const content = child(node, NS.w, "sdtContent");
862
+ if (content) this.inline(content, target, inherited, depth + 1);
863
+ } else if (is(node, NS.mc, "AlternateContent")) {
864
+ const fallback = child(node, NS.mc, "Fallback");
865
+ if (fallback) this.inline(fallback, target, inherited, depth + 1);
866
+ } else if (node.namespaceURI === "http://schemas.openxmlformats.org/officeDocument/2006/math") this.warn("OBJECT_DROPPED");
867
+ }
868
+ }
869
+ hyperlink(link, target, inherited, depth) {
870
+ const id = link.getAttributeNS(NS.r, "id");
871
+ const relationship = id ? this.relationships.get(id) : void 0;
872
+ const href = relationship?.type === REL_HYPERLINK && relationship.external ? cleanLink(relationship.target) : null;
873
+ if (id && !href) this.warn("LINK_DROPPED");
874
+ if (!href) {
875
+ this.inline(link, target, inherited, depth);
876
+ return;
877
+ }
878
+ const anchor = this.doc.createElement("a");
879
+ anchor.setAttribute("href", href);
880
+ if ((wAttr(link, "tgtFrame") ?? "").toLowerCase() === "_blank") anchor.setAttribute("target", "_blank");
881
+ this.inline(link, anchor, inherited, depth);
882
+ target.append(anchor);
883
+ }
884
+ run(run, target, inherited, depth) {
885
+ const rPr = child(run, NS.w, "rPr");
886
+ const style = this.runStyles.get(wAttr(child(rPr, NS.w, "rStyle"), "val") ?? "") ?? {};
887
+ const format = {
888
+ ...inherited,
889
+ ...style,
890
+ ...readRunFormat(rPr)
891
+ };
892
+ if (format.hidden) {
893
+ if (run.textContent) this.warn("HIDDEN_TEXT");
894
+ return;
895
+ }
896
+ for (const node of run.children) {
897
+ if (!this.visit(depth)) return;
898
+ if (is(node, NS.w, "fldChar")) {
899
+ const type = wAttr(node, "fldCharType");
900
+ if (type === "begin") {
901
+ this.fieldStack.push("instruction");
902
+ this.instructions += 1;
903
+ } else if (type === "separate" && this.fieldStack.at(-1) === "instruction") {
904
+ this.fieldStack[this.fieldStack.length - 1] = "result";
905
+ this.instructions -= 1;
906
+ } else if (type === "end" && this.fieldStack.pop() === "instruction") this.instructions -= 1;
907
+ continue;
908
+ }
909
+ if (this.instructions > 0) continue;
910
+ if (is(node, NS.w, "t") || this.deletion && is(node, NS.w, "delText")) this.text(node.textContent ?? "", format, target);
911
+ else if (is(node, NS.w, "drawing") && this.deletion) this.warn("OBJECT_DROPPED");
912
+ else if (is(node, NS.w, "tab")) this.text(" ", format, target);
913
+ else if (is(node, NS.w, "noBreakHyphen")) this.text("‑", format, target);
914
+ else if (is(node, NS.w, "br") || is(node, NS.w, "cr")) {
915
+ const type = wAttr(node, "type");
916
+ if (type !== "page" && type !== "column") target.append(this.tracked(this.doc.createElement("br")));
917
+ } else if (is(node, NS.w, "drawing")) this.drawing(node, target);
918
+ else if (is(node, NS.w, "pict") || is(node, NS.w, "object")) this.warn("OBJECT_DROPPED");
919
+ else if (is(node, NS.mc, "AlternateContent")) {
920
+ const fallback = child(node, NS.mc, "Fallback");
921
+ if (fallback && child(fallback, NS.w, "drawing")) this.drawing(child(fallback, NS.w, "drawing"), target);
922
+ else this.warn("OBJECT_DROPPED");
923
+ }
924
+ }
925
+ }
926
+ text(value, format, target) {
927
+ const text = without(value, isControl);
928
+ if (!text) return;
929
+ let node = this.doc.createTextNode(text);
930
+ const wrap = (tag, style) => {
931
+ const element = this.doc.createElement(tag);
932
+ if (style) element.style.setProperty(style[0], style[1]);
933
+ element.append(node);
934
+ node = element;
935
+ };
936
+ if (format.highlight) wrap("mark", ["background-color", format.highlight]);
937
+ if (format.color) wrap("span", ["color", format.color]);
938
+ const points = pointsOf(format.size, this.paragraphSize);
939
+ if (points) wrap("span", ["font-size", points]);
940
+ const family = !!format.font && format.font.toLowerCase() === this.styles.defaultFont?.toLowerCase() ? null : this.fonts(format.font);
941
+ if (family) wrap("span", ["font-family", family]);
942
+ if (format.strike) wrap("s");
943
+ if (format.underline) wrap("u");
944
+ if (format.italic) wrap("em");
945
+ if (format.script) wrap(format.script);
946
+ if (format.code) wrap("code");
947
+ if (format.bold) wrap("strong");
948
+ node = this.tracked(node);
949
+ for (const root of this.openComments) {
950
+ const comment = this.wordComments.comments.get(root);
951
+ if (!comment) continue;
952
+ this.visit(0);
953
+ const span = this.doc.createElement("span");
954
+ span.setAttribute("data-vive-comment", comment.id);
955
+ span.append(node);
956
+ node = span;
957
+ this.anchored.add(root);
958
+ }
959
+ target.append(node);
960
+ }
961
+ drawing(drawing, target) {
962
+ const frame = child(drawing, NS.wp, "inline") ?? child(drawing, NS.wp, "anchor");
963
+ const id = descendant(frame, [
964
+ [NS.a, "graphic"],
965
+ [NS.a, "graphicData"],
966
+ [NS.pic, "pic"],
967
+ [NS.pic, "blipFill"],
968
+ [NS.a, "blip"]
969
+ ])?.getAttributeNS(NS.r, "embed");
970
+ const relationship = id ? this.relationships.get(id) : void 0;
971
+ const path = relationship && relationship.type === REL_IMAGE && !relationship.external ? resolvePart("word/", relationship.target) : null;
972
+ const bytes = path ? this.media.get(path) : void 0;
973
+ if (!bytes || this.images.length >= this.limits.images) {
974
+ this.warn("IMAGE_DROPPED");
975
+ return;
976
+ }
977
+ const image = this.doc.createElement("img");
978
+ const docPr = child(frame, NS.wp, "docPr");
979
+ const alt = cleanText(docPr?.getAttribute("descr") || docPr?.getAttribute("title"));
980
+ if (alt) image.setAttribute("alt", alt);
981
+ const extent = child(frame, NS.wp, "extent");
982
+ const width = Math.round(Number(extent?.getAttribute("cx")) / EMU_PER_PIXEL$1);
983
+ const height = Math.round(Number(extent?.getAttribute("cy")) / EMU_PER_PIXEL$1);
984
+ if (width >= 1 && height >= 1 && width <= MAX_DIMENSION$1 && height <= MAX_DIMENSION$1) {
985
+ image.setAttribute("width", String(width));
986
+ image.setAttribute("height", String(height));
987
+ }
988
+ this.images.push({
989
+ element: image,
990
+ bytes
991
+ });
992
+ target.append(image);
993
+ }
994
+ table(table, target, depth, tableDepth) {
995
+ if (tableDepth > MAX_TABLE_DEPTH) {
996
+ this.warn("NESTING_FLATTENED");
997
+ this.flatten(table, target, depth);
998
+ return;
999
+ }
1000
+ 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)));
1001
+ const element = this.doc.createElement("table");
1002
+ const tblPr = child(table, NS.w, "tblPr");
1003
+ const tableWidth = child(tblPr, NS.w, "tblW");
1004
+ if (wAttr(tableWidth, "type") === "pct" && ["5000", "100%"].includes(wAttr(tableWidth, "w") ?? "")) element.setAttribute("data-width", "full");
1005
+ if (wAttr(child(tblPr, NS.w, "jc"), "val") === "center") element.setAttribute("data-align", "center");
1006
+ const borders = readBorders(child(tblPr, NS.w, "tblBorders"));
1007
+ if (borders.border) element.setAttribute("data-border", borders.border);
1008
+ if (borders.color) element.setAttribute("style", `--vive-table-border-color: ${borders.color}`);
1009
+ const body = this.doc.createElement("tbody");
1010
+ element.append(body);
1011
+ const origins = /* @__PURE__ */ new Map();
1012
+ const rows = children(table, NS.w, "tr").filter((row) => child(row, NS.w, "tc"));
1013
+ let widest = 0;
1014
+ const stripes = [];
1015
+ rows.forEach((row, rowIndex) => {
1016
+ if (!this.visit(depth)) return;
1017
+ const trPr = child(row, NS.w, "trPr");
1018
+ const header = onOff(child(trPr, NS.w, "tblHeader"));
1019
+ const tableRow = this.doc.createElement("tr");
1020
+ const height = rowHeightOf(child(trPr, NS.w, "trHeight"));
1021
+ if (height) tableRow.setAttribute("style", `height: ${height}px`);
1022
+ let column = 0;
1023
+ for (const cell of children(row, NS.w, "tc")) {
1024
+ const tcPr = child(cell, NS.w, "tcPr");
1025
+ const span = clampInt(wAttr(child(tcPr, NS.w, "gridSpan"), "val"), 1, 63, 1);
1026
+ const merge = child(tcPr, NS.w, "vMerge");
1027
+ const continues = merge !== null && wAttr(merge, "val") !== "restart";
1028
+ if (column + span > MAX_COLUMNS) throw new DocxError("TOO_COMPLEX", "The Word document has a table that is too wide.");
1029
+ const origin = origins.get(column);
1030
+ if (continues && origin) {
1031
+ const rowspan = Math.min(rows.length - rowIndex + 1, (origin.rowSpan || 1) + 1);
1032
+ origin.setAttribute("rowspan", String(rowspan));
1033
+ column += span;
1034
+ continue;
1035
+ }
1036
+ this.cells += 1;
1037
+ if (this.cells > this.limits.cells) throw new DocxError("TOO_COMPLEX", "The Word document has too many table cells.");
1038
+ const tableCell = this.doc.createElement(header ? "th" : "td");
1039
+ if (span > 1) tableCell.setAttribute("colspan", String(span));
1040
+ const cellWidths = widths.slice(column, column + span);
1041
+ 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(","));
1042
+ const cellStyle = cellStyleOf(tcPr);
1043
+ stripes.push({
1044
+ cell: tableCell,
1045
+ even: rowIndex % 2 === 1 && !header,
1046
+ fill: (wAttr(child(tcPr, NS.w, "shd"), "fill") ?? "").toUpperCase()
1047
+ });
1048
+ if (cellStyle) tableCell.setAttribute("style", cellStyle);
1049
+ for (let offset = 0; offset < span; offset++) if (merge) origins.set(column + offset, tableCell);
1050
+ else origins.delete(column + offset);
1051
+ this.pendingBreak = null;
1052
+ this.blocks(cell, new BlockWriter(this.doc, tableCell), depth + 1, tableDepth);
1053
+ if (!tableCell.firstChild) tableCell.append(this.doc.createElement("p"));
1054
+ tableRow.append(tableCell);
1055
+ column += span;
1056
+ }
1057
+ widest = Math.max(widest, column);
1058
+ if (widest * (rowIndex + 1) > this.limits.cells) throw new DocxError("TOO_COMPLEX", "The Word document has too many table cells.");
1059
+ body.append(tableRow);
1060
+ });
1061
+ this.pendingBreak = null;
1062
+ this.stripes(element, stripes);
1063
+ target.block(element);
1064
+ }
1065
+ stripes(table, cells) {
1066
+ const even = cells.filter((entry) => entry.even);
1067
+ const stripe = (entry) => entry.fill === STRIPE_FILL$1;
1068
+ if (!even.some(stripe) || !even.every((entry) => entry.fill !== "" && entry.fill !== "AUTO") || cells.some((entry) => !entry.even && stripe(entry))) return;
1069
+ table.setAttribute("data-striped", "true");
1070
+ for (const { cell } of even.filter(stripe)) {
1071
+ cell.style.removeProperty("background-color");
1072
+ if (!cell.getAttribute("style")) cell.removeAttribute("style");
1073
+ }
1074
+ }
1075
+ flatten(container, target, depth) {
1076
+ for (const node of container.children) {
1077
+ if (!this.visit(depth)) return;
1078
+ if (is(node, NS.w, "p")) this.paragraph(node, target, depth + 1);
1079
+ else if ([
1080
+ "tbl",
1081
+ "tr",
1082
+ "tc",
1083
+ "sdt",
1084
+ "sdtContent",
1085
+ "ins",
1086
+ "moveTo",
1087
+ "customXml"
1088
+ ].some((name) => is(node, NS.w, name))) this.flatten(node, target, depth + 1);
1089
+ else if (is(node, NS.mc, "AlternateContent")) {
1090
+ const fallback = child(node, NS.mc, "Fallback");
1091
+ if (fallback) this.flatten(fallback, target, depth + 1);
1092
+ }
1093
+ }
1094
+ }
1095
+ };
1096
+ var BlockWriter = class {
1097
+ doc;
1098
+ parent;
1099
+ lists = [];
1100
+ quoteElement = null;
1101
+ codeElement = null;
1102
+ constructor(doc, parent) {
1103
+ this.doc = doc;
1104
+ this.parent = parent;
1105
+ }
1106
+ reset(keep) {
1107
+ if (keep !== "list") this.lists = [];
1108
+ if (keep !== "quote") this.quoteElement = null;
1109
+ if (keep !== "code") this.codeElement = null;
1110
+ }
1111
+ block(element) {
1112
+ this.reset(null);
1113
+ this.parent.append(element);
1114
+ }
1115
+ quote(element) {
1116
+ this.reset("quote");
1117
+ if (!this.quoteElement) {
1118
+ this.quoteElement = this.doc.createElement("blockquote");
1119
+ this.parent.append(this.quoteElement);
1120
+ }
1121
+ this.quoteElement.append(element);
1122
+ }
1123
+ caption(text) {
1124
+ const figure = this.parent.lastElementChild;
1125
+ if (figure?.localName !== "figure" || figure.querySelector("figcaption")) return false;
1126
+ const caption = this.doc.createElement("figcaption");
1127
+ caption.append(text);
1128
+ figure.append(caption);
1129
+ this.reset(null);
1130
+ return true;
1131
+ }
1132
+ code(text) {
1133
+ this.reset("code");
1134
+ if (this.codeElement) {
1135
+ this.codeElement.append(`\n${text}`);
1136
+ return;
1137
+ }
1138
+ const pre = this.doc.createElement("pre");
1139
+ this.codeElement = this.doc.createElement("code");
1140
+ this.codeElement.append(text);
1141
+ pre.append(this.codeElement);
1142
+ this.parent.append(pre);
1143
+ }
1144
+ continueItem(element) {
1145
+ const item = this.lists.at(-1)?.lastItem;
1146
+ if (!item) return false;
1147
+ item.append(element);
1148
+ return true;
1149
+ }
1150
+ listItem(element, numId, ilvl, level) {
1151
+ this.reset("list");
1152
+ while (this.lists.length > 0 && (this.lists.at(-1)?.ilvl ?? 0) > ilvl) this.lists.pop();
1153
+ let top = this.lists.at(-1);
1154
+ if (top && top.ilvl === ilvl && (top.numId !== numId || top.ordered !== level.ordered)) {
1155
+ this.lists.pop();
1156
+ top = this.lists.at(-1);
1157
+ }
1158
+ if (!top || top.ilvl < ilvl) {
1159
+ const list = this.doc.createElement(level.ordered ? "ol" : "ul");
1160
+ if (level.ordered && level.start !== 1) list.setAttribute("start", String(level.start));
1161
+ if (level.ordered && level.type) list.setAttribute("type", level.type);
1162
+ if (!level.ordered && level.bullet) list.style.setProperty("list-style-type", level.bullet);
1163
+ (top?.lastItem ?? this.parent).append(list);
1164
+ top = {
1165
+ ilvl,
1166
+ numId,
1167
+ ordered: level.ordered,
1168
+ element: list,
1169
+ lastItem: null
1170
+ };
1171
+ this.lists.push(top);
1172
+ }
1173
+ const item = this.doc.createElement("li");
1174
+ item.append(element);
1175
+ top.element.append(item);
1176
+ top.lastItem = item;
1177
+ }
1178
+ };
1179
+ function isImage(node) {
1180
+ if (!(node instanceof Element)) return false;
1181
+ if (node.localName === "img") return true;
1182
+ return node.localName === "a" && node.childElementCount === 1 && node.firstElementChild?.localName === "img" && !(node.textContent ?? "").trim();
1183
+ }
1184
+ function base64(bytes) {
1185
+ let binary = "";
1186
+ for (let offset = 0; offset < bytes.length; offset += 32768) binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768));
1187
+ return btoa(binary);
1188
+ }
1189
+ const EXTENSIONS = {
1190
+ "image/png": "png",
1191
+ "image/jpeg": "jpg",
1192
+ "image/gif": "gif",
1193
+ "image/webp": "webp",
1194
+ "image/avif": "avif"
1195
+ };
1196
+ async function resolveImages(reader, options, limits) {
1197
+ const policy = {
1198
+ ...DEFAULT_SOURCE_POLICY,
1199
+ ...options.imagePolicy,
1200
+ allowBase64: options.allowBase64 === true
1201
+ };
1202
+ let index = 0;
1203
+ for (const { element, bytes } of reader.images) {
1204
+ throwIfAborted(options.signal);
1205
+ if (!reader.doc.body.contains(element)) continue;
1206
+ index += 1;
1207
+ const type = sniffImageType(bytes);
1208
+ const size = imageSize(bytes);
1209
+ const tooBig = bytes.length > limits.imageBytes || size === null || size.width * size.height > limits.imagePixels;
1210
+ let src = null;
1211
+ if (type && !tooBig && options.upload) try {
1212
+ const file = new File([bytes], `image-${index}.${EXTENSIONS[type] ?? "bin"}`, { type });
1213
+ const result = await options.upload(file, {
1214
+ signal: options.signal ?? new AbortController().signal,
1215
+ onProgress: () => void 0
1216
+ });
1217
+ src = normalizeImageSrc(typeof result === "string" ? result : result.src, policy);
1218
+ const width = typeof result === "string" ? 0 : Math.round(Number(result.width));
1219
+ const height = typeof result === "string" ? 0 : Math.round(Number(result.height));
1220
+ if (src && width >= 1 && height >= 1 && width <= MAX_DIMENSION$1 && height <= MAX_DIMENSION$1) {
1221
+ element.setAttribute("width", String(width));
1222
+ element.setAttribute("height", String(height));
1223
+ }
1224
+ } catch {
1225
+ throwIfAborted(options.signal);
1226
+ }
1227
+ else if (type && !tooBig && policy.allowBase64) src = normalizeImageSrc(`data:${type};base64,${base64(bytes)}`, policy);
1228
+ if (src) element.setAttribute("src", src);
1229
+ else {
1230
+ (element.closest("figure") ?? element).remove();
1231
+ reader.warn("IMAGE_DROPPED");
1232
+ }
1233
+ }
1234
+ }
1235
+ const COMMENT_PARTS = ["word/comments.xml", "word/commentsExtended.xml"];
1236
+ async function importDocx(file, options = {}) {
1237
+ const limits = cleanLimits$1(options.limits);
1238
+ if (file.size > limits.fileBytes) throw new DocxError("TOO_LARGE", "The Word document is too large.");
1239
+ throwIfAborted(options.signal);
1240
+ const bytes = new Uint8Array(await file.arrayBuffer());
1241
+ throwIfAborted(options.signal);
1242
+ const root = readZip(bytes, (name) => name === "_rels/.rels", {
1243
+ totalBytes: limits.totalBytes,
1244
+ partBytes: () => limits.partBytes
1245
+ }).get("_rels/.rels");
1246
+ const office = [...readRelationships(root ? parseXml(root) : null).values()].find((relationship) => relationship.type === REL_OFFICE_DOCUMENT);
1247
+ const documentPath = office ? resolvePart("", office.target) : null;
1248
+ if (!documentPath || !/^word\/[^/]+\.xml$/.test(documentPath)) throw new DocxError("NOT_DOCX", "The file is not a Word document.");
1249
+ const relsPath = documentPath.replace(/^word\/(.+)$/, "word/_rels/$1.rels");
1250
+ let mediaCount = 0;
1251
+ const parts = readZip(bytes, (name) => {
1252
+ if ([
1253
+ documentPath,
1254
+ relsPath,
1255
+ "word/styles.xml",
1256
+ "word/numbering.xml"
1257
+ ].includes(name)) return true;
1258
+ if (options.comments !== false && COMMENT_PARTS.includes(name)) return true;
1259
+ if (!/^word\/media\/[^/]+$/.test(name) || mediaCount >= limits.images) return false;
1260
+ mediaCount += 1;
1261
+ return true;
1262
+ }, {
1263
+ totalBytes: limits.totalBytes,
1264
+ partBytes: (name) => name === documentPath ? limits.documentBytes : name.startsWith("word/media/") ? limits.imageBytes : limits.partBytes
1265
+ });
1266
+ const part = (name) => {
1267
+ const data = parts.get(name);
1268
+ return data ? parseXml(data) : null;
1269
+ };
1270
+ const body = child(part(documentPath)?.documentElement, NS.w, "body");
1271
+ if (!body) throw new DocxError("UNSUPPORTED", "This kind of Word document is not supported.");
1272
+ const styles = readStyles(part("word/styles.xml"));
1273
+ const media = new Map([...parts].filter(([name]) => name.startsWith("word/media/")));
1274
+ const reader = new Reader(limits, readRelationships(part(relsPath)), media, styles, readNumbering(part("word/numbering.xml")), fontLookup(options.fontFamilies ?? DEFAULT_FONT_FAMILIES), options.comments === false ? NO_COMMENTS : readComments(part("word/comments.xml"), part("word/commentsExtended.xml")), options.trackedChanges === "keep");
1275
+ reader.blocks(body, new BlockWriter(reader.doc, reader.doc.body), 0, 0);
1276
+ await resolveImages(reader, options, limits);
1277
+ throwIfAborted(options.signal);
1278
+ return {
1279
+ html: reader.doc.body.innerHTML,
1280
+ warnings: reader.warningList(),
1281
+ threads: reader.threads()
1282
+ };
1283
+ }
1284
+ // src/write.ts
1285
+ const DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
1286
+ const DEFAULT_EXPORT_LIMITS = Object.freeze({
1287
+ imageBytes: 10485760,
1288
+ images: 200,
1289
+ timeout: 15e3
1290
+ });
1291
+ const W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
1292
+ const R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
1293
+ const PACKAGE_REL = "http://schemas.openxmlformats.org/package/2006/relationships";
1294
+ const DECLARATION = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
1295
+ const PAGE_WIDTH_TWIPS = 9360;
1296
+ const MAX_IMAGE_PIXELS = 624;
1297
+ const EMU_PER_PIXEL = 9525;
1298
+ const TWIPS_PER_PIXEL = 15;
1299
+ const MAX_ROW_HEIGHT = 2e3;
1300
+ const MAX_LEVEL = 8;
1301
+ const STEP_HALF_POINTS = {
1302
+ tiny: 16,
1303
+ small: 19,
1304
+ big: 28,
1305
+ huge: 33
1306
+ };
1307
+ const POINT_SIZE = /^([0-9]{1,2})(?:\.([05]))?pt$/;
1308
+ const INDENT_TWIPS = 720;
1309
+ const MAX_INDENT = 8;
1310
+ function halfPoints(size) {
1311
+ if (typeof size !== "string") return null;
1312
+ if (Object.hasOwn(STEP_HALF_POINTS, size)) return STEP_HALF_POINTS[size] ?? null;
1313
+ const match = POINT_SIZE.exec(size);
1314
+ if (!match) return null;
1315
+ const halves = Number(match[1]) * 2 + (match[2] === "5" ? 1 : 0);
1316
+ return halves >= 12 && halves <= 192 ? halves : null;
1317
+ }
1318
+ const WATCH_URLS = {
1319
+ youtube: (id) => `https://www.youtube.com/watch?v=${id}`,
1320
+ vimeo: (id) => `https://vimeo.com/${id}`,
1321
+ spotify: (id) => `https://open.spotify.com/${id.replace(":", "/")}`
1322
+ };
1323
+ const IMAGE_EXTENSIONS = {
1324
+ "image/png": "png",
1325
+ "image/jpeg": "jpeg",
1326
+ "image/gif": "gif"
1327
+ };
1328
+ const MAX_DIMENSION = 1e4;
1329
+ const ALIGNMENTS = {
1330
+ center: "center",
1331
+ right: "right",
1332
+ justify: "both"
1333
+ };
1334
+ const LINE_TWIPS = {
1335
+ "1": 240,
1336
+ "1.15": 276,
1337
+ "1.5": 360,
1338
+ "2": 480
1339
+ };
1340
+ const GENERIC_FONTS = {
1341
+ serif: "Times New Roman",
1342
+ "sans-serif": "Arial",
1343
+ monospace: "Courier New"
1344
+ };
1345
+ const FONT_NAME = /^[A-Za-z][A-Za-z0-9 -]{0,63}$/;
1346
+ const ORDERED_FORMATS = {
1347
+ a: "lowerLetter",
1348
+ A: "upperLetter",
1349
+ i: "lowerRoman",
1350
+ I: "upperRoman"
1351
+ };
1352
+ const BULLET_TEXTS = {
1353
+ disc: "•",
1354
+ circle: "◦",
1355
+ square: "▪"
1356
+ };
1357
+ const DEFAULT_BULLETS = [
1358
+ "•",
1359
+ "◦",
1360
+ "▪"
1361
+ ];
1362
+ const STRIPE_FILL = "F2F2F2";
1363
+ const W14 = "http://schemas.microsoft.com/office/word/2010/wordml";
1364
+ const W15 = "http://schemas.microsoft.com/office/word/2012/wordml";
1365
+ const COMMENTS_EXTENDED = "http://schemas.microsoft.com/office/2011/relationships/commentsExtended";
1366
+ const COMMENT_ID = /^[A-Za-z0-9_-]{1,64}$/;
1367
+ const WORD_TIME = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.\d{3})?Z$/;
1368
+ const MAX_WORD_COMMENTS = 1e4;
1369
+ const MAX_CONVERT_PIXELS = 5e7;
1370
+ const EMBEDDABLE = new Set(Object.keys(IMAGE_EXTENSIONS));
1371
+ const CONVERTIBLE = /* @__PURE__ */ new Set(["image/webp", "image/avif"]);
1372
+ function validXmlCharacter(code) {
1373
+ return code === 9 || code === 10 || code === 13 || code >= 32 && code <= 55295 || code >= 57344 && code <= 65533 || code >= 65536;
1374
+ }
1375
+ function escapeXml(value) {
1376
+ let result = "";
1377
+ for (const character of String(value ?? "")) {
1378
+ if (!validXmlCharacter(character.codePointAt(0) ?? 0)) continue;
1379
+ if (character === "&") result += "&amp;";
1380
+ else if (character === "<") result += "&lt;";
1381
+ else if (character === ">") result += "&gt;";
1382
+ else if (character === "\"") result += "&quot;";
1383
+ else if (character === "'") result += "&apos;";
1384
+ else result += character;
1385
+ }
1386
+ return result;
1387
+ }
1388
+ function cleanLimits(input) {
1389
+ const limits = { ...DEFAULT_EXPORT_LIMITS };
1390
+ for (const key of Object.keys(limits)) {
1391
+ const value = input?.[key];
1392
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) limits[key] = value;
1393
+ }
1394
+ return limits;
1395
+ }
1396
+ const hexColor = (value) => {
1397
+ const match = typeof value === "string" ? /^#([0-9a-f]{6})(?:[0-9a-f]{2})?$/i.exec(value) : null;
1398
+ return match?.[1] ? match[1].toUpperCase() : null;
1399
+ };
1400
+ function wordFont(family) {
1401
+ if (typeof family !== "string") return null;
1402
+ const first = (family.split(",")[0] ?? "").trim().replace(/^(['"])(.*)\1$/, "$2");
1403
+ const generic = first.toLowerCase();
1404
+ if (Object.hasOwn(GENERIC_FONTS, generic)) return GENERIC_FONTS[generic] ?? null;
1405
+ return FONT_NAME.test(first) ? first : null;
1406
+ }
1407
+ function tableBorders(border, color) {
1408
+ if (border !== "rows" && border !== "none" && !color) return "";
1409
+ const edge = (name, shown) => shown ? `<w:${name} w:val="single" w:sz="4" w:space="0" w:color="${color ?? "auto"}"/>` : `<w:${name} w:val="nil"/>`;
1410
+ const lines = border !== "none";
1411
+ const grid = lines && border !== "rows";
1412
+ return `<w:tblBorders>${edge("top", lines)}${edge("left", grid)}${edge("bottom", lines)}${edge("right", grid)}${edge("insideH", lines)}${edge("insideV", grid)}</w:tblBorders>`;
1413
+ }
1414
+ const positiveInt = (value) => {
1415
+ const number = Number(value);
1416
+ return Number.isFinite(number) && number >= 1 ? Math.min(MAX_DIMENSION, Math.round(number)) : null;
1417
+ };
1418
+ function combinedSignal(signal, timeout) {
1419
+ const timer = AbortSignal.timeout(timeout);
1420
+ if (!signal) return timer;
1421
+ const controller = new AbortController();
1422
+ const abort = () => controller.abort();
1423
+ if (signal.aborted || timer.aborted) abort();
1424
+ signal.addEventListener("abort", abort, { once: true });
1425
+ timer.addEventListener("abort", abort, { once: true });
1426
+ return controller.signal;
1427
+ }
1428
+ function decodeDataUrl(src) {
1429
+ const match = /^data:image\/[a-z0-9.+-]+;base64,([a-z0-9+/=\s]+)$/i.exec(src);
1430
+ if (!match?.[1]) return null;
1431
+ try {
1432
+ const binary = atob(match[1].replace(/\s+/g, ""));
1433
+ const bytes = new Uint8Array(binary.length);
1434
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
1435
+ return bytes;
1436
+ } catch {
1437
+ return null;
1438
+ }
1439
+ }
1440
+ async function readLimited(response, max) {
1441
+ const declared = Number(response.headers.get("content-length"));
1442
+ if (Number.isFinite(declared) && declared > max) return null;
1443
+ const reader = response.body?.getReader();
1444
+ if (!reader) return null;
1445
+ const chunks = [];
1446
+ let total = 0;
1447
+ for (;;) {
1448
+ const { done, value } = await reader.read();
1449
+ if (done) break;
1450
+ total += value.length;
1451
+ if (total > max) {
1452
+ await reader.cancel();
1453
+ return null;
1454
+ }
1455
+ chunks.push(value);
1456
+ }
1457
+ const bytes = new Uint8Array(total);
1458
+ let offset = 0;
1459
+ for (const chunk of chunks) {
1460
+ bytes.set(chunk, offset);
1461
+ offset += chunk.length;
1462
+ }
1463
+ return bytes;
1464
+ }
1465
+ async function toPng(bytes, type) {
1466
+ if (typeof createImageBitmap !== "function" || typeof document === "undefined") return null;
1467
+ try {
1468
+ const bitmap = await createImageBitmap(new Blob([bytes], { type }));
1469
+ const canvas = document.createElement("canvas");
1470
+ canvas.width = bitmap.width;
1471
+ canvas.height = bitmap.height;
1472
+ const context = canvas.getContext("2d");
1473
+ if (!context) return null;
1474
+ context.drawImage(bitmap, 0, 0);
1475
+ bitmap.close();
1476
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
1477
+ return blob ? new Uint8Array(await blob.arrayBuffer()) : null;
1478
+ } catch {
1479
+ return null;
1480
+ }
1481
+ }
1482
+ var Writer = class {
1483
+ options;
1484
+ limits;
1485
+ relationships = [];
1486
+ numbering = [];
1487
+ media = {};
1488
+ relationshipCount = 2;
1489
+ numCount = 0;
1490
+ imageCount = 0;
1491
+ imageAttempts = 0;
1492
+ drawingCount = 0;
1493
+ notes = [];
1494
+ abstracts = /* @__PURE__ */ new Map();
1495
+ cellAlign = null;
1496
+ threads = /* @__PURE__ */ new Map();
1497
+ wordIds = /* @__PURE__ */ new Map();
1498
+ wordComments = [];
1499
+ remaining = /* @__PURE__ */ new Map();
1500
+ openComments = /* @__PURE__ */ new Set();
1501
+ breaks = /* @__PURE__ */ new Map();
1502
+ revisionCount = MAX_WORD_COMMENTS;
1503
+ constructor(options, limits) {
1504
+ this.options = options;
1505
+ this.limits = limits;
1506
+ for (const thread of options.threads ?? []) if (COMMENT_ID.test(String(thread?.id)) && Array.isArray(thread.comments)) {
1507
+ if (thread.comments.length > 0) this.threads.set(thread.id, thread);
1508
+ }
1509
+ }
1510
+ get hasComments() {
1511
+ return this.wordComments.length > 0;
1512
+ }
1513
+ commentIdsOf(node) {
1514
+ if (this.threads.size === 0) return [];
1515
+ return node.marks.filter((mark) => mark.type.name === "comment" && this.threads.has(String(mark.attrs.id))).map((mark) => String(mark.attrs.id));
1516
+ }
1517
+ countComments(doc) {
1518
+ if (this.threads.size === 0) return;
1519
+ doc.descendants((node) => {
1520
+ if (!node.isTextblock) return true;
1521
+ if (node.type.spec.code) return false;
1522
+ node.forEach((child) => {
1523
+ for (const id of this.commentIdsOf(child)) this.remaining.set(id, (this.remaining.get(id) ?? 0) + 1);
1524
+ });
1525
+ return false;
1526
+ });
1527
+ }
1528
+ countBreaks(doc) {
1529
+ let previous = null;
1530
+ doc.descendants((node) => {
1531
+ if (!node.isTextblock && !node.isLeaf) return true;
1532
+ const change = node.attrs.change;
1533
+ if (previous && (change?.kind === "insert" || change?.kind === "delete")) this.breaks.set(previous, change);
1534
+ previous = node;
1535
+ return false;
1536
+ });
1537
+ }
1538
+ revision(tag, change, content) {
1539
+ this.revisionCount += 1;
1540
+ const time = WORD_TIME.exec(String(change.time));
1541
+ const open = `<w:${tag} w:id="${this.revisionCount}" w:author="${escapeXml(cleanAuthor(change.name))}"${time ? ` w:date="${time[1]}Z"` : ""}`;
1542
+ return content === void 0 ? `${open}/>` : `${open}>${content}</w:${tag}>`;
1543
+ }
1544
+ startComment(threadId) {
1545
+ this.openComments.add(threadId);
1546
+ let ids = this.wordIds.get(threadId);
1547
+ if (!ids) {
1548
+ const thread = this.threads.get(threadId);
1549
+ ids = [];
1550
+ let parent = null;
1551
+ for (const comment of thread.comments) {
1552
+ if (this.wordComments.length >= MAX_WORD_COMMENTS) break;
1553
+ const id = this.wordComments.length;
1554
+ const paraId = (id + 1).toString(16).toUpperCase().padStart(8, "0");
1555
+ this.wordComments.push({
1556
+ id,
1557
+ paraId,
1558
+ parent,
1559
+ done: thread.resolved === true,
1560
+ comment
1561
+ });
1562
+ parent ??= paraId;
1563
+ ids.push(id);
1564
+ }
1565
+ this.wordIds.set(threadId, ids);
1566
+ }
1567
+ return ids.map((id) => `<w:commentRangeStart w:id="${id}"/>`).join("");
1568
+ }
1569
+ endComment(threadId) {
1570
+ this.openComments.delete(threadId);
1571
+ return (this.wordIds.get(threadId) ?? []).map((id) => `<w:commentRangeEnd w:id="${id}"/><w:r><w:commentReference w:id="${id}"/></w:r>`).join("");
1572
+ }
1573
+ closeComments() {
1574
+ if (this.openComments.size === 0) return "";
1575
+ return `<w:p>${[...this.openComments].map((id) => this.endComment(id)).join("")}</w:p>`;
1576
+ }
1577
+ commentsXml() {
1578
+ const comments = this.wordComments.map(({ id, paraId, comment }) => {
1579
+ const author = cleanAuthor(comment.author?.name);
1580
+ const time = WORD_TIME.exec(String(comment.created));
1581
+ const lines = String(comment.body ?? "").split("\n");
1582
+ const paragraphs = lines.map((line, index) => {
1583
+ const last = index === lines.length - 1;
1584
+ const reference = index === 0 ? "<w:r><w:annotationRef/></w:r>" : "";
1585
+ return `<w:p${last ? ` w14:paraId="${paraId}" w14:textId="77777777"` : ""}>${reference}${this.textRun(line, "")}</w:p>`;
1586
+ }).join("");
1587
+ return `<w:comment w:id="${id}" w:author="${escapeXml(author)}"${time ? ` w:date="${time[1]}Z"` : ""} w:initials="${escapeXml(initials(author))}">${paragraphs}</w:comment>`;
1588
+ });
1589
+ return `${DECLARATION}<w:comments xmlns:w="${W}" xmlns:w14="${W14}">${comments.join("")}</w:comments>`;
1590
+ }
1591
+ commentsExtendedXml() {
1592
+ const entries = this.wordComments.map(({ paraId, parent, done }) => `<w15:commentEx w15:paraId="${paraId}"${parent ? ` w15:paraIdParent="${parent}"` : ""} w15:done="${done ? 1 : 0}"/>`);
1593
+ return `${DECLARATION}<w15:commentsEx xmlns:w15="${W15}">${entries.join("")}</w15:commentsEx>`;
1594
+ }
1595
+ relationship(type, target, external = false) {
1596
+ this.relationshipCount += 1;
1597
+ const id = `rId${this.relationshipCount}`;
1598
+ this.relationships.push(`<Relationship Id="${id}" Type="${R}/${type}" Target="${escapeXml(target)}"${external ? " TargetMode=\"External\"" : ""}/>`);
1599
+ return id;
1600
+ }
1601
+ relationshipsXml() {
1602
+ const comments = this.hasComments ? `<Relationship Id="rIdComments" Type="${R}/comments" Target="comments.xml"/><Relationship Id="rIdCommentsExtended" Type="${COMMENTS_EXTENDED}" Target="commentsExtended.xml"/>` : "";
1603
+ return `${DECLARATION}<Relationships xmlns="${PACKAGE_REL}"><Relationship Id="rId1" Type="${R}/styles" Target="styles.xml"/><Relationship Id="rId2" Type="${R}/numbering" Target="numbering.xml"/>${comments}${this.relationships.join("")}</Relationships>`;
1604
+ }
1605
+ notesXml() {
1606
+ if (this.notes.length === 0) return "";
1607
+ 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("");
1608
+ }
1609
+ numberingXml() {
1610
+ const abstract = (id, format, text) => `<w:abstractNum w:abstractNumId="${id}"><w:multiLevelType w:val="hybridMultilevel"/>${Array.from({ length: 9 }, (_, level) => `<w:lvl w:ilvl="${level}"><w:start w:val="1"/><w:numFmt w:val="${format}"/><w:lvlText w:val="${text(level)}"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="${720 * (level + 1)}" w:hanging="360"/></w:pPr></w:lvl>`).join("")}</w:abstractNum>`;
1611
+ const numbered = (level) => `%${level + 1}.`;
1612
+ let abstracts = abstract(0, "bullet", (level) => DEFAULT_BULLETS[level % 3] ?? "") + abstract(1, "decimal", numbered);
1613
+ for (const [key, id] of this.abstracts) {
1614
+ const value = key.slice(1);
1615
+ abstracts += key.startsWith("o") ? abstract(id, ORDERED_FORMATS[value] ?? "decimal", numbered) : abstract(id, "bullet", () => BULLET_TEXTS[value] ?? "");
1616
+ }
1617
+ return `${DECLARATION}<w:numbering xmlns:w="${W}">${abstracts}${this.numbering.join("")}</w:numbering>`;
1618
+ }
1619
+ abstractFor(node, ordered) {
1620
+ const value = String(ordered ? node.attrs.type : node.attrs.bulletStyle);
1621
+ if (!Object.hasOwn(ordered ? ORDERED_FORMATS : BULLET_TEXTS, value)) return ordered ? 1 : 0;
1622
+ const key = `${ordered ? "o" : "b"}${value}`;
1623
+ let id = this.abstracts.get(key);
1624
+ if (id === void 0) {
1625
+ id = this.abstracts.size + 2;
1626
+ this.abstracts.set(key, id);
1627
+ }
1628
+ return id;
1629
+ }
1630
+ newList(node, ordered, level) {
1631
+ this.numCount += 1;
1632
+ const start = Number(node.attrs.start);
1633
+ const override = ordered ? `<w:lvlOverride w:ilvl="${level}"><w:startOverride w:val="${Number.isInteger(start) ? Math.min(9999, Math.max(0, start)) : 1}"/></w:lvlOverride>` : "";
1634
+ this.numbering.push(`<w:num w:numId="${this.numCount}"><w:abstractNumId w:val="${this.abstractFor(node, ordered)}"/>${override}</w:num>`);
1635
+ return this.numCount;
1636
+ }
1637
+ async blocks(parent, level, quote) {
1638
+ let xml = "";
1639
+ for (let index = 0; index < parent.childCount; index++) {
1640
+ const node = parent.child(index);
1641
+ xml += await this.block(node, level, quote);
1642
+ const next = index + 1 < parent.childCount ? parent.child(index + 1) : null;
1643
+ if (node.type.name === "table" && (!next || next.type.name === "table")) xml += "<w:p/>";
1644
+ }
1645
+ return xml;
1646
+ }
1647
+ async block(node, level, quote) {
1648
+ switch (node.type.name) {
1649
+ case "paragraph": return this.paragraph(node, quote ? "Quote" : null);
1650
+ case "heading": return this.paragraph(node, `Heading${Math.min(6, Math.max(1, Number(node.attrs.level) || 1))}`);
1651
+ case "blockquote": return this.blocks(node, level, true);
1652
+ case "bulletList":
1653
+ case "orderedList":
1654
+ case "taskList": return this.list(node, level);
1655
+ 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("");
1656
+ 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>";
1657
+ case "table": return this.table(node);
1658
+ case "image": return this.figure(node);
1659
+ case "embed": return `<w:p>${this.embed(node)}</w:p>`;
1660
+ 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("");
1661
+ default: return node.isTextblock ? this.paragraph(node, null) : node.childCount > 0 ? this.blocks(node, level, quote) : "";
1662
+ }
1663
+ }
1664
+ paragraphProperties(node, style, list) {
1665
+ let properties = style ? `<w:pStyle w:val="${style}"/>` : "";
1666
+ if (list) properties += `<w:numPr><w:ilvl w:val="${list[1]}"/><w:numId w:val="${list[0]}"/></w:numPr>`;
1667
+ const lineHeight = String(node.attrs.lineHeight);
1668
+ const line = Object.hasOwn(LINE_TWIPS, lineHeight) ? LINE_TWIPS[lineHeight] : void 0;
1669
+ if (line) properties += `<w:spacing w:line="${line}" w:lineRule="auto"/>`;
1670
+ const indent = node.attrs.indent;
1671
+ if (!list && Number.isInteger(indent) && indent >= 1) properties += `<w:ind w:left="${Math.min(MAX_INDENT, indent) * INDENT_TWIPS}"/>`;
1672
+ const textAlign = String(node.attrs.textAlign);
1673
+ const align = Object.hasOwn(ALIGNMENTS, textAlign) ? ALIGNMENTS[textAlign] : this.cellAlign;
1674
+ if (align) properties += `<w:jc w:val="${align}"/>`;
1675
+ const change = this.breaks.get(node);
1676
+ if (change) properties += `<w:rPr>${this.revision(change.kind === "insert" ? "ins" : "del", change)}</w:rPr>`;
1677
+ return properties ? `<w:pPr>${properties}</w:pPr>` : "";
1678
+ }
1679
+ paragraph(node, style, list, prefix = "") {
1680
+ return `<w:p>${this.paragraphProperties(node, style, list)}${prefix ? this.textRun(prefix, "") : ""}${this.inline(node)}</w:p>`;
1681
+ }
1682
+ async list(node, level) {
1683
+ const ordered = node.type.name === "orderedList";
1684
+ const depth = Math.min(MAX_LEVEL, level);
1685
+ const numId = this.newList(node, ordered, depth);
1686
+ let xml = "";
1687
+ for (let index = 0; index < node.childCount; index++) {
1688
+ const item = node.child(index);
1689
+ const prefix = item.type.name === "taskItem" ? item.attrs.checked ? "☑ " : "☐ " : "";
1690
+ let first = true;
1691
+ for (let offset = 0; offset < item.childCount; offset++) {
1692
+ const content = item.child(offset);
1693
+ if (first && content.isTextblock && content.type.name !== "codeBlock") xml += this.paragraph(content, null, [numId, depth], prefix);
1694
+ else if (content.isTextblock && content.type.name === "paragraph") xml += this.paragraph(content, "ListParagraph");
1695
+ else xml += await this.block(content, level + 1, false);
1696
+ first = false;
1697
+ }
1698
+ if (first) xml += this.paragraph(item, null, [numId, depth], prefix);
1699
+ }
1700
+ return xml;
1701
+ }
1702
+ inline(node) {
1703
+ let xml = "";
1704
+ let link = null;
1705
+ let linkRuns = "";
1706
+ const flush = () => {
1707
+ if (link) xml += `<w:hyperlink r:id="${link.id}"${link.blank ? " w:tgtFrame=\"_blank\"" : ""}>${linkRuns}</w:hyperlink>`;
1708
+ link = null;
1709
+ linkRuns = "";
1710
+ };
1711
+ node.forEach((child) => {
1712
+ const linkMark = child.marks.find((mark) => mark.type.name === "link");
1713
+ const href = linkMark ? cleanLink(String(linkMark.attrs.href ?? "")) : null;
1714
+ const blank = linkMark?.attrs.target === "_blank";
1715
+ const key = href ? `${blank ? "blank" : "self"} ${href}` : null;
1716
+ if ((link?.key ?? null) !== key) {
1717
+ flush();
1718
+ if (href && key) link = {
1719
+ key,
1720
+ id: this.relationship("hyperlink", href, true),
1721
+ blank
1722
+ };
1723
+ }
1724
+ const properties = this.runProperties(child.marks, href !== null);
1725
+ const comments = this.commentIdsOf(child);
1726
+ let run = comments.filter((id) => !this.openComments.has(id)).map((id) => this.startComment(id)).join("");
1727
+ const insertion = child.marks.find((mark) => mark.type.name === "insertion");
1728
+ const deletion = child.marks.find((mark) => mark.type.name === "deletion");
1729
+ let content = child.isText ? this.textRun(child.text ?? "", properties, !!deletion) : this.inlineNode(child, properties, !!deletion);
1730
+ if (deletion && content) content = this.revision("del", deletion.attrs, content);
1731
+ if (insertion && content) content = this.revision("ins", insertion.attrs, content);
1732
+ run += content;
1733
+ for (const id of comments) {
1734
+ const left = (this.remaining.get(id) ?? 1) - 1;
1735
+ this.remaining.set(id, left);
1736
+ if (left <= 0 && this.openComments.has(id)) run += this.endComment(id);
1737
+ }
1738
+ if (link) linkRuns += run;
1739
+ else xml += run;
1740
+ });
1741
+ flush();
1742
+ return xml;
1743
+ }
1744
+ inlineNode(node, properties, deleted) {
1745
+ switch (node.type.name) {
1746
+ case "hardBreak": return "<w:r><w:br/></w:r>";
1747
+ case "mention": return this.textRun(String(node.type.spec.leafText?.(node) ?? ""), properties, deleted);
1748
+ case "mathInline": return this.textRun(String(node.attrs.latex ?? ""), "<w:rStyle w:val=\"CodeChar\"/>", deleted);
1749
+ case "footnote":
1750
+ this.notes.push(node);
1751
+ return this.textRun(String(this.notes.length), "<w:vertAlign w:val=\"superscript\"/>", deleted);
1752
+ default: return "";
1753
+ }
1754
+ }
1755
+ runProperties(marks, linked) {
1756
+ let properties = linked ? "<w:rStyle w:val=\"Hyperlink\"/>" : "";
1757
+ const names = new Set(marks.map((mark) => mark.type.name));
1758
+ if (names.has("code") && !linked) properties += "<w:rStyle w:val=\"CodeChar\"/>";
1759
+ const font = wordFont(marks.find((mark) => mark.type.name === "fontFamily")?.attrs.family);
1760
+ if (font) properties += `<w:rFonts w:ascii="${font}" w:hAnsi="${font}" w:cs="${font}"/>`;
1761
+ if (names.has("bold")) properties += "<w:b/>";
1762
+ if (names.has("italic")) properties += "<w:i/>";
1763
+ if (names.has("strike")) properties += "<w:strike/>";
1764
+ const color = hexColor(marks.find((mark) => mark.type.name === "textColor")?.attrs.color);
1765
+ if (color) properties += `<w:color w:val="${color}"/>`;
1766
+ const size = halfPoints(marks.find((mark) => mark.type.name === "fontSize")?.attrs.size);
1767
+ if (size !== null) properties += `<w:sz w:val="${size}"/><w:szCs w:val="${size}"/>`;
1768
+ if (names.has("underline")) properties += "<w:u w:val=\"single\"/>";
1769
+ const fill = hexColor(marks.find((mark) => mark.type.name === "highlight")?.attrs.color);
1770
+ if (names.has("highlight")) properties += `<w:shd w:val="clear" w:color="auto" w:fill="${fill ?? "FFFF00"}"/>`;
1771
+ if (names.has("superscript")) properties += "<w:vertAlign w:val=\"superscript\"/>";
1772
+ else if (names.has("subscript")) properties += "<w:vertAlign w:val=\"subscript\"/>";
1773
+ return properties;
1774
+ }
1775
+ textRun(text, properties, deleted = false) {
1776
+ const tag = deleted ? "w:delText" : "w:t";
1777
+ const body = text.split(" ").map((part) => part ? `<${tag} xml:space="preserve">${escapeXml(part)}</${tag}>` : "").join("<w:tab/>");
1778
+ return body ? `<w:r>${properties ? `<w:rPr>${properties}</w:rPr>` : ""}${body}</w:r>` : "";
1779
+ }
1780
+ linkParagraphContent(href, text) {
1781
+ const label = text || href || "";
1782
+ if (!href) return this.textRun(label, "");
1783
+ return `<w:hyperlink r:id="${this.relationship("hyperlink", href, true)}">${this.textRun(label, "<w:rStyle w:val=\"Hyperlink\"/>")}</w:hyperlink>`;
1784
+ }
1785
+ embed(node) {
1786
+ const provider = String(node.attrs.provider);
1787
+ const watch = Object.hasOwn(WATCH_URLS, provider) ? WATCH_URLS[provider] : void 0;
1788
+ const href = watch && typeof node.attrs.id === "string" ? cleanLink(watch(node.attrs.id)) : null;
1789
+ return this.linkParagraphContent(href, String(node.attrs.title ?? ""));
1790
+ }
1791
+ async loadImage(src) {
1792
+ if (src.startsWith("data:")) return decodeDataUrl(src);
1793
+ if (!this.options.fetchImages || !/^https:\/\//i.test(src)) return null;
1794
+ const signal = combinedSignal(this.options.signal, this.limits.timeout);
1795
+ try {
1796
+ const response = await fetch(src, {
1797
+ credentials: "omit",
1798
+ referrerPolicy: "no-referrer",
1799
+ mode: "cors",
1800
+ redirect: "follow",
1801
+ signal
1802
+ });
1803
+ if (!response.ok || !/^https:\/\//i.test(response.url || src)) return null;
1804
+ return await readLimited(response, this.limits.imageBytes);
1805
+ } catch {
1806
+ if (this.options.signal?.aborted) throw this.options.signal.reason;
1807
+ return null;
1808
+ }
1809
+ }
1810
+ async embedImage(node) {
1811
+ if (this.imageAttempts >= this.limits.images) return null;
1812
+ this.imageAttempts += 1;
1813
+ const src = typeof node.attrs.src === "string" ? node.attrs.src : "";
1814
+ let bytes = await this.loadImage(src);
1815
+ if (!bytes || bytes.length > this.limits.imageBytes) return null;
1816
+ let type = sniffImageType(bytes);
1817
+ const measured = imageSize(bytes);
1818
+ if (type && CONVERTIBLE.has(type) && measured && measured.width * measured.height <= MAX_CONVERT_PIXELS) {
1819
+ bytes = await toPng(bytes, type);
1820
+ type = bytes ? "image/png" : null;
1821
+ }
1822
+ if (!bytes || !type || !EMBEDDABLE.has(type)) return null;
1823
+ const natural = imageSize(bytes);
1824
+ let width = positiveInt(node.attrs.width) ?? natural?.width ?? MAX_IMAGE_PIXELS;
1825
+ let height = positiveInt(node.attrs.height) ?? (natural ? Math.round(natural.height * width / natural.width) : Math.round(width * .75));
1826
+ if (width > MAX_IMAGE_PIXELS) {
1827
+ height = Math.max(1, Math.round(height * MAX_IMAGE_PIXELS / width));
1828
+ width = MAX_IMAGE_PIXELS;
1829
+ }
1830
+ this.imageCount += 1;
1831
+ return {
1832
+ bytes,
1833
+ type,
1834
+ width,
1835
+ height: Math.min(MAX_DIMENSION, Math.max(1, height))
1836
+ };
1837
+ }
1838
+ async image(node) {
1839
+ const image = await this.embedImage(node);
1840
+ const alt = String(node.attrs.alt ?? "");
1841
+ if (!image) {
1842
+ const src = typeof node.attrs.src === "string" ? cleanLink(node.attrs.src) : null;
1843
+ return this.linkParagraphContent(src, alt);
1844
+ }
1845
+ const name = `image${this.imageCount}.${IMAGE_EXTENSIONS[image.type]}`;
1846
+ this.media[`word/media/${name}`] = [image.bytes, { level: 0 }];
1847
+ const id = this.relationship("image", `media/${name}`);
1848
+ this.drawingCount += 1;
1849
+ const cx = image.width * EMU_PER_PIXEL;
1850
+ const cy = image.height * EMU_PER_PIXEL;
1851
+ const number = this.drawingCount;
1852
+ const href = typeof node.attrs.href === "string" ? cleanLink(node.attrs.href) : null;
1853
+ const run = `<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>`;
1854
+ if (!href) return run;
1855
+ return `<w:hyperlink r:id="${this.relationship("hyperlink", href, true)}">${run}</w:hyperlink>`;
1856
+ }
1857
+ async figure(node) {
1858
+ const align = node.attrs.align;
1859
+ const justify = align === "center" || align === "right" ? `<w:jc w:val="${align}"/>` : "";
1860
+ const image = `<w:p>${justify && `<w:pPr>${justify}</w:pPr>`}${await this.image(node)}</w:p>`;
1861
+ const caption = this.textRun(String(node.attrs.caption ?? ""), "");
1862
+ if (!caption) return image;
1863
+ return `${image}<w:p><w:pPr><w:pStyle w:val="Caption"/>${justify}</w:pPr>${caption}</w:p>`;
1864
+ }
1865
+ async table(node) {
1866
+ const rows = [];
1867
+ node.forEach((row) => {
1868
+ rows.push(row);
1869
+ });
1870
+ const pending = /* @__PURE__ */ new Map();
1871
+ const firstWidths = [];
1872
+ rows[0]?.forEach((cell) => {
1873
+ const span = positiveInt(cell.attrs.colspan) ?? 1;
1874
+ const widths = cell.attrs.colwidth;
1875
+ for (let index = 0; index < span; index++) firstWidths.push(Array.isArray(widths) ? positiveInt(widths[index]) : null);
1876
+ });
1877
+ let rowXml = "";
1878
+ let gridColumns = 0;
1879
+ const outerAlign = this.cellAlign;
1880
+ const striped = node.attrs.striped === true;
1881
+ for (const [rowIndex, row] of rows.entries()) {
1882
+ let column = 0;
1883
+ let cellIndex = 0;
1884
+ let cells = "";
1885
+ let header = row.childCount > 0;
1886
+ const continuation = () => {
1887
+ const merge = pending.get(column);
1888
+ if (!merge) return false;
1889
+ cells += `<w:tc><w:tcPr>${merge.span > 1 ? `<w:gridSpan w:val="${merge.span}"/>` : ""}<w:vMerge/></w:tcPr><w:p/></w:tc>`;
1890
+ merge.left -= 1;
1891
+ if (merge.left <= 0) pending.delete(column);
1892
+ column += merge.span;
1893
+ return true;
1894
+ };
1895
+ while (cellIndex < row.childCount) {
1896
+ if (continuation()) continue;
1897
+ const cell = row.child(cellIndex);
1898
+ cellIndex += 1;
1899
+ if (cell.type.name !== "tableHeader") header = false;
1900
+ const span = Math.min(63, positiveInt(cell.attrs.colspan) ?? 1);
1901
+ const rowspan = positiveInt(cell.attrs.rowspan) ?? 1;
1902
+ const widths = cell.attrs.colwidth;
1903
+ const width = Array.isArray(widths) ? widths.reduce((sum, value) => sum + (positiveInt(value) ?? 0), 0) * TWIPS_PER_PIXEL : 0;
1904
+ let properties = width > 0 ? `<w:tcW w:w="${width}" w:type="dxa"/>` : "";
1905
+ if (span > 1) properties += `<w:gridSpan w:val="${span}"/>`;
1906
+ if (rowspan > 1) {
1907
+ properties += "<w:vMerge w:val=\"restart\"/>";
1908
+ pending.set(column, {
1909
+ left: rowspan - 1,
1910
+ span
1911
+ });
1912
+ }
1913
+ const shade = hexColor(cell.attrs.background);
1914
+ const stripe = striped && rowIndex % 2 === 1 && cell.type.name === "tableCell" ? STRIPE_FILL : null;
1915
+ const fill = shade ?? stripe;
1916
+ if (fill) properties += `<w:shd w:val="clear" w:color="auto" w:fill="${fill}"/>`;
1917
+ const vertical = cell.attrs.verticalAlign;
1918
+ if (vertical === "middle" || vertical === "bottom") properties += `<w:vAlign w:val="${vertical === "middle" ? "center" : vertical}"/>`;
1919
+ const cellAlign = String(cell.attrs.textAlign);
1920
+ this.cellAlign = Object.hasOwn(ALIGNMENTS, cellAlign) ? ALIGNMENTS[cellAlign] ?? null : null;
1921
+ let content = await this.blocks(cell, 0, false);
1922
+ this.cellAlign = outerAlign;
1923
+ if (!content.endsWith("</w:p>")) content += "<w:p/>";
1924
+ cells += `<w:tc>${properties ? `<w:tcPr>${properties}</w:tcPr>` : ""}${content}</w:tc>`;
1925
+ column += span;
1926
+ }
1927
+ while (pending.has(column)) continuation();
1928
+ gridColumns = Math.max(gridColumns, column);
1929
+ const rowHeight = positiveInt(row.attrs.height);
1930
+ const rowProperties = `${rowHeight ? `<w:trHeight w:val="${Math.min(MAX_ROW_HEIGHT, rowHeight) * TWIPS_PER_PIXEL}" w:hRule="atLeast"/>` : ""}${header ? "<w:tblHeader/>" : ""}`;
1931
+ rowXml += `<w:tr>${rowProperties ? `<w:trPr>${rowProperties}</w:trPr>` : ""}${cells}</w:tr>`;
1932
+ }
1933
+ gridColumns = Math.max(1, gridColumns);
1934
+ const fallback = Math.round(PAGE_WIDTH_TWIPS / gridColumns);
1935
+ const grid = Array.from({ length: gridColumns }, (_, index) => {
1936
+ const width = firstWidths[index];
1937
+ return `<w:gridCol w:w="${width ? width * TWIPS_PER_PIXEL : fallback}"/>`;
1938
+ }).join("");
1939
+ return `<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/>${node.attrs.width === "full" ? "<w:tblW w:w=\"5000\" w:type=\"pct\"/>" : "<w:tblW w:w=\"0\" w:type=\"auto\"/>"}${node.attrs.align === "center" ? "<w:jc w:val=\"center\"/>" : ""}${tableBorders(node.attrs.border, hexColor(node.attrs.borderColor))}<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>${grid}</w:tblGrid>${rowXml}</w:tbl>`;
1940
+ }
1941
+ };
1942
+ function cleanAuthor(name) {
1943
+ let author = "";
1944
+ for (const character of String(name ?? "")) {
1945
+ if (author.length >= 100) break;
1946
+ const code = character.codePointAt(0) ?? 0;
1947
+ author += code < 32 || code === 127 ? " " : character;
1948
+ }
1949
+ return author.trim() || "viveEditor";
1950
+ }
1951
+ function initials(author) {
1952
+ return author.split(/\s+/).filter(Boolean).slice(0, 2).map((word) => [...word][0]?.toLocaleUpperCase() ?? "").join("");
1953
+ }
1954
+ function stylesXml() {
1955
+ 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>`;
1956
+ 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="Caption"><w:name w:val="caption"/><w:basedOn w:val="Normal"/><w:rPr><w:i/><w:sz w:val="18"/></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>`;
1957
+ }
1958
+ const encoder = new TextEncoder();
1959
+ async function exportDocx(source, options = {}) {
1960
+ const doc = source.schema.nodeFromJSON(repairContent(source.schema, source.getJSON()));
1961
+ doc.check();
1962
+ const writer = new Writer(options, cleanLimits(options.limits));
1963
+ writer.countComments(doc);
1964
+ writer.countBreaks(doc);
1965
+ const body = await writer.blocks(doc, 0, false) + writer.closeComments() + writer.notesXml();
1966
+ options.signal?.throwIfAborted();
1967
+ const title = escapeXml((options.title ?? "").trim().slice(0, 255));
1968
+ const files = {
1969
+ "[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"/>${writer.hasComments ? "<Override PartName=\"/word/comments.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml\"/><Override PartName=\"/word/commentsExtended.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml\"/>" : ""}</Types>`),
1970
+ "_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>`),
1971
+ "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>`),
1972
+ "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>`),
1973
+ "word/styles.xml": encoder.encode(stylesXml()),
1974
+ "word/numbering.xml": encoder.encode(writer.numberingXml()),
1975
+ "word/_rels/document.xml.rels": encoder.encode(writer.relationshipsXml()),
1976
+ ...writer.media
1977
+ };
1978
+ if (writer.hasComments) {
1979
+ files["word/comments.xml"] = encoder.encode(writer.commentsXml());
1980
+ files["word/commentsExtended.xml"] = encoder.encode(writer.commentsExtendedXml());
1981
+ }
1982
+ return new Blob([zipSync(files)], { type: DOCX_MIME });
1983
+ }
1984
+ export { DEFAULT_IMPORT_LIMITS, DOCX_MIME, DocxError, exportDocx, importDocx };
1985
+
1986
+ //# sourceMappingURL=index.js.map