A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
// Tests for the ds-bot Office CLI (src/office → office.js). Fixtures are the
// small packages under fixtures/office generated by dev/office-fixtures.py.
import { execFileSync } from 'node:child_process'
import { mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync, existsSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, test } from 'node:test'
import assert from 'node:assert'
import { readZip, writeZip } from '../src/office/zip.js'
import { Package } from '../src/office/package.js'
import { checkPackage, fixPackage } from '../src/office/check.js'
import { docxRead, docxEdit, resolveChanges } from '../src/office/docx.js'
import { pptxInventory, pptxLayout, pptxClean, pptxSlides } from '../src/office/pptx.js'
import { xlsxInventory, xlsxRead } from '../src/office/xlsx.js'
import { decodePng, encodePng, contactSheet } from '../src/office/png.js'
import { parseXml, elementsOf, childrenOf, textOf } from '../src/office/xml.js'
const ROOT = dirname(dirname(fileURLToPath(import.meta.url)))
const FIXTURES = join(ROOT, 'test', 'fixtures', 'office')
const CLI = join(ROOT, 'office.js')
const NODE = process.execPath
const fixture = (name) => join(FIXTURES, name)
const tmp = () => mkdtempSync(join(tmpdir(), 'office-test-'))
// exit 1 means "findings remain" — still a JSON result, not a failure.
const cli = (...args) => {
try {
return JSON.parse(execFileSync(NODE, [CLI, ...args, '--json'], { encoding: 'utf8' }))
} catch (error) {
if (error.stdout) return JSON.parse(error.stdout)
throw error
}
}
describe('zip', () => {
test('round trip keeps unchanged members byte-identical', () => {
const docx = fixture('sample.docx')
const pkg = Package.open(docx)
const before = readZip(readFileSync(docx))
pkg.put('word/styles.xml', pkg.get('word/styles.xml')) // same bytes through put()
const after = readZip(pkg.save())
const a = before.find(m => m.name === 'word/document.xml')
const b = after.find(m => m.name === 'word/document.xml')
assert.deepEqual(b.raw, a.raw) // compressed bytes preserved for untouched parts
assert.equal(after[0].name, '[Content_Types].xml')
assert.equal(before.length, after.length)
})
test('rejects zip64 with a clear error', () => {
const docx = readFileSync(fixture('sample.docx'))
const copy = Buffer.from(docx)
const eocd = copy.length - 22
copy.writeUInt32LE(0xffffffff, eocd + 16)
assert.throws(() => readZip(copy), /zip64/)
})
})
describe('check', () => {
const rules = [
['malformed-xml', (pkg) => pkg.put('word/styles.xml', '<w:styles><broken')],
['override-absent-part', (pkg) => pkg.overrides.set('word/ghost.xml', 'application/x')],
['dangling-rel', (pkg) => {
const doc = pkg.xml('word/_rels/document.xml.rels')
const rel = doc.createElement('Relationship')
rel.setAttribute('Id', 'rId99'); rel.setAttribute('Type', 'x'); rel.setAttribute('Target', 'gone.xml')
doc.documentElement.appendChild(rel)
pkg.putXml('word/_rels/document.xml.rels', doc)
}],
['missing-xml-space', (pkg) => {
const doc = pkg.xml('word/document.xml')
const p = parseXml('<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:r><w:t> tail</w:t></w:r></w:p>').documentElement
doc.documentElement.appendChild(p.ownerDocument === doc ? p : doc.importNode(p, true))
pkg.putXml('word/document.xml', doc)
}],
]
for (const [rule, breakIt] of rules) {
test(`reports ${rule}`, () => {
const pkg = Package.open(fixture('sample.docx'))
breakIt(pkg)
assert.ok(checkPackage(pkg).some(f => f.rule === rule), `no ${rule}`)
})
}
test('clean fixture passes', () => {
assert.deepEqual(checkPackage(Package.open(fixture('sample.docx'))), [])
assert.deepEqual(checkPackage(Package.open(fixture('sample.pptx'))), [])
assert.deepEqual(checkPackage(Package.open(fixture('sample.xlsx'))), [])
})
test('--against reports only new issues', () => {
const original = Package.open(fixture('sample.docx'))
const edited = Package.open(fixture('sample.docx'))
const doc = edited.xml('word/_rels/document.xml.rels')
const rel = doc.createElement('Relationship')
rel.setAttribute('Id', 'rId99'); rel.setAttribute('Type', 'x'); rel.setAttribute('Target', 'gone.xml')
doc.documentElement.appendChild(rel)
edited.putXml('word/_rels/document.xml.rels', doc)
const found = checkPackage(edited, original)
assert.equal(found.length, 1)
assert.equal(found[0].rule, 'dangling-rel')
})
test('--fix repairs missing-xml-space and dangling rels', () => {
const pkg = Package.open(fixture('sample.docx'))
const doc = pkg.xml('word/document.xml')
const p = parseXml('<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:r><w:t> tail</w:t></w:r></w:p>').documentElement
doc.documentElement.appendChild(doc.importNode(p, true))
pkg.putXml('word/document.xml', doc)
pkg.rels.get('word/document.xml').set('rId99', { id: 'rId99', type: 'x', target: 'gone.xml', mode: 'Internal' })
const { remaining } = fixPackage(pkg)
assert.deepEqual(remaining, [])
})
})
describe('docx', () => {
test('read gives pN/tN ids, tables, headers, comments', () => {
const { blocks, sections, comments } = docxRead(Package.open(fixture('sample.docx')))
assert.equal(blocks[0].id, 'p1')
assert.equal(blocks[0].style, 'Title')
const table = blocks.find(b => b.id === 't1')
assert.equal(table.rows[0][0].gridSpan, 2)
assert.ok(blocks.some(b => b.deletedParagraphMark))
assert.equal(sections.find(s => s.kind === 'header').text, 'Report header')
assert.equal(comments[0].author, 'Ana')
assert.equal(comments[0].anchorsTo, 'p3')
})
test('read --changes marks tracked changes inline', () => {
const { blocks } = docxRead(Package.open(fixture('sample.docx')), { changes: true })
const text = blocks[1].text
assert.match(text, /\{\+ fast \(Ana\)\+\}/)
assert.match(text, /\{- old \(Ana\)-\}/)
})
test('replace works across runs and keeps start formatting', () => {
const dir = tmp()
const out = join(dir, 'out.docx')
const res = cli('docx', 'edit', fixture('sample.docx'), '-o', out, '--ops',
JSON.stringify([{ replace: { find: 'north region', with: 'south area' } }]))
assert.ok(res.ok)
const { blocks } = docxRead(Package.open(out))
assert.match(blocks[1].text, /south area/)
assert.deepEqual(cli('check', out, '--against', fixture('sample.docx')).data.findings, [])
})
test('all-or-nothing: a failing op writes nothing', () => {
const dir = tmp()
const out = join(dir, 'out.docx')
for (const op of [{ insert: { after: 'p999', text: 'x' } }, { comment: { paragraph: 'p1', text: 'gone' } }]) {
assert.throws(() => execFileSync(NODE, [CLI, 'docx', 'edit', fixture('sample.docx'), '-o', out, '--ops',
JSON.stringify([{ delete: { paragraphs: ['p1'] } }, op]), '--json']))
assert.ok(!existsSync(out))
}
})
test('a batch keeps the original paragraph ids after deletions', () => {
const dir = tmp()
const out = join(dir, 'out.docx')
cli('docx', 'edit', fixture('sample.docx'), '-o', out, '--ops', JSON.stringify([
{ delete: { paragraphs: ['p1'] } },
{ delete: { paragraphs: ['p2'] } },
]))
assert.equal(docxRead(Package.open(out)).blocks.find(b => b.type === 'paragraph').text, 'Second paragraph with a field:')
})
test('insertions keep later anchors, style references and comments on the original paragraphs', () => {
const dir = tmp()
const out = join(dir, 'out.docx')
cli('docx', 'edit', fixture('sample.docx'), '-o', out, '--ops', JSON.stringify([
{ insert: { before: 'p1', text: 'Introduction' } },
{ insert: { after: 'p3', text: 'Follow-up', like: 'p1' } },
{ comment: { paragraph: 'p2', text: 'Check the revenue.' } },
]))
const { blocks, comments } = docxRead(Package.open(out))
const following = blocks.find(b => b.text === 'Follow-up')
assert.equal(following.style, 'Title')
assert.equal(blocks[blocks.indexOf(following) - 1].text, 'Second paragraph with a field:')
const comment = comments.find(c => c.text === 'Check the revenue.')
assert.equal(blocks.find(b => b.id === comment.anchorsTo).text, 'Revenue grew fast in the north region. moved')
})
test('accept and reject changes resolve to expected text', () => {
const dir = tmp()
const accepted = join(dir, 'a.docx'), rejected = join(dir, 'r.docx')
cli('docx', 'edit', fixture('sample.docx'), '-o', accepted, '--ops', JSON.stringify([{ accept_changes: {} }]))
cli('docx', 'edit', fixture('sample.docx'), '-o', rejected, '--ops', JSON.stringify([{ reject_changes: {} }]))
const acc = docxRead(Package.open(accepted)).blocks[1].text
const rej = docxRead(Package.open(rejected)).blocks[1].text
assert.equal(acc, 'Revenue grew fast in the north region. moved')
assert.equal(rej, 'Revenue grew in the north old region.')
})
test('set_cell, insert, delete, comment, set_field ops apply', () => {
const dir = tmp()
const out = join(dir, 'ops.docx')
cli('docx', 'edit', fixture('sample.docx'), '-o', out, '--ops', JSON.stringify([
{ set_cell: { table: 1, row: 2, col: 2, text: '99' } },
{ insert: { after: 'p5', text: 'Added', style: 'Normal' } },
{ delete: { paragraphs: ['p4'] } },
{ comment: { paragraph: 'p2', text: 'Noted', author: 'Bo' } },
{ set_field: { match: 'PAGE', value: '7' } },
]))
const { blocks, comments } = docxRead(Package.open(out))
assert.equal(blocks.find(b => b.id === 't1').rows[1][1].text, '99')
assert.ok(comments.some(c => c.author === 'Bo'))
assert.deepEqual(cli('check', out, '--against', fixture('sample.docx')).data.findings, [])
})
})
describe('pptx', () => {
test('inventory resolves boxes incl. inherited placeholder and group transform', () => {
const inv = pptxInventory(Package.open(fixture('sample.pptx')))
assert.equal(inv.slideSize.cx, 10)
const s1 = inv.slides[0]
assert.equal(s1.layout, 'Title Slide')
assert.equal(s1.notes, 'Speaker notes for the overview.')
const title = s1.shapes.find(s => s.name === 'Title 1')
assert.ok(title.box.w > 0) // box inherited from the layout placeholder
assert.ok(s1.shapes.some(s => s.kind === 'chart') && s1.shapes.some(s => s.media))
assert.equal(inv.slides[1].hidden, true)
})
test('layout reports overlap; autofit sets normAutofit', () => {
const dir = tmp()
const out = join(dir, 'fit.pptx')
const res = cli('pptx', 'layout', fixture('sample.pptx'), '--autofit', '-o', out, '--json')
assert.ok(res.data.findings.some(f => f.rule === 'overlap' && f.slide === 3))
const fitted = pptxLayout(Package.open(out)).findings
assert.ok(fitted.length > 0) // boxes unchanged; normAutofit flag written
})
test('slides reorder, duplicate, remove; check stays clean', () => {
const dir = tmp()
const out = join(dir, 'reordered.pptx')
const res = cli('pptx', 'slides', fixture('sample.pptx'), '-o', out, '--order', '3,1,1')
assert.deepEqual(res.data.order, [3, 1, 1])
const inv = pptxInventory(Package.open(out))
assert.equal(inv.slides.length, 3)
assert.equal(inv.slides[0].part, 'ppt/slides/slide3.xml')
assert.equal(checkPackage(Package.open(out)).length, 0)
})
test('clean --dry-run lists without removing', () => {
const res = cli('pptx', 'clean', fixture('sample.pptx'), '--dry-run')
assert.deepEqual(res.data.removed, [])
})
})
describe('xlsx', () => {
test('inventory lists sheets, names, formula counts', () => {
const inv = xlsxInventory(Package.open(fixture('sample.xlsx')))
assert.equal(inv.sheets[0].name, 'Sheet1')
assert.equal(inv.sheets[0].formulas, 3)
assert.equal(inv.sheets[0].merged, 1)
assert.ok(inv.definedNames.some(n => n.name === 'Totals'))
})
test('read returns cached values, formulas and ISO dates', () => {
const grid = xlsxRead(Package.open(fixture('sample.xlsx')), 'Sheet1')
const row2 = grid.rows.find(r => r.row === 2).cells
assert.equal(row2.D2.v, '2026-10-01')
assert.equal(row2.C2.f, 'B2*2')
})
})
describe('png + sheet', () => {
test('decode/encode round trip', () => {
const png = { width: 2, height: 2, data: Buffer.from([255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 0, 255]), channels: 4 }
const decoded = decodePng(encodePng(png))
assert.equal(decoded.width, 2)
assert.deepEqual(decoded.data, png.data)
})
test('contact sheet dimensions and tiles', () => {
const imgs = [1, 2, 3].map(() => ({ width: 10, height: 10, data: Buffer.alloc(400, 255) }))
const sheet = contactSheet(imgs, { cols: 2, width: 10 })
assert.equal(sheet.width, 20)
assert.equal(sheet.height, 40)
})
test('sheet command writes a contact png', () => {
const dir = tmp()
const one = join(dir, '1.png'), two = join(dir, '2.png')
writeFileSync(one, encodePng({ width: 4, height: 4, data: Buffer.alloc(64, 200), channels: 4 }))
writeFileSync(two, encodePng({ width: 4, height: 4, data: Buffer.alloc(64, 100), channels: 4 }))
const res = cli('sheet', dir, '-o', join(dir, 'out.png'), '--cols', '2', '--width', '4')
const png = decodePng(readFileSync(res.data.file))
assert.equal(png.width, 8)
})
})
describe('unpack/pack', () => {
test('unpack writes pretty XML and pack --against checks the result', () => {
const dir = tmp()
const dest = join(dir, 'un')
cli('unpack', fixture('sample.docx'), dest)
assert.ok(readFileSync(join(dest, 'word', 'document.xml'), 'utf8').includes('\n'))
const res = cli('pack', dest, join(dir, 'back.docx'), '--against', fixture('sample.docx'))
assert.ok(res.ok)
assert.equal(checkPackage(Package.open(join(dir, 'back.docx'))).length, 0)
})
test('unpack reuses an earlier unpack and removes stale files', () => {
const dir = tmp()
const dest = join(dir, 'un')
cli('unpack', fixture('sample.docx'), dest)
writeFileSync(join(dest, 'stale.xml'), '<x/>')
cli('unpack', fixture('sample.docx'), dest)
assert.ok(!existsSync(join(dest, 'stale.xml')))
})
test('unpack refuses an existing directory that is not an unpack', () => {
const dir = tmp()
writeFileSync(join(dir, 'random.txt'), 'hi')
assert.throws(() => execFileSync(NODE, [CLI, 'unpack', fixture('sample.docx'), dir, '--json']), /unpack/)
})
})
describe('paragraph and row marks (review 1)', () => {
test('accept merges a paragraph with a deleted mark into the next, in order', () => {
const dir = tmp()
const out = join(dir, 'merged.docx')
cli('docx', 'edit', fixture('sample.docx'), '-o', out, '--ops', JSON.stringify([{ accept_changes: {} }]))
const { blocks } = docxRead(Package.open(out))
assert.equal(blocks.length, 6) // p5 merged into the field paragraph
const merged = blocks.find(b => /Final closing/.test(b.text))
assert.match(merged.text, /Final closing paragraph\. PAGE/)
assert.ok(!merged.deletedParagraphMark)
})
test('reject drops the deleted paragraph mark and keeps both paragraphs', () => {
const dir = tmp()
const out = join(dir, 'rejected.docx')
cli('docx', 'edit', fixture('sample.docx'), '-o', out, '--ops', JSON.stringify([{ reject_changes: {} }]))
const { blocks } = docxRead(Package.open(out))
assert.ok(blocks.some(b => b.text === 'Final closing paragraph.' && !b.deletedParagraphMark))
assert.ok(blocks.some(b => / PAGE /.test(b.text)))
})
})
describe('property change restore (review 2)', () => {
test('reject restores stored run properties under the run rPr', () => {
const dir = tmp()
const out = join(dir, 'rej.docx')
cli('docx', 'edit', fixture('sample.docx'), '-o', out, '--ops', JSON.stringify([{ reject_changes: {} }]))
const doc = Package.open(out).xml('word/document.xml')
// The "." run carried rPrChange storing a bold rPr: on reject the run
// becomes bold again, with no change element left.
const runs = elementsOf(doc.documentElement, 'w:r')
const dot = runs.find(r => textOf(r) === '.')
assert.ok(dot, 'no "." run')
assert.ok(childrenOf(childrenOf(dot, 'w:rPr')[0], 'w:b')[0] !== undefined)
assert.equal(elementsOf(doc.documentElement, 'w:rPrChange').length, 0)
})
})
describe('replace edge cases (review 3)', () => {
test('zero-width regex replacements include paragraph ends and empty paragraphs', () => {
const runs = '<w:r><w:rPr><w:b/></w:rPr><w:t>ab</w:t></w:r><w:r><w:t>cd</w:t></w:r><w:r><w:t/></w:r>'
for (const [content, find, expected] of [
[runs, '$', 'abcd!'],
[runs, '^|$', '!abcd!'],
[runs, '(?=cd)|$', 'ab!cd!'],
[runs, 'd?$', 'abc!!'],
['', '^$', '!'],
]) {
const pkg = Package.open(fixture('sample.docx'))
const doc = pkg.xml('word/document.xml')
const body = childrenOf(doc.documentElement, 'w:body')[0]
for (const child of [...body.childNodes]) body.removeChild(child)
const p = parseXml(`<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${content}</w:p>`).documentElement
body.appendChild(doc.importNode(p, true))
pkg.putXml('word/document.xml', doc)
docxEdit(pkg, [{ replace: { find, with: '!', regex: true } }])
assert.equal(docxRead(pkg).blocks[0].text, expected, find)
}
})
test('a→aa terminates (no re-scan of inserted text)', () => {
const dir = tmp()
const out = join(dir, 'aa.docx')
cli('docx', 'edit', fixture('sample.docx'), '-o', out, '--ops', JSON.stringify([{ replace: { find: 'a', with: 'aa' } }]))
const { blocks } = docxRead(Package.open(out))
assert.ok(blocks.some(b => (b.text ?? '').includes('aa')))
})
test('regex groups expand ($1), and case-insensitive flags hold', () => {
const dir = tmp()
const out = join(dir, 're.docx')
cli('docx', 'edit', fixture('sample.docx'), '-o', out, '--ops',
JSON.stringify([{ replace: { find: '(north) region', with: 'south-$1 area', regex: true } }]))
assert.match(docxRead(Package.open(out)).blocks[1].text, /south-north area/)
})
})
describe('comment op (review 4)', () => {
test('anchor wraps exactly the phrase and passes check', () => {
const dir = tmp()
const out = join(dir, 'c.docx')
cli('docx', 'edit', fixture('sample.docx'), '-o', out, '--ops',
JSON.stringify([{ comment: { paragraph: 'p2', text: 'look here', anchor: 'north' } }]))
const pkg = Package.open(out)
assert.deepEqual(checkPackage(pkg), [])
const doc = pkg.xml('word/document.xml')
const p = elementsOf(doc.documentElement, 'w:p').find(p => textOf(p).includes('south') || textOf(p).includes('north'))
const start = elementsOf(p, 'w:commentRangeStart')[0]
assert.ok(start)
// The range opens right before the run holding the phrase.
assert.match(textOf(start.nextSibling), /^north$/)
})
test('an anchor that is not in the paragraph fails the whole batch', () => {
const dir = tmp()
const out = join(dir, 'c2.docx')
const res = cli('docx', 'edit', fixture('sample.docx'), '-o', out, '--ops',
JSON.stringify([{ comment: { paragraph: 'p2', text: 'x', anchor: 'zz-not-there' } }]))
assert.equal(res.ok, false)
assert.match(res.error.message, /op 0/)
assert.ok(!existsSync(out))
})
})
describe('field and cell edits (review 5, 6)', () => {
test('set_field rewrites the complex result and touches only document.xml', () => {
const dir = tmp()
const out = join(dir, 'f.docx')
const res = cli('docx', 'edit', fixture('sample.docx'), '-o', out, '--ops',
JSON.stringify([{ set_field: { match: 'PAGE', value: '7' } }]))
assert.deepEqual(res.data.changed, ['word/document.xml'])
const fields = cli('docx', 'fields', out).data
assert.ok(fields.some(f => f.instruction.includes('PAGE') && f.result === '7'))
})
test('set_cell keeps tcPr, pPr and the run rPr', () => {
const dir = tmp()
const out = join(dir, 'cell.docx')
cli('docx', 'edit', fixture('sample.docx'), '-o', out, '--ops',
JSON.stringify([{ set_cell: { table: 1, row: 1, col: 1, text: 'New title' } }]))
const { blocks } = docxRead(Package.open(out))
assert.equal(blocks.find(b => b.id === 't1').rows[0][0].gridSpan, 2)
})
})
describe('pptx duplication and clean (review 7, 8)', () => {
test('duplicated slide gets its Override and the notes slide points back at it', () => {
const dir = tmp()
const out = join(dir, 'dup.pptx')
cli('pptx', 'slides', fixture('sample.pptx'), '-o', out, '--order', '1,1,2,3')
const pkg = Package.open(out)
const dup = 'ppt/slides/slide4.xml'
assert.equal(pkg.contentType(dup), 'application/vnd.openxmlformats-officedocument.presentationml.slide+xml')
const notesRel = [...pkg.relsOf(dup).values()].find(r => r.type.endsWith('/notesSlide'))
assert.ok(notesRel, 'duplicated slide kept no notes slide')
const notes = pkg.targetOf(dup, notesRel.target)
const back = [...pkg.relsOf(notes).values()].find(r => r.type.endsWith('/slide'))
assert.equal(pkg.targetOf(notes, back.target), dup)
assert.deepEqual(checkPackage(pkg), [])
})
test('clean drops relationship ids that no XML uses', () => {
const dir = tmp()
const broken = join(dir, 'b.pptx')
const pkg = Package.open(fixture('sample.pptx'))
const doc = pkg.xml('ppt/slides/slide1.xml')
const pic = elementsOf(doc.documentElement, 'p:pic')[0]
pic.parentNode.removeChild(pic)
pkg.putXml('ppt/slides/slide1.xml', doc)
writeFileSync(broken, pkg.save())
const res = cli('pptx', 'clean', broken, '-o', join(dir, 'c.pptx'))
assert.ok(res.data.removed.some(n => n === 'ppt/media/image1.png'))
assert.deepEqual(checkPackage(Package.open(res.data.file)), [])
})
})
describe('check rules (review 10, 11)', () => {
test('o:id in VML is not a relationship reference', () => {
const pkg = Package.open(fixture('sample.docx'))
const doc = pkg.xml('word/document.xml')
const p = parseXml(`<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><w:r><w:pict><v:shape o:id="_x0000_s1" id="x" style="width:10pt;height:10pt"/></w:pict></w:r></w:p>`).documentElement
doc.documentElement.appendChild(doc.importNode(p, true))
pkg.putXml('word/document.xml', doc)
assert.ok(!checkPackage(pkg).some(f => f.rule === 'unknown-rel-ref'))
})
test('wrong-content-type reports and --fix sets the Override', () => {
const pkg = Package.open(fixture('sample.docx'))
pkg.override('word/styles.xml', 'application/xml')
const found = checkPackage(pkg)
assert.ok(found.some(f => f.rule === 'wrong-content-type' && f.part === 'word/styles.xml'))
const { remaining } = fixPackage(pkg)
assert.deepEqual(remaining, [])
assert.equal(pkg.contentType('word/styles.xml'), 'application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml')
})
})
describe('re-review fixes', () => {
test('clean keeps a single-quoted r:embed', () => {
const pkg = Package.open(fixture('sample.pptx'))
const rel = [...pkg.relsOf('ppt/slides/slide1.xml').values()].find(r => r.type.endsWith('/image'))
const xml = String(pkg.get('ppt/slides/slide1.xml')).replace(`"${rel.id}"`, `'${rel.id}'`)
pkg.put('ppt/slides/slide1.xml', xml)
assert.ok(pptxClean(pkg, { dryRun: true }).removed.every(n => n !== 'ppt/media/image1.png'))
})
test('sectPr reject puts header/footer references before restored properties', () => {
const pkg = Package.open(fixture('sample.docx'))
const doc = pkg.xml('word/document.xml')
const sectPr = elementsOf(doc.documentElement, 'w:sectPr')[0]
const ref = doc.createElement('w:headerReference')
ref.setAttribute('w:type', 'default')
sectPr.insertBefore(ref, sectPr.firstChild)
const change = doc.createElement('w:sectPrChange')
const stored = doc.createElement('w:sectPr')
const sz = doc.createElement('w:pgSz')
sz.setAttribute('w:w', '11906'); sz.setAttribute('w:h', '16838')
stored.appendChild(sz); change.appendChild(stored)
sectPr.appendChild(change)
resolveChanges(doc, false)
const names = childrenOf(sectPr).map(c => c.tagName)
assert.equal(names[0], 'w:headerReference')
assert.ok(names.includes('w:pgSz'))
assert.ok(!names.includes('w:sectPrChange'))
})
test('comment anchor inside a w:hyperlink wraps the phrase', () => {
const pkg = Package.open(fixture('sample.docx'))
const doc = pkg.xml('word/document.xml')
const p = parseXml(`<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:hyperlink w:history="1" w:anchor="top"><w:r><w:t xml:space="preserve">click here text</w:t></w:r></w:hyperlink></w:p>`).documentElement
childrenOf(doc.documentElement, 'w:body')[0].appendChild(doc.importNode(p, true))
pkg.putXml('word/document.xml', doc)
const dir = tmp(), out = join(dir, 'hl.docx')
writeFileSync(join(dir, 'hl-src.docx'), pkg.save())
cli('docx', 'edit', join(dir, 'hl-src.docx'), '-o', out, '--ops',
JSON.stringify([{ comment: { paragraph: 'p7', text: 'hi', anchor: 'here' } }]))
const read = docxRead(Package.open(out))
assert.ok(read.comments.some(c => c.text === 'hi' && c.anchorsTo === 'p7'))
assert.deepEqual(checkPackage(Package.open(out)), [])
})
})
describe('re-review pass 2', () => {
test('zip slip: unsafe member names are refused on open', () => {
for (const name of ['../evil.xml', 'word/../../x.xml', '/abs/x.xml', 'C:/win/x.xml', 'word\\..\\x.xml']) {
const buf = writeZip([{ name, data: Buffer.from('x') }])
const file = join(tmp(), 'z.docx')
writeFileSync(file, buf)
assert.throws(() => Package.open(file), /unsafe member name/)
}
})
test('zip bomb: inflate stops at the declared size', () => {
const buf = writeZip([{ name: 'x.xml', data: Buffer.alloc(5000, 65) }])
buf.writeUInt32LE(10, 22) // lie: declared usize 10, real 5000
const cdOff = buf.readUInt32LE(buf.length - 22 + 16)
buf.writeUInt32LE(10, cdOff + 24)
assert.throws(() => readZip(buf), /past its declared size/)
})
test('replace: several matches in one run, adjacent and spanning', () => {
const pkg = Package.open(fixture('sample.docx'))
const doc = pkg.xml('word/document.xml')
const body = childrenOf(doc.documentElement, 'w:body')[0]
const addP = (runs) => {
const p = parseXml(`<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${runs.map(r => `<w:r><w:t xml:space="preserve">${r}</w:t></w:r>`).join('')}</w:p>`).documentElement
body.appendChild(doc.importNode(p, true))
}
addP(['cat cat'])
addP(['x x x'])
addP(['catcat'])
addP(['ca', 't c', 'at'])
pkg.putXml('word/document.xml', doc)
docxEdit(pkg, [{ replace: { find: 'cat', with: 'dog' } }, { replace: { find: 'x', with: 'y' } }])
const { blocks } = docxRead(pkg)
const texts = blocks.slice(-4).map(b => b.text)
assert.equal(texts[0], 'dog dog')
assert.equal(texts[1], 'y y y')
assert.equal(texts[2], 'dogdog')
assert.equal(texts[3], 'dog dog')
})
test('replace and comment keep run rPr', () => {
const pkg = Package.open(fixture('sample.docx'))
const doc = pkg.xml('word/document.xml')
const body = childrenOf(doc.documentElement, 'w:body')[0]
body.appendChild(doc.importNode(parseXml(`<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:r><w:rPr><w:b/></w:rPr><w:t>bold bold</w:t></w:r></w:p>`).documentElement, true))
pkg.putXml('word/document.xml', doc)
docxEdit(pkg, [{ replace: { find: 'bold', with: 'strong' } }])
const fresh = pkg.xml('word/document.xml')
const strongs = elementsOf(fresh.documentElement, 'w:r').filter(r => elementsOf(r, 'w:t').some(t => t.textContent === 'strong'))
assert.equal(strongs.length, 2)
assert.ok(strongs.every(r => childrenOf(childrenOf(r, 'w:rPr')[0], 'w:b')[0] !== undefined))
})
test('comment anchors: mid-run, run edges, spanning, hyperlink', () => {
const mkPkg = (runs) => {
const pkg = Package.open(fixture('sample.docx'))
const doc = pkg.xml('word/document.xml')
const body = childrenOf(doc.documentElement, 'w:body')[0]
body.appendChild(doc.importNode(parseXml(`<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${runs}</w:p>`).documentElement, true))
pkg.putXml('word/document.xml', doc)
return pkg
}
const anchorOk = (pkg, pId, anchor) => {
docxEdit(pkg, [{ comment: { paragraph: pId, text: 'c', anchor } }])
const doc = pkg.xml('word/document.xml')
const p = elementsOf(doc.documentElement, 'w:p').at(-1)
const order = []
for (const el of elementsOf(p)) {
if (el.tagName === 'w:commentRangeStart') order.push('S')
if (el.tagName === 'w:commentRangeEnd') order.push('E')
if (el.tagName === 'w:commentReference') order.push('R')
}
assert.ok(order.indexOf('S') < order.indexOf('E'), `${anchor}: ${order}`)
assert.ok(order.indexOf('E') < order.indexOf('R'))
}
anchorOk(mkPkg('<w:r><w:t xml:space="preserve">aa bb cc</w:t></w:r>'), 'p7', 'bb')
anchorOk(mkPkg('<w:r><w:t xml:space="preserve">aa bb cc</w:t></w:r>'), 'p7', 'aa')
anchorOk(mkPkg('<w:r><w:t xml:space="preserve">aa bb cc</w:t></w:r>'), 'p7', 'cc')
anchorOk(mkPkg('<w:r><w:t>ab</w:t></w:r><w:r><w:t>cd</w:t></w:r>'), 'p7', 'bc')
anchorOk(mkPkg('<w:hyperlink w:anchor="t"><w:r><w:t>click here</w:t></w:r></w:hyperlink>'), 'p7', 'here')
})
test('check --fix on an unpacked dir flushes the model to disk', () => {
const dir = join(tmp(), 'un')
cli('unpack', fixture('sample.docx'), dir)
const pkg = Package.loadDir(dir)
pkg.override('word/styles.xml', 'application/xml')
pkg.relsOf('word/document.xml').set('rId99', { id: 'rId99', type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/header', target: 'missing.xml', mode: 'Internal' })
pkg.unpack(dir)
const res = cli('check', dir, '--fix', '--in-place')
assert.equal(res.ok, true)
assert.deepEqual(res.data.findings, [])
assert.deepEqual(checkPackage(Package.loadDir(dir)), [])
assert.ok(!readFileSync(join(dir, 'word/_rels/document.xml.rels'), 'utf8').includes('rId99'))
})
test('check --fix on a file no longer reports the dangling rel it fixed', () => {
const dir = tmp()
const bad = join(dir, 'b.docx')
const pkg = Package.open(fixture('sample.docx'))
pkg.relsOf('word/document.xml').set('rId99', { id: 'rId99', type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/header', target: 'missing.xml', mode: 'Internal' })
writeFileSync(bad, pkg.save())
const res = cli('check', bad, '--fix', '-o', join(dir, 'fixed.docx'))
assert.equal(res.ok, true)
assert.deepEqual(res.data.findings, [])
assert.deepEqual(checkPackage(Package.open(join(dir, 'fixed.docx'))), [])
})
test('pptx clean works on docx and xlsx', () => {
const dir = tmp()
for (const ext of ['docx', 'xlsx']) {
const res = cli('pptx', 'clean', fixture(`sample.${ext}`), '-o', join(dir, `c.${ext}`))
assert.equal(res.ok, true, JSON.stringify(res))
}
})
test('duplicated slides never overwrite a live rel id', () => {
const pkg = Package.open(fixture('sample.pptx'))
const pres = pkg.xml('ppt/presentation.xml')
const lst = childrenOf(pres.documentElement, 'p:sldIdLst')[0]
const entries = childrenOf(lst, 'p:sldId')
const removedRid = entries[1].getAttribute('r:id')
lst.removeChild(entries[1]) // gap in the rel ids
pkg.rels.get('ppt/presentation.xml').delete(removedRid)
pkg.putXml('ppt/presentation.xml', pres)
pptxSlides(pkg, [1, 1, 2])
const after = pkg.xml('ppt/presentation.xml')
const rids = childrenOf(childrenOf(after.documentElement, 'p:sldIdLst')[0], 'p:sldId').map(e => e.getAttribute('r:id'))
assert.equal(new Set(rids).size, rids.length)
for (const rid of rids) {
const rel = pkg.rels.get('ppt/presentation.xml').get(rid)
assert.ok(rel && pkg.parts.has(pkg.targetOf('ppt/presentation.xml', rel.target)), `${rid} unresolved`)
}
assert.equal(rids.length, 3)
})
test('docx read shows comments on their anchored block', () => {
const { blocks, comments } = docxRead(Package.open(fixture('sample.docx')))
const p3 = blocks.find(b => b.id === 'p3') // the fixture comment anchors to p3
assert.ok(comments.length > 0)
assert.ok(p3.comments?.length > 0)
})
test('xlsx dates honour date1904', () => {
const read = (pkg) => xlsxRead(pkg, 'Sheet1').rows.flatMap(r => Object.values(r.cells).map(c => c.v)).find(v => /^\d{4}-\d{2}-\d{2}/.test(String(v)))
const normal = read(Package.open(fixture('sample.xlsx')))
const pkg = Package.open(fixture('sample.xlsx'))
const wb = pkg.xml('xl/workbook.xml')
let pr = childrenOf(wb.documentElement, 'workbookPr')[0]
if (!pr) { pr = wb.createElement('workbookPr'); wb.documentElement.appendChild(pr) }
pr.setAttribute('date1904', '1')
pkg.putXml('xl/workbook.xml', wb)
const shifted = read(pkg)
assert.notEqual(shifted, normal)
assert.ok(Date.parse(shifted) > Date.parse(normal))
})
test('layout flags a picture past the slide edge', () => {
const pkg = Package.open(fixture('sample.pptx'))
const doc = pkg.xml('ppt/slides/slide1.xml')
const pic = elementsOf(doc.documentElement, 'p:pic')[0]
const off = elementsOf(pic, 'a:off')[0]
off.setAttribute('x', String(9144000)) // one inch past a 10in slide
pkg.putXml('ppt/slides/slide1.xml', doc)
const { findings } = pptxLayout(pkg)
assert.ok(findings.some(f => f.rule === 'off-slide' && /picture|pic/i.test(f.shape ?? '')))
})
})
describe('re-review pass 3', () => {
test('malformed .rels survives unpack and save byte-identical, check still reports it', () => {
const dir = tmp()
const members = readZip(readFileSync(fixture('sample.docx')))
const garbage = Buffer.from('<Relationships><broken')
for (const m of members) if (m.name === 'word/_rels/document.xml.rels') { delete m.raw; m.data = garbage }
const file = join(dir, 'bad.docx')
writeFileSync(file, writeZip(members))
const pkg = Package.open(file)
const out = join(dir, 'un')
pkg.unpack(out)
assert.equal(readFileSync(join(out, 'word/_rels/document.xml.rels')).toString(), garbage.toString())
const saved = readZip(pkg.save()).find(m => m.name === 'word/_rels/document.xml.rels')
assert.deepEqual(saved.data, garbage)
assert.ok(checkPackage(pkg).length > 0)
})
test('a valid-but-empty .rels keeps its bytes; a model-emptied map still deletes it', () => {
const dir = tmp()
const members = readZip(readFileSync(fixture('sample.docx')))
const empty = Buffer.from('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"/>')
for (const m of members) if (m.name === 'word/_rels/document.xml.rels') { delete m.raw; m.data = empty }
const file = join(dir, 'e.docx')
writeFileSync(file, writeZip(members))
const pkg = Package.open(file)
const out = join(dir, 'un')
pkg.unpack(out)
assert.equal(readFileSync(join(out, 'word/_rels/document.xml.rels')).toString(), empty.toString())
const full = Package.open(fixture('sample.docx'))
full.rels.get('word/document.xml').clear()
const names = readZip(full.save()).map(m => m.name)
assert.ok(!names.includes('word/_rels/document.xml.rels'))
})
test('xlsx dates honour date1904="true" too', () => {
const pkg = Package.open(fixture('sample.xlsx'))
const wb = pkg.xml('xl/workbook.xml')
const pr = childrenOf(wb.documentElement, 'workbookPr')[0] ?? wb.documentElement.appendChild(wb.createElement('workbookPr'))
pr.setAttribute('date1904', 'true')
pkg.putXml('xl/workbook.xml', wb)
const v = xlsxRead(pkg, 'Sheet1').rows.flatMap(r => Object.values(r.cells).map(c => c.v)).find(v => /^\d{4}-/.test(String(v)))
const normal = xlsxRead(Package.open(fixture('sample.xlsx')), 'Sheet1').rows.flatMap(r => Object.values(r.cells).map(c => c.v)).find(v => /^\d{4}-/.test(String(v)))
assert.ok(Date.parse(v) > Date.parse(normal))
})
test('a deflated member declaring 0 bytes but carrying data fails; a real empty member opens', () => {
const buf = writeZip([{ name: 'x.xml', data: Buffer.alloc(64, 66) }])
buf.writeUInt32LE(0, 22) // lie: declares 0 uncompressed bytes
const cdOff = buf.readUInt32LE(buf.length - 22 + 16)
buf.writeUInt32LE(0, cdOff + 24)
assert.throws(() => readZip(buf))
const ok = readZip(writeZip([{ name: 'e.xml', data: Buffer.alloc(0) }]))
assert.equal(ok[0].data.length, 0)
})
test('unpack refuses a linked subdirectory inside the destination', () => {
const dir = join(tmp(), 'un')
cli('unpack', fixture('sample.docx'), dir)
const outside = join(tmp(), 'real')
mkdirSync(outside, { recursive: true })
writeFileSync(join(outside, 'keep.txt'), 'x')
rmSync(join(dir, 'word'), { recursive: true })
symlinkSync(outside, join(dir, 'word'), 'junction')
assert.throws(() => execFileSync(NODE, [CLI, 'unpack', fixture('sample.docx'), dir, '--json']))
assert.ok(!existsSync(join(outside, 'document.xml')))
})
test('unpack refuses a symlinked file inside the destination', (t) => {
const dir = join(tmp(), 'un')
cli('unpack', fixture('sample.docx'), dir)
const outside = join(tmp(), 'out.xml')
writeFileSync(outside, '<x/>')
rmSync(join(dir, 'word/document.xml'))
try { symlinkSync(outside, join(dir, 'word/document.xml')) }
catch (err) { if (err.code === 'EPERM') { t.skip('no symlink privilege'); return } throw err }
assert.throws(() => execFileSync(NODE, [CLI, 'unpack', fixture('sample.docx'), dir, '--json']))
assert.ok(!readFileSync(outside, 'utf8').includes('w:document'))
})
})
describe('JSON findings shape (review 14)', () => {
test('findings come back ok:true with exit 1', () => {
const dir = tmp()
const pkg = Package.open(fixture('sample.docx'))
pkg.override('word/styles.xml', 'application/xml')
const file = join(dir, 'bad.docx')
writeFileSync(file, pkg.save())
const res = cli('check', file)
assert.equal(res.ok, true)
assert.ok(res.data.findings.some(f => f.rule === 'wrong-content-type'))
let status = 0
try { execFileSync(NODE, [CLI, 'check', file, '--json']) } catch (e) { status = e.status }
assert.equal(status, 1)
})
})
describe('flush keeps untouched members (review 16)', () => {
test('a document.xml-only edit preserves every other member byte', () => {
const src = fixture('sample.docx')
const pkg = Package.open(src)
const before = readZip(readFileSync(src))
docxEdit(pkg, [{ set_cell: { table: 1, row: 2, col: 2, text: '99' } }])
const after = readZip(pkg.save())
const changed = after.filter(m => {
const old = before.find(b => b.name === m.name)
return !old || !old.raw.equals(m.raw)
}).map(m => m.name)
assert.deepEqual(changed.sort(), ['word/document.xml'])
})
})