fix(docx): handle numeric char refs, NBSP edges and empty self-closing runs in field patch (#359)

* fix(docx): handle numeric char refs, NBSP edges and empty self-closing runs in field patch

* fix(docx): correct NBSP test expectation for trimmed fieldDisplay

* fix(docx): guard char-ref codepoints and assert NBSP on patched XML only

- decodeXmlText leaves out-of-range (>0x10FFFF) and surrogate (0xD800-0xDFFF) refs untouched instead of throwing RangeError; regression test covers �, � and surrogates.

NBSP edge test now asserts patched XML only (xml:space preserve + NBSP in <w:t>), dropping the fieldDisplay round-trip which normalizes edge whitespace regardless of xml:space.

---------

Co-authored-by: Aniruddha Adak <aniruddhaadak80@users.noreply.github.com>
This commit is contained in:
ANIRUDDHA ADAK
2026-09-14 14:25:09 +08:00
committed by GitHub
co-authored by Aniruddha Adak
parent 78f133c216
commit cbcd289e49
2 changed files with 84 additions and 3 deletions
+37 -3
View File
@@ -256,11 +256,24 @@ function decodeXmlText(text: string): string {
.replace(/&gt;/g, '>') .replace(/&gt;/g, '>')
.replace(/&quot;/g, '"') .replace(/&quot;/g, '"')
.replace(/&apos;/g, "'") .replace(/&apos;/g, "'")
.replace(/&#(\d+);/g, (_m, dec: string) => {
const cp = Number(dec)
if (!Number.isFinite(cp) || cp < 0 || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff))
return _m
return String.fromCodePoint(cp)
})
.replace(/&#x([0-9a-fA-F]+);/g, (_m, hex: string) => {
const cp = parseInt(hex, 16)
if (!Number.isFinite(cp) || cp < 0 || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff))
return _m
return String.fromCodePoint(cp)
})
.replace(/&amp;/g, '&') .replace(/&amp;/g, '&')
} }
function textNodes(xml: string, tag: 'w:t' | 'm:t'): XmlTextNode[] { function textNodes(xml: string, tag: 'w:t' | 'm:t'): XmlTextNode[] {
const nodes: XmlTextNode[] = [] const nodes: XmlTextNode[] = []
// Paired text nodes: <w:t>text</w:t> (may carry xml:space)
const re = new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${tag}>`, 'g') const re = new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${tag}>`, 'g')
let match: RegExpExecArray | null let match: RegExpExecArray | null
while ((match = re.exec(xml)) !== null) { while ((match = re.exec(xml)) !== null) {
@@ -274,6 +287,20 @@ function textNodes(xml: string, tag: 'w:t' | 'm:t'): XmlTextNode[] {
text: decodeXmlText(match[1]), text: decodeXmlText(match[1]),
}) })
} }
// Self-closing empty text nodes: <w:t/> (Word sometimes emits these for empty runs)
const selfRe = new RegExp(`<${tag}(?:\\s[^>]*)?/>`, 'g')
while ((match = selfRe.exec(xml)) !== null) {
// Avoid double-counting when the paired regex already consumed it (it doesn't, but be safe)
if (nodes.some((n) => n.start === match!.index)) continue
nodes.push({
start: match.index,
end: match.index + match[0].length,
open: match[0],
close: '',
text: '',
})
}
nodes.sort((a, b) => a.start - b.start)
return nodes return nodes
} }
@@ -300,12 +327,19 @@ function replaceTextNodes(
let out = xml let out = xml
for (const { node, text } of [...replacements].sort((a, b) => b.node.start - a.node.start)) { for (const { node, text } of [...replacements].sort((a, b) => b.node.start - a.node.start)) {
// wtText drops edge whitespace without xml:space="preserve": pin it when // wtText drops edge whitespace without xml:space="preserve": pin it when
// the replacement introduces a leading/trailing space or tab. // the replacement introduces leading/trailing whitespace. Word trims more
// than just tab/space (NBSP, zero-width, line breaks, CJK spaces).
const hasEdgeWs =
text.length > 0 &&
(/^\s|\s$/.test(text) || text.startsWith('\u200B') || text.endsWith('\u200B'))
const open = const open =
/xml:space\s*=/.test(node.open) || !/(^[\t ]|[\t ]$)/.test(text) /xml:space\s*=/.test(node.open) || !hasEdgeWs
? node.open ? node.open
: node.open.replace(/<w:t(?=\s|>)/, '<w:t xml:space="preserve"') : node.open.replace(/<w:t(?=\s|>)/, '<w:t xml:space="preserve"')
const replacement = open + escapeXmlText(text) + node.close // Self-closing empty run: expand to paired form so the replacement lands
const close = node.close || `</w:t>`
const openPaired = node.close ? open : open.replace(/\/>$/, '>')
const replacement = openPaired + escapeXmlText(text) + close
out = out.slice(0, node.start) + replacement + out.slice(node.end) out = out.slice(0, node.start) + replacement + out.slice(node.end)
} }
return out return out
@@ -75,4 +75,51 @@ describe('protected visible-text patching', () => {
it('refuses a formula patch when token count changes', () => { it('refuses a formula patch when token count changes', () => {
expect(patchMathTokens(FORMULA, ['only-one'])).toBe(FORMULA) expect(patchMathTokens(FORMULA, ['only-one'])).toBe(FORMULA)
}) })
it('handles numeric char refs so distribution stays aligned', async () => {
const entry =
'<w:p><w:pPr><w:pStyle w:val="TOC1"/></w:pPr>' +
'<w:r><w:t>Foo &#8211; Bar</w:t></w:r><w:r><w:tab/></w:r>' +
'<w:r><w:t>12</w:t></w:r></w:p>'
const patched = patchFieldParagraphXml(entry, { left: 'Foo – Baz', right: '13' })
const parsed = await parseDocx(await buildDocx({ bodyXml: patched }))
expect(parsed.blocks[0].fieldDisplay?.left).toBe('Foo – Baz')
expect(parsed.blocks[0].fieldDisplay?.right).toBe('13')
})
it('pins preserve for NBSP and other whitespace at edges (not just tab/space)', () => {
const entry =
'<w:p><w:pPr><w:pStyle w:val="TOC1"/></w:pPr>' +
'<w:r><w:t>Title</w:t></w:r><w:r><w:tab/></w:r>' +
'<w:r><w:t>7</w:t></w:r></w:p>'
const nbsp = '\u00A0Title\u00A0'
const patched = patchFieldParagraphXml(entry, { left: nbsp, right: '7' })
expect(patched).toContain('xml:space="preserve"')
expect(patched).toContain(`<w:t xml:space="preserve">${nbsp}</w:t>`)
expect(patched).toContain('\u00A0Title\u00A0')
})
it('patches a self-closing empty run (<w:t/>) instead of no-oping', async () => {
const entry =
'<w:p><w:pPr><w:pStyle w:val="TOC1"/></w:pPr>' +
'<w:r><w:t/></w:r><w:r><w:tab/></w:r>' +
'<w:r><w:t>7</w:t></w:r></w:p>'
const patched = patchFieldParagraphXml(entry, { left: 'Hello', right: '7' })
expect(patched).toContain('<w:t>Hello</w:t>')
const parsed = await parseDocx(await buildDocx({ bodyXml: patched }))
expect(parsed.blocks[0].fieldDisplay?.left).toBe('Hello')
})
it('leaves out-of-range and surrogate char refs untouched instead of throwing', () => {
const base =
'<w:p><w:pPr><w:pStyle w:val="TOC1"/></w:pPr>' +
'<w:r><w:t>REFTEXT</w:t></w:r><w:r><w:tab/></w:r>' +
'<w:r><w:t>12</w:t></w:r></w:p>'
for (const ref of ['&#99999999;', '&#xFFFFFFFF;', '&#55296;', '&#xD800;']) {
const entry = base.replace('REFTEXT', `A ${ref} B`)
expect(() => patchFieldParagraphXml(entry, { left: 'A X B', right: '13' })).not.toThrow()
const patched = patchFieldParagraphXml(entry, { left: 'A X B', right: '13' })
expect(patched).toContain('A X B')
}
})
}) })