@hilvana/office 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/parse.js ADDED
@@ -0,0 +1,873 @@
1
+ import { unzipSync, strFromU8 } from 'fflate';
2
+ import { DOMParser } from '@xmldom/xmldom';
3
+ /* ------------------------------------------------------------------ XML helpers */
4
+ const W_NS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
5
+ const R_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
6
+ function parseXml(text) {
7
+ return new DOMParser({ onError: () => undefined }).parseFromString(text, 'text/xml');
8
+ }
9
+ function kids(el, name) {
10
+ if (!el)
11
+ return [];
12
+ const out = [];
13
+ for (let n = el.firstChild; n; n = n.nextSibling) {
14
+ if (n.nodeType === 1 && (!name || n.localName === name))
15
+ out.push(n);
16
+ }
17
+ return out;
18
+ }
19
+ const kid = (el, name) => kids(el, name)[0];
20
+ function attr(el, name) {
21
+ if (!el)
22
+ return undefined;
23
+ const v = el.getAttributeNS(W_NS, name) || el.getAttribute(`w:${name}`) || el.getAttribute(name);
24
+ return v === null || v === '' ? undefined : v;
25
+ }
26
+ function rAttr(el, name) {
27
+ if (!el)
28
+ return undefined;
29
+ return el.getAttributeNS(R_NS, name) || el.getAttribute(`r:${name}`) || undefined;
30
+ }
31
+ /** First descendant with this local name (depth-first). */
32
+ function find(el, name) {
33
+ if (!el)
34
+ return undefined;
35
+ for (const c of kids(el)) {
36
+ if (c.localName === name)
37
+ return c;
38
+ const deep = find(c, name);
39
+ if (deep)
40
+ return deep;
41
+ }
42
+ return undefined;
43
+ }
44
+ /** Toggle properties: <w:b/> is on; w:val="0"/"false"/"none" is off. */
45
+ function toggle(el) {
46
+ if (!el)
47
+ return undefined;
48
+ const v = attr(el, 'val');
49
+ return !(v === '0' || v === 'false' || v === 'off' || v === 'none');
50
+ }
51
+ const twip = (v) => (v === undefined ? undefined : Number(v) / 20);
52
+ const HIGHLIGHT = {
53
+ yellow: 'FFFF00', green: '00FF00', cyan: '00FFFF', magenta: 'FF00FF', blue: '0000FF', red: 'FF0000',
54
+ darkBlue: '000080', darkCyan: '008080', darkGreen: '008000', darkMagenta: '800080', darkRed: '800000',
55
+ darkYellow: '808000', darkGray: '808080', lightGray: 'C0C0C0', black: '000000', white: 'FFFFFF',
56
+ };
57
+ function readRPr(rPr) {
58
+ const p = {};
59
+ if (!rPr)
60
+ return p;
61
+ const fonts = kid(rPr, 'rFonts');
62
+ if (fonts) {
63
+ const name = attr(fonts, 'ascii') ?? attr(fonts, 'hAnsi');
64
+ const theme = attr(fonts, 'asciiTheme') ?? attr(fonts, 'hAnsiTheme');
65
+ if (name)
66
+ p.font = name;
67
+ else if (theme)
68
+ p.fontTheme = theme.startsWith('major') ? 'major' : 'minor';
69
+ }
70
+ const sz = attr(kid(rPr, 'sz'), 'val');
71
+ if (sz)
72
+ p.size = Number(sz) / 2;
73
+ const b = toggle(kid(rPr, 'b'));
74
+ if (b !== undefined)
75
+ p.bold = b;
76
+ const i = toggle(kid(rPr, 'i'));
77
+ if (i !== undefined)
78
+ p.italic = i;
79
+ const u = kid(rPr, 'u');
80
+ if (u)
81
+ p.underline = attr(u, 'val') !== 'none';
82
+ const s = toggle(kid(rPr, 'strike')) ?? toggle(kid(rPr, 'dstrike'));
83
+ if (s !== undefined)
84
+ p.strike = s;
85
+ const caps = toggle(kid(rPr, 'caps')) ?? toggle(kid(rPr, 'smallCaps'));
86
+ if (caps !== undefined)
87
+ p.caps = caps;
88
+ const color = attr(kid(rPr, 'color'), 'val');
89
+ if (color && /^[0-9a-f]{6}$/i.test(color))
90
+ p.color = color.toUpperCase();
91
+ else if (color === 'auto')
92
+ p.color = 'auto';
93
+ const hl = attr(kid(rPr, 'highlight'), 'val');
94
+ if (hl && HIGHLIGHT[hl])
95
+ p.highlight = HIGHLIGHT[hl];
96
+ const shd = attr(kid(rPr, 'shd'), 'fill');
97
+ if (shd && /^[0-9a-f]{6}$/i.test(shd) && !p.highlight)
98
+ p.highlight = shd.toUpperCase();
99
+ const va = attr(kid(rPr, 'vertAlign'), 'val');
100
+ if (va === 'superscript' || va === 'subscript')
101
+ p.vertAlign = va;
102
+ const rs = attr(kid(rPr, 'rStyle'), 'val');
103
+ if (rs)
104
+ p.charStyle = rs;
105
+ if (toggle(kid(rPr, 'vanish')))
106
+ p.size = 0; // hidden text
107
+ return p;
108
+ }
109
+ function readPPr(pPr) {
110
+ const p = {};
111
+ if (!pPr)
112
+ return p;
113
+ const jc = attr(kid(pPr, 'jc'), 'val');
114
+ if (jc)
115
+ p.align = jc === 'center' ? 'center' : jc === 'right' || jc === 'end' ? 'right' : jc === 'both' || jc === 'distribute' ? 'justify' : 'left';
116
+ const sp = kid(pPr, 'spacing');
117
+ if (sp) {
118
+ const before = twip(attr(sp, 'before'));
119
+ if (before !== undefined)
120
+ p.spaceBefore = before;
121
+ const after = twip(attr(sp, 'after'));
122
+ if (after !== undefined)
123
+ p.spaceAfter = after;
124
+ if (attr(sp, 'beforeAutospacing') === '1')
125
+ p.spaceBefore = 14;
126
+ if (attr(sp, 'afterAutospacing') === '1')
127
+ p.spaceAfter = 14;
128
+ const line = attr(sp, 'line');
129
+ if (line) {
130
+ const rule = attr(sp, 'lineRule') ?? 'auto';
131
+ p.line = rule === 'auto' ? { rule: 'auto', value: Number(line) / 240 } : { rule: rule === 'exact' ? 'exact' : 'atLeast', value: Number(line) / 20 };
132
+ }
133
+ }
134
+ const ind = kid(pPr, 'ind');
135
+ if (ind) {
136
+ const left = twip(attr(ind, 'left') ?? attr(ind, 'start'));
137
+ if (left !== undefined)
138
+ p.indentLeft = left;
139
+ const right = twip(attr(ind, 'right') ?? attr(ind, 'end'));
140
+ if (right !== undefined)
141
+ p.indentRight = right;
142
+ const first = twip(attr(ind, 'firstLine'));
143
+ if (first !== undefined)
144
+ p.firstLine = first;
145
+ const hanging = twip(attr(ind, 'hanging'));
146
+ if (hanging !== undefined)
147
+ p.firstLine = -hanging;
148
+ }
149
+ const pb = toggle(kid(pPr, 'pageBreakBefore'));
150
+ if (pb !== undefined)
151
+ p.pageBreakBefore = pb;
152
+ const kn = toggle(kid(pPr, 'keepNext'));
153
+ if (kn !== undefined)
154
+ p.keepNext = kn;
155
+ const cs = toggle(kid(pPr, 'contextualSpacing'));
156
+ if (cs !== undefined)
157
+ p.contextualSpacing = cs;
158
+ const numPr = kid(pPr, 'numPr');
159
+ if (numPr) {
160
+ const numId = attr(kid(numPr, 'numId'), 'val');
161
+ if (numId !== undefined)
162
+ p.numId = numId;
163
+ const ilvl = attr(kid(numPr, 'ilvl'), 'val');
164
+ if (ilvl !== undefined)
165
+ p.ilvl = Number(ilvl);
166
+ }
167
+ const shd = attr(kid(pPr, 'shd'), 'fill');
168
+ if (shd && /^[0-9a-f]{6}$/i.test(shd))
169
+ p.shading = shd.toUpperCase();
170
+ const bottom = kid(kid(pPr, 'pBdr'), 'bottom');
171
+ if (bottom && attr(bottom, 'val') !== 'none' && attr(bottom, 'val') !== 'nil') {
172
+ const c = attr(bottom, 'color');
173
+ p.borderBottom = { width: Number(attr(bottom, 'sz') ?? 4) / 8, color: c && c !== 'auto' ? c : '000000' };
174
+ }
175
+ const ps = attr(kid(pPr, 'pStyle'), 'val');
176
+ if (ps)
177
+ p.styleId = ps;
178
+ return p;
179
+ }
180
+ const clean = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
181
+ class Context {
182
+ files;
183
+ styles = new Map();
184
+ defaultParaStyle;
185
+ docRPr = {};
186
+ docPPr = {};
187
+ theme = { major: 'Calibri Light', minor: 'Calibri' };
188
+ abstract = new Map();
189
+ nums = new Map();
190
+ counters = new Map();
191
+ defaultTab = 36;
192
+ /** Word compatibility mode: 15 = Word 2013+. Older modes shift tables left by their cell padding. */
193
+ compatMode = 14;
194
+ /** Paragraph/run properties from the enclosing table's style, applied to cell paragraphs in the default style. */
195
+ cellStyle = null;
196
+ warnings = new Set();
197
+ /** Complex field state across runs: inside the instruction part, or showing a PAGE/NUMPAGES result. */
198
+ field = null;
199
+ constructor(files) {
200
+ this.files = files;
201
+ }
202
+ text(path) {
203
+ const f = this.files[path];
204
+ return f ? strFromU8(f) : undefined;
205
+ }
206
+ styleChain(id) {
207
+ const chain = [];
208
+ const seen = new Set();
209
+ while (id && !seen.has(id)) {
210
+ seen.add(id);
211
+ const s = this.styles.get(id);
212
+ if (!s)
213
+ break;
214
+ chain.unshift(s);
215
+ id = s.basedOn;
216
+ }
217
+ return chain;
218
+ }
219
+ resolveFont(p) {
220
+ if (p.font)
221
+ return p.font;
222
+ if (p.fontTheme)
223
+ return this.theme[p.fontTheme];
224
+ return undefined;
225
+ }
226
+ }
227
+ function loadStyles(ctx) {
228
+ const theme = ctx.text('word/theme/theme1.xml');
229
+ if (theme) {
230
+ const doc = parseXml(theme).documentElement;
231
+ const major = attr(kid(find(doc, 'majorFont'), 'latin'), 'typeface');
232
+ const minor = attr(kid(find(doc, 'minorFont'), 'latin'), 'typeface');
233
+ if (major)
234
+ ctx.theme.major = major;
235
+ if (minor)
236
+ ctx.theme.minor = minor;
237
+ }
238
+ const settings = ctx.text('word/settings.xml');
239
+ if (settings) {
240
+ const root = parseXml(settings).documentElement;
241
+ const tab = attr(find(root, 'defaultTabStop'), 'val');
242
+ if (tab)
243
+ ctx.defaultTab = Number(tab) / 20 || 36;
244
+ for (const cs of kids(find(root, 'compat'), 'compatSetting')) {
245
+ if (attr(cs, 'name') === 'compatibilityMode')
246
+ ctx.compatMode = Number(attr(cs, 'val') ?? 15);
247
+ }
248
+ }
249
+ const stylesXml = ctx.text('word/styles.xml');
250
+ if (stylesXml) {
251
+ const root = parseXml(stylesXml).documentElement;
252
+ const defaults = kid(root, 'docDefaults');
253
+ ctx.docRPr = readRPr(kid(kid(defaults, 'rPrDefault'), 'rPr'));
254
+ ctx.docPPr = readPPr(kid(kid(defaults, 'pPrDefault'), 'pPr'));
255
+ for (const s of kids(root, 'style')) {
256
+ const id = attr(s, 'styleId');
257
+ if (!id)
258
+ continue;
259
+ const type = attr(s, 'type') ?? 'paragraph';
260
+ const def = { type, basedOn: attr(kid(s, 'basedOn'), 'val'), ppr: readPPr(kid(s, 'pPr')), rpr: readRPr(kid(s, 'rPr')) };
261
+ const tblBorders = kid(kid(s, 'tblPr'), 'tblBorders');
262
+ if (tblBorders)
263
+ def.borders = readBorders(tblBorders);
264
+ ctx.styles.set(id, def);
265
+ if (type === 'paragraph' && attr(s, 'default') === '1')
266
+ ctx.defaultParaStyle = id;
267
+ }
268
+ }
269
+ const numbering = ctx.text('word/numbering.xml');
270
+ if (numbering) {
271
+ const root = parseXml(numbering).documentElement;
272
+ for (const a of kids(root, 'abstractNum')) {
273
+ const levels = new Map();
274
+ for (const l of kids(a, 'lvl')) {
275
+ levels.set(Number(attr(l, 'ilvl') ?? 0), {
276
+ start: Number(attr(kid(l, 'start'), 'val') ?? 1),
277
+ fmt: attr(kid(l, 'numFmt'), 'val') ?? 'decimal',
278
+ text: attr(kid(l, 'lvlText'), 'val') ?? '',
279
+ ppr: readPPr(kid(l, 'pPr')),
280
+ rpr: readRPr(kid(l, 'rPr')),
281
+ });
282
+ }
283
+ ctx.abstract.set(attr(a, 'abstractNumId') ?? '', levels);
284
+ }
285
+ for (const n of kids(root, 'num')) {
286
+ const overrides = new Map();
287
+ for (const o of kids(n, 'lvlOverride')) {
288
+ const start = attr(kid(o, 'startOverride'), 'val');
289
+ if (start !== undefined)
290
+ overrides.set(Number(attr(o, 'ilvl') ?? 0), Number(start));
291
+ }
292
+ ctx.nums.set(attr(n, 'numId') ?? '', { abstractId: attr(kid(n, 'abstractNumId'), 'val') ?? '', overrides });
293
+ }
294
+ }
295
+ }
296
+ function readBorders(el) {
297
+ let on = false;
298
+ let color = '000000';
299
+ for (const b of kids(el)) {
300
+ const v = attr(b, 'val');
301
+ if (v && v !== 'nil' && v !== 'none') {
302
+ on = true;
303
+ const c = attr(b, 'color');
304
+ if (c && c !== 'auto')
305
+ color = c;
306
+ }
307
+ }
308
+ return { on, color };
309
+ }
310
+ /* ------------------------------------------------------------------ List labels */
311
+ function roman(n) {
312
+ const map = [[1000, 'm'], [900, 'cm'], [500, 'd'], [400, 'cd'], [100, 'c'], [90, 'xc'], [50, 'l'], [40, 'xl'], [10, 'x'], [9, 'ix'], [5, 'v'], [4, 'iv'], [1, 'i']];
313
+ let out = '';
314
+ for (const [v, s] of map)
315
+ while (n >= v) {
316
+ out += s;
317
+ n -= v;
318
+ }
319
+ return out;
320
+ }
321
+ function letters(n) {
322
+ let s = '';
323
+ while (n > 0) {
324
+ n--;
325
+ s = String.fromCharCode(97 + (n % 26)) + s;
326
+ n = Math.floor(n / 26);
327
+ }
328
+ return s;
329
+ }
330
+ function formatNumber(n, fmt) {
331
+ switch (fmt) {
332
+ case 'lowerLetter': return letters(n);
333
+ case 'upperLetter': return letters(n).toUpperCase();
334
+ case 'lowerRoman': return roman(n);
335
+ case 'upperRoman': return roman(n).toUpperCase();
336
+ case 'decimalZero': return n < 10 ? `0${n}` : String(n);
337
+ case 'none': return '';
338
+ default: return String(n);
339
+ }
340
+ }
341
+ /** Word bullets often use private-use characters from the Symbol/Wingdings fonts. */
342
+ function bulletText(text) {
343
+ // Map Symbol/Wingdings private-use bullets to real Unicode shapes.
344
+ return [...text].map((c) => {
345
+ const cp = c.codePointAt(0);
346
+ // Symbol/Wingdings private-use characters have no Unicode meaning; geometric shapes (● ○ ■ ✓) are kept
347
+ // and drawn with the symbols fallback font.
348
+ if (cp >= 0xf000 && cp <= 0xf0ff)
349
+ return cp === 0xf06f ? '\u25CB' : cp === 0xf0a7 || cp === 0xf06e ? '\u25AA' : '\u2022';
350
+ // A black circle bullet looks like a text bullet in Word; the symbol font's ● is much larger.
351
+ if (cp === 0x25cf)
352
+ return '\u2022';
353
+ return c;
354
+ }).join('');
355
+ }
356
+ function listLabel(ctx, numId, ilvl) {
357
+ const num = ctx.nums.get(numId);
358
+ if (!num || numId === '0')
359
+ return undefined;
360
+ const levels = ctx.abstract.get(num.abstractId);
361
+ const level = levels?.get(ilvl);
362
+ if (!levels || !level)
363
+ return undefined;
364
+ const counters = ctx.counters.get(numId) ?? [];
365
+ const startOf = (l) => num.overrides.get(l) ?? levels.get(l)?.start ?? 1;
366
+ counters[ilvl] = counters[ilvl] === undefined ? startOf(ilvl) : counters[ilvl] + 1;
367
+ for (let l = ilvl + 1; l < 9; l++)
368
+ counters[l] = undefined;
369
+ ctx.counters.set(numId, counters);
370
+ if (level.fmt === 'bullet')
371
+ return { text: bulletText(level.text), level };
372
+ const text = level.text.replace(/%(\d)/g, (_, d) => {
373
+ const l = Number(d) - 1;
374
+ return formatNumber(counters[l] ?? startOf(l), levels.get(l)?.fmt ?? 'decimal');
375
+ });
376
+ return { text, level };
377
+ }
378
+ function loadRels(ctx, partPath) {
379
+ const dir = partPath.slice(0, partPath.lastIndexOf('/'));
380
+ const relsPath = `${dir}/_rels/${partPath.slice(dir.length + 1)}.rels`;
381
+ const map = new Map();
382
+ const xml = ctx.text(relsPath);
383
+ if (!xml)
384
+ return map;
385
+ for (const r of kids(parseXml(xml).documentElement, 'Relationship')) {
386
+ const id = r.getAttribute('Id');
387
+ const target = r.getAttribute('Target');
388
+ if (!id || !target || r.getAttribute('TargetMode') === 'External')
389
+ continue;
390
+ map.set(id, target.startsWith('/') ? target.slice(1) : normalize(`${dir}/${target}`));
391
+ }
392
+ return map;
393
+ }
394
+ function normalize(p) {
395
+ const out = [];
396
+ for (const seg of p.split('/')) {
397
+ if (seg === '..')
398
+ out.pop();
399
+ else if (seg !== '.' && seg !== '')
400
+ out.push(seg);
401
+ }
402
+ return out.join('/');
403
+ }
404
+ function paragraphStyle(ctx, pp, styleId) {
405
+ const chain = ctx.styleChain(styleId ?? ctx.defaultParaStyle);
406
+ const merged = { ...clean(ctx.docPPr) };
407
+ let runBase = { ...clean(ctx.docRPr) };
408
+ for (const s of chain) {
409
+ Object.assign(merged, clean(s.ppr));
410
+ runBase = { ...runBase, ...clean(s.rpr) };
411
+ if (s.rpr.font)
412
+ delete runBase.fontTheme;
413
+ }
414
+ const effectiveStyle = styleId ?? ctx.defaultParaStyle;
415
+ if (ctx.cellStyle && (effectiveStyle === ctx.defaultParaStyle || effectiveStyle === undefined)) {
416
+ // Word lets the table style override Normal inside cells (e.g. Table Grid removes spacing after).
417
+ Object.assign(merged, clean(ctx.cellStyle.ppr));
418
+ runBase = { ...runBase, ...clean(ctx.cellStyle.rpr) };
419
+ }
420
+ Object.assign(merged, clean(pp));
421
+ const style = {
422
+ align: merged.align ?? 'left',
423
+ spaceBefore: merged.spaceBefore ?? 0,
424
+ spaceAfter: merged.spaceAfter ?? 0,
425
+ line: merged.line ?? { rule: 'auto', value: 1 },
426
+ indentLeft: merged.indentLeft ?? 0,
427
+ indentRight: merged.indentRight ?? 0,
428
+ firstLine: merged.firstLine ?? 0,
429
+ pageBreakBefore: merged.pageBreakBefore ?? false,
430
+ keepNext: merged.keepNext ?? false,
431
+ contextualSpacing: merged.contextualSpacing ?? false,
432
+ styleId: styleId ?? ctx.defaultParaStyle,
433
+ shading: merged.shading,
434
+ borderBottom: merged.borderBottom,
435
+ };
436
+ return { style, runBase };
437
+ }
438
+ function finalizeRun(ctx, base, direct) {
439
+ let props = { ...base };
440
+ const charStyle = direct.charStyle;
441
+ for (const s of ctx.styleChain(charStyle)) {
442
+ props = { ...props, ...clean(s.rpr) };
443
+ if (s.rpr.font)
444
+ delete props.fontTheme;
445
+ }
446
+ props = { ...props, ...clean(direct) };
447
+ if (direct.font)
448
+ delete props.fontTheme;
449
+ // Word's built-in fallback when nothing sets a font or size: Times New Roman, 10 pt.
450
+ const font = ctx.resolveFont(props) ?? 'Times New Roman';
451
+ const autoColor = !props.color || props.color === 'auto';
452
+ return {
453
+ font,
454
+ size: props.size ?? 10,
455
+ bold: props.bold ?? false,
456
+ italic: props.italic ?? false,
457
+ underline: props.underline ?? false,
458
+ strike: props.strike ?? false,
459
+ color: autoColor ? '000000' : props.color,
460
+ autoColor,
461
+ highlight: props.highlight,
462
+ vertAlign: props.vertAlign,
463
+ caps: props.caps ?? false,
464
+ };
465
+ }
466
+ function readImage(ctx, part, drawing) {
467
+ const extent = find(drawing, 'extent');
468
+ const blip = find(drawing, 'blip');
469
+ if (find(drawing, 'txbx') || find(drawing, 'txbxContent'))
470
+ ctx.warnings.add('TEXTBOX_SKIPPED');
471
+ if (!blip)
472
+ return undefined;
473
+ if (kid(drawing, 'anchor'))
474
+ ctx.warnings.add('FLOATING_IMAGE_INLINED');
475
+ const target = part.rels.get(rAttr(blip, 'embed') ?? '');
476
+ const bytes = target ? ctx.files[target] : undefined;
477
+ if (!bytes)
478
+ return undefined;
479
+ const format = bytes[0] === 0x89 && bytes[1] === 0x50 ? 'png' : bytes[0] === 0xff && bytes[1] === 0xd8 ? 'jpg' : undefined;
480
+ if (!format) {
481
+ ctx.warnings.add('UNSUPPORTED_IMAGE_FORMAT');
482
+ return undefined;
483
+ }
484
+ const cx = Number(extent?.getAttribute('cx') ?? 0) / 12700;
485
+ const cy = Number(extent?.getAttribute('cy') ?? 0) / 12700;
486
+ if (!cx || !cy)
487
+ return undefined;
488
+ return { kind: 'image', bytes, format, width: cx, height: cy };
489
+ }
490
+ function readRunContent(ctx, part, r, base, out) {
491
+ const style = finalizeRun(ctx, base, readRPr(kid(r, 'rPr')));
492
+ if (style.size === 0)
493
+ return; // hidden text
494
+ const push = (text) => {
495
+ if (ctx.field?.phase === 'instr')
496
+ return;
497
+ if (ctx.field?.phase === 'result' && ctx.field.dynamic)
498
+ return; // replaced by the live value
499
+ if (!text)
500
+ return;
501
+ if (style.caps)
502
+ text = text.toUpperCase();
503
+ const last = out[out.length - 1];
504
+ if (last?.kind === 'text' && last.style === style)
505
+ last.text += text;
506
+ else
507
+ out.push({ kind: 'text', text, style });
508
+ };
509
+ for (const c of kids(r)) {
510
+ switch (c.localName) {
511
+ case 't':
512
+ push(c.textContent ?? '');
513
+ break;
514
+ case 'tab':
515
+ if (!ctx.field || ctx.field.phase === 'result')
516
+ out.push({ kind: 'tab', style });
517
+ break;
518
+ case 'br': {
519
+ const type = attr(c, 'type');
520
+ if (type === 'page')
521
+ out.push({ kind: 'break', style: { ...style, size: -1 } });
522
+ else
523
+ out.push({ kind: 'break', style });
524
+ break;
525
+ }
526
+ case 'cr':
527
+ out.push({ kind: 'break', style });
528
+ break;
529
+ case 'noBreakHyphen':
530
+ push('-');
531
+ break;
532
+ case 'softHyphen': break;
533
+ case 'sym':
534
+ push('•');
535
+ break;
536
+ case 'fldChar': {
537
+ const t = attr(c, 'fldCharType');
538
+ if (t === 'begin')
539
+ ctx.field = { phase: 'instr', instr: '' };
540
+ else if (t === 'separate' && ctx.field) {
541
+ ctx.field.phase = 'result';
542
+ const instr = ctx.field.instr.trim().split(/\s+/)[0]?.toUpperCase();
543
+ if (instr === 'PAGE' || instr === 'NUMPAGES') {
544
+ ctx.field.dynamic = instr;
545
+ out.push({ kind: 'text', text: `\u0001${instr}\u0001`, style });
546
+ }
547
+ }
548
+ else if (t === 'end')
549
+ ctx.field = null;
550
+ break;
551
+ }
552
+ case 'instrText':
553
+ if (ctx.field)
554
+ ctx.field.instr += c.textContent ?? '';
555
+ break;
556
+ case 'drawing': {
557
+ const img = readImage(ctx, part, c);
558
+ if (img)
559
+ out.push(img);
560
+ break;
561
+ }
562
+ case 'pict':
563
+ ctx.warnings.add('LEGACY_SHAPE_SKIPPED');
564
+ break;
565
+ case 'footnoteReference':
566
+ case 'endnoteReference':
567
+ ctx.warnings.add('NOTES_SKIPPED');
568
+ break;
569
+ case 'AlternateContent': {
570
+ const choice = kid(c, 'Choice') ?? kid(c, 'Fallback');
571
+ const drawing = choice && find(choice, 'drawing');
572
+ if (drawing) {
573
+ const img = readImage(ctx, part, drawing);
574
+ if (img)
575
+ out.push(img);
576
+ }
577
+ break;
578
+ }
579
+ default: break;
580
+ }
581
+ }
582
+ }
583
+ function readInlines(ctx, part, container, base, out) {
584
+ for (const c of kids(container)) {
585
+ switch (c.localName) {
586
+ case 'r':
587
+ readRunContent(ctx, part, c, base, out);
588
+ break;
589
+ case 'hyperlink':
590
+ case 'ins':
591
+ case 'smartTag':
592
+ case 'customXml':
593
+ case 'dir':
594
+ case 'bdo':
595
+ readInlines(ctx, part, c, base, out);
596
+ break;
597
+ case 'sdt':
598
+ readInlines(ctx, part, kid(c, 'sdtContent') ?? c, base, out);
599
+ break;
600
+ case 'fldSimple': {
601
+ const instr = (attr(c, 'instr') ?? '').trim().split(/\s+/)[0]?.toUpperCase();
602
+ if (instr === 'PAGE' || instr === 'NUMPAGES') {
603
+ const r = find(c, 'r');
604
+ out.push({ kind: 'text', text: `\u0001${instr}\u0001`, style: finalizeRun(ctx, base, readRPr(kid(r, 'rPr'))) });
605
+ }
606
+ else
607
+ readInlines(ctx, part, c, base, out);
608
+ break;
609
+ }
610
+ case 'del':
611
+ case 'moveFrom': break;
612
+ default: break;
613
+ }
614
+ }
615
+ }
616
+ function readParagraph(ctx, part, p) {
617
+ const pPr = kid(p, 'pPr');
618
+ const direct = readPPr(pPr);
619
+ const styleId = direct.styleId;
620
+ // Numbering may come from the paragraph or from its style.
621
+ let numId = direct.numId;
622
+ let ilvl = direct.ilvl;
623
+ if (numId === undefined) {
624
+ for (const s of ctx.styleChain(styleId ?? ctx.defaultParaStyle)) {
625
+ if (s.ppr.numId !== undefined) {
626
+ numId = s.ppr.numId;
627
+ ilvl = s.ppr.ilvl ?? ilvl;
628
+ }
629
+ }
630
+ }
631
+ const label = numId !== undefined ? listLabel(ctx, numId, ilvl ?? 0) : undefined;
632
+ // Indents: style < numbering level < direct formatting.
633
+ const withNumbering = { ...clean(label?.level.ppr ?? {}), ...clean(direct) };
634
+ const { style, runBase } = paragraphStyle(ctx, withNumbering, styleId);
635
+ if (label && direct.indentLeft === undefined && label.level.ppr.indentLeft !== undefined) {
636
+ style.indentLeft = label.level.ppr.indentLeft;
637
+ style.firstLine = label.level.ppr.firstLine ?? style.firstLine;
638
+ }
639
+ const paraMark = readRPr(kid(pPr, 'rPr'));
640
+ const inlines = [];
641
+ readInlines(ctx, part, p, runBase, inlines);
642
+ const para = { type: 'paragraph', style, inlines };
643
+ if (label?.text) {
644
+ const labelProps = { ...runBase, ...clean(paraMark), ...clean(label.level.rpr) };
645
+ const st = finalizeRun(ctx, labelProps, {});
646
+ if (label.level.fmt === 'bullet') {
647
+ // Symbol/Wingdings bullets render larger than a text bullet; compensate a little.
648
+ const fromSymbolFont = /symbol|wingdings/i.test(label.level.rpr.font ?? '');
649
+ st.font = ctx.resolveFont(runBase) ?? ctx.theme.minor;
650
+ if (fromSymbolFont && label.text === '\u2022')
651
+ st.size *= 1.3;
652
+ }
653
+ para.label = { text: label.text, style: st };
654
+ }
655
+ // An empty paragraph still takes one line in the font of its paragraph mark.
656
+ if (inlines.length === 0)
657
+ para.inlines.push({ kind: 'text', text: '', style: finalizeRun(ctx, runBase, paraMark) });
658
+ return para;
659
+ }
660
+ function isDark(hex) {
661
+ const n = parseInt(hex, 16);
662
+ const [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255];
663
+ return 0.299 * r + 0.587 * g + 0.114 * b < 128;
664
+ }
665
+ /** Word draws "automatic" text color as white on dark shading. */
666
+ function whitenAuto(blocks) {
667
+ for (const b of blocks) {
668
+ if (b.type !== 'paragraph')
669
+ continue;
670
+ for (const i of b.inlines)
671
+ if (i.kind !== 'image' && i.style.autoColor)
672
+ i.style = { ...i.style, color: 'FFFFFF' };
673
+ if (b.label?.style.autoColor)
674
+ b.label.style = { ...b.label.style, color: 'FFFFFF' };
675
+ }
676
+ }
677
+ function readTable(ctx, part, tbl) {
678
+ const tblPr = kid(tbl, 'tblPr');
679
+ const styleId = attr(kid(tblPr, 'tblStyle'), 'val');
680
+ let borders = { on: false, color: '000000' };
681
+ const tableStyle = { ppr: {}, rpr: {} };
682
+ for (const s of ctx.styleChain(styleId)) {
683
+ if (s.borders)
684
+ borders = s.borders;
685
+ Object.assign(tableStyle.ppr, clean(s.ppr));
686
+ Object.assign(tableStyle.rpr, clean(s.rpr));
687
+ }
688
+ const outerCellStyle = ctx.cellStyle;
689
+ ctx.cellStyle = tableStyle;
690
+ const direct = kid(tblPr, 'tblBorders');
691
+ if (direct)
692
+ borders = readBorders(direct);
693
+ const columns = kids(kid(tbl, 'tblGrid'), 'gridCol').map((g) => twip(attr(g, 'w')) ?? 0);
694
+ const mar = kid(tblPr, 'tblCellMar');
695
+ const pad = (side, alt, d) => twip(attr(kid(mar, side) ?? kid(mar, alt), 'w')) ?? d;
696
+ const rows = [];
697
+ for (const tr of kids(tbl, 'tr')) {
698
+ const trPr = kid(tr, 'trPr');
699
+ const cells = [];
700
+ for (const tc of kids(tr).filter((c) => c.localName === 'tc' || c.localName === 'sdt')) {
701
+ const cell = tc.localName === 'sdt' ? find(tc, 'tc') : tc;
702
+ if (!cell)
703
+ continue;
704
+ const tcPr = kid(cell, 'tcPr');
705
+ const vm = kid(tcPr, 'vMerge');
706
+ const shading = attr(kid(tcPr, 'shd'), 'fill');
707
+ const cellBlocks = readBlocks(ctx, part, cell);
708
+ const tcBorders = kid(tcPr, 'tcBorders');
709
+ let cellBorders;
710
+ if (tcBorders) {
711
+ cellBorders = {};
712
+ for (const side of ['top', 'right', 'bottom', 'left']) {
713
+ const el = kid(tcBorders, side) ?? kid(tcBorders, side === 'left' ? 'start' : side === 'right' ? 'end' : side);
714
+ if (!el)
715
+ continue;
716
+ const v = attr(el, 'val');
717
+ const c = attr(el, 'color');
718
+ cellBorders[side] = !v || v === 'nil' || v === 'none' ? null : { width: Math.max(0.25, Number(attr(el, 'sz') ?? 4) / 8), color: c && c !== 'auto' ? c : '000000' };
719
+ }
720
+ }
721
+ if (shading && /^[0-9a-f]{6}$/i.test(shading) && isDark(shading))
722
+ whitenAuto(cellBlocks);
723
+ cells.push({
724
+ blocks: cellBlocks,
725
+ span: Number(attr(kid(tcPr, 'gridSpan'), 'val') ?? 1),
726
+ vMerge: vm ? (attr(vm, 'val') === 'restart' ? 'restart' : 'continue') : undefined,
727
+ shading: shading && /^[0-9a-f]{6}$/i.test(shading) ? shading.toUpperCase() : undefined,
728
+ vAlign: attr(kid(tcPr, 'vAlign'), 'val') ?? 'top',
729
+ borders: cellBorders,
730
+ });
731
+ }
732
+ rows.push({ cells, minHeight: twip(attr(kid(trPr, 'trHeight'), 'val')) ?? 0, header: !!toggle(kid(trPr, 'tblHeader')) });
733
+ }
734
+ ctx.cellStyle = outerCellStyle;
735
+ return {
736
+ type: 'table',
737
+ columns,
738
+ rows,
739
+ borders: borders.on,
740
+ borderColor: borders.color,
741
+ indent: (twip(attr(kid(tblPr, 'tblInd'), 'w')) ?? 0) - (ctx.compatMode < 15 ? pad('left', 'start', 5.4) : 0),
742
+ cellPadding: { top: pad('top', 'top', 0), bottom: pad('bottom', 'bottom', 0), left: pad('left', 'start', 5.4), right: pad('right', 'end', 5.4) },
743
+ };
744
+ }
745
+ function readBlocks(ctx, part, container) {
746
+ const blocks = [];
747
+ for (const c of kids(container)) {
748
+ if (c.localName === 'p') {
749
+ blocks.push(readParagraph(ctx, part, c));
750
+ // A section break inside a paragraph starts a new page (next-page sections).
751
+ const sect = kid(kid(c, 'pPr'), 'sectPr');
752
+ if (sect) {
753
+ if (Number(attr(kid(sect, 'cols'), 'num') ?? 1) > 1)
754
+ ctx.warnings.add('COLUMNS_IGNORED');
755
+ if (attr(kid(sect, 'type'), 'val') !== 'continuous') {
756
+ const { width, height, margin } = readPage(sect);
757
+ blocks.push({ type: 'pageBreak', section: { width, height, margin } });
758
+ }
759
+ }
760
+ }
761
+ else if (c.localName === 'tbl')
762
+ blocks.push(readTable(ctx, part, c));
763
+ else if (c.localName === 'sdt')
764
+ blocks.push(...readBlocks(ctx, part, kid(c, 'sdtContent') ?? c));
765
+ else if (c.localName === 'customXml')
766
+ blocks.push(...readBlocks(ctx, part, c));
767
+ }
768
+ return blocks;
769
+ }
770
+ function readPage(sect) {
771
+ const pgSz = kid(sect, 'pgSz');
772
+ const pgMar = kid(sect, 'pgMar');
773
+ const w = twip(attr(pgSz, 'w')) ?? 612;
774
+ const h = twip(attr(pgSz, 'h')) ?? 792;
775
+ const landscape = attr(pgSz, 'orient') === 'landscape';
776
+ return {
777
+ width: landscape ? Math.max(w, h) : w,
778
+ height: landscape ? Math.min(w, h) : h,
779
+ margin: {
780
+ top: Math.abs(twip(attr(pgMar, 'top')) ?? 72),
781
+ right: twip(attr(pgMar, 'right')) ?? 72,
782
+ bottom: Math.abs(twip(attr(pgMar, 'bottom')) ?? 72),
783
+ left: (twip(attr(pgMar, 'left')) ?? 72) + (twip(attr(pgMar, 'gutter')) ?? 0),
784
+ },
785
+ header: twip(attr(pgMar, 'header')) ?? 36,
786
+ footer: twip(attr(pgMar, 'footer')) ?? 36,
787
+ };
788
+ }
789
+ export class DocxError extends Error {
790
+ code;
791
+ constructor(code, message) {
792
+ super(message ?? code);
793
+ this.code = code;
794
+ this.name = 'DocxError';
795
+ }
796
+ }
797
+ /** True when the bytes look like a Word .docx package. */
798
+ export function isDocx(bytes) {
799
+ if (!(bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04))
800
+ return false;
801
+ try {
802
+ let found = false;
803
+ unzipSync(bytes, { filter: (f) => { if (f.name === 'word/document.xml')
804
+ found = true; return false; } });
805
+ return found;
806
+ }
807
+ catch {
808
+ return false;
809
+ }
810
+ }
811
+ export function parseDocx(bytes) {
812
+ // Encrypted Office files are OLE containers, not zips.
813
+ if (bytes[0] === 0xd0 && bytes[1] === 0xcf && bytes[2] === 0x11 && bytes[3] === 0xe0)
814
+ throw new DocxError('ENCRYPTED_DOCX');
815
+ let files;
816
+ try {
817
+ files = unzipSync(bytes);
818
+ }
819
+ catch (err) {
820
+ throw new DocxError('CORRUPT_DOCX', String(err.message));
821
+ }
822
+ if (!files['word/document.xml'])
823
+ throw new DocxError('NOT_DOCX');
824
+ const ctx = new Context(files);
825
+ loadStyles(ctx);
826
+ const docPart = { path: 'word/document.xml', rels: loadRels(ctx, 'word/document.xml') };
827
+ const body = kid(parseXml(ctx.text(docPart.path)).documentElement, 'body');
828
+ if (!body)
829
+ throw new DocxError('CORRUPT_DOCX', 'missing body');
830
+ const blocks = readBlocks(ctx, docPart, body);
831
+ const sect = kid(body, 'sectPr');
832
+ const page = readPage(sect);
833
+ if (Number(attr(kid(sect, 'cols'), 'num') ?? 1) > 1)
834
+ ctx.warnings.add('COLUMNS_IGNORED');
835
+ // Each section break carries the setup of the section it closes; the body's sectPr is the last one's.
836
+ const sections = [];
837
+ let current = [];
838
+ for (const b of blocks) {
839
+ if (b.type === 'pageBreak' && b.section) {
840
+ sections.push({ page: b.section, blocks: current });
841
+ current = [];
842
+ }
843
+ else
844
+ current.push(b);
845
+ }
846
+ sections.push({ page: { width: page.width, height: page.height, margin: page.margin }, blocks: current });
847
+ const readHf = (kind) => {
848
+ const ref = kids(sect, `${kind}Reference`).find((r) => (attr(r, 'type') ?? 'default') === 'default');
849
+ const target = ref ? docPart.rels.get(rAttr(ref, 'id') ?? '') : undefined;
850
+ const xml = target ? ctx.text(target) : undefined;
851
+ if (!target || !xml)
852
+ return undefined;
853
+ ctx.field = null;
854
+ const part = { path: target, rels: loadRels(ctx, target) };
855
+ const content = readBlocks(ctx, part, parseXml(xml).documentElement);
856
+ const hasText = content.some((b) => b.type !== 'paragraph' || b.inlines.some((i) => i.kind !== 'text' || i.text.trim()));
857
+ return hasText ? content : undefined;
858
+ };
859
+ if (kid(sect, 'titlePg'))
860
+ ctx.warnings.add('FIRST_PAGE_HEADER_IGNORED');
861
+ return {
862
+ page: { width: page.width, height: page.height, margin: page.margin },
863
+ blocks,
864
+ sections,
865
+ defaultTab: ctx.defaultTab,
866
+ warnings: [...ctx.warnings],
867
+ header: readHf('header'),
868
+ footer: readHf('footer'),
869
+ headerDistance: page.header,
870
+ footerDistance: page.footer,
871
+ };
872
+ }
873
+ //# sourceMappingURL=parse.js.map