Skip to content

Headless agent edits corrupt the document: cloneDocument JSON-clones away Maps/ArrayBuffers, breaking export + dropping images #992

Description

@aldrinjenson

Describe the bug

cloneDocument runs on every headless agent edit (executeCommandcloneDocument) and deep-clones via JSON.parse(JSON.stringify(doc)). JSON can't represent several fields the document model carries, so the clone silently corrupts them:

  • package.headers / package.footers / package.media are Maps → become {}
  • originalBuffer and each MediaFile.data are ArrayBuffers → become {}
  • package.properties.created / modified are Dates → become strings

The result is load-bearing: a no-edit export works, but after the first edit export throws and images are lost.

To Reproduce

import { DocumentAgent } from '@eigenpal/docx-editor-core/headless';

const agent = await DocumentAgent.fromBuffer(bytes);   // any real .docx
await agent.toBuffer();                                  // ✅ works (no edit)

const edited = agent.insertText({ paragraphIndex: 0, offset: 0 }, 'Hello ');
await edited.toBuffer();                                 // ❌ throws

Depending on the document, the throw is one of:

  • Can't read the data of 'the loaded zip file'repackDocxJSZip.loadAsync(originalBuffer) on the {} left where the ArrayBuffer was.
  • map.entries is not a functionrepackDocx's collectParts iterating package.headers / footers, now {} instead of Maps.

Any document with images also loses every image on the first edit (the media Map is gone). insertTable(...).toBuffer() fails the same way.

Expected behavior

A headless generate → edit → export round-trip should produce a valid .docx (and keep headers/footers and images), since this is the documented fromBuffer → edit → toBuffer flow.

Root cause

cloneDocument (packages/core/src/agent/executor/helpers.ts) uses JSON.parse(JSON.stringify(doc)), which cannot round-trip Map, ArrayBuffer, or Date.

Additional context

  • Affects the fully headless / server-side workflow (generate + edit + export without ever opening the editor).
  • Reproduced on @eigenpal/docx-editor-core 1.9.0.
  • Fix proposed in fix(core): preserve Maps and buffers when cloning a document for edits #990 (clone with structuredClone; share the read-only originalBuffer and shallow-copy the immutable media map so large binaries aren't recopied per edit).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions