Sync snapshot (2026-08-19) (#110)
- Improve Docs pagination, anchored-object fidelity, password protection, recovery safety, and multilingual font fallback - Scale Sheets editing and saves for large workbooks with safer AI bulk operations, aggregation, undo, recovery, and richer visual fidelity - Expand Slides fidelity with 3D rendering, SmartArt and WordArt improvements, pattern and texture fills, and resource cleanup - Add AI PDF creation, text insertion, reading-position restore, safer atomic saves, and improved comments and page workflows - Add Markdown math rendering and protect linked assets across save, conversion, and document lifecycle operations - Read legacy DOC and PPT attachments locally and strengthen document package resource cleanup - Document default-on usage analytics with a persistent Settings opt-out and a dedicated, tested privacy page Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
04a994b9e9
commit
fe2e17403c
@@ -983,10 +983,12 @@ function formatPPrChildren(format: ParaFormat | undefined): PPrChild[] {
|
||||
out.push({ name: 'w:spacing', xml: `<w:spacing ${spacingAttrs.join(' ')}/>` })
|
||||
}
|
||||
const indAttrs: string[] = []
|
||||
if (format.indentLeft && format.indentLeft > 0)
|
||||
indAttrs.push(`w:left="${Math.round(format.indentLeft)}"`)
|
||||
if (format.indentRight && format.indentRight > 0)
|
||||
indAttrs.push(`w:right="${Math.round(format.indentRight)}"`)
|
||||
// w:left/w:right are signed in OOXML — negative indents (text extending
|
||||
// into the margin) are valid and must survive a paragraph rebuild; the
|
||||
// old > 0 guard silently dropped them, shifting rebuilt paragraphs
|
||||
// rightward on save (alpha ledger r116).
|
||||
if (format.indentLeft) indAttrs.push(`w:left="${Math.round(format.indentLeft)}"`)
|
||||
if (format.indentRight) indAttrs.push(`w:right="${Math.round(format.indentRight)}"`)
|
||||
if (format.indentFirstLine) {
|
||||
if (format.indentFirstLine > 0)
|
||||
indAttrs.push(`w:firstLine="${Math.round(format.indentFirstLine)}"`)
|
||||
@@ -2576,6 +2578,9 @@ function generateRunXml(run: Run, insideLink: boolean): string {
|
||||
} else if (ch === '\f') {
|
||||
flush()
|
||||
segments.push('<w:br w:type="page"/>')
|
||||
} else if (ch === '\v') {
|
||||
flush()
|
||||
segments.push('<w:br w:type="column"/>')
|
||||
} else {
|
||||
buffer += ch
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import type {
|
||||
DiagramShape,
|
||||
DocDefaults,
|
||||
DocProtection,
|
||||
WriteProtection,
|
||||
FieldDisplay,
|
||||
InkInfo,
|
||||
NoteInfo,
|
||||
@@ -103,6 +104,9 @@ export function assertZipWithinLimits(zip: JSZip): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** w:br w:type → run-text control char (\f page, \v column; else soft \n) */
|
||||
const BREAK_CHAR: Record<string, string> = { page: '\f', column: '\v' }
|
||||
|
||||
const IMAGE_MIME: Record<string, string> = {
|
||||
png: 'image/png',
|
||||
jpg: 'image/jpeg',
|
||||
@@ -180,9 +184,14 @@ export interface ParseExtras {
|
||||
export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras: ParseExtras }> {
|
||||
const zip = await loadDocxZip(bytes)
|
||||
assertZipWithinLimits(zip)
|
||||
const docFile = zip.file('word/document.xml')
|
||||
if (!docFile) throw new Error('not a docx: missing word/document.xml')
|
||||
const documentXml = await docFile.async('string')
|
||||
const docPath = await resolveMainDocumentPath(zip)
|
||||
if (!docPath) {
|
||||
const mime = (await zip.file('mimetype')?.async('string'))?.trim()
|
||||
if (mime?.startsWith('application/vnd.oasis.opendocument'))
|
||||
throw new Error(`OpenDocument file (${mime}), not OOXML — save as .docx to open`)
|
||||
throw new Error('not a docx: missing word/document.xml')
|
||||
}
|
||||
const documentXml = await zip.file(docPath)!.async('string')
|
||||
|
||||
const theme = await parseTheme(zip)
|
||||
const { styles, docDefaults } = await parseStyles(zip, theme.colors, theme.fonts)
|
||||
@@ -197,10 +206,12 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
}
|
||||
}
|
||||
|
||||
const rels = await parseRels(zip, 'word/_rels/document.xml.rels')
|
||||
const rels = await parseRels(zip, docPath.replace(/([^/]+)$/, '_rels/$1.rels'))
|
||||
const { formats: numFormats, defs: numbering } = await parseNumbering(zip)
|
||||
const comments = await parseComments(zip)
|
||||
const protection = await parseProtection(zip)
|
||||
const writeProtection = await parseWriteProtection(zip)
|
||||
const removePersonalInfo = await parseRemovePersonalInfo(zip)
|
||||
const footnotes = await parseNotesPart(zip, 'footnote')
|
||||
const endnotes = await parseNotesPart(zip, 'endnote')
|
||||
const sources = await parseSources(zip)
|
||||
@@ -343,6 +354,7 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
const titlePg = xmlFlagOn(documentXml, 'w:titlePg')
|
||||
const evenAndOddHeaders = await parseEvenAndOddHeaders(zip)
|
||||
const compatibilityMode = await parseCompatibilityMode(zip)
|
||||
const layoutSettings = await parseLayoutSettings(zip)
|
||||
const hfParts = await parseAllHfParts(zip, rels, styles, theme.colors)
|
||||
|
||||
// ink annotations (freehand strokes): our own anchored floating pictures, restored
|
||||
@@ -367,6 +379,8 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
blocks,
|
||||
comments,
|
||||
protection,
|
||||
writeProtection,
|
||||
removePersonalInfo,
|
||||
footnotes,
|
||||
endnotes,
|
||||
sources,
|
||||
@@ -385,6 +399,7 @@ export async function parseDocx(bytes: Uint8Array): Promise<ParsedDoc & { extras
|
||||
titlePg,
|
||||
evenAndOddHeaders,
|
||||
compatibilityMode,
|
||||
...layoutSettings,
|
||||
headerFirst: hfPartInfo(headerFirst),
|
||||
footerFirst: hfPartInfo(footerFirst),
|
||||
headerEven: hfPartInfo(headerEven),
|
||||
@@ -455,6 +470,11 @@ function listKindOf(ctx: BuildContext, numId: string, ilvl: number): 'bullet' |
|
||||
return ctx.numFormats.get(numId) ?? 'bullet'
|
||||
}
|
||||
|
||||
/** hex color value tolerance: Word/LO accept a leading '#' (tdf#57589) */
|
||||
function stripHash(v: string): string {
|
||||
return v.startsWith('#') ? v.slice(1) : v
|
||||
}
|
||||
|
||||
/** w:color -> display hex; w:themeColor resolves against the live palette (beats stale w:val) */
|
||||
function colorFrom(container: XNode | undefined, theme?: ThemeColors | null): string | undefined {
|
||||
if (!container) return undefined
|
||||
@@ -469,7 +489,7 @@ function colorFrom(container: XNode | undefined, theme?: ThemeColors | null): st
|
||||
if (resolved) return resolved
|
||||
}
|
||||
const val = a['w:val']
|
||||
return val && val !== 'auto' ? val : undefined
|
||||
return val && val !== 'auto' ? stripHash(val) : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -725,7 +745,7 @@ async function buildBlock(
|
||||
// A content-less sdt (w:sdtPr only, or empty sdtContent) renders as nothing
|
||||
// in Word, so it must not produce a visible placeholder chip.
|
||||
const sdtPreview = plainText(xml)
|
||||
if (!sdtPreview.trim() && !xml.includes('<w:drawing') && !xml.includes('<w:pict')) {
|
||||
if (!sdtPreview.trim() && !xml.includes('<w:drawing') && !/<w:pict[\s>]/.test(xml)) {
|
||||
return { ...base, type: 'passthrough', label: 'Content control', invisibleMarker: true }
|
||||
}
|
||||
return { ...base, type: 'passthrough', label: 'Content control', previewText: sdtPreview }
|
||||
@@ -765,12 +785,16 @@ async function buildBlock(
|
||||
// Regenerating them would silently drop structure (section breaks, fields,
|
||||
// footnote anchors...), which is exactly the kind of damage patch-save exists
|
||||
// to prevent.
|
||||
if (detect.includes('<w:sectPr')) {
|
||||
// Only a content-less section-break paragraph is protected: one with visible
|
||||
// text renders as a normal paragraph (Word shows its content on the section's
|
||||
// last page); its w:sectPr rides along in rawPPr, which mergePPrFormat keeps
|
||||
// verbatim on edits, so the section survives regeneration.
|
||||
if (detect.includes('<w:sectPr') && !plainText(detect).trim()) {
|
||||
return {
|
||||
...base,
|
||||
type: 'passthrough',
|
||||
label: 'Section break paragraph',
|
||||
previewText: plainText(detect),
|
||||
previewText: '',
|
||||
}
|
||||
}
|
||||
// Field chars inside textbox content don't make the paragraph itself a field
|
||||
@@ -885,7 +909,7 @@ async function buildBlock(
|
||||
},
|
||||
}
|
||||
}
|
||||
if (detect.includes('<w:object') || detect.includes('<w:pict')) {
|
||||
if (detect.includes('<w:object') || /<w:pict[\s>]/.test(detect)) {
|
||||
// Legacy VML textboxes (v:shape/v:textbox) and WordArt (v:textpath) in
|
||||
// w:pict: extract the structured display model instead of flattening every
|
||||
// nested paragraph and table into one unreadable run — or degrading the
|
||||
@@ -1254,6 +1278,34 @@ function buildTextParagraph(
|
||||
const emptySz = emptyParaSizeHalfPoints(pNode, pPr)
|
||||
if (emptySz) format = { ...(format ?? {}), emptyRunSizeHalfPoints: emptySz }
|
||||
}
|
||||
|
||||
// allowOverlap="0" colliding with a sibling anchor (tdf#134114): Word displaces
|
||||
// the object out of the other's box instead of stacking the wrapped floats
|
||||
// vertically; approximate with a front overlay at the collider's bottom (it may
|
||||
// hang into the margin, like Word). Horizontal overlap is presumed — the align
|
||||
// gallery drops the X, so only the declared vertical ranges are compared.
|
||||
{
|
||||
const wrapped = runs.filter(
|
||||
(r) => r.image?.wrap && r.image.wrap !== 'front' && r.image.wrap !== 'behind',
|
||||
)
|
||||
if (wrapped.length > 1) {
|
||||
for (const r of wrapped) {
|
||||
const img = r.image!
|
||||
if (!img.noOverlap) continue
|
||||
const top = (img.offsetYEmu ?? 0) / EMU_PER_PX
|
||||
const hit = wrapped.find((o) => {
|
||||
if (o === r || o.image!.noOverlap) return false
|
||||
const oTop = (o.image!.offsetYEmu ?? 0) / EMU_PER_PX
|
||||
return top < oTop + (o.image!.heightPx ?? 0) && oTop < top + (img.heightPx ?? 0)
|
||||
})
|
||||
if (!hit) continue
|
||||
img.wrap = 'front'
|
||||
img.offsetXEmu = 0
|
||||
// the collider float renders at its line top (run floats ignore posOffset)
|
||||
img.offsetYEmu = ((hit.image!.heightPx ?? 0) + 2) * EMU_PER_PX
|
||||
}
|
||||
}
|
||||
}
|
||||
const { bookmarks, hiddenBookmarks } = bookmarkNamesOf(stripTextboxes(xml))
|
||||
const { commentStarts, commentEnds } = crossParaCommentMarkers(stripTextboxes(xml))
|
||||
|
||||
@@ -1306,12 +1358,26 @@ function buildTextParagraph(
|
||||
}
|
||||
}
|
||||
|
||||
// --- deleted paragraph mark (w:pPr/w:rPr/w:del) ---
|
||||
let paraMarkDel: Block['paraMarkDel']
|
||||
{
|
||||
const pRPr = pPr ? findChild(pPr, 'w:rPr') : undefined
|
||||
const delEl = pRPr ? findChild(pRPr, 'w:del') : undefined
|
||||
if (delEl) {
|
||||
const a = attrsOf(delEl)
|
||||
paraMarkDel = { author: a['w:author'] ?? '' }
|
||||
if (a['w:date']) paraMarkDel.date = a['w:date']
|
||||
if (a['w:id']) paraMarkDel.id = a['w:id']
|
||||
}
|
||||
}
|
||||
|
||||
// list item?
|
||||
const listRef = listRefOf(ctx, pPr, styleId)
|
||||
/** extra revision fields shared across all return paths */
|
||||
const revExtras = {
|
||||
...(moveRevision ? { moveRevision } : {}),
|
||||
...(pPrChangeInfo ? { pPrChangeInfo } : {}),
|
||||
...(paraMarkDel ? { paraMarkDel } : {}),
|
||||
}
|
||||
if (listRef) {
|
||||
const kind = listKindOf(ctx, listRef.numId, listRef.ilvl)
|
||||
@@ -2361,16 +2427,25 @@ function extractTextboxes(
|
||||
: null
|
||||
}
|
||||
if (hasLineShapes && !opts?.shapes) return null
|
||||
// textless preset shape (star/arrow/…): visible geometry, no text body.
|
||||
// rect stays on its existing paths (thin rules, background boxes)
|
||||
if (!opts?.shapes || !prstOf || prstOf === 'rect') return null
|
||||
if (!opts?.shapes || !prstOf) return null
|
||||
if (prstOf === 'rect') {
|
||||
// near-flat rects stay on the decorative thin-rule path; a real
|
||||
// rectangle (pattern/solid-filled swatch, tdf dml-shape-fillpattern)
|
||||
// renders like any other textless preset shape
|
||||
const xfrm = findChild(spPr ?? {}, 'a:xfrm')
|
||||
const cy = parseInt(attrsOf(findChild(xfrm ?? {}, 'a:ext') ?? {})['cy'] ?? '', 10)
|
||||
if (!Number.isFinite(cy) || cy <= 130000) return null
|
||||
}
|
||||
}
|
||||
const box: TextboxDisplay = { paras: [] }
|
||||
if (spPr) {
|
||||
if (!findChild(spPr, 'a:noFill')) {
|
||||
// a:pattFill approximates to its foreground color (same tradeoff as gradFill)
|
||||
const pattFill = findChild(spPr, 'a:pattFill')
|
||||
const fill =
|
||||
colorNodeHex(findChild(spPr, 'a:solidFill'), ctx.themeColors) ??
|
||||
gradFillApproxHex(spPr, ctx.themeColors)
|
||||
gradFillApproxHex(spPr, ctx.themeColors) ??
|
||||
(pattFill ? colorNodeHex(findChild(pattFill, 'a:fgClr'), ctx.themeColors) : undefined)
|
||||
if (fill) box.fill = fill
|
||||
const blipFill = findChild(spPr, 'a:blipFill')
|
||||
if (blipFill) {
|
||||
@@ -2586,6 +2661,16 @@ function extractTextboxes(
|
||||
if (stroke && shapeAttrs['stroked'] !== 'f') box.borderColor = stroke
|
||||
// canvas textboxes: VML strokes default to on/black, and Word draws them
|
||||
else if (!stroke && shapeAttrs['stroked'] !== 'f' && scale) box.borderColor = '000000'
|
||||
// absolutely positioned VML shape: leaves the flow like a wp:anchor box
|
||||
// (page banners stack at full height otherwise, tdf 1194 family).
|
||||
// Canvas (v:group) children use unitless group coordinates — not ours to float.
|
||||
if (!scale && /position:absolute/.test(style)) {
|
||||
box.floating = true
|
||||
const mx = parseFloat(/margin-left:(-?[\d.]+)pt/.exec(style)?.[1] ?? '')
|
||||
const my = parseFloat(/margin-top:(-?[\d.]+)pt/.exec(style)?.[1] ?? '')
|
||||
if (Number.isFinite(mx)) box.offsetXEmu = Math.round(mx * EMU_PER_PT)
|
||||
if (Number.isFinite(my)) box.offsetYEmu = Math.round(my * EMU_PER_PT)
|
||||
}
|
||||
for (const content of contents) box.paras.push(...txbxContentParas(content, ctx))
|
||||
if (contents.some(txbxHasStructuredContent)) box.readOnly = true
|
||||
if (box.paras.some((p) => p.runs.length > 0)) out.push(box)
|
||||
@@ -2764,7 +2849,11 @@ function extractParaFormat(pPr: XNode): ParaFormat | undefined {
|
||||
if (hanging > 0) format.indentFirstLine = -hanging
|
||||
else if (firstLine > 0) format.indentFirstLine = firstLine
|
||||
}
|
||||
if (boolProp(pPr, 'w:pageBreakBefore')) format.pageBreakBefore = true
|
||||
{
|
||||
// tri-state: an explicit w:val="0" must override a style-chain true
|
||||
const pbb = onOffOf(pPr, 'w:pageBreakBefore')
|
||||
if (pbb !== undefined) format.pageBreakBefore = pbb
|
||||
}
|
||||
if (boolProp(pPr, 'w:keepNext')) format.keepNext = true
|
||||
if (boolProp(pPr, 'w:keepLines')) format.keepLines = true
|
||||
// snapToGrid: default ON; only store when explicitly set to OFF
|
||||
@@ -2786,7 +2875,7 @@ function extractParaFormat(pPr: XNode): ParaFormat | undefined {
|
||||
const shd = findChild(pPr, 'w:shd')
|
||||
if (shd) {
|
||||
const fill = attrsOf(shd)['w:fill']
|
||||
if (fill && fill !== 'auto') format.shadingFill = fill
|
||||
if (fill && fill !== 'auto') format.shadingFill = stripHash(fill)
|
||||
}
|
||||
const pBdrs = findChildren(pPr, 'w:pBdr')
|
||||
if (pBdrs.length > 0) {
|
||||
@@ -2808,7 +2897,8 @@ function extractParaFormat(pPr: XNode): ParaFormat | undefined {
|
||||
if (!el || val === 'none' || val === 'nil') continue
|
||||
borders += ch
|
||||
const line: import('./types').ParaBorderLine = {}
|
||||
if (attrs?.['w:color'] && attrs['w:color'] !== 'auto') line.color = attrs['w:color']
|
||||
if (attrs?.['w:color'] && attrs['w:color'] !== 'auto')
|
||||
line.color = stripHash(attrs['w:color'])
|
||||
const sz = parseInt(attrs?.['w:sz'] ?? '', 10)
|
||||
if (Number.isFinite(sz) && sz > 0) line.szPt = sz / 8
|
||||
if (line.color !== undefined || line.szPt !== undefined) lines[ch] = line
|
||||
@@ -3140,7 +3230,7 @@ function extractRuns(
|
||||
walk(childrenOf(node), link, rev)
|
||||
} else if (name === 'w:br') {
|
||||
// Word honors a <w:br> sitting outside any <w:r> (direct child of w:p / w:ins)
|
||||
pushRun({ text: attrsOf(node)['w:type'] === 'page' ? '\f' : '\n' }, rev)
|
||||
pushRun({ text: BREAK_CHAR[attrsOf(node)['w:type'] ?? ''] ?? '\n' }, rev)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3247,10 +3337,17 @@ function buildRun(
|
||||
let text = ''
|
||||
for (const child of childrenOf(rNode)) {
|
||||
const name = nameOf(child)
|
||||
if (name === 'w:t' || name === 'w:delText') text += decodeNumericCharRefs(textOf(child))
|
||||
else if (name === 'w:tab' || name === 'w:ptab') text += '\t'
|
||||
if (name === 'w:t' || name === 'w:delText') {
|
||||
const raw = decodeNumericCharRefs(textOf(child))
|
||||
// without xml:space="preserve" Word drops the element's leading/trailing
|
||||
// XML whitespace (pretty-printed documents carry literal newlines + tabs)
|
||||
text +=
|
||||
attrsOf(child)['xml:space'] === 'preserve'
|
||||
? raw
|
||||
: raw.replace(/^[ \t\r\n]+|[ \t\r\n]+$/g, '')
|
||||
} else if (name === 'w:tab' || name === 'w:ptab') text += '\t'
|
||||
// In-paragraph page breaks (w:br w:type="page") are encoded as \f and preserved; column/soft breaks become \n
|
||||
else if (name === 'w:br') text += attrsOf(child)['w:type'] === 'page' ? '\f' : '\n'
|
||||
else if (name === 'w:br') text += BREAK_CHAR[attrsOf(child)['w:type'] ?? ''] ?? '\n'
|
||||
else if (name === 'w:cr') text += '\n'
|
||||
else if (name === 'w:noBreakHyphen') text += '\u2011'
|
||||
else if (name === 'w:sym') {
|
||||
@@ -3275,6 +3372,8 @@ function buildRun(
|
||||
const cy = Number(extent?.[2])
|
||||
if (cx > 0) image.widthPx = Math.round(cx / EMU_PER_PX)
|
||||
if (cy > 0) image.heightPx = Math.round(cy / EMU_PER_PX)
|
||||
const border = picBorderOf(drawingXml)
|
||||
if (border) image.border = border
|
||||
// anchored (floating) picture kept as a run image: carry the wrap kind
|
||||
// and anchor offsets so the editor can float it instead of inlining
|
||||
if (/<wp:anchor[\s>]/.test(drawingXml)) {
|
||||
@@ -3282,6 +3381,15 @@ function buildRun(
|
||||
if (meta.imageWrap) image.wrap = meta.imageWrap
|
||||
if (meta.imageOffsetXEmu !== undefined) image.offsetXEmu = meta.imageOffsetXEmu
|
||||
if (meta.imageOffsetYEmu !== undefined) image.offsetYEmu = meta.imageOffsetYEmu
|
||||
// Word centers the object on the anchor line (tdf#162551: the picture
|
||||
// juts above the line rather than hanging below it)
|
||||
if (
|
||||
/<wp:positionV[^>]*relativeFrom="line"[^>]*>\s*<wp:align>center<\/wp:align>/.test(
|
||||
drawingXml,
|
||||
)
|
||||
)
|
||||
image.lineCenterV = true
|
||||
if (meta.imageNoOverlap) image.noOverlap = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3361,7 +3469,7 @@ function buildRun(
|
||||
const highlight = attrsOf(findChild(rPr, 'w:highlight') ?? {})['w:val']
|
||||
if (highlight && highlight !== 'none') run.highlight = highlight
|
||||
const shdFill = attrsOf(findChild(rPr, 'w:shd') ?? {})['w:fill']
|
||||
if (shdFill && shdFill !== 'auto') run.shading = shdFill
|
||||
if (shdFill && shdFill !== 'auto') run.shading = stripHash(shdFill)
|
||||
const vertAlign = attrsOf(findChild(rPr, 'w:vertAlign') ?? {})['w:val']
|
||||
if (vertAlign === 'superscript' || vertAlign === 'subscript') run.vertAlign = vertAlign
|
||||
const em = attrsOf(findChild(rPr, 'w:em') ?? {})['w:val']
|
||||
@@ -3612,6 +3720,17 @@ function extractTableModel(tbl: XNode, ctx: BuildContext, depth = 1): TableModel
|
||||
tblJc === 'center' ? 'center' : tblJc === 'right' || tblJc === 'end' ? 'right' : undefined
|
||||
const tblInd = attrsOf(findChild(tblPrNode ?? {}, 'w:tblInd') ?? {})
|
||||
const tblIndTwips = !tblInd['w:type'] || tblInd['w:type'] === 'dxa' ? Number(tblInd['w:w']) : NaN
|
||||
const tblpPr = attrsOf(findChild(tblPrNode ?? {}, 'w:tblpPr') ?? {})
|
||||
let floatSide: TableModel['floatSide']
|
||||
if (Object.keys(tblpPr).length > 0) {
|
||||
const xSpec = tblpPr['w:tblpXSpec']
|
||||
// no alignment keyword: an absolute X past mid-body (~9360 twips of usable
|
||||
// width on Letter/A4) means the table hugs the right side
|
||||
floatSide =
|
||||
xSpec === 'right' || xSpec === 'outside' || (!xSpec && Number(tblpPr['w:tblpX']) > 4680)
|
||||
? 'right'
|
||||
: 'left'
|
||||
}
|
||||
|
||||
const rows: TableCell[][] = []
|
||||
const rowHeightsTwips: Array<number | null> = []
|
||||
@@ -3662,6 +3781,7 @@ function extractTableModel(tbl: XNode, ctx: BuildContext, depth = 1): TableModel
|
||||
if (effCellMar) model.cellMarTwips = effCellMar
|
||||
if (effBorders) model.borders = effBorders
|
||||
if (tblAlign) model.align = tblAlign
|
||||
if (floatSide) model.floatSide = floatSide
|
||||
if (Number.isFinite(tblIndTwips) && tblIndTwips !== 0) model.indentTwips = tblIndTwips
|
||||
const tblStyle = attrsOf(findChild(findChild(tbl, 'w:tblPr') ?? {}, 'w:tblStyle') ?? {})['w:val']
|
||||
if (tblStyle) model.tblStyleId = tblStyle
|
||||
@@ -3804,7 +3924,7 @@ function borderLinesOf(node: XNode | undefined, withInside: boolean): TableBorde
|
||||
borders[side] = {
|
||||
style: a['w:val'],
|
||||
...(a['w:sz'] ? { szEighths: Number(a['w:sz']) || undefined } : {}),
|
||||
...(a['w:color'] ? { color: a['w:color'] } : {}),
|
||||
...(a['w:color'] ? { color: stripHash(a['w:color']) } : {}),
|
||||
}
|
||||
}
|
||||
return Object.keys(borders).length > 0 ? borders : undefined
|
||||
@@ -3880,7 +4000,7 @@ function extractCell(tc: XNode, ctx: BuildContext, depth: number): TableCell {
|
||||
cell.vMerge = attrsOf(vMerge)['w:val'] === 'restart' ? 'restart' : 'continue'
|
||||
}
|
||||
const fill = attrsOf(findChild(tcPr, 'w:shd') ?? {})['w:fill']
|
||||
if (fill && fill !== 'auto') cell.fill = fill
|
||||
if (fill && fill !== 'auto') cell.fill = stripHash(fill)
|
||||
const vAlign = attrsOf(findChild(tcPr, 'w:vAlign') ?? {})['w:val']
|
||||
if (vAlign === 'center' || vAlign === 'bottom' || vAlign === 'top') cell.vAlign = vAlign
|
||||
const tcMar = cellMarginsOf(findChild(tcPr, 'w:tcMar'))
|
||||
@@ -3938,7 +4058,7 @@ function extractCell(tc: XNode, ctx: BuildContext, depth: number): TableCell {
|
||||
const pXml = rawPXml.includes('<mc:Fallback')
|
||||
? rawPXml.replace(/<mc:Fallback>[\s\S]*?<\/mc:Fallback>/g, '')
|
||||
: rawPXml
|
||||
if (pXml.includes('<wp:anchor') || pXml.includes('<w:pict')) {
|
||||
if (pXml.includes('<wp:anchor') || /<w:pict[\s>]/.test(pXml)) {
|
||||
const boxes = extractTextboxes(pXml, ctx, { shapes: true })
|
||||
if (boxes.length > 0) {
|
||||
cell.anchoredBoxes = [...(cell.anchoredBoxes ?? []), ...boxes]
|
||||
@@ -4205,6 +4325,20 @@ async function parseCompatibilityMode(zip: JSZip): Promise<number> {
|
||||
return m ? parseInt(m[1], 10) : 0
|
||||
}
|
||||
|
||||
/** settings.xml w:autoHyphenation + w:defaultTabStop (absent = Word's 720 twips) */
|
||||
async function parseLayoutSettings(
|
||||
zip: JSZip,
|
||||
): Promise<{ autoHyphenation?: boolean; defaultTabStopTwips?: number }> {
|
||||
const file = zip.file('word/settings.xml')
|
||||
if (!file) return {}
|
||||
const xml = await file.async('string')
|
||||
const tab = /<w:defaultTabStop[^>]*w:val="(-?\d+)"/.exec(xml)
|
||||
return {
|
||||
...(xmlFlagOn(xml, 'w:autoHyphenation') ? { autoHyphenation: true } : {}),
|
||||
...(tab ? { defaultTabStopTwips: parseInt(tab[1], 10) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** settings.xml <w:evenAndOddHeaders/> (w:val="0|false" counts as off) */
|
||||
async function parseEvenAndOddHeaders(zip: JSZip): Promise<boolean> {
|
||||
const file = zip.file('word/settings.xml')
|
||||
@@ -4509,7 +4643,7 @@ function hfCellContent(
|
||||
const paras: Run[][] = []
|
||||
let align: HfTableCell['align']
|
||||
const shd = attrsOf(findChild(findChild(tc, 'w:tcPr') ?? {}, 'w:shd') ?? {})['w:fill']
|
||||
let fill = shd && shd !== 'auto' ? shd : undefined
|
||||
let fill = shd && shd !== 'auto' ? stripHash(shd) : undefined
|
||||
let sawNested = false
|
||||
for (const node of childrenThroughSdt(tc, ['w:p', 'w:tbl'])) {
|
||||
if (nameOf(node) === 'w:tbl') {
|
||||
@@ -4783,7 +4917,11 @@ type ImageMeta = Pick<
|
||||
| 'imageFlipV'
|
||||
| 'imageCrop'
|
||||
| 'imageFillRect'
|
||||
>
|
||||
| 'imageBorder'
|
||||
> & {
|
||||
/** wp:anchor allowOverlap="0": Word displaces the object out of a colliding anchor's box */
|
||||
imageNoOverlap?: boolean
|
||||
}
|
||||
|
||||
/** a:srcRect / a:fillRect attribute (1000ths of a percent; some writers emit decimals) → fraction */
|
||||
function rectFrac(tag: string, name: string): number {
|
||||
@@ -4791,6 +4929,26 @@ function rectFrac(tag: string, name: string): number {
|
||||
return Number.isFinite(v) ? v / 100000 : 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Picture outline (a:ln with a solid fill on the pic's own spPr, so a sibling
|
||||
* textbox outline in the same drawing is not picked up); rendered as a CSS
|
||||
* border, display-only like crop. Theme-colored (schemeClr) outlines stay
|
||||
* unrendered.
|
||||
*/
|
||||
function picBorderOf(xml: string): { color: string; widthPt: number } | undefined {
|
||||
const picSpPr = /<pic:spPr[^>]*>([\s\S]*?)<\/pic:spPr>/.exec(xml)?.[1]
|
||||
const picLn = picSpPr ? /<a:ln\b[^>]*>[\s\S]*?<\/a:ln>/.exec(picSpPr)?.[0] : undefined
|
||||
if (!picLn || /<a:noFill\s*\/>/.test(picLn)) return undefined
|
||||
const color = /<a:solidFill>\s*<a:srgbClr val="([0-9A-Fa-f]{6})"/.exec(picLn)?.[1]
|
||||
if (!color) return undefined
|
||||
const w = parseInt(/<a:ln\b[^>]*\bw="(\d+)"/.exec(picLn)?.[1] ?? '', 10)
|
||||
// DrawingML default stroke width is 0.75pt (9525 EMU)
|
||||
return {
|
||||
color: color.toUpperCase(),
|
||||
widthPt: Number.isFinite(w) && w > 0 ? w / EMU_PER_PT : 0.75,
|
||||
}
|
||||
}
|
||||
|
||||
function imageMeta(xml: string): ImageMeta {
|
||||
const meta: ImageMeta = {}
|
||||
const extent = /<wp:extent[^>]*\/?>/.exec(xml)?.[0]
|
||||
@@ -4813,6 +4971,8 @@ function imageMeta(xml: string): ImageMeta {
|
||||
if (/\bflipH="(?:1|true)"/.test(picXfrm)) meta.imageFlipH = true
|
||||
if (/\bflipV="(?:1|true)"/.test(picXfrm)) meta.imageFlipV = true
|
||||
}
|
||||
const border = picBorderOf(xml)
|
||||
if (border) meta.imageBorder = border
|
||||
// source crop (a:srcRect) and fill placement (a:stretch/a:fillRect): applied
|
||||
// by the renderer as an overflow-hidden window over a scaled/offset image
|
||||
const srcRect = /<a:srcRect\s[^>]*\/>/.exec(xml)?.[0]
|
||||
@@ -4837,13 +4997,26 @@ function imageMeta(xml: string): ImageMeta {
|
||||
}
|
||||
const anchor = /<wp:anchor[^>]*>/.exec(xml)?.[0]
|
||||
if (anchor) {
|
||||
if (/behindDoc="1"/.test(anchor)) meta.imageWrap = 'behind'
|
||||
if (/allowOverlap="(?:0|false)"/.test(anchor)) meta.imageNoOverlap = true
|
||||
// an explicit wrap element wins over behindDoc: Word draws a
|
||||
// behindDoc+wrapTight object behind the text and still wraps around it
|
||||
if (/behindDoc="1"/.test(anchor) && !/<wp:wrap(Square|Tight|Through|TopAndBottom)/.test(xml))
|
||||
meta.imageWrap = 'behind'
|
||||
else if (/<wp:wrapTopAndBottom/.test(xml)) meta.imageWrap = 'topBottom'
|
||||
else if (/<wp:wrap(Square|Tight|Through)/.test(xml)) {
|
||||
const kind = /<wp:wrap(Square|Tight|Through)/.exec(xml)![1]
|
||||
const alignRight =
|
||||
/<wp:positionH[^>]*>(?:(?!<\/wp:positionH>)[\s\S])*?<wp:align>right<\/wp:align>/.test(xml)
|
||||
const side = alignRight ? 'right' : 'left'
|
||||
// wrapText names the side the text goes on — the object floats opposite;
|
||||
// with bothSides, an absolute X past mid-body (~4680 twips usable half on
|
||||
// Letter/A4) means the object hugs the right side
|
||||
const wrapText = /<wp:wrap(?:Square|Tight|Through)[^>]*wrapText="([^"]+)"/.exec(xml)?.[1]
|
||||
const posH = /<wp:positionH[^>]*>([\s\S]*?)<\/wp:positionH>/.exec(xml)?.[1] ?? ''
|
||||
const offX = Number(/<wp:posOffset>(-?\d+)<\/wp:posOffset>/.exec(posH)?.[1] ?? NaN)
|
||||
const side =
|
||||
alignRight || wrapText === 'left' || (wrapText !== 'right' && offX > 4680 * 635)
|
||||
? 'right'
|
||||
: 'left'
|
||||
meta.imageWrap =
|
||||
kind === 'Tight'
|
||||
? `tight-${side}`
|
||||
@@ -5250,7 +5423,13 @@ async function extractDiagramDrawing(
|
||||
const drawingPath = dmPath.replace(/data(\d*)\.xml$/, 'drawing$1.xml')
|
||||
const file = drawingPath !== dmPath ? ctx.zip.file(drawingPath) : null
|
||||
if (!file) return null
|
||||
const extent = /<wp:extent[^>]*cx="(\d+)"[^>]*cy="(\d+)"/.exec(xml)
|
||||
// the owning drawing's extent is the last one before its dgm:relIds (a
|
||||
// paragraph can hold several drawings)
|
||||
const dmAt = xml.indexOf('r:dm="')
|
||||
const extents = [
|
||||
...(dmAt >= 0 ? xml.slice(0, dmAt) : xml).matchAll(/<wp:extent[^>]*cx="(\d+)"[^>]*cy="(\d+)"/g),
|
||||
]
|
||||
const extent = extents[extents.length - 1]
|
||||
const widthPx = extent ? Math.round(parseInt(extent[1], 10) / EMU_PER_PX) : 0
|
||||
const heightPx = extent ? Math.round(parseInt(extent[2], 10) / EMU_PER_PX) : 0
|
||||
if (!widthPx || !heightPx) return null
|
||||
@@ -5298,11 +5477,23 @@ async function extractDiagramDrawing(
|
||||
wPx: Math.round(parseInt(attrsOf(ext)['cx'] ?? '0', 10) / EMU_PER_PX),
|
||||
hPx: Math.round(parseInt(attrsOf(ext)['cy'] ?? '0', 10) / EMU_PER_PX),
|
||||
}
|
||||
if (shape.wPx <= 0 || shape.hPx <= 0) continue
|
||||
const rot = parseInt(attrsOf(xfrm!)['rot'] ?? '', 10)
|
||||
if (Number.isFinite(rot) && rot !== 0) shape.rotDeg = Math.round(rot / 60000)
|
||||
const prst = attrsOf(findChild(spPr, 'a:prstGeom') ?? {})['prst']
|
||||
if (prst) shape.prst = prst
|
||||
// connectors carry cy="0"/cx="0"; only they may be zero-extent
|
||||
const isLine = prst === 'line' || (prst?.includes('Connector') ?? false)
|
||||
if ((shape.wPx <= 0 || shape.hPx <= 0) && !(isLine && (shape.wPx > 0 || shape.hPx > 0)))
|
||||
continue
|
||||
const rot = parseInt(attrsOf(xfrm!)['rot'] ?? '', 10)
|
||||
if (Number.isFinite(rot) && rot !== 0) shape.rotDeg = Math.round(rot / 60000)
|
||||
const ln = findChild(spPr, 'a:ln')
|
||||
if (ln && !findChild(ln, 'a:noFill')) {
|
||||
const lnHex = colorNodeHex(findChild(ln, 'a:solidFill'), ctx.themeColors)
|
||||
if (lnHex) {
|
||||
shape.lnHex = lnHex
|
||||
const w = parseInt(attrsOf(ln)['w'] ?? '', 10)
|
||||
shape.lnWPx = Number.isFinite(w) && w > 0 ? Math.max(1, Math.round(w / EMU_PER_PX)) : 1
|
||||
}
|
||||
}
|
||||
const blipFill = findChild(spPr, 'a:blipFill')
|
||||
if (blipFill) {
|
||||
const rId = attrsOf(findChild(blipFill, 'a:blip') ?? {})['r:embed']
|
||||
@@ -5502,6 +5693,8 @@ async function parseStyles(
|
||||
if (onFlag('w:i')) dd.italic = true
|
||||
const color = colorFrom(rPr, theme)
|
||||
if (color) dd.color = color
|
||||
const lang = attrsOf(findChild(rPr, 'w:lang') ?? {})['w:val']
|
||||
if (lang) dd.lang = lang
|
||||
}
|
||||
const pPr = findChild(findChild(defaultsNode, 'w:pPrDefault') ?? {}, 'w:pPr')
|
||||
const spacingAttrs = pPr ? attrsOf(findChild(pPr, 'w:spacing') ?? {}) : {}
|
||||
@@ -5585,6 +5778,19 @@ async function parseStyles(
|
||||
})
|
||||
}
|
||||
|
||||
// Word's effective default per style type (ECMA-376 §17.7.4.17): the last
|
||||
// w:default="1" wins; a type declaring none defaults to its first style
|
||||
{
|
||||
const firstOfType = new Map<string, StyleInfo>()
|
||||
const declared = new Map<string, StyleInfo>()
|
||||
for (const info of styles.values()) {
|
||||
if (!firstOfType.has(info.type)) firstOfType.set(info.type, info)
|
||||
if (info.isDefault) declared.set(info.type, info)
|
||||
info.isDefault = undefined
|
||||
}
|
||||
for (const [type, first] of firstOfType) (declared.get(type) ?? first).isDefault = true
|
||||
}
|
||||
|
||||
// resolve basedOn chains: a style inherits every display prop it doesn't set itself
|
||||
const resolved = new Set<string>()
|
||||
const resolve = (styleId: string, seen: Set<string>): StyleInfo | undefined => {
|
||||
@@ -5681,16 +5887,23 @@ function tableStyleDisplayOf(
|
||||
const display: TableStyleDisplay = {}
|
||||
const shdFill = (node: XNode | undefined): string | undefined => {
|
||||
const fill = node ? attrsOf(findChild(node, 'w:shd') ?? {})['w:fill'] : undefined
|
||||
return fill && fill !== 'auto' ? fill : undefined
|
||||
return fill && fill !== 'auto' ? stripHash(fill) : undefined
|
||||
}
|
||||
const baseFill = shdFill(findChild(styleNode, 'w:tcPr'))
|
||||
if (baseFill) display.fill = baseFill
|
||||
const szHalfOf = (rPr: XNode | undefined): number | undefined => {
|
||||
const val = parseInt(attrsOf(findChild(rPr ?? {}, 'w:sz') ?? {})['w:val'] ?? '', 10)
|
||||
return val > 0 ? val : undefined
|
||||
}
|
||||
const styleRPr = findChild(styleNode, 'w:rPr')
|
||||
if (styleRPr) {
|
||||
const wholeTable: NonNullable<TableStyleDisplay['wholeTable']> = {}
|
||||
const color = colorFrom(styleRPr, theme)
|
||||
if (color) wholeTable.color = color
|
||||
if (boolProp(styleRPr, 'w:b')) wholeTable.bold = true
|
||||
if (boolProp(styleRPr, 'w:i')) wholeTable.italic = true
|
||||
const sz = szHalfOf(styleRPr)
|
||||
if (sz) wholeTable.sizeHalfPoints = sz
|
||||
if (Object.keys(wholeTable).length > 0) display.wholeTable = wholeTable
|
||||
}
|
||||
for (const cond of findChildren(styleNode, 'w:tblStylePr')) {
|
||||
@@ -5704,6 +5917,8 @@ function tableStyleDisplayOf(
|
||||
if (rPr && boolProp(rPr, 'w:b')) fmt.bold = true
|
||||
const color = colorFrom(rPr, theme)
|
||||
if (color) fmt.color = color
|
||||
const sz = szHalfOf(rPr)
|
||||
if (sz) fmt.sizeHalfPoints = sz
|
||||
if (Object.keys(fmt).length > 0) display[type] = fmt
|
||||
} else if (type === 'band1Horz' && fill) {
|
||||
display.band1Fill = fill
|
||||
@@ -5716,7 +5931,10 @@ function tableStyleDisplayOf(
|
||||
if (borders) display.borders = borders
|
||||
const cellMar = cellMarginsOf(findChild(styleTblPr ?? {}, 'w:tblCellMar'))
|
||||
if (cellMar) display.cellMarTwips = cellMar
|
||||
const stylePPrSpacing = findChild(findChild(styleNode, 'w:pPr') ?? {}, 'w:spacing')
|
||||
const stylePPr = findChild(styleNode, 'w:pPr')
|
||||
const jc = attrsOf(findChild(stylePPr ?? {}, 'w:jc') ?? {})['w:val']
|
||||
if (jc) display.paraJc = jc
|
||||
const stylePPrSpacing = findChild(stylePPr ?? {}, 'w:spacing')
|
||||
if (stylePPrSpacing) {
|
||||
const a = attrsOf(stylePPrSpacing)
|
||||
const ps: NonNullable<TableStyleDisplay['paraSpacing']> = {}
|
||||
@@ -5818,13 +6036,18 @@ function styleDisplayOf(
|
||||
}
|
||||
if (boolProp(pPr, 'w:keepNext')) display.keepNext = true
|
||||
if (boolProp(pPr, 'w:keepLines')) display.keepLines = true
|
||||
if (boolProp(pPr, 'w:pageBreakBefore')) display.pageBreakBefore = true
|
||||
{
|
||||
const pbb = onOffOf(pPr, 'w:pageBreakBefore')
|
||||
if (pbb !== undefined) display.pageBreakBefore = pbb
|
||||
}
|
||||
if (boolProp(pPr, 'w:contextualSpacing')) display.contextualSpacing = true
|
||||
const autoSpace = autoSpaceOf(pPr)
|
||||
if (autoSpace !== undefined) display.autoSpace = autoSpace
|
||||
const jc = attrsOf(findChild(pPr, 'w:jc') ?? {})['w:val']
|
||||
if (jc === 'center' || jc === 'right' || jc === 'left' || jc === 'justify') display.align = jc
|
||||
else if (jc === 'both' || jc === 'distribute') display.align = 'justify'
|
||||
const shdFill = attrsOf(findChild(pPr, 'w:shd') ?? {})['w:fill']
|
||||
if (shdFill && shdFill !== 'auto') display.shadingFill = stripHash(shdFill)
|
||||
const stops = tabStopsOf(pPr)
|
||||
if (stops) display.tabStops = stops
|
||||
const ind = findChild(pPr, 'w:ind')
|
||||
@@ -5843,6 +6066,21 @@ function styleDisplayOf(
|
||||
return Object.keys(display).length > 0 ? display : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Main document part: word/document.xml when present, else the package-level
|
||||
* officeDocument relationship target (LO corpus has e.g. word/trial.xml).
|
||||
*/
|
||||
export async function resolveMainDocumentPath(zip: JSZip): Promise<string | null> {
|
||||
if (zip.file('word/document.xml')) return 'word/document.xml'
|
||||
const rels = await parseRels(zip, '_rels/.rels')
|
||||
for (const rel of rels.values()) {
|
||||
if (!/\/officeDocument$/.test(rel.type) || rel.targetMode === 'External') continue
|
||||
const target = rel.target.replace(/^\//, '')
|
||||
if (zip.file(target)) return target
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function parseRels(zip: JSZip, path: string): Promise<Map<string, RelInfo>> {
|
||||
const rels = new Map<string, RelInfo>()
|
||||
const file = zip.file(path)
|
||||
@@ -5929,6 +6167,60 @@ async function parseProtection(zip: JSZip): Promise<DocProtection | null> {
|
||||
}
|
||||
}
|
||||
|
||||
/** w:writeProtection from word/settings.xml (password to modify / read-only recommended) */
|
||||
async function parseWriteProtection(zip: JSZip): Promise<WriteProtection | null> {
|
||||
const file = zip.file('word/settings.xml')
|
||||
if (!file) return null
|
||||
const tag = /<w:writeProtection[^>]*\/>/.exec(await file.async('string'))?.[0]
|
||||
if (!tag) return null
|
||||
const recommended = /w:recommended="(?:1|true|on)"/.test(tag)
|
||||
const hash = /w:hash="([^"]+)"/.exec(tag)?.[1]
|
||||
const salt = /w:salt="([^"]+)"/.exec(tag)?.[1]
|
||||
const spin = /w:cryptSpinCount="(\d+)"/.exec(tag)?.[1]
|
||||
const sid = /w:cryptAlgorithmSid="(\d+)"/.exec(tag)?.[1]
|
||||
if (!recommended && !hash) return null
|
||||
return {
|
||||
...(recommended ? { recommended } : {}),
|
||||
...(hash ? { hash } : {}),
|
||||
...(salt ? { salt } : {}),
|
||||
...(spin ? { spinCount: parseInt(spin, 10) } : {}),
|
||||
...(sid ? { algorithmSid: parseInt(sid, 10) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** settings.xml removePersonalInformation (namespace prefix and quote style are arbitrary). */
|
||||
async function parseRemovePersonalInfo(zip: JSZip): Promise<boolean> {
|
||||
const file = zip.file('word/settings.xml')
|
||||
if (!file) return false
|
||||
const xml = await file.async('string')
|
||||
const prefixes = new Set<string>()
|
||||
const namespace = /\bxmlns(?::([A-Za-z_][\w.-]*))?\s*=\s*(["'])([^"']*)\2/g
|
||||
let declaration: RegExpExecArray | null
|
||||
while ((declaration = namespace.exec(xml)) !== null) {
|
||||
if (
|
||||
declaration[3] === 'http://schemas.openxmlformats.org/wordprocessingml/2006/main' ||
|
||||
declaration[3] === 'http://purl.oclc.org/ooxml/wordprocessingml/main'
|
||||
) {
|
||||
prefixes.add(declaration[1] ?? '')
|
||||
}
|
||||
}
|
||||
const escapedPrefixes = [...prefixes]
|
||||
.filter(Boolean)
|
||||
.map((prefix) => prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
|
||||
for (const prefix of prefixes) {
|
||||
const qName = prefix ? `${prefix}:removePersonalInformation` : 'removePersonalInformation'
|
||||
const escapedName = qName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
const tag = new RegExp(`<${escapedName}\\b[^>]*(?:\\/\\s*>|>\\s*<\\/${escapedName}\\s*>)`).exec(
|
||||
xml,
|
||||
)?.[0]
|
||||
if (!tag) continue
|
||||
const valPrefix = escapedPrefixes.length > 0 ? `(?:${escapedPrefixes.join('|')}):` : ''
|
||||
const val = new RegExp(`(?:^|\\s)(?:${valPrefix})?val\\s*=\\s*(["'])(0|false)\\1`, 'i')
|
||||
return !val.test(tag)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** w:numFmt of a w:lvl, including w14 custom formats hidden in mc:AlternateContent
|
||||
* (mc:Choice carries val="custom" + w:format; mc:Fallback the standard substitute) */
|
||||
function numFmtOfLevel(lvlNode: XNode): { numFmt?: string; customFormat?: string } {
|
||||
|
||||
@@ -15,14 +15,13 @@ import {
|
||||
type NoteKind,
|
||||
} from './notes'
|
||||
import {
|
||||
INK_MEDIA_PATH_RE,
|
||||
INK_MEDIA_PREFIX,
|
||||
INK_REL_RE,
|
||||
anchoredInkRunXml,
|
||||
injectInkRunsIntoParagraph,
|
||||
stripInkRuns,
|
||||
} from './ink'
|
||||
import { assertZipWithinLimits, type ParseExtras } from './parse'
|
||||
import { assertZipWithinLimits, resolveMainDocumentPath, type ParseExtras } from './parse'
|
||||
import { cleanupDocxOwnedResources } from './resource-cleanup'
|
||||
import { loadDocxZip } from './zip-load'
|
||||
import { BLANK_NUMBERING_XML, abstractNumXml, type CustomNumberingLevel } from './blank'
|
||||
import { applyPageNumType, applySectionSettings, applySectionStartType } from './section'
|
||||
@@ -44,6 +43,7 @@ import { buildChartPartXml, buildChartWorkbookXlsxBase64, CHART_WORKBOOK_REL_TYP
|
||||
import type {
|
||||
CommentInfo,
|
||||
DocProtection,
|
||||
WriteProtection,
|
||||
GeneratedBlock,
|
||||
HeaderFooter,
|
||||
NewChart,
|
||||
@@ -93,7 +93,7 @@ export interface SaveOptions {
|
||||
/** rewrite page size / margins in the trailing w:sectPr */
|
||||
section?: SectionSettings
|
||||
/** last-section start type (w:type); rewrites the trailing sectPr when inserting a continuous section break; undefined = keep */
|
||||
sectionStartType?: 'nextPage' | 'continuous' | 'evenPage' | 'oddPage'
|
||||
sectionStartType?: 'nextPage' | 'continuous' | 'evenPage' | 'oddPage' | 'nextColumn'
|
||||
/** last-section page numbering (w:pgNumType): both fmt/start unset = remove the tag; undefined = keep */
|
||||
pgNumType?: { fmt?: string; start?: number }
|
||||
/** page color: hex without '#' to set, null to remove, undefined to keep as-is */
|
||||
@@ -160,6 +160,14 @@ export interface SaveOptions {
|
||||
comments?: CommentInfo[]
|
||||
/** editing restriction; null removes w:documentProtection, undefined keeps */
|
||||
protection?: DocProtection | null
|
||||
/** password to modify / read-only recommended; null removes w:writeProtection, undefined keeps */
|
||||
writeProtection?: WriteProtection | null
|
||||
/**
|
||||
* settings.xml w:removePersonalInformation flag; undefined keeps the current value.
|
||||
* Whenever the flag is effective (set here or already in the document), the save
|
||||
* removes known author and organization metadata throughout the final package.
|
||||
*/
|
||||
removePersonalInfo?: boolean
|
||||
/**
|
||||
* Full desired footnote / endnote lists; the part is regenerated from them
|
||||
* (separator entries preserved). undefined = keep byte-identical.
|
||||
@@ -368,6 +376,7 @@ export async function saveDocx(
|
||||
): Promise<Uint8Array> {
|
||||
const { documentXml, originalBytes, bodyInnerStart, bodyInnerEnd } = parsed.internal
|
||||
const elements = parsed.extras.elements
|
||||
const scrubPersonalInfo = options.removePersonalInfo ?? parsed.removePersonalInfo ?? false
|
||||
|
||||
const visibleOriginalOrder = parsed.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex)
|
||||
const isUnchanged =
|
||||
@@ -395,6 +404,8 @@ export async function saveDocx(
|
||||
options.evenAndOddHeaders === undefined &&
|
||||
options.comments === undefined &&
|
||||
options.protection === undefined &&
|
||||
options.writeProtection === undefined &&
|
||||
options.removePersonalInfo === undefined &&
|
||||
options.footnotes === undefined &&
|
||||
options.endnotes === undefined &&
|
||||
options.watermark === undefined &&
|
||||
@@ -404,13 +415,14 @@ export async function saveDocx(
|
||||
options.themeColors === undefined &&
|
||||
(options.partXml === undefined || Object.keys(options.partXml).length === 0) &&
|
||||
(options.partBinary === undefined || Object.keys(options.partBinary).length === 0)
|
||||
if (isUnchanged) return originalBytes
|
||||
if (isUnchanged && !scrubPersonalInfo) return originalBytes
|
||||
|
||||
const zip = await loadDocxZip(originalBytes)
|
||||
assertZipWithinLimits(zip)
|
||||
const docPath = (await resolveMainDocumentPath(zip)) ?? 'word/document.xml'
|
||||
|
||||
// Relationship allocation for newly created hyperlinks and images.
|
||||
const relsPath = 'word/_rels/document.xml.rels'
|
||||
const relsPath = docPath.replace(/([^/]+)$/, '_rels/$1.rels')
|
||||
const relsFile = zip.file(relsPath)
|
||||
// fall back to an empty part so newly allocated rIds are never dangling
|
||||
let relsXml = relsFile
|
||||
@@ -968,6 +980,13 @@ export async function saveDocx(
|
||||
let newDocumentXml =
|
||||
documentXml.slice(0, bodyInnerStart) + parts.join('') + documentXml.slice(bodyInnerEnd)
|
||||
|
||||
if (options.comments !== undefined) {
|
||||
newDocumentXml = removeDeletedCommentMarkers(
|
||||
newDocumentXml,
|
||||
new Set(options.comments.map((comment) => comment.id)),
|
||||
)
|
||||
}
|
||||
|
||||
// editor-generated formulas need the math namespace on the document root;
|
||||
// docx produced by non-Word generators may not declare it
|
||||
if (newDocumentXml.includes('<m:') && !/<w:document[^>]*xmlns:m=/.test(newDocumentXml)) {
|
||||
@@ -987,6 +1006,8 @@ export async function saveDocx(
|
||||
if (
|
||||
options.pageColor ||
|
||||
options.protection !== undefined ||
|
||||
options.writeProtection !== undefined ||
|
||||
options.removePersonalInfo !== undefined ||
|
||||
options.evenAndOddHeaders !== undefined
|
||||
) {
|
||||
const file = zip.file(settingsPath)
|
||||
@@ -1012,10 +1033,21 @@ export async function saveDocx(
|
||||
xml = xml.replace(/(<w:settings[^>]*>)/, '$1<w:displayBackgroundShape/>')
|
||||
touched = true
|
||||
}
|
||||
// Each apply* inserts right after the settings root, so run them in reverse
|
||||
// schema order — the final order becomes writeProtection, removePersonalInformation,
|
||||
// documentProtection (CT_Settings sequence).
|
||||
if (options.protection !== undefined) {
|
||||
xml = applyProtection(xml, options.protection)
|
||||
touched = true
|
||||
}
|
||||
if (options.removePersonalInfo !== undefined) {
|
||||
xml = applyRemovePersonalInfo(xml, options.removePersonalInfo)
|
||||
touched = true
|
||||
}
|
||||
if (options.writeProtection !== undefined) {
|
||||
xml = applyWriteProtection(xml, options.writeProtection)
|
||||
touched = true
|
||||
}
|
||||
if (options.evenAndOddHeaders !== undefined) {
|
||||
xml = applyEvenAndOddHeaders(xml, options.evenAndOddHeaders)
|
||||
touched = true
|
||||
@@ -1024,14 +1056,6 @@ export async function saveDocx(
|
||||
}
|
||||
|
||||
let relsChanged = false
|
||||
// drop relationships of stripped ink runs (their media parts are dropped too)
|
||||
if (options.inks !== undefined && relsXml) {
|
||||
const cleaned = relsXml.replace(INK_REL_RE, '')
|
||||
if (cleaned !== relsXml) {
|
||||
relsXml = cleaned
|
||||
relsChanged = true
|
||||
}
|
||||
}
|
||||
if (newRels.length > 0 && relsXml) {
|
||||
const inserts = newRels
|
||||
.map(
|
||||
@@ -1134,10 +1158,8 @@ export async function saveDocx(
|
||||
out.folder(name)
|
||||
continue
|
||||
}
|
||||
// old ink PNGs are re-emitted from options.inks; don't carry orphans over
|
||||
if (options.inks !== undefined && INK_MEDIA_PATH_RE.test(name)) continue
|
||||
const hfPart = hfParts.find((p) => p.path === name)
|
||||
if (name === 'word/document.xml') {
|
||||
if (name === docPath) {
|
||||
out.file(name, newDocumentXml, { date: entry.date })
|
||||
} else if (hfPart) {
|
||||
out.file(name, hfPart.xml, { date: entry.date })
|
||||
@@ -1222,6 +1244,8 @@ export async function saveDocx(
|
||||
if (themePart?.isNew) {
|
||||
out.file(THEME_PART_PATH, themePart.xml)
|
||||
}
|
||||
await cleanupDocxOwnedResources(out, docPath)
|
||||
if (scrubPersonalInfo) await scrubPersonalMetadata(out)
|
||||
return out.generateAsync({
|
||||
type: 'uint8array',
|
||||
compression: 'DEFLATE',
|
||||
@@ -1229,6 +1253,20 @@ export async function saveDocx(
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* A comment-list edit is authoritative. Remove body markers for ids no longer
|
||||
* present even when their paragraphs were copied through as original XML.
|
||||
*/
|
||||
function removeDeletedCommentMarkers(xml: string, liveIds: Set<string>): string {
|
||||
return xml.replace(
|
||||
/<w:comment(?:RangeStart|RangeEnd|Reference)\b[^>]*(?:\/\s*>|>\s*<\/w:comment(?:RangeStart|RangeEnd|Reference)\s*>)/g,
|
||||
(tag) => {
|
||||
const id = /\bw:id\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(tag)
|
||||
return id && !liveIds.has(id[1] ?? id[2]) ? '' : tag
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Standalone header/footer part: one centered paragraph, optional PAGE field.
|
||||
* PAGE_MARK in the text marks where the page number goes; a user-typed '#'
|
||||
@@ -1522,6 +1560,223 @@ function applyProtection(xml: string, protection: DocProtection | null): string
|
||||
return out
|
||||
}
|
||||
|
||||
/** set or remove <w:writeProtection> (password to modify) right after the settings root opens */
|
||||
function applyWriteProtection(xml: string, wp: WriteProtection | null): string {
|
||||
let out = xml.replace(/<w:writeProtection[^>]*\/>/, '')
|
||||
if (wp && (wp.recommended || wp.hash)) {
|
||||
const crypt = wp.hash
|
||||
? ' w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash" w:cryptAlgorithmType="typeAny"' +
|
||||
` w:cryptAlgorithmSid="${wp.algorithmSid ?? 14}"` +
|
||||
` w:cryptSpinCount="${wp.spinCount ?? 100000}"` +
|
||||
` w:hash="${escapeXmlAttr(wp.hash)}"` +
|
||||
(wp.salt ? ` w:salt="${escapeXmlAttr(wp.salt)}"` : '')
|
||||
: ''
|
||||
const tag = `<w:writeProtection${wp.recommended ? ' w:recommended="1"' : ''}${crypt}/>`
|
||||
out = out.replace(/(<w:settings[^>]*>)/, `$1${tag}`)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Set or remove removePersonalInformation while retaining the settings part's prefix. */
|
||||
function applyRemovePersonalInfo(xml: string, on: boolean): string {
|
||||
const prefixes = namespacePrefixes(xml, WORDPROCESSINGML_NAMESPACES)
|
||||
const prefix = prefixes.find(Boolean) ?? (prefixes.includes('') ? '' : 'w')
|
||||
const propertyName = prefix ? `${prefix}:removePersonalInformation` : 'removePersonalInformation'
|
||||
const escapedProperty = regexEscape(propertyName)
|
||||
const out = xml.replace(
|
||||
new RegExp(`<${escapedProperty}\\b[^>]*(?:\\/\\s*>|>\\s*<\\/${escapedProperty}\\s*>)`, 'g'),
|
||||
'',
|
||||
)
|
||||
if (!on) return out
|
||||
const settingsName = prefix ? `${prefix}:settings` : 'settings'
|
||||
return out.replace(new RegExp(`(<${regexEscape(settingsName)}\\b[^>]*>)`), `$1<${propertyName}/>`)
|
||||
}
|
||||
|
||||
const WORDPROCESSINGML_NAMESPACES = [
|
||||
'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
|
||||
'http://purl.oclc.org/ooxml/wordprocessingml/main',
|
||||
] as const
|
||||
const CORE_PROPERTIES_NAMESPACE =
|
||||
'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'
|
||||
const DUBLIN_CORE_NAMESPACE = 'http://purl.org/dc/elements/1.1/'
|
||||
const EXTENDED_PROPERTIES_NAMESPACES = [
|
||||
'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties',
|
||||
'http://purl.oclc.org/ooxml/officeDocument/extendedProperties',
|
||||
] as const
|
||||
const PEOPLE_NAMESPACE = 'http://schemas.microsoft.com/office/word/2012/wordml'
|
||||
|
||||
const regexEscape = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
|
||||
/** Rewrite start tags only; text, CDATA, comments and processing instructions stay byte-identical. */
|
||||
function mapXmlStartTags(xml: string, rewrite: (tag: string) => string): string {
|
||||
let out = ''
|
||||
let cursor = 0
|
||||
while (cursor < xml.length) {
|
||||
const start = xml.indexOf('<', cursor)
|
||||
if (start < 0) return out + xml.slice(cursor)
|
||||
out += xml.slice(cursor, start)
|
||||
|
||||
const specialEnd = xml.startsWith('<!--', start)
|
||||
? '-->'
|
||||
: xml.startsWith('<![CDATA[', start)
|
||||
? ']]>'
|
||||
: xml.startsWith('<?', start)
|
||||
? '?>'
|
||||
: null
|
||||
if (specialEnd !== null) {
|
||||
const at = xml.indexOf(specialEnd, start + 2)
|
||||
if (at < 0) return out + xml.slice(start)
|
||||
const end = at + specialEnd.length
|
||||
out += xml.slice(start, end)
|
||||
cursor = end
|
||||
continue
|
||||
}
|
||||
|
||||
let quote = ''
|
||||
let end = start + 1
|
||||
for (; end < xml.length; end += 1) {
|
||||
const char = xml[end]!
|
||||
if (quote) {
|
||||
if (char === quote) quote = ''
|
||||
} else if (char === '"' || char === "'") {
|
||||
quote = char
|
||||
} else if (char === '>') {
|
||||
break
|
||||
}
|
||||
}
|
||||
if (end >= xml.length) return out + xml.slice(start)
|
||||
const tag = xml.slice(start, end + 1)
|
||||
out += tag.startsWith('</') || tag.startsWith('<!') ? tag : rewrite(tag)
|
||||
cursor = end + 1
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Namespace prefixes declared anywhere in this standalone XML part. */
|
||||
function namespacePrefixes(xml: string, namespaces: readonly string[]): string[] {
|
||||
const wanted = new Set(namespaces)
|
||||
const found = new Set<string>()
|
||||
const declaration = /\bxmlns(?::([A-Za-z_][\w.-]*))?\s*=\s*(["'])([^"']*)\2/g
|
||||
let match: RegExpExecArray | null
|
||||
while ((match = declaration.exec(xml)) !== null) {
|
||||
if (wanted.has(match[3])) found.add(match[1] ?? '')
|
||||
}
|
||||
return [...found]
|
||||
}
|
||||
|
||||
function replaceQualifiedAttributes(
|
||||
xml: string,
|
||||
prefixes: readonly string[],
|
||||
replacements: Readonly<Record<string, string>>,
|
||||
): string {
|
||||
const qualifiedPrefixes = prefixes.filter(Boolean)
|
||||
if (qualifiedPrefixes.length === 0) return xml
|
||||
const prefixPattern = qualifiedPrefixes.map(regexEscape).join('|')
|
||||
const localPattern = Object.keys(replacements).map(regexEscape).join('|')
|
||||
const attribute = new RegExp(
|
||||
`(\\b(?:${prefixPattern}):(${localPattern})\\s*=\\s*)(["'])([\\s\\S]*?)\\3`,
|
||||
'g',
|
||||
)
|
||||
return mapXmlStartTags(xml, (tag) =>
|
||||
tag.replace(
|
||||
attribute,
|
||||
(_whole, start: string, localName: string, quote: string) =>
|
||||
`${start}${quote}${replacements[localName]}${quote}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
function replaceUnqualifiedAttributes(
|
||||
xml: string,
|
||||
replacements: Readonly<Record<string, string>>,
|
||||
): string {
|
||||
const localPattern = Object.keys(replacements).map(regexEscape).join('|')
|
||||
const attribute = new RegExp(`(\\s(${localPattern})\\s*=\\s*)(["'])([\\s\\S]*?)\\3`, 'g')
|
||||
return mapXmlStartTags(xml, (tag) =>
|
||||
tag.replace(
|
||||
attribute,
|
||||
(_whole, start: string, localName: string, quote: string) =>
|
||||
`${start}${quote}${replacements[localName]}${quote}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
function clearQualifiedElements(
|
||||
xml: string,
|
||||
namespaces: readonly string[],
|
||||
localNames: readonly string[],
|
||||
): string {
|
||||
const qNames = namespacePrefixes(xml, namespaces).flatMap((prefix) =>
|
||||
localNames.map((localName) => (prefix ? `${prefix}:${localName}` : localName)),
|
||||
)
|
||||
let out = xml
|
||||
for (const qName of qNames) {
|
||||
const escaped = regexEscape(qName)
|
||||
out = out.replace(
|
||||
new RegExp(`(<${escaped}\\b[^>]*>)[\\s\\S]*?(<\\/${escaped}\\s*>)`, 'g'),
|
||||
'$1$2',
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function scrubWordprocessingMetadata(xml: string): string {
|
||||
const prefixes = namespacePrefixes(xml, WORDPROCESSINGML_NAMESPACES)
|
||||
if (prefixes.length === 0) return xml
|
||||
const replacements = { author: 'Author', initials: 'A' }
|
||||
return replaceUnqualifiedAttributes(
|
||||
replaceQualifiedAttributes(xml, prefixes, replacements),
|
||||
replacements,
|
||||
)
|
||||
}
|
||||
|
||||
function scrubPeopleMetadata(xml: string): string {
|
||||
const prefixes = namespacePrefixes(xml, [PEOPLE_NAMESPACE])
|
||||
if (prefixes.length === 0) return xml
|
||||
let out = xml
|
||||
for (const prefix of prefixes) {
|
||||
const qName = prefix ? `${prefix}:person` : 'person'
|
||||
const escaped = regexEscape(qName)
|
||||
out = out.replace(
|
||||
new RegExp(`<${escaped}\\b[^>]*(?:\\/\\s*>|>[\\s\\S]*?<\\/${escaped}\\s*>)`, 'g'),
|
||||
'',
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Strict final-package scrub. It runs after generated and copy-through parts
|
||||
* have been assembled, so headers, footers, notes, glossary and people data all
|
||||
* receive the same namespace-aware treatment. Custom XML/properties and binary
|
||||
* parts are deliberately untouched.
|
||||
*/
|
||||
async function scrubPersonalMetadata(zip: JSZip): Promise<void> {
|
||||
for (const [name, entry] of Object.entries(zip.files)) {
|
||||
if (entry.dir || !/\.xml$/i.test(name)) continue
|
||||
const isCustomData = name.startsWith('customXml/') || name === 'docProps/custom.xml'
|
||||
const isCore = name === CORE_PROPS_PATH
|
||||
const isApp = name === 'docProps/app.xml'
|
||||
const isPeople = name === 'word/people.xml'
|
||||
if (isCustomData) continue
|
||||
|
||||
const original = await entry.async('string')
|
||||
let scrubbed = scrubWordprocessingMetadata(original)
|
||||
if (isCore) {
|
||||
scrubbed = clearQualifiedElements(scrubbed, [DUBLIN_CORE_NAMESPACE], ['creator'])
|
||||
scrubbed = clearQualifiedElements(scrubbed, [CORE_PROPERTIES_NAMESPACE], ['lastModifiedBy'])
|
||||
}
|
||||
if (isApp) {
|
||||
scrubbed = clearQualifiedElements(scrubbed, EXTENDED_PROPERTIES_NAMESPACES, [
|
||||
'Manager',
|
||||
'Company',
|
||||
])
|
||||
}
|
||||
if (isPeople) scrubbed = scrubPeopleMetadata(scrubbed)
|
||||
if (scrubbed !== original) zip.file(name, scrubbed, { date: entry.date })
|
||||
}
|
||||
}
|
||||
|
||||
/** set or remove <w:titlePg/> ("different first page"), before w:docGrid per schema order */
|
||||
function applyTitlePg(sectPrXml: string, on: boolean): string {
|
||||
let xml = sectPrXml.replace(/<w:titlePg[^>]*\/>/, '')
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
import type JSZip from 'jszip'
|
||||
|
||||
/**
|
||||
* Relationship kinds whose references live directly in document XML and whose
|
||||
* targets are safe for this engine to lifecycle-manage.
|
||||
*/
|
||||
const DOCUMENT_OWNED_REL_TYPES = new Set([
|
||||
'chart',
|
||||
'diagramcolors',
|
||||
'diagramdata',
|
||||
'diagramdrawing',
|
||||
'diagramlayout',
|
||||
'diagramquickstyle',
|
||||
'hyperlink',
|
||||
'image',
|
||||
'oleobject',
|
||||
])
|
||||
|
||||
const RELATIONSHIP_TAG_RE =
|
||||
/<(?:[A-Za-z_][\w.-]*:)?Relationship\b[^>]*(?:\/\s*>|>\s*<\/(?:[A-Za-z_][\w.-]*:)?Relationship\s*>)/g
|
||||
const OVERRIDE_TAG_RE =
|
||||
/<(?:[A-Za-z_][\w.-]*:)?Override\b[^>]*(?:\/\s*>|>\s*<\/(?:[A-Za-z_][\w.-]*:)?Override\s*>)/g
|
||||
|
||||
interface Relationship {
|
||||
id: string
|
||||
type: string
|
||||
target: string
|
||||
external: boolean
|
||||
}
|
||||
|
||||
interface RelationshipEdge {
|
||||
source: string
|
||||
target: string
|
||||
}
|
||||
|
||||
function xmlAttr(tag: string, name: string): string | undefined {
|
||||
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
const match = new RegExp(`(?:^|\\s)${escaped}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(tag)
|
||||
const value = match?.[1] ?? match?.[2]
|
||||
return value === undefined ? undefined : decodeXmlEntities(value)
|
||||
}
|
||||
|
||||
function decodeXmlEntities(value: string): string {
|
||||
const codePoint = (match: string, raw: string, radix: number) => {
|
||||
const value = parseInt(raw, radix)
|
||||
return Number.isInteger(value) && value >= 0 && value <= 0x10ffff
|
||||
? String.fromCodePoint(value)
|
||||
: match
|
||||
}
|
||||
return value
|
||||
.replace(/&#x([0-9a-f]+);/gi, (match, hex: string) => codePoint(match, hex, 16))
|
||||
.replace(/&#(\d+);/g, (match, decimal: string) => codePoint(match, decimal, 10))
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/&/g, '&')
|
||||
}
|
||||
|
||||
function relationshipsOf(xml: string): Relationship[] {
|
||||
const relationships: Relationship[] = []
|
||||
for (const tag of xml.match(RELATIONSHIP_TAG_RE) ?? []) {
|
||||
const id = xmlAttr(tag, 'Id')
|
||||
const type = xmlAttr(tag, 'Type')
|
||||
const target = xmlAttr(tag, 'Target')
|
||||
if (!id || !type || !target) continue
|
||||
relationships.push({
|
||||
id,
|
||||
type,
|
||||
target,
|
||||
external: xmlAttr(tag, 'TargetMode')?.toLowerCase() === 'external',
|
||||
})
|
||||
}
|
||||
return relationships
|
||||
}
|
||||
|
||||
function relationshipTypeName(type: string): string {
|
||||
return (type.slice(type.lastIndexOf('/') + 1) || type).toLowerCase()
|
||||
}
|
||||
|
||||
function relationshipSourcePath(relsPath: string): string | null {
|
||||
if (relsPath === '_rels/.rels') return ''
|
||||
const match = /^(.*\/)?_rels\/([^/]+)\.rels$/.exec(relsPath)
|
||||
return match ? `${match[1] ?? ''}${match[2]}` : null
|
||||
}
|
||||
|
||||
function relationshipPartPath(sourcePath: string): string {
|
||||
const slash = sourcePath.lastIndexOf('/')
|
||||
const dir = slash >= 0 ? sourcePath.slice(0, slash + 1) : ''
|
||||
const filename = slash >= 0 ? sourcePath.slice(slash + 1) : sourcePath
|
||||
return `${dir}_rels/${filename}.rels`
|
||||
}
|
||||
|
||||
function decodePartUri(uri: string): string {
|
||||
try {
|
||||
return decodeURIComponent(uri)
|
||||
} catch {
|
||||
return uri
|
||||
}
|
||||
}
|
||||
|
||||
function normalizePartPath(path: string): string | null {
|
||||
const parts: string[] = []
|
||||
for (const segment of path.replace(/\\/g, '/').split('/')) {
|
||||
if (!segment || segment === '.') continue
|
||||
if (segment === '..') {
|
||||
if (parts.length === 0) return null
|
||||
parts.pop()
|
||||
} else {
|
||||
parts.push(segment)
|
||||
}
|
||||
}
|
||||
return parts.join('/')
|
||||
}
|
||||
|
||||
function resolveTargetPath(sourcePath: string, target: string): string | null {
|
||||
const withoutFragment = target.split('#', 1)[0]
|
||||
if (!withoutFragment || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(withoutFragment)) return null
|
||||
const decoded = decodePartUri(withoutFragment)
|
||||
if (decoded.startsWith('/')) return normalizePartPath(decoded.slice(1))
|
||||
const slash = sourcePath.lastIndexOf('/')
|
||||
const dir = slash >= 0 ? sourcePath.slice(0, slash + 1) : ''
|
||||
return normalizePartPath(dir + decoded)
|
||||
}
|
||||
|
||||
function isOwnedPart(path: string): boolean {
|
||||
return (
|
||||
path.startsWith('word/media/') ||
|
||||
path.startsWith('word/charts/') ||
|
||||
path.startsWith('word/embeddings/') ||
|
||||
path.startsWith('word/diagrams/')
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Find relationship ids actually referenced by the source XML. Prefixes are
|
||||
* discovered from namespace declarations so strict OOXML and non-"r" prefixes
|
||||
* remain safe. A missing declaration still gets the conventional "r" fallback.
|
||||
*/
|
||||
function referencedRelationshipIds(xml: string): Set<string> {
|
||||
const prefixes = new Set(['r'])
|
||||
const namespaceRe =
|
||||
/\bxmlns:([A-Za-z_][\w.-]*)\s*=\s*(?:"([^"]*\/relationships)"|'([^']*\/relationships)')/g
|
||||
let namespace: RegExpExecArray | null
|
||||
while ((namespace = namespaceRe.exec(xml)) !== null) prefixes.add(namespace[1])
|
||||
|
||||
const ids = new Set<string>()
|
||||
for (const prefix of prefixes) {
|
||||
const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
const attrRe = new RegExp(
|
||||
`\\b${escaped}:[A-Za-z_][\\w.-]*\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,
|
||||
'g',
|
||||
)
|
||||
let attr: RegExpExecArray | null
|
||||
while ((attr = attrRe.exec(xml)) !== null) ids.add(decodeXmlEntities(attr[1] ?? attr[2]))
|
||||
}
|
||||
// Legacy VML/Office producers occasionally put a package relationship id in
|
||||
// a non-r namespace attribute (for example o:relid). Preserve any id that is
|
||||
// still present as an exact XML attribute value rather than risking damage.
|
||||
const attributeRe = /\s[A-Za-z_][\w.:-]*\s*=\s*(?:"([^"]*)"|'([^']*)')/g
|
||||
let attribute: RegExpExecArray | null
|
||||
while ((attribute = attributeRe.exec(xml)) !== null) {
|
||||
const value = decodeXmlEntities(attribute[1] ?? attribute[2])
|
||||
if (/^rId[\w.-]*$/i.test(value)) ids.add(value)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
async function relationshipEdges(zip: JSZip): Promise<RelationshipEdge[]> {
|
||||
const edges: RelationshipEdge[] = []
|
||||
for (const path of Object.keys(zip.files)) {
|
||||
if (!path.endsWith('.rels')) continue
|
||||
const source = relationshipSourcePath(path)
|
||||
const file = zip.file(path)
|
||||
if (source === null || !file) continue
|
||||
for (const rel of relationshipsOf(await file.async('string'))) {
|
||||
if (rel.external) continue
|
||||
const target = resolveTargetPath(source, rel.target)
|
||||
if (target) edges.push({ source, target })
|
||||
}
|
||||
}
|
||||
return edges
|
||||
}
|
||||
|
||||
function addReachableOwnedParts(
|
||||
starts: Iterable<string>,
|
||||
outgoing: Map<string, string[]>,
|
||||
allowed: Set<string> | null = null,
|
||||
): Set<string> {
|
||||
const reached = new Set<string>()
|
||||
const pending = [...starts]
|
||||
while (pending.length > 0) {
|
||||
const part = pending.pop()!
|
||||
if (reached.has(part) || (allowed && !allowed.has(part))) continue
|
||||
reached.add(part)
|
||||
for (const target of outgoing.get(part) ?? []) {
|
||||
if (isOwnedPart(target) && (!allowed || allowed.has(target))) pending.push(target)
|
||||
}
|
||||
}
|
||||
return reached
|
||||
}
|
||||
|
||||
/**
|
||||
* Prune resources made unreachable by the final main-document XML.
|
||||
*
|
||||
* The pass is intentionally narrow:
|
||||
* - only known drawing/hyperlink relationship kinds are pruned at the document root;
|
||||
* - only owned Word resource directories are recursively removed;
|
||||
* - inbound references from any surviving part retain a shared target and its dependencies;
|
||||
* - unknown/custom parts are never selected for deletion.
|
||||
*/
|
||||
export async function cleanupDocxOwnedResources(zip: JSZip, documentPath: string): Promise<void> {
|
||||
const documentFile = zip.file(documentPath)
|
||||
const relsPath = relationshipPartPath(documentPath)
|
||||
const relsFile = zip.file(relsPath)
|
||||
if (!documentFile || !relsFile) return
|
||||
|
||||
const documentXml = await documentFile.async('string')
|
||||
const referencedIds = referencedRelationshipIds(documentXml)
|
||||
const candidateRoots = new Set<string>()
|
||||
const relsXml = await relsFile.async('string')
|
||||
const cleanedRelsXml = relsXml.replace(RELATIONSHIP_TAG_RE, (tag) => {
|
||||
const id = xmlAttr(tag, 'Id')
|
||||
const type = xmlAttr(tag, 'Type')
|
||||
if (
|
||||
!id ||
|
||||
!type ||
|
||||
referencedIds.has(id) ||
|
||||
!DOCUMENT_OWNED_REL_TYPES.has(relationshipTypeName(type))
|
||||
) {
|
||||
return tag
|
||||
}
|
||||
const external = xmlAttr(tag, 'TargetMode')?.toLowerCase() === 'external'
|
||||
const target = xmlAttr(tag, 'Target')
|
||||
if (!external && target) {
|
||||
const targetPath = resolveTargetPath(documentPath, target)
|
||||
if (targetPath && isOwnedPart(targetPath)) candidateRoots.add(targetPath)
|
||||
}
|
||||
return ''
|
||||
})
|
||||
if (cleanedRelsXml === relsXml) return
|
||||
zip.file(relsPath, cleanedRelsXml, { date: relsFile.date })
|
||||
|
||||
const edges = await relationshipEdges(zip)
|
||||
const outgoing = new Map<string, string[]>()
|
||||
for (const edge of edges) {
|
||||
const targets = outgoing.get(edge.source)
|
||||
if (targets) targets.push(edge.target)
|
||||
else outgoing.set(edge.source, [edge.target])
|
||||
}
|
||||
|
||||
const candidates = addReachableOwnedParts(
|
||||
[...candidateRoots].filter((path) => zip.file(path) !== null),
|
||||
outgoing,
|
||||
)
|
||||
for (const path of [...candidates]) {
|
||||
if (!zip.file(path)) candidates.delete(path)
|
||||
}
|
||||
if (candidates.size === 0) return
|
||||
|
||||
// Any inbound edge from outside the candidate subgraph makes that target
|
||||
// shared. Retain it and every owned dependency reachable from it.
|
||||
const sharedRoots = new Set<string>()
|
||||
for (const edge of edges) {
|
||||
if (candidates.has(edge.target) && !candidates.has(edge.source)) sharedRoots.add(edge.target)
|
||||
}
|
||||
const retained = addReachableOwnedParts(sharedRoots, outgoing, candidates)
|
||||
const removed = new Set<string>()
|
||||
for (const path of candidates) {
|
||||
if (retained.has(path)) continue
|
||||
removed.add(path)
|
||||
zip.remove(path)
|
||||
const dependencyRelsPath = relationshipPartPath(path)
|
||||
if (zip.file(dependencyRelsPath)) {
|
||||
removed.add(dependencyRelsPath)
|
||||
zip.remove(dependencyRelsPath)
|
||||
}
|
||||
}
|
||||
if (removed.size === 0) return
|
||||
|
||||
const contentTypesPath = '[Content_Types].xml'
|
||||
const contentTypesFile = zip.file(contentTypesPath)
|
||||
if (!contentTypesFile) return
|
||||
const contentTypesXml = await contentTypesFile.async('string')
|
||||
const cleanedContentTypesXml = contentTypesXml.replace(OVERRIDE_TAG_RE, (tag) => {
|
||||
const partName = xmlAttr(tag, 'PartName')
|
||||
if (!partName) return tag
|
||||
const path = normalizePartPath(decodePartUri(partName.replace(/^\//, '')))
|
||||
return path && removed.has(path) ? '' : tag
|
||||
})
|
||||
if (cleanedContentTypesXml !== contentTypesXml) {
|
||||
zip.file(contentTypesPath, cleanedContentTypesXml, { date: contentTypesFile.date })
|
||||
}
|
||||
}
|
||||
@@ -130,9 +130,7 @@ function sectionFromSectPr(
|
||||
const pgNumFmt = /<w:pgNumType[^>]*w:fmt="([^"]+)"/.exec(sectPrXml)?.[1]
|
||||
return {
|
||||
settings: sectionSettingsFromXml(sectPrXml),
|
||||
// nextColumn is rare; treat it as continuous (no forced page break)
|
||||
startType:
|
||||
type === 'nextColumn' ? 'continuous' : ((type as SectionInfo['startType']) ?? 'nextPage'),
|
||||
startType: (type as SectionInfo['startType']) ?? 'nextPage',
|
||||
firstBlockIndex,
|
||||
lastBlockIndex,
|
||||
sectPrXml,
|
||||
@@ -260,7 +258,7 @@ export function applySectionSettings(sectPrXml: string, settings: SectionSetting
|
||||
*/
|
||||
export function applySectionStartType(
|
||||
sectPrXml: string,
|
||||
type: 'nextPage' | 'continuous' | 'evenPage' | 'oddPage',
|
||||
type: 'nextPage' | 'continuous' | 'evenPage' | 'oddPage' | 'nextColumn',
|
||||
): string {
|
||||
let xml = sectPrXml.replace(/<w:type[^>]*\/>/, '')
|
||||
if (type === 'nextPage') return xml
|
||||
|
||||
@@ -138,6 +138,13 @@ export interface Run {
|
||||
wrap?: ImageWrap
|
||||
offsetXEmu?: number
|
||||
offsetYEmu?: number
|
||||
/** wp:anchor allowOverlap="0" (display-only collision hint) */
|
||||
noOverlap?: boolean
|
||||
/** picture outline (pic:spPr a:ln solid fill, display-only) */
|
||||
border?: { color: string; widthPt: number }
|
||||
/** wp:positionV relativeFrom="line" align="center": the floating picture
|
||||
* centers on its anchor line instead of hanging below it (display-only) */
|
||||
lineCenterV?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,7 +328,7 @@ export interface SectionSettings {
|
||||
export interface SectionInfo {
|
||||
settings: SectionSettings
|
||||
/** Section-break type w:type (how this section starts; meaningless for the first section), default nextPage */
|
||||
startType: 'nextPage' | 'continuous' | 'evenPage' | 'oddPage'
|
||||
startType: 'nextPage' | 'continuous' | 'evenPage' | 'oddPage' | 'nextColumn'
|
||||
/** docxIndex range of this section's blocks (inclusive; the section-break paragraph / trailing hidden sectPr block belong to this section) */
|
||||
firstBlockIndex: number
|
||||
lastBlockIndex: number
|
||||
@@ -542,6 +549,10 @@ export interface DiagramShape {
|
||||
prst?: string
|
||||
/** solid fill (hex without '#') */
|
||||
fillHex?: string
|
||||
/** a:ln stroke color (hex without '#'); connectors (prst=line, zero cx/cy) render as rules */
|
||||
lnHex?: string
|
||||
/** a:ln stroke width in px */
|
||||
lnWPx?: number
|
||||
/** picture fill (a:blipFill) */
|
||||
imageDataUrl?: string
|
||||
/** a:stretch/a:fillRect fractions of the picture fill (negative = bleed) */
|
||||
@@ -673,6 +684,8 @@ export interface TableModel {
|
||||
align?: 'left' | 'center' | 'right'
|
||||
/** table left indent (w:tblInd, twips; effective only with left alignment) */
|
||||
indentTwips?: number
|
||||
/** floating table (w:tblpPr): text wraps around the side opposite the anchor */
|
||||
floatSide?: 'left' | 'right'
|
||||
/** per-row height (twips, w:trHeight; null = not set), aligned with rows */
|
||||
rowHeightsTwips?: Array<number | null>
|
||||
/** per-row height rule (w:trHeight w:hRule; absent/legacy models = atLeast), aligned with rows */
|
||||
@@ -834,6 +847,8 @@ export interface Block {
|
||||
/** picture mirror flips (pic a:xfrm flipH/flipV) */
|
||||
imageFlipH?: boolean
|
||||
imageFlipV?: boolean
|
||||
/** picture outline (pic:spPr a:ln solid fill; display-only, like crop) */
|
||||
imageBorder?: { color: string; widthPt: number }
|
||||
/** editable structure (type === 'table'); untouched original XML still saves byte-identically */
|
||||
table?: TableModel
|
||||
/** display-only rendering for field passthrough paragraphs (TOC lines etc.) */
|
||||
@@ -898,6 +913,8 @@ export interface Block {
|
||||
}
|
||||
/** Top-level block insertion/deletion wrapper (w:ins/w:del around w:p or w:tbl). */
|
||||
blockRevision?: { kind: 'ins' | 'del' } & RevisionInfo
|
||||
/** Tracked deletion of the paragraph mark (w:pPr/w:rPr/w:del): Word joins the paragraph into the next one. */
|
||||
paraMarkDel?: { author: string; date?: string; id?: string }
|
||||
}
|
||||
|
||||
/** one paragraph inside an anchored textbox */
|
||||
@@ -1070,6 +1087,8 @@ export interface StyleDisplay {
|
||||
contextualSpacing?: boolean
|
||||
/** paragraph alignment from the style (w:pPr w:jc) */
|
||||
align?: 'left' | 'center' | 'right' | 'justify'
|
||||
/** paragraph shading from the style (w:pPr w:shd w:fill, hex without '#') */
|
||||
shadingFill?: string
|
||||
/** CJK-Latin/digit auto spacing from the style pPr (w:autoSpaceDE/DN) */
|
||||
autoSpace?: boolean
|
||||
/** style-level w:vanish (hidden text, e.g. z-TopofForm/z-BottomofForm HTML form markers) */
|
||||
@@ -1081,13 +1100,13 @@ export interface TableStyleDisplay {
|
||||
/** whole-table cell shading (hex without '#') */
|
||||
fill?: string
|
||||
/** whole-table run formatting (style-level w:rPr) */
|
||||
wholeTable?: { color?: string; bold?: boolean }
|
||||
wholeTable?: { color?: string; bold?: boolean; italic?: boolean; sizeHalfPoints?: number }
|
||||
/** conditional first-row formatting (w:tblStylePr w:type="firstRow") */
|
||||
firstRow?: { fill?: string; bold?: boolean; color?: string }
|
||||
firstRow?: { fill?: string; bold?: boolean; color?: string; sizeHalfPoints?: number }
|
||||
/** conditional first/last-column and last-row formatting (w:tblStylePr) */
|
||||
firstCol?: { fill?: string; bold?: boolean; color?: string }
|
||||
lastCol?: { fill?: string; bold?: boolean; color?: string }
|
||||
lastRow?: { fill?: string; bold?: boolean; color?: string }
|
||||
firstCol?: { fill?: string; bold?: boolean; color?: string; sizeHalfPoints?: number }
|
||||
lastCol?: { fill?: string; bold?: boolean; color?: string; sizeHalfPoints?: number }
|
||||
lastRow?: { fill?: string; bold?: boolean; color?: string; sizeHalfPoints?: number }
|
||||
/** odd-band row shading (band1Horz) */
|
||||
band1Fill?: string
|
||||
/** even-band row shading (band2Horz) */
|
||||
@@ -1105,6 +1124,8 @@ export interface TableStyleDisplay {
|
||||
lineRule?: 'auto' | 'atLeast' | 'exact'
|
||||
lineSpacing?: number
|
||||
}
|
||||
/** style-level w:pPr w:jc applied to every cell paragraph (Calendar styles center) */
|
||||
paraJc?: string
|
||||
}
|
||||
|
||||
export interface StyleInfo {
|
||||
@@ -1152,6 +1173,8 @@ export interface DocDefaults {
|
||||
spaceBeforeTwips?: number
|
||||
/** F1: paragraph spacing after default (twips); undefined = not set in docDefaults */
|
||||
spaceAfterTwips?: number
|
||||
/** rPrDefault w:lang w:val (BCP-47) — hyphenation/locale of the body text */
|
||||
lang?: string
|
||||
}
|
||||
|
||||
/** word/settings.xml w:documentProtection (only the editing restriction subset). */
|
||||
@@ -1170,6 +1193,20 @@ export interface DocProtection {
|
||||
algorithmSid?: number
|
||||
}
|
||||
|
||||
/** word/settings.xml w:writeProtection (password to modify; honor-system, no encryption). */
|
||||
export interface WriteProtection {
|
||||
/** w:recommended="1" — Word suggests opening read-only */
|
||||
recommended?: boolean
|
||||
/** password-to-modify hash (base64, same iterated-SHA-512 scheme as DocProtection); absent = no modify password */
|
||||
hash?: string
|
||||
/** salt (base64) */
|
||||
salt?: string
|
||||
/** iteration count (w:cryptSpinCount), Word default 100000 */
|
||||
spinCount?: number
|
||||
/** w:cryptAlgorithmSid, 14 = SHA-512 (the only supported value) */
|
||||
algorithmSid?: number
|
||||
}
|
||||
|
||||
/** One bibliography source (subset of the Word b:Sources schema). */
|
||||
export interface SourceInfo {
|
||||
/** unique tag (b:Tag), e.g. "Wang2024" */
|
||||
@@ -1239,6 +1276,10 @@ export interface ParsedDoc {
|
||||
themeColors?: ThemeColors | null
|
||||
/** editing restriction from word/settings.xml, null when none */
|
||||
protection: DocProtection | null
|
||||
/** password-to-modify / read-only-recommended from word/settings.xml, null when none */
|
||||
writeProtection: WriteProtection | null
|
||||
/** settings.xml w:removePersonalInformation — remove author/organization metadata on save */
|
||||
removePersonalInfo: boolean
|
||||
/** plain text of the default page header, null when the document has none */
|
||||
headerText?: string | null
|
||||
/** rich paragraphs of the default header (PAGE fields appear as PAGE_MARK runs) */
|
||||
@@ -1262,6 +1303,10 @@ export interface ParsedDoc {
|
||||
evenAndOddHeaders?: boolean
|
||||
/** settings.xml compatSetting compatibilityMode (0 when absent; >=15 = Word 2013+ layout) */
|
||||
compatibilityMode?: number
|
||||
/** settings.xml <w:autoHyphenation/> — Word breaks words at line ends automatically */
|
||||
autoHyphenation?: boolean
|
||||
/** settings.xml w:defaultTabStop in twips (absent = Word's 720); 0 = zero-width default tabs */
|
||||
defaultTabStopTwips?: number
|
||||
/** first-page header/footer parts (w:type="first"), null when absent */
|
||||
headerFirst?: HfPartInfo | null
|
||||
footerFirst?: HfPartInfo | null
|
||||
|
||||
@@ -19,12 +19,12 @@ const COMMENTS_XML =
|
||||
|
||||
/** paragraph with an in-paragraph comment range over its middle run */
|
||||
const COMMENTED_P =
|
||||
'<w:p><w:r><w:t>before </w:t></w:r>' +
|
||||
'<w:p><w:r><w:t xml:space="preserve">before </w:t></w:r>' +
|
||||
'<w:commentRangeStart w:id="1"/>' +
|
||||
'<w:r><w:t>marked</w:t></w:r>' +
|
||||
'<w:commentRangeEnd w:id="1"/>' +
|
||||
'<w:r><w:commentReference w:id="1"/></w:r>' +
|
||||
'<w:r><w:t> after</w:t></w:r></w:p>'
|
||||
'<w:r><w:t xml:space="preserve"> after</w:t></w:r></w:p>'
|
||||
|
||||
/** comment 2 spans two paragraphs: start in one, end in the next */
|
||||
const CROSS_P_A = '<w:p><w:commentRangeStart w:id="2"/><w:r><w:t>range opens here</w:t></w:r></w:p>'
|
||||
@@ -140,6 +140,21 @@ describe('comment parsing', () => {
|
||||
'<w:commentRangeEnd w:id="2"/><w:r><w:commentReference w:id="2"/></w:r>',
|
||||
)
|
||||
})
|
||||
|
||||
it('removes cross-paragraph markers when the authoritative comment list deletes the comment', async () => {
|
||||
const doc = await parseDocx(await buildCommentedDocx())
|
||||
const saved = await saveDocx(
|
||||
doc,
|
||||
doc.blocks
|
||||
.filter((block) => !block.hidden)
|
||||
.map((block): SaveBlock => ({ kind: 'original', docxIndex: block.docxIndex! })),
|
||||
{ comments: doc.comments.filter((comment) => comment.id !== '2') },
|
||||
)
|
||||
const docXml = await (await JSZip.loadAsync(saved)).file('word/document.xml')!.async('string')
|
||||
expect(docXml).not.toContain('w:id="2"')
|
||||
expect(docXml).not.toMatch(/<w:comment(?:RangeStart|RangeEnd|Reference)\b[^>]*w:id="2"/)
|
||||
expect(docXml).toContain('<w:commentRangeStart w:id="1"/>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('comment save fidelity', () => {
|
||||
|
||||
@@ -120,3 +120,26 @@ describe('paragraphs with decorative shapes + VML fallbacks', () => {
|
||||
expect(block.originalXml).toContain('<w:pict>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('picture content controls (w:picture in sdtPr, tdf#165359)', () => {
|
||||
it('an sdt-wrapped inline picture with text stays an editable paragraph, not an Embedded object chip', async () => {
|
||||
const drawing =
|
||||
'<w:drawing><wp:inline><wp:extent cx="914400" cy="914400"/>' +
|
||||
'<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>' +
|
||||
'</a:graphicData></a:graphic></wp:inline></w:drawing>'
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:sdt><w:sdtPr><w:picture/></w:sdtPr>' +
|
||||
`<w:sdtContent><w:r>${drawing}</w:r></w:sdtContent></w:sdt>` +
|
||||
'<w:r><w:t>ITEM NUMBER</w:t></w:r></w:p>',
|
||||
withImage: true,
|
||||
}),
|
||||
)
|
||||
const block = doc.blocks[0]
|
||||
expect(block.label).not.toBe('Embedded object')
|
||||
expect(JSON.stringify(block.runs?.map((r) => r.text))).toContain('ITEM NUMBER')
|
||||
expect(block.runs?.some((r) => r.image)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -118,6 +118,28 @@ describe('paragraph-level formatting (align / line spacing / indent)', () => {
|
||||
expect(hangingXml).toContain('<w:ind w:left="720" w:hanging="360"/>')
|
||||
})
|
||||
|
||||
it('round-trips negative indents (text extending into the margins)', async () => {
|
||||
// Word allows signed w:left/w:right; a rebuilt paragraph must not lose
|
||||
// them (they used to be dropped, shifting the paragraph on save — r116)
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:ind w:left="-284" w:right="-427"/></w:pPr>' +
|
||||
'<w:r><w:t>into the margins</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].format).toEqual({ indentLeft: -284, indentRight: -427 })
|
||||
|
||||
const negativeXml = generateParagraphXml(
|
||||
{
|
||||
type: 'paragraph',
|
||||
format: { indentLeft: -284, indentRight: -427 },
|
||||
runs: [{ text: 'a' }],
|
||||
},
|
||||
GEN_CTX,
|
||||
)
|
||||
expect(negativeXml).toContain('<w:ind w:left="-284" w:right="-427"/>')
|
||||
})
|
||||
|
||||
it('exposes exact/atLeast spacing as lineRawTwips+lineRule (F1)', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
|
||||
@@ -9,6 +9,8 @@ export interface BuildDocxOptions {
|
||||
bodyXml: string
|
||||
/** extra <w:style> entries appended to the default styles.xml */
|
||||
extraStylesXml?: string
|
||||
/** full word/styles.xml content, replacing the default (extraStylesXml ignored) */
|
||||
stylesXml?: string
|
||||
withNumbering?: boolean
|
||||
/** full word/numbering.xml content (implies withNumbering) */
|
||||
numberingXml?: string
|
||||
@@ -101,7 +103,10 @@ export async function buildDocx(options: BuildDocxOptions): Promise<Uint8Array>
|
||||
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${docRels}</Relationships>`,
|
||||
)
|
||||
|
||||
zip.file('word/styles.xml', `${STYLES_XML_OPEN}${options.extraStylesXml ?? ''}</w:styles>`)
|
||||
zip.file(
|
||||
'word/styles.xml',
|
||||
options.stylesXml ?? `${STYLES_XML_OPEN}${options.extraStylesXml ?? ''}</w:styles>`,
|
||||
)
|
||||
if (withNumbering) zip.file('word/numbering.xml', options.numberingXml ?? NUMBERING_XML)
|
||||
if (options.withImage) zip.file('word/media/image1.png', TINY_PNG_BASE64, { base64: true })
|
||||
for (const part of options.extraParts ?? []) zip.file(part.path, part.xml)
|
||||
|
||||
@@ -24,7 +24,17 @@ describe('image text wrap (wp:anchor)', () => {
|
||||
})
|
||||
|
||||
it('parses behind / topAndBottom / front variants', async () => {
|
||||
const behind = ANCHOR_SQUARE_RIGHT_XML.replace('behindDoc="0"', 'behindDoc="1"')
|
||||
// behind = behindDoc with NO wrap element; an explicit wrap element wins
|
||||
// (Word draws behindDoc+wrapSquare behind the text and still wraps around it)
|
||||
const behind = ANCHOR_SQUARE_RIGHT_XML.replace('behindDoc="0"', 'behindDoc="1"').replace(
|
||||
'<wp:wrapSquare wrapText="bothSides"/>',
|
||||
'<wp:wrapNone/>',
|
||||
)
|
||||
const behindWithWrap = ANCHOR_SQUARE_RIGHT_XML.replace('behindDoc="0"', 'behindDoc="1"')
|
||||
expect(
|
||||
(await parseDocx(await buildDocx({ bodyXml: behindWithWrap, withImage: true }))).blocks[0]
|
||||
.imageWrap,
|
||||
).toBe('square-right')
|
||||
const topBottom = ANCHOR_SQUARE_RIGHT_XML.replace(
|
||||
'<wp:wrapSquare wrapText="bothSides"/>',
|
||||
'<wp:wrapTopAndBottom/>',
|
||||
@@ -47,6 +57,64 @@ describe('image text wrap (wp:anchor)', () => {
|
||||
expect(inline.blocks[0].imageWrap).toBeUndefined()
|
||||
})
|
||||
|
||||
it('parses the picture outline (pic:spPr a:ln solid fill, tdf#162551)', async () => {
|
||||
const withLn = ANCHOR_SQUARE_RIGHT_XML.replace(
|
||||
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>',
|
||||
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill>' +
|
||||
'<pic:spPr><a:ln w="28575"><a:solidFill><a:srgbClr val="FFD428"/></a:solidFill></a:ln></pic:spPr></pic:pic>',
|
||||
)
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: withLn, withImage: true }))
|
||||
expect(doc.blocks[0].imageBorder).toEqual({ color: 'FFD428', widthPt: 2.25 })
|
||||
const noFill = withLn.replace(
|
||||
'<a:solidFill><a:srgbClr val="FFD428"/></a:solidFill>',
|
||||
'<a:noFill/>',
|
||||
)
|
||||
expect(
|
||||
(await parseDocx(await buildDocx({ bodyXml: noFill, withImage: true }))).blocks[0]
|
||||
.imageBorder,
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it('derives the float side from wrapText and far posOffset (tdf#97090)', async () => {
|
||||
const withPosH = (posH: string, wrapText = 'bothSides') =>
|
||||
ANCHOR_SQUARE_RIGHT_XML.replace(
|
||||
'<wp:positionH relativeFrom="column"><wp:align>right</wp:align></wp:positionH>',
|
||||
posH,
|
||||
).replace('wrapText="bothSides"', `wrapText="${wrapText}"`)
|
||||
const cases: Array<[string, string, string]> = [
|
||||
// text on the left only -> object floats right
|
||||
[
|
||||
'<wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH>',
|
||||
'left',
|
||||
'square-right',
|
||||
],
|
||||
// text on the right only -> object floats left even with a far offset
|
||||
[
|
||||
'<wp:positionH relativeFrom="column"><wp:posOffset>5000000</wp:posOffset></wp:positionH>',
|
||||
'right',
|
||||
'square-left',
|
||||
],
|
||||
// bothSides + absolute X past mid-body -> right
|
||||
[
|
||||
'<wp:positionH relativeFrom="column"><wp:posOffset>3187064</wp:posOffset></wp:positionH>',
|
||||
'bothSides',
|
||||
'square-right',
|
||||
],
|
||||
// bothSides + near X -> left
|
||||
[
|
||||
'<wp:positionH relativeFrom="column"><wp:posOffset>100000</wp:posOffset></wp:positionH>',
|
||||
'bothSides',
|
||||
'square-left',
|
||||
],
|
||||
]
|
||||
for (const [posH, wrapText, expected] of cases) {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({ bodyXml: withPosH(posH, wrapText), withImage: true }),
|
||||
)
|
||||
expect(doc.blocks[0].imageWrap, `${wrapText} ${posH}`).toBe(expected)
|
||||
}
|
||||
})
|
||||
|
||||
it('converts inline -> square anchor with position and wrap elements', () => {
|
||||
const out = applyImageWrap(IMAGE_PARAGRAPH_XML, 'square-left')
|
||||
expect(out).toContain('<wp:anchor')
|
||||
@@ -190,6 +258,34 @@ describe('tight / through wrap (wrapPolygon fidelity)', () => {
|
||||
expect(out).not.toContain('wp:wrapTight')
|
||||
})
|
||||
|
||||
it('displaces an allowOverlap="0" anchor colliding with a sibling (tdf#134114)', async () => {
|
||||
const anchorPic = (attrs: string, cx: number, cy: number) =>
|
||||
'<w:r><w:drawing>' +
|
||||
`<wp:anchor distT="0" distB="0" distL="114300" distR="114300" simplePos="0" relativeHeight="1" behindDoc="0" locked="0" layoutInCell="1" ${attrs}>` +
|
||||
'<wp:simplePos x="0" y="0"/>' +
|
||||
'<wp:positionH relativeFrom="column"><wp:align>center</wp:align></wp:positionH>' +
|
||||
'<wp:positionV relativeFrom="paragraph"><wp:posOffset>180340</wp:posOffset></wp:positionV>' +
|
||||
`<wp:extent cx="${cx}" cy="${cy}"/>` +
|
||||
'<wp:wrapSquare wrapText="bothSides"/>' +
|
||||
'<wp:docPr id="1" name="p"/>' +
|
||||
'<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
|
||||
'<pic:pic><pic:blipFill><a:blip r:embed="rId10"/></pic:blipFill></pic:pic>' +
|
||||
'</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>'
|
||||
const body =
|
||||
'<w:p>' +
|
||||
anchorPic('allowOverlap="1"', 802800, 1198800) +
|
||||
anchorPic('allowOverlap="0"', 1432800, 1076400) +
|
||||
'<w:r><w:t>No overlap in the frames, please.</w:t></w:r></w:p>'
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: body, withImage: true }))
|
||||
const imgs = (doc.blocks[0].runs ?? []).filter((r) => r.image)
|
||||
expect(imgs).toHaveLength(2)
|
||||
expect(imgs[0].image!.wrap).toBe('square-left')
|
||||
// the colliding allowOverlap="0" picture leaves the flow as a front overlay
|
||||
// under the collider's box
|
||||
expect(imgs[1].image!.wrap).toBe('front')
|
||||
expect(imgs[1].image!.offsetYEmu).toBe((126 + 2) * 9525)
|
||||
})
|
||||
|
||||
it('tight wrap round-trips through save + reparse', async () => {
|
||||
const bytes = await buildDocx({ bodyXml: tightXml, withImage: true })
|
||||
const parsed = await parseDocx(bytes)
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
const SETTINGS_CT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml'
|
||||
|
||||
const settingsPart = (inner: string) => ({
|
||||
path: 'word/settings.xml',
|
||||
xml:
|
||||
XML_DECL +
|
||||
`<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${inner}</w:settings>`,
|
||||
contentType: SETTINGS_CT,
|
||||
})
|
||||
|
||||
describe('w:t whitespace handling', () => {
|
||||
it('trims leading/trailing XML whitespace unless xml:space="preserve"', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:t>\n\t\t\tL1: \n\t\t</w:t></w:r>' +
|
||||
'<w:r><w:t>\n \t\tcancelled\n\t</w:t></w:r>' +
|
||||
'<w:r><w:t xml:space="preserve"> kept </w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].runs!.map((r) => r.text).join('')).toBe('L1:cancelled kept ')
|
||||
})
|
||||
})
|
||||
|
||||
describe('hex color tolerance', () => {
|
||||
it("accepts a leading '#' on w:color and w:shd fills (tdf#57589)", async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:shd w:val="clear" w:fill="#e6e6e6"/></w:pPr>' +
|
||||
'<w:r><w:rPr><w:color w:val="#004080"/><w:shd w:val="clear" w:fill="#ff00ff"/></w:rPr>' +
|
||||
'<w:t>colored</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.blocks[0].format?.shadingFill).toBe('e6e6e6')
|
||||
expect(doc.blocks[0].runs![0].color).toBe('004080')
|
||||
expect(doc.blocks[0].runs![0].shading).toBe('ff00ff')
|
||||
})
|
||||
})
|
||||
|
||||
describe('default style resolution', () => {
|
||||
it('the last w:default="1" paragraph style wins', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
|
||||
extraStylesXml:
|
||||
'<w:style w:type="paragraph" w:default="1" w:styleId="Title"><w:name w:val="Title"/>' +
|
||||
'<w:rPr><w:b/><w:sz w:val="56"/></w:rPr></w:style>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
const defaults = [...doc.styles.values()].filter((s) => s.isDefault && s.type === 'paragraph')
|
||||
expect(defaults.map((s) => s.styleId)).toEqual(['Title'])
|
||||
})
|
||||
|
||||
it('without any w:default, the first style of the type is the default', async () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
|
||||
stylesXml:
|
||||
XML_DECL +
|
||||
'<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||
'<w:style w:type="paragraph" w:styleId="Normal"><w:name w:val="Normal"/>' +
|
||||
'<w:rPr><w:color w:val="FF00FF"/><w:sz w:val="48"/></w:rPr></w:style>' +
|
||||
'<w:style w:type="paragraph" w:styleId="MyStyle"><w:name w:val="MyStyle"/></w:style>' +
|
||||
'</w:styles>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
const defaults = [...doc.styles.values()].filter((s) => s.isDefault && s.type === 'paragraph')
|
||||
expect(defaults.map((s) => s.styleId)).toEqual(['Normal'])
|
||||
expect(defaults[0].display?.color).toBe('FF00FF')
|
||||
})
|
||||
})
|
||||
|
||||
describe('settings.xml layout flags', () => {
|
||||
it('parses w:autoHyphenation and w:defaultTabStop (including 0)', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
|
||||
extraParts: [settingsPart('<w:autoHyphenation/><w:defaultTabStop w:val="0"/>')],
|
||||
}),
|
||||
)
|
||||
expect(doc.autoHyphenation).toBe(true)
|
||||
expect(doc.defaultTabStopTwips).toBe(0)
|
||||
})
|
||||
|
||||
it('leaves both unset without a settings part', async () => {
|
||||
const doc = await parseDocx(await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' }))
|
||||
expect(doc.autoHyphenation).toBeUndefined()
|
||||
expect(doc.defaultTabStopTwips).toBeUndefined()
|
||||
})
|
||||
|
||||
it('w:autoHyphenation w:val="false" counts as off', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>',
|
||||
extraParts: [
|
||||
settingsPart('<w:autoHyphenation w:val="false"/><w:defaultTabStop w:val="709"/>'),
|
||||
],
|
||||
}),
|
||||
)
|
||||
expect(doc.autoHyphenation).toBeUndefined()
|
||||
expect(doc.defaultTabStopTwips).toBe(709)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,58 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx, type SaveBlock } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
|
||||
/** Rename the main part to word/trial.xml the way LO's tdf104713 sample does. */
|
||||
async function withRenamedMainPart(bytes: Uint8Array): Promise<Uint8Array> {
|
||||
const zip = await JSZip.loadAsync(bytes)
|
||||
const move = async (from: string, to: string) => {
|
||||
const data = await zip.file(from)!.async('uint8array')
|
||||
zip.remove(from)
|
||||
zip.file(to, data)
|
||||
}
|
||||
await move('word/document.xml', 'word/trial.xml')
|
||||
await move('word/_rels/document.xml.rels', 'word/_rels/trial.xml.rels')
|
||||
for (const meta of ['_rels/.rels', '[Content_Types].xml']) {
|
||||
const xml = await zip.file(meta)!.async('string')
|
||||
zip.file(meta, xml.replaceAll('word/document.xml', 'word/trial.xml'))
|
||||
}
|
||||
return zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE' })
|
||||
}
|
||||
|
||||
describe('nonstandard main document part', () => {
|
||||
it('parses when the officeDocument relationship targets word/trial.xml', async () => {
|
||||
const bytes = await withRenamedMainPart(
|
||||
await buildDocx({ bodyXml: '<w:p><w:r><w:t>trial part text</w:t></w:r></w:p>' }),
|
||||
)
|
||||
const doc = await parseDocx(bytes)
|
||||
const allText = JSON.stringify(doc.blocks)
|
||||
expect(allText).toContain('trial part text')
|
||||
})
|
||||
|
||||
it('save writes the edited XML into the renamed part', async () => {
|
||||
const bytes = await withRenamedMainPart(
|
||||
await buildDocx({ bodyXml: '<w:p><w:r><w:t>before edit</w:t></w:r></w:p>' }),
|
||||
)
|
||||
const doc = await parseDocx(bytes)
|
||||
const finalBlocks: SaveBlock[] = [
|
||||
{ kind: 'generated', block: { type: 'paragraph', runs: [{ text: 'after edit' }] } },
|
||||
]
|
||||
const saved = await saveDocx(doc, finalBlocks)
|
||||
const zip = await JSZip.loadAsync(saved)
|
||||
expect(zip.file('word/document.xml')).toBeNull()
|
||||
const xml = await zip.file('word/trial.xml')!.async('string')
|
||||
expect(xml).toContain('after edit')
|
||||
expect(xml).not.toContain('before edit')
|
||||
})
|
||||
|
||||
it('rejects an ODT masquerading as .docx with a clear error', async () => {
|
||||
const zip = new JSZip()
|
||||
zip.file('mimetype', 'application/vnd.oasis.opendocument.text')
|
||||
zip.file('content.xml', `${XML_DECL}<office:document-content/>`)
|
||||
const bytes = await zip.generateAsync({ type: 'uint8array' })
|
||||
await expect(parseDocx(bytes)).rejects.toThrow(/OpenDocument/)
|
||||
})
|
||||
})
|
||||
@@ -182,9 +182,13 @@ describe('ommlToLatex', () => {
|
||||
|
||||
it('returns null for structures outside the subset', () => {
|
||||
expect(
|
||||
ommlToLatex('<m:oMath><m:sPre><m:sub><m:r><m:t>a</m:t></m:r></m:sub><m:e><m:r><m:t>X</m:t></m:r></m:e></m:sPre></m:oMath>'),
|
||||
ommlToLatex(
|
||||
'<m:oMath><m:sPre><m:sub><m:r><m:t>a</m:t></m:r></m:sub><m:e><m:r><m:t>X</m:t></m:r></m:e></m:sPre></m:oMath>',
|
||||
),
|
||||
).toBeNull()
|
||||
expect(
|
||||
ommlToLatex(`<m:oMath>${latexToOmml('a')}</m:oMath><m:oMath>${latexToOmml('b')}</m:oMath>`),
|
||||
).toBeNull()
|
||||
expect(ommlToLatex(`<m:oMath>${latexToOmml('a')}</m:oMath><m:oMath>${latexToOmml('b')}</m:oMath>`)).toBeNull()
|
||||
})
|
||||
|
||||
it('escapes parser-special characters', () => {
|
||||
@@ -206,7 +210,7 @@ describe('formula parse + save integration', () => {
|
||||
})
|
||||
|
||||
it('parses paragraphs mixing math and text into editable runs with math runs', async () => {
|
||||
const mixed = `<w:p><w:r><w:t>see </w:t></w:r>${FRACTION_OMATH}<w:r><w:t> here</w:t></w:r></w:p>`
|
||||
const mixed = `<w:p><w:r><w:t xml:space="preserve">see </w:t></w:r>${FRACTION_OMATH}<w:r><w:t xml:space="preserve"> here</w:t></w:r></w:p>`
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: mixed }))
|
||||
const block = parsed.blocks[0]
|
||||
expect(block.type).toBe('paragraph')
|
||||
@@ -215,7 +219,7 @@ describe('formula parse + save integration', () => {
|
||||
})
|
||||
|
||||
it('a mixed paragraph regenerates with the math run emitted verbatim', async () => {
|
||||
const mixed = `<w:p><w:r><w:t>see </w:t></w:r>${FRACTION_OMATH}</w:p>`
|
||||
const mixed = `<w:p><w:r><w:t xml:space="preserve">see </w:t></w:r>${FRACTION_OMATH}</w:p>`
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: mixed }))
|
||||
const block = parsed.blocks[0]
|
||||
const bytes = await saveDocx(parsed, [
|
||||
@@ -242,7 +246,9 @@ describe('formula parse + save integration', () => {
|
||||
})
|
||||
|
||||
it('an inserted equation paragraph survives save and reparse', async () => {
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: '<w:p><w:r><w:t>hi</w:t></w:r></w:p>' }))
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({ bodyXml: '<w:p><w:r><w:t>hi</w:t></w:r></w:p>' }),
|
||||
)
|
||||
const omml = latexToOmml('a^2 + b^2 = c^2')
|
||||
const bytes = await saveDocx(parsed, [
|
||||
{ kind: 'original', docxIndex: parsed.blocks[0].docxIndex! },
|
||||
|
||||
@@ -54,3 +54,20 @@ describe('w:br outside a w:r (Word honors these; tdf108714 family)', () => {
|
||||
expect(box.fieldDisplay?.kind).toBe('pageBreak')
|
||||
})
|
||||
})
|
||||
|
||||
describe('column breaks (w:br w:type="column")', () => {
|
||||
it('parses to \\v and round-trips through save (fdo#74153)', async () => {
|
||||
const { saveDocx } = await import('../src/index')
|
||||
const source = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>col one</w:t><w:br w:type="column"/><w:t>col two</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(source)
|
||||
expect(doc.blocks[0].runs?.[0].text).toBe('col one\vcol two')
|
||||
const saved = await saveDocx(doc, [
|
||||
{ kind: 'generated', block: { type: 'paragraph', runs: doc.blocks[0].runs! } },
|
||||
])
|
||||
const { loadDocxZip } = await import('../src/zip-load')
|
||||
const xml = await (await loadDocxZip(saved)).file('word/document.xml')!.async('string')
|
||||
expect(xml).toContain('<w:br w:type="column"/>')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -167,6 +167,23 @@ describe('style-level pageBreakBefore', () => {
|
||||
// style-level value must not leak into paragraph format (would be saved as redundant pPr)
|
||||
expect(doc.blocks[0].format?.pageBreakBefore).toBeUndefined()
|
||||
})
|
||||
|
||||
it('an explicit w:val="0" overrides an inherited true (fdo#45183)', async () => {
|
||||
const bytes = await buildDocx({
|
||||
extraStylesXml:
|
||||
'<w:style w:type="paragraph" w:styleId="ChapterTitle"><w:name w:val="Chapter Title"/>' +
|
||||
'<w:pPr><w:pageBreakBefore/></w:pPr></w:style>' +
|
||||
'<w:style w:type="paragraph" w:styleId="NoBreak"><w:name w:val="No Break"/>' +
|
||||
'<w:basedOn w:val="ChapterTitle"/><w:pPr><w:pageBreakBefore w:val="0"/></w:pPr></w:style>',
|
||||
bodyXml:
|
||||
'<w:p><w:pPr><w:pStyle w:val="ChapterTitle"/><w:pageBreakBefore w:val="0"/></w:pPr>' +
|
||||
'<w:r><w:t>off</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
expect(doc.styles.get('NoBreak')?.display?.pageBreakBefore).toBe(false)
|
||||
// direct-format off must survive so it can veto the style chain's true
|
||||
expect(doc.blocks[0].format?.pageBreakBefore).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('empty paragraph line size', () => {
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import JSZip from 'jszip'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseDocx, saveDocx, type SaveBlock } from '../src/index'
|
||||
import { IMAGE_PARAGRAPH_XML, TINY_PNG_BASE64, buildDocx } from './helpers/build-docx'
|
||||
|
||||
const IMAGE_REL_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'
|
||||
|
||||
function originalBlocksWithout(
|
||||
parsed: Awaited<ReturnType<typeof parseDocx>>,
|
||||
excluded: (block: Awaited<ReturnType<typeof parseDocx>>['blocks'][number]) => boolean,
|
||||
): SaveBlock[] {
|
||||
return parsed.blocks
|
||||
.filter((block) => !block.hidden && !excluded(block))
|
||||
.map((block) => ({ kind: 'original', docxIndex: block.docxIndex! }))
|
||||
}
|
||||
|
||||
async function documentRels(zip: JSZip): Promise<string> {
|
||||
return zip.file('word/_rels/document.xml.rels')!.async('string')
|
||||
}
|
||||
|
||||
function mediaPaths(zip: JSZip): string[] {
|
||||
return Object.keys(zip.files).filter(
|
||||
(path) => /^word\/media\/[^/]+$/.test(path) && !zip.files[path].dir,
|
||||
)
|
||||
}
|
||||
|
||||
describe('DOCX-owned resource cleanup', () => {
|
||||
it('removes the relationship and media part when an image block is deleted', async () => {
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML, withImage: true }),
|
||||
)
|
||||
const zip = await JSZip.loadAsync(await saveDocx(parsed, []))
|
||||
expect(zip.file('word/media/image1.png')).toBeNull()
|
||||
expect(await documentRels(zip)).not.toContain('media/image1.png')
|
||||
})
|
||||
|
||||
it('keeps only the newest media part across repeated image replacements', async () => {
|
||||
let bytes = await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML, withImage: true })
|
||||
for (let replacement = 0; replacement < 3; replacement++) {
|
||||
const parsed = await parseDocx(bytes)
|
||||
const image = parsed.blocks.find((block) => block.type === 'image')!
|
||||
bytes = await saveDocx(parsed, [
|
||||
{
|
||||
kind: 'xml',
|
||||
xml: image.originalXml!,
|
||||
docxIndex: image.docxIndex!,
|
||||
replaceImage: { base64: TINY_PNG_BASE64, mime: 'image/png' },
|
||||
},
|
||||
])
|
||||
const zip = await JSZip.loadAsync(bytes)
|
||||
expect(mediaPaths(zip)).toHaveLength(1)
|
||||
expect(
|
||||
(await documentRels(zip)).match(new RegExp(`Type="${IMAGE_REL_TYPE}"`, 'g')),
|
||||
).toHaveLength(1)
|
||||
}
|
||||
const finalZip = await JSZip.loadAsync(bytes)
|
||||
expect(mediaPaths(finalZip)).toEqual(['word/media/aidocs3.png'])
|
||||
})
|
||||
|
||||
it('retains a shared image target while another surviving block still references it', async () => {
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: IMAGE_PARAGRAPH_XML + IMAGE_PARAGRAPH_XML,
|
||||
withImage: true,
|
||||
}),
|
||||
)
|
||||
const zip = await JSZip.loadAsync(await saveDocx(parsed, [{ kind: 'original', docxIndex: 1 }]))
|
||||
expect(zip.file('word/media/image1.png')).not.toBeNull()
|
||||
expect(await documentRels(zip)).toContain('media/image1.png')
|
||||
})
|
||||
|
||||
it('retains an image target referenced by a surviving header part', async () => {
|
||||
const sourceZip = await JSZip.loadAsync(
|
||||
await buildDocx({
|
||||
bodyXml: IMAGE_PARAGRAPH_XML,
|
||||
withImage: true,
|
||||
extraRels:
|
||||
'<Relationship Id="rId20" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/header1.xml',
|
||||
xml:
|
||||
'<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' +
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' +
|
||||
IMAGE_PARAGRAPH_XML +
|
||||
'</w:hdr>',
|
||||
contentType:
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
|
||||
},
|
||||
],
|
||||
sectPrExtra: '<w:headerReference w:type="default" r:id="rId20"/>',
|
||||
}),
|
||||
)
|
||||
sourceZip.file(
|
||||
'word/_rels/header1.xml.rels',
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
||||
`<Relationship Id="rId10" Type="${IMAGE_REL_TYPE}" Target="media/image1.png"/>` +
|
||||
'</Relationships>',
|
||||
)
|
||||
const parsed = await parseDocx(await sourceZip.generateAsync({ type: 'uint8array' }))
|
||||
const zip = await JSZip.loadAsync(
|
||||
await saveDocx(
|
||||
parsed,
|
||||
originalBlocksWithout(parsed, (block) => block.type === 'image'),
|
||||
),
|
||||
)
|
||||
expect(zip.file('word/media/image1.png')).not.toBeNull()
|
||||
expect(await documentRels(zip)).not.toContain('media/image1.png')
|
||||
expect(await zip.file('word/_rels/header1.xml.rels')!.async('string')).toContain(
|
||||
'media/image1.png',
|
||||
)
|
||||
})
|
||||
|
||||
it('removes an external hyperlink relationship after its link is removed', async () => {
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:hyperlink r:id="rId20"><w:r><w:t>linked</w:t></w:r></w:hyperlink>' +
|
||||
'<w:r><w:t xml:space="preserve"> tail</w:t></w:r></w:p>',
|
||||
extraRels:
|
||||
'<Relationship Id="rId20" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" ' +
|
||||
'Target="https://example.com/" TargetMode="External"/>',
|
||||
}),
|
||||
)
|
||||
const zip = await JSZip.loadAsync(
|
||||
await saveDocx(parsed, [
|
||||
{
|
||||
kind: 'generated',
|
||||
block: { type: 'paragraph', runs: [{ text: 'linked' }, { text: ' tail' }] },
|
||||
},
|
||||
]),
|
||||
)
|
||||
const rels = await documentRels(zip)
|
||||
expect(rels).not.toContain('relationships/hyperlink')
|
||||
expect(rels).not.toContain('https://example.com/')
|
||||
})
|
||||
|
||||
it('removes a deleted chart and its relationship/workbook subgraph and overrides', async () => {
|
||||
const source = await buildDocx({
|
||||
bodyXml: '<w:p><w:r><w:t>keep</w:t></w:r></w:p>',
|
||||
})
|
||||
const parsed = await parseDocx(source)
|
||||
const withChart = await saveDocx(parsed, [
|
||||
{ kind: 'original', docxIndex: 0 },
|
||||
{
|
||||
kind: 'chart',
|
||||
chart: {
|
||||
kind: 'bar',
|
||||
title: 'Sales',
|
||||
categories: ['Q1', 'Q2'],
|
||||
series: [{ name: 'East', values: [1, 2] }],
|
||||
},
|
||||
},
|
||||
])
|
||||
const chartDoc = await parseDocx(withChart)
|
||||
const saved = await saveDocx(
|
||||
chartDoc,
|
||||
originalBlocksWithout(chartDoc, (block) => block.chartDisplay !== undefined),
|
||||
)
|
||||
const zip = await JSZip.loadAsync(saved)
|
||||
expect(zip.file('word/charts/chart1.xml')).toBeNull()
|
||||
expect(zip.file('word/charts/_rels/chart1.xml.rels')).toBeNull()
|
||||
expect(zip.file('word/charts/embeddings/workbook1.xlsx')).toBeNull()
|
||||
expect(await documentRels(zip)).not.toContain('relationships/chart')
|
||||
const contentTypes = await zip.file('[Content_Types].xml')!.async('string')
|
||||
expect(contentTypes).not.toContain('/word/charts/chart1.xml')
|
||||
expect(contentTypes).not.toContain('/word/charts/embeddings/workbook1.xlsx')
|
||||
})
|
||||
|
||||
it('cleans image resources owned by a deleted table block', async () => {
|
||||
const tableWithImage =
|
||||
'<w:tbl><w:tr><w:tc><w:p><w:r><w:drawing><wp:inline>' +
|
||||
'<a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="rId10"/>' +
|
||||
'</pic:blipFill></pic:pic></a:graphicData></a:graphic>' +
|
||||
'</wp:inline></w:drawing></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: tableWithImage, withImage: true }))
|
||||
expect(parsed.blocks[0].type).toBe('table')
|
||||
const zip = await JSZip.loadAsync(await saveDocx(parsed, []))
|
||||
expect(zip.file('word/media/image1.png')).toBeNull()
|
||||
expect(await documentRels(zip)).not.toContain('media/image1.png')
|
||||
})
|
||||
|
||||
it('cleans explicit OLE and diagram resources but preserves unknown custom parts', async () => {
|
||||
const bodyXml =
|
||||
'<w:p><w:r><w:object><v:shape><v:imagedata r:id="rId10"/></v:shape>' +
|
||||
'<o:OLEObject r:id="rId40" Type="Embed" ProgID="Package"/></w:object></w:r></w:p>' +
|
||||
'<w:p><w:r><w:drawing><wp:inline><a:graphic><a:graphicData>' +
|
||||
'<dgm:relIds r:dm="rId41"/></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>' +
|
||||
'<w:p><w:r><w:drawing><wp:inline><a:graphic><a:graphicData>' +
|
||||
'<c:chart r:id="rId42"/></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>'
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml,
|
||||
withImage: true,
|
||||
extraRels:
|
||||
'<Relationship Id="rId40" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject" Target="embeddings/oleObject1.bin"/>' +
|
||||
'<Relationship Id="rId41" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramData" Target="diagrams/data1.xml"/>' +
|
||||
'<Relationship Id="rId42" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart" Target="../customXml/custom-chart.xml"/>',
|
||||
extraParts: [
|
||||
{
|
||||
path: 'word/diagrams/data1.xml',
|
||||
xml: '<dgm:dataModel/>',
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml',
|
||||
},
|
||||
{
|
||||
path: 'customXml/custom-chart.xml',
|
||||
xml: '<custom:extension/>',
|
||||
contentType: 'application/vnd.example.custom+xml',
|
||||
},
|
||||
],
|
||||
binaryParts: [
|
||||
{
|
||||
path: 'word/embeddings/oleObject1.bin',
|
||||
base64: TINY_PNG_BASE64,
|
||||
extension: 'bin',
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.oleObject',
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
const zip = await JSZip.loadAsync(await saveDocx(parsed, []))
|
||||
expect(zip.file('word/media/image1.png')).toBeNull()
|
||||
expect(zip.file('word/embeddings/oleObject1.bin')).toBeNull()
|
||||
expect(zip.file('word/diagrams/data1.xml')).toBeNull()
|
||||
expect(zip.file('customXml/custom-chart.xml')).not.toBeNull()
|
||||
const contentTypes = await zip.file('[Content_Types].xml')!.async('string')
|
||||
expect(contentTypes).not.toContain('/word/diagrams/data1.xml')
|
||||
expect(contentTypes).toContain('/customXml/custom-chart.xml')
|
||||
})
|
||||
})
|
||||
@@ -60,6 +60,46 @@ describe('readSections enumerates all sections', () => {
|
||||
expect(sections[1].firstBlockIndex).toBe(sections[0].lastBlockIndex + 1)
|
||||
})
|
||||
|
||||
it('a section-break paragraph with visible text stays an editable paragraph (tdf#159032)', async () => {
|
||||
const withText =
|
||||
'<w:p><w:pPr><w:spacing w:after="0"/><w:sectPr>' +
|
||||
'<w:pgSz w:w="11906" w:h="16838"/></w:sectPr></w:pPr>' +
|
||||
'<w:r><w:t>section one tail</w:t></w:r></w:p>'
|
||||
const source = await buildDocx({ bodyXml: P('a') + withText + P('b') })
|
||||
const parsed = await parseDocx(source)
|
||||
const blk = parsed.blocks[1]
|
||||
expect(blk.type).toBe('paragraph')
|
||||
expect(blk.runs).toEqual([{ text: 'section one tail' }])
|
||||
expect(blk.rawPPr).toContain('<w:sectPr')
|
||||
// section boundary still closes at this block
|
||||
const sections = readSections(parsed)
|
||||
expect(sections.length).toBe(2)
|
||||
expect(sections[0].lastBlockIndex).toBe(1)
|
||||
|
||||
// unedited: byte-identical
|
||||
const visible = parsed.blocks.filter((b) => !b.hidden).map((b) => b.docxIndex!)
|
||||
const asIs: SaveBlock[] = visible.map((docxIndex) => ({ kind: 'original', docxIndex }))
|
||||
expect(await saveDocx(parsed, asIs)).toBe(source)
|
||||
|
||||
// edited text: the sectPr must survive regeneration
|
||||
const edited: SaveBlock[] = visible.map((docxIndex) =>
|
||||
docxIndex === blk.docxIndex
|
||||
? {
|
||||
kind: 'generated',
|
||||
block: {
|
||||
type: 'paragraph',
|
||||
rawPPr: blk.rawPPr,
|
||||
runs: [{ text: 'edited tail' }],
|
||||
},
|
||||
}
|
||||
: { kind: 'original', docxIndex },
|
||||
)
|
||||
const saved = await saveDocx(parsed, edited)
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(readSections(reparsed).length).toBe(2)
|
||||
expect(JSON.stringify(reparsed.blocks)).toContain('edited tail')
|
||||
})
|
||||
|
||||
it('parses startType/titlePg/pgNumType/header-footer references per section', async () => {
|
||||
const extra =
|
||||
'<w:headerReference w:type="default" r:id="rId7"/>' +
|
||||
|
||||
@@ -88,6 +88,29 @@ describe('textless preset shapes render as display boxes', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('pattern-filled rectangles (dml-shape-fillpattern)', () => {
|
||||
it('a textless full-height rect with a:pattFill renders with its foreground color', async () => {
|
||||
const patt =
|
||||
'<a:pattFill prst="ltHorz"><a:fgClr><a:srgbClr val="9BFF66"/></a:fgClr>' +
|
||||
'<a:bgClr><a:srgbClr val="FFFFFF"/></a:bgClr></a:pattFill>'
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: anchorParagraph(wsp({ prst: 'rect', cx: 1905000, cy: 794520, ln: patt })),
|
||||
}),
|
||||
)
|
||||
const box = doc.blocks[0].textboxes?.[0]
|
||||
expect(box).toBeTruthy()
|
||||
expect(box!.fill).toBe('9BFF66')
|
||||
})
|
||||
|
||||
it('a near-flat textless rect stays on the decorative thin-rule path', async () => {
|
||||
const doc = await parseDocx(
|
||||
await buildDocx({ bodyXml: anchorParagraph(wsp({ prst: 'rect', cx: 1905000, cy: 9525 })) }),
|
||||
)
|
||||
expect(doc.blocks[0].textboxes).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('anchored connectors', () => {
|
||||
it('a flipV straightConnector with a tail arrow renders as a diagonal lineArrow', async () => {
|
||||
const doc = await parseDocx(
|
||||
|
||||
@@ -71,7 +71,7 @@ describe('symbol runs in document.xml', () => {
|
||||
const bytes = await buildDocx({
|
||||
bodyXml:
|
||||
'<w:p><w:r><w:rPr><w:rFonts w:ascii="Symbol" w:hAnsi="Symbol"/></w:rPr><w:t></w:t></w:r>' +
|
||||
'<w:r><w:t> 后文</w:t></w:r></w:p>',
|
||||
'<w:r><w:t xml:space="preserve"> 后文</w:t></w:r></w:p>',
|
||||
})
|
||||
const doc = await parseDocx(bytes)
|
||||
const run = doc.blocks[0].runs![0]
|
||||
|
||||
@@ -257,6 +257,32 @@ describe('duplicated border containers merge per side, later wins', () => {
|
||||
expect(cell.borders?.top).toEqual({ style: 'nil' })
|
||||
})
|
||||
|
||||
it('w:tblpPr marks a floating table with its wrap side (tdf#97090)', async () => {
|
||||
const wrap = (tblpPr: string) =>
|
||||
`<w:tbl><w:tblPr>${tblpPr}</w:tblPr><w:tblGrid><w:gridCol w:w="3000"/></w:tblGrid>` +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>x</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||
const right = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: wrap('<w:tblpPr w:horzAnchor="margin" w:tblpXSpec="right" w:vertAnchor="text"/>'),
|
||||
}),
|
||||
)
|
||||
expect(right.blocks[0].table!.floatSide).toBe('right')
|
||||
const farX = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: wrap('<w:tblpPr w:vertAnchor="text" w:horzAnchor="page" w:tblpX="7523"/>'),
|
||||
}),
|
||||
)
|
||||
expect(farX.blocks[0].table!.floatSide).toBe('right')
|
||||
const nearX = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: wrap('<w:tblpPr w:vertAnchor="text" w:tblpX="100" w:tblpY="10"/>'),
|
||||
}),
|
||||
)
|
||||
expect(nearX.blocks[0].table!.floatSide).toBe('left')
|
||||
const plain = await parseDocx(await buildDocx({ bodyXml: wrap('') }))
|
||||
expect(plain.blocks[0].table!.floatSide).toBeUndefined()
|
||||
})
|
||||
|
||||
it('a second w:tblBorders overrides the sides of the first one', async () => {
|
||||
const xml =
|
||||
'<w:tbl><w:tblPr>' +
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
/**
|
||||
* w:writeProtection (password to modify) and w:removePersonalInformation
|
||||
* (anonymize authors on save) — parse / patch round-trips and the save-time
|
||||
* author scrub.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import JSZip from 'jszip'
|
||||
import { hashProtectionPassword, parseDocx, saveDocx, verifyProtectionPassword } from '../src/index'
|
||||
import { buildDocx } from './helpers/build-docx'
|
||||
|
||||
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||
|
||||
function originalBlocks(parsed: Awaited<ReturnType<typeof parseDocx>>) {
|
||||
return parsed.blocks
|
||||
.filter((b) => !b.hidden && b.docxIndex !== null)
|
||||
.map((b) => ({ kind: 'original' as const, docxIndex: b.docxIndex! }))
|
||||
}
|
||||
|
||||
describe('writeProtection (password to modify)', () => {
|
||||
it('round-trips: saved credentials verify the right password and land in settings.xml', async () => {
|
||||
const creds = await hashProtectionPassword('m0dify', 1000)
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' }),
|
||||
)
|
||||
expect(parsed.writeProtection).toBeNull()
|
||||
const restriction = await hashProtectionPassword('restrict', 1000)
|
||||
const saved = await saveDocx(parsed, originalBlocks(parsed), {
|
||||
writeProtection: creds,
|
||||
protection: { edit: 'trackedChanges', enforced: true, ...restriction },
|
||||
})
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.writeProtection).toMatchObject({ spinCount: 1000, algorithmSid: 14 })
|
||||
expect(reparsed.writeProtection?.hash).toBe(creds.hash)
|
||||
expect(await verifyProtectionPassword('m0dify', reparsed.writeProtection!)).toBe(true)
|
||||
expect(await verifyProtectionPassword('nope', reparsed.writeProtection!)).toBe(false)
|
||||
expect(reparsed.protection?.edit).toBe('trackedChanges')
|
||||
|
||||
// CT_Settings sequence: writeProtection must come before documentProtection
|
||||
const settings = await (await JSZip.loadAsync(saved)).file('word/settings.xml')!.async('string')
|
||||
expect(settings.indexOf('<w:writeProtection')).toBeGreaterThan(-1)
|
||||
expect(settings.indexOf('<w:writeProtection')).toBeLessThan(
|
||||
settings.indexOf('<w:documentProtection'),
|
||||
)
|
||||
})
|
||||
|
||||
it('null removes an existing writeProtection', async () => {
|
||||
const creds = await hashProtectionPassword('m0dify', 1000)
|
||||
const first = await parseDocx(
|
||||
await buildDocx({ bodyXml: '<w:p><w:r><w:t>x</w:t></w:r></w:p>' }),
|
||||
)
|
||||
const withWp = await parseDocx(
|
||||
await saveDocx(first, originalBlocks(first), { writeProtection: creds }),
|
||||
)
|
||||
expect(withWp.writeProtection?.hash).toBe(creds.hash)
|
||||
const removed = await parseDocx(
|
||||
await saveDocx(withWp, originalBlocks(withWp), { writeProtection: null }),
|
||||
)
|
||||
expect(removed.writeProtection).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('removePersonalInformation', () => {
|
||||
const bodyWithRevision =
|
||||
'<w:p><w:ins w:id="1" w:author="张三" w:date="2026-01-01T00:00:00Z">' +
|
||||
'<w:r><w:t>inserted</w:t></w:r></w:ins></w:p>'
|
||||
|
||||
const commentsPart = {
|
||||
path: 'word/comments.xml',
|
||||
xml:
|
||||
`${XML_DECL}<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">` +
|
||||
'<w:comment w:id="0" w:author="张三" w:initials="ZS"><w:p><w:r><w:t>hi</w:t></w:r></w:p></w:comment>' +
|
||||
'</w:comments>',
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml',
|
||||
}
|
||||
const commentsRel =
|
||||
'<Relationship Id="rId40" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>'
|
||||
|
||||
const corePart = {
|
||||
path: 'docProps/core.xml',
|
||||
xml:
|
||||
`${XML_DECL}<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" ` +
|
||||
'xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/">' +
|
||||
'<dc:creator>张三</dc:creator><cp:lastModifiedBy>李四</cp:lastModifiedBy>' +
|
||||
'<dcterms:modified xsi:type="dcterms:W3CDTF" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">2026-01-01T00:00:00Z</dcterms:modified>' +
|
||||
'</cp:coreProperties>',
|
||||
contentType: 'application/vnd.openxmlformats-package.core-properties+xml',
|
||||
}
|
||||
|
||||
it('flag round-trips and scrubs revision/comment authors and core props on save', async () => {
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: bodyWithRevision,
|
||||
extraRels: commentsRel,
|
||||
extraParts: [commentsPart, corePart],
|
||||
}),
|
||||
)
|
||||
expect(parsed.removePersonalInfo).toBe(false)
|
||||
const saved = await saveDocx(parsed, originalBlocks(parsed), { removePersonalInfo: true })
|
||||
const reparsed = await parseDocx(saved)
|
||||
expect(reparsed.removePersonalInfo).toBe(true)
|
||||
|
||||
const zip = await JSZip.loadAsync(saved)
|
||||
const docXml = await zip.file('word/document.xml')!.async('string')
|
||||
expect(docXml).toContain('w:author="Author"')
|
||||
expect(docXml).not.toContain('张三')
|
||||
// comments.xml is scrubbed even though comments were not edited
|
||||
const commentsXml = await zip.file('word/comments.xml')!.async('string')
|
||||
expect(commentsXml).toContain('w:author="Author"')
|
||||
expect(commentsXml).toContain('w:initials="A"')
|
||||
expect(commentsXml).not.toContain('张三')
|
||||
const coreXml = await zip.file('docProps/core.xml')!.async('string')
|
||||
expect(coreXml).toContain('<dc:creator></dc:creator>')
|
||||
expect(coreXml).toContain('<cp:lastModifiedBy></cp:lastModifiedBy>')
|
||||
})
|
||||
|
||||
it('scrubs all known metadata after copy-through assembly without touching document data', async () => {
|
||||
const wml = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
|
||||
const extraParts = [
|
||||
{
|
||||
path: 'word/comments.xml',
|
||||
xml:
|
||||
`${XML_DECL}<c:comments xmlns:c='${wml}'>` +
|
||||
"<c:comment c:id='comment-7' c:author='Comment Person' c:initials='CP' c:date='2024-03-01T02:03:04Z'>" +
|
||||
'<c:p><c:r><c:t>Comment Person remains as comment text</c:t></c:r></c:p>' +
|
||||
'</c:comment></c:comments>',
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml',
|
||||
},
|
||||
{
|
||||
path: 'word/header1.xml',
|
||||
xml:
|
||||
`${XML_DECL}<h:hdr xmlns:h="${wml}">` +
|
||||
'<h:p><h:ins h:id="header-rev" h:author="Header Person" h:date="2024-03-02T02:03:04Z">' +
|
||||
'<h:r><h:t>Header content</h:t></h:r></h:ins></h:p></h:hdr>',
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml',
|
||||
},
|
||||
{
|
||||
path: 'word/footer1.xml',
|
||||
xml:
|
||||
`${XML_DECL}<f:ftr xmlns:f='${wml}'>` +
|
||||
"<f:p><f:del f:id='footer-rev' f:author='Footer Person' f:date='2024-03-03T02:03:04Z'>" +
|
||||
'<f:r><f:delText>Footer content</f:delText></f:r></f:del></f:p></f:ftr>',
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml',
|
||||
},
|
||||
{
|
||||
path: 'word/footnotes.xml',
|
||||
xml:
|
||||
`${XML_DECL}<n:footnotes xmlns:n="${wml}">` +
|
||||
'<n:footnote n:id="2"><n:p><n:ins n:id="foot-rev" n:author="Foot Person" n:date="2024-03-04T02:03:04Z">' +
|
||||
'<n:r><n:t>Footnote content</n:t></n:r></n:ins></n:p></n:footnote></n:footnotes>',
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml',
|
||||
},
|
||||
{
|
||||
path: 'word/endnotes.xml',
|
||||
xml:
|
||||
`${XML_DECL}<n:endnotes xmlns:n='${wml}'>` +
|
||||
"<n:endnote n:id='3'><n:p><n:ins n:id='end-rev' n:author='End Person' n:date='2024-03-05T02:03:04Z'>" +
|
||||
'<n:r><n:t>Endnote content</n:t></n:r></n:ins></n:p></n:endnote></n:endnotes>',
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml',
|
||||
},
|
||||
{
|
||||
path: 'word/glossary/document.xml',
|
||||
xml:
|
||||
`${XML_DECL}<g:document xmlns:g="${wml}"><g:body>` +
|
||||
'<g:p><g:ins g:id="glossary-rev" g:author="Glossary Person" g:date="2024-03-06T02:03:04Z">' +
|
||||
'<g:r><g:t>Glossary content</g:t></g:r></g:ins></g:p>' +
|
||||
'</g:body></g:document>',
|
||||
contentType:
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml',
|
||||
},
|
||||
{
|
||||
path: 'docProps/core.xml',
|
||||
xml:
|
||||
`${XML_DECL}<meta:coreProperties xmlns:meta='http://schemas.openxmlformats.org/package/2006/metadata/core-properties' ` +
|
||||
"xmlns:d='http://purl.org/dc/elements/1.1/' xmlns:t='http://purl.org/dc/terms/'>" +
|
||||
"<d:creator role='writer'>Core Person</d:creator>" +
|
||||
'<meta:lastModifiedBy>Last Person</meta:lastModifiedBy>' +
|
||||
'<d:title>Preserved title</d:title>' +
|
||||
'<t:created>2024-01-01T00:00:00Z</t:created>' +
|
||||
'</meta:coreProperties>',
|
||||
contentType: 'application/vnd.openxmlformats-package.core-properties+xml',
|
||||
},
|
||||
{
|
||||
path: 'docProps/app.xml',
|
||||
xml:
|
||||
`${XML_DECL}<ep:Properties xmlns:ep='http://schemas.openxmlformats.org/officeDocument/2006/extended-properties'>` +
|
||||
'<ep:Manager>Manager Person</ep:Manager><ep:Company>Example Org</ep:Company>' +
|
||||
'<ep:Application>Preserved App</ep:Application></ep:Properties>',
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.extended-properties+xml',
|
||||
},
|
||||
{
|
||||
path: 'word/people.xml',
|
||||
xml:
|
||||
`${XML_DECL}<p:people xmlns:p="http://schemas.microsoft.com/office/word/2012/wordml">` +
|
||||
'<p:person p:author="People Person" p:initials="PP" p:personId="person-keep">' +
|
||||
"<p:presenceInfo p:providerId='Example Org' p:userId='person@example.com'/>" +
|
||||
'</p:person></p:people>',
|
||||
contentType: 'application/vnd.ms-word.person+xml',
|
||||
},
|
||||
{
|
||||
path: 'customXml/item1.xml',
|
||||
xml:
|
||||
`${XML_DECL}<custom xmlns:w="${wml}" author="Custom Person">` +
|
||||
'<w:ins w:id="custom-rev" w:author="Custom Person"><value>Keep me</value></w:ins>' +
|
||||
'</custom>',
|
||||
contentType: 'application/xml',
|
||||
},
|
||||
{
|
||||
path: 'docProps/custom.xml',
|
||||
xml:
|
||||
`${XML_DECL}<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties">` +
|
||||
'<property name="Company"><value>Custom Org</value></property></Properties>',
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.custom-properties+xml',
|
||||
},
|
||||
]
|
||||
const customXml = extraParts.find((part) => part.path === 'customXml/item1.xml')!.xml
|
||||
const customProps = extraParts.find((part) => part.path === 'docProps/custom.xml')!.xml
|
||||
const binary = Buffer.from([0, 255, 17, 34, 51])
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml:
|
||||
`<w:p xmlns:x='${wml}'><w:ins x:id='body-rev' x:author='Body Person' x:date='2024-02-01T02:03:04Z'>` +
|
||||
'<w:r><w:t>Body Person remains as content; author="Visible Person"; w:author=\'Visible Qualified\'</w:t></w:r></w:ins></w:p>',
|
||||
extraRels:
|
||||
'<Relationship Id="rId40" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>' +
|
||||
'<Relationship Id="rId41" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/>' +
|
||||
'<Relationship Id="rId42" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>',
|
||||
sectPrExtra:
|
||||
'<w:headerReference w:type="default" r:id="rId40"/><w:footerReference w:type="default" r:id="rId41"/>',
|
||||
extraParts,
|
||||
binaryParts: [
|
||||
{
|
||||
path: 'word/media/privacy-proof.bin',
|
||||
base64: binary.toString('base64'),
|
||||
extension: 'bin',
|
||||
contentType: 'application/octet-stream',
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
|
||||
const saved = await saveDocx(parsed, originalBlocks(parsed), {
|
||||
removePersonalInfo: true,
|
||||
savedAt: '2026-01-01T00:00:00Z',
|
||||
})
|
||||
const zip = await JSZip.loadAsync(saved)
|
||||
const read = (path: string) => zip.file(path)!.async('string')
|
||||
|
||||
const documentXml = await read('word/document.xml')
|
||||
expect(documentXml).toContain("x:author='Author'")
|
||||
expect(documentXml).toContain("x:id='body-rev'")
|
||||
expect(documentXml).toContain("x:date='2024-02-01T02:03:04Z'")
|
||||
expect(documentXml).toContain('Body Person remains as content')
|
||||
expect(documentXml).toContain('author="Visible Person"')
|
||||
expect(documentXml).toContain("w:author='Visible Qualified'")
|
||||
|
||||
for (const [path, removed, kept, id, date] of [
|
||||
[
|
||||
'word/comments.xml',
|
||||
'Comment Person',
|
||||
'Comment Person remains as comment text',
|
||||
'comment-7',
|
||||
'2024-03-01T02:03:04Z',
|
||||
],
|
||||
['word/header1.xml', 'Header Person', 'Header content', 'header-rev', '2024-03-02T02:03:04Z'],
|
||||
['word/footer1.xml', 'Footer Person', 'Footer content', 'footer-rev', '2024-03-03T02:03:04Z'],
|
||||
['word/footnotes.xml', 'Foot Person', 'Footnote content', 'foot-rev', '2024-03-04T02:03:04Z'],
|
||||
['word/endnotes.xml', 'End Person', 'Endnote content', 'end-rev', '2024-03-05T02:03:04Z'],
|
||||
[
|
||||
'word/glossary/document.xml',
|
||||
'Glossary Person',
|
||||
'Glossary content',
|
||||
'glossary-rev',
|
||||
'2024-03-06T02:03:04Z',
|
||||
],
|
||||
] as const) {
|
||||
const xml = await read(path)
|
||||
expect(xml).not.toContain(`${removed}'`)
|
||||
expect(xml).not.toContain(`${removed}"`)
|
||||
expect(xml).toContain(kept)
|
||||
expect(xml).toContain('author=')
|
||||
expect(xml).toContain(id)
|
||||
expect(xml).toContain(date)
|
||||
}
|
||||
const comments = await read('word/comments.xml')
|
||||
expect(comments).toContain("c:author='Author'")
|
||||
expect(comments).toContain("c:initials='A'")
|
||||
expect(comments).toContain("c:id='comment-7'")
|
||||
expect(comments).toContain("c:date='2024-03-01T02:03:04Z'")
|
||||
|
||||
const core = await read('docProps/core.xml')
|
||||
expect(core).toContain("<d:creator role='writer'></d:creator>")
|
||||
expect(core).toContain('<meta:lastModifiedBy></meta:lastModifiedBy>')
|
||||
expect(core).toContain('<d:title>Preserved title</d:title>')
|
||||
expect(core).toContain('<t:created>2024-01-01T00:00:00Z</t:created>')
|
||||
|
||||
const app = await read('docProps/app.xml')
|
||||
expect(app).toContain('<ep:Manager></ep:Manager>')
|
||||
expect(app).toContain('<ep:Company></ep:Company>')
|
||||
expect(app).toContain('<ep:Application>Preserved App</ep:Application>')
|
||||
|
||||
const people = await read('word/people.xml')
|
||||
expect(people).toContain('<p:people')
|
||||
expect(people).not.toContain('<p:person ')
|
||||
expect(people).not.toContain('People Person')
|
||||
expect(people).not.toContain('person@example.com')
|
||||
expect(people).not.toContain('person-keep')
|
||||
|
||||
expect(await read('customXml/item1.xml')).toBe(customXml)
|
||||
expect(await read('docProps/custom.xml')).toBe(customProps)
|
||||
expect(await zip.file('word/media/privacy-proof.bin')!.async('nodebuffer')).toEqual(binary)
|
||||
})
|
||||
|
||||
it('a document that already carries the flag scrubs an otherwise unchanged save', async () => {
|
||||
const settingsPart = {
|
||||
path: 'word/settings.xml',
|
||||
xml:
|
||||
`${XML_DECL}<s:settings xmlns:s='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>` +
|
||||
"<s:removePersonalInformation s:val='true'/></s:settings>",
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml',
|
||||
}
|
||||
const settingsRel =
|
||||
'<Relationship Id="rId41" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/>'
|
||||
const parsed = await parseDocx(
|
||||
await buildDocx({
|
||||
bodyXml: bodyWithRevision + '<w:p><w:r><w:t>tail</w:t></w:r></w:p>',
|
||||
extraRels: settingsRel,
|
||||
extraParts: [settingsPart],
|
||||
}),
|
||||
)
|
||||
expect(parsed.removePersonalInfo).toBe(true)
|
||||
const saved = await saveDocx(parsed, originalBlocks(parsed), {})
|
||||
const docXml = await (await JSZip.loadAsync(saved)).file('word/document.xml')!.async('string')
|
||||
expect(docXml).toContain('w:author="Author"')
|
||||
expect(docXml).not.toContain('张三')
|
||||
})
|
||||
|
||||
it('false removes the settings flag and leaves authors alone', async () => {
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: bodyWithRevision }))
|
||||
const withFlag = await parseDocx(
|
||||
await saveDocx(parsed, originalBlocks(parsed), { removePersonalInfo: true }),
|
||||
)
|
||||
expect(withFlag.removePersonalInfo).toBe(true)
|
||||
const cleared = await saveDocx(withFlag, originalBlocks(withFlag), {
|
||||
removePersonalInfo: false,
|
||||
})
|
||||
const reparsed = await parseDocx(cleared)
|
||||
expect(reparsed.removePersonalInfo).toBe(false)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user