From cbcd289e49e41a2968a1fd7485e422fa748a2af7 Mon Sep 17 00:00:00 2001 From: ANIRUDDHA ADAK Date: Mon, 14 Sep 2026 11:55:09 +0530 Subject: [PATCH] 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 ), dropping the fieldDisplay round-trip which normalizes edge whitespace regardless of xml:space. --------- Co-authored-by: Aniruddha Adak --- packages/docx-engine/src/generate.ts | 40 ++++++++++++++-- .../tests/protected-text-edit.test.ts | 47 +++++++++++++++++++ 2 files changed, 84 insertions(+), 3 deletions(-) diff --git a/packages/docx-engine/src/generate.ts b/packages/docx-engine/src/generate.ts index 7db69b6..dbbd5f5 100644 --- a/packages/docx-engine/src/generate.ts +++ b/packages/docx-engine/src/generate.ts @@ -256,11 +256,24 @@ function decodeXmlText(text: string): string { .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/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(/&/g, '&') } function textNodes(xml: string, tag: 'w:t' | 'm:t'): XmlTextNode[] { const nodes: XmlTextNode[] = [] + // Paired text nodes: text (may carry xml:space) const re = new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${tag}>`, 'g') let match: RegExpExecArray | 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]), }) } + // Self-closing empty text nodes: (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 } @@ -300,12 +327,19 @@ function replaceTextNodes( let out = xml 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 - // 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 = - /xml:space\s*=/.test(node.open) || !/(^[\t ]|[\t ]$)/.test(text) + /xml:space\s*=/.test(node.open) || !hasEdgeWs ? node.open : node.open.replace(/)/, '` + const openPaired = node.close ? open : open.replace(/\/>$/, '>') + const replacement = openPaired + escapeXmlText(text) + close out = out.slice(0, node.start) + replacement + out.slice(node.end) } return out diff --git a/packages/docx-engine/tests/protected-text-edit.test.ts b/packages/docx-engine/tests/protected-text-edit.test.ts index 3cd6f98..6950a08 100644 --- a/packages/docx-engine/tests/protected-text-edit.test.ts +++ b/packages/docx-engine/tests/protected-text-edit.test.ts @@ -75,4 +75,51 @@ describe('protected visible-text patching', () => { it('refuses a formula patch when token count changes', () => { expect(patchMathTokens(FORMULA, ['only-one'])).toBe(FORMULA) }) + + it('handles numeric char refs so distribution stays aligned', async () => { + const entry = + '' + + 'Foo – Bar' + + '12' + 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 = + '' + + 'Title' + + '7' + const nbsp = '\u00A0Title\u00A0' + const patched = patchFieldParagraphXml(entry, { left: nbsp, right: '7' }) + expect(patched).toContain('xml:space="preserve"') + expect(patched).toContain(`${nbsp}`) + expect(patched).toContain('\u00A0Title\u00A0') + }) + + it('patches a self-closing empty run () instead of no-oping', async () => { + const entry = + '' + + '' + + '7' + const patched = patchFieldParagraphXml(entry, { left: 'Hello', right: '7' }) + expect(patched).toContain('Hello') + 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 = + '' + + 'REFTEXT' + + '12' + for (const ref of ['�', '�', '�', '�']) { + 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') + } + }) })