Skip to content

text.rewrite rejects where: { by: 'target' } at runtime although TargetWhere is part of the public StepWhere union #3969

Closed

Description

@palmoni5

Summary

doc.mutations.apply({ atomic: true, steps: [{ op: 'text.rewrite', where: { by: 'target', target }, ... }] }) is rejected at runtime, although TargetWhere is part of the public StepWhere union in document-api/src/types/mutation-plan.types.d.ts:

export type TargetWhere = { by: 'target'; target: SelectionTarget };
export type StepWhere = SelectWhere | RefWhere | TargetWhere | BlockWhere;

The call fails with:

DocumentApiValidationError: v2 text.rewrite currently requires a ref produced by query.match/find or a single text selector.

So the types advertise a by-offset target, but the v2 implementation only accepts by: 'ref' and by: 'select'.

Versions

  • Measured against the packaged dist of superdoc@2.10.0.
  • superdoc@2.11.0: the TargetWhere declaration in mutation-plan.types.d.ts is unchanged.

Why this matters

A "fix all" style tool (hundreds of small, offset-addressed text edits across a document, each already resolved to a SelectionTarget) has exactly two options today:

  • where: { by: 'select', select: { type: 'text', pattern }, within: block, require: 'all' } — works and gives a single undo step, but it addresses by pattern, so it cannot express "the same pattern gets two different replacements in the same paragraph" (e.g. " ." becomes "." at one place and ". " at another, depending on what follows).
  • where: { by: 'block' } — rewrites the whole block text. Works, but on a paragraph with mixed run formatting the rewritten text is re-styled with onNonUniform: 'majority', silently flattening bold/italic runs. That is a worse regression than losing atomic undo.

Result: we fall back to N separate doc.replace({ target, text }) calls, which means N undo steps for the user (300 fixes = 300 Ctrl+Z).

Expected

Either by: 'target' is accepted by text.rewrite (it is the most natural input for callers that already computed exact ranges), or the member is removed from StepWhere so the gap shows up at compile time instead of at runtime. The first would be far more useful.

Minimal reproduction

const doc = superdoc.activeEditor.doc;
const { blocks } = await doc.blocks.list({ includeText: true });
const block = blocks[0];
// a text range inside `block`, as returned by doc.find / query.match or computed from block.text
const target = {
  kind: 'selection',
  start: { kind: 'text', blockId: block.nodeId, offset: 0 },
  end:   { kind: 'text', blockId: block.nodeId, offset: 3 },
};
await doc.mutations.apply({
  atomic: true,
  changeMode: 'direct',
  steps: [{ op: 'text.rewrite', where: { by: 'target', target }, text: 'xyz' }],
});
// -> DocumentApiValidationError: v2 text.rewrite currently requires a ref produced by query.match/find or a single text selector.

The same step with where: { by: 'select', select: { type: 'text', pattern: '...' }, within: { kind: 'block', nodeType: 'paragraph', nodeId: block.nodeId }, require: 'all' } succeeds.

Activity

  1. linear-code commented on Sep 3, 2026

    @linear-code
  2. added
    status: triage
    on Sep 3, 2026
  3. Nathaniel-260 commented on Sep 5, 2026

    @Nathaniel-260
    Contributor

    @caio-pizzol @vivienne-sd @jelkes1 — a bit of context first: @palmoni5, who opened this issue and its two siblings (#3970, #3971), is a developer on my team. We are building an open-source (AGPLv3) Word add-on for Otzaria on top of SuperDoc together, and PR #3950 came from us as well. And let me say it plainly: it is a pleasure working with you — the attention our reports have gotten has been genuinely great.

    We already have this repo checked out and building locally, so before anyone on our side starts writing code, we would rather ask than guess: would you accept PRs for the three issues below, and does the code that has to change actually live in this repo?

    #3969 — text.rewrite rejects where: { by: 'target' }

    The public contract already admits it in two places: TargetWhere is part of the exported StepWhere union (packages/document-api/src/types/mutation-plan.types.ts), and textRewriteStepSchema validates where with stepWhereSchema, whose oneOf includes targetWhereSchema (packages/document-api/src/contract/schemas.ts). The runtime rejection message, however, does not appear anywhere in this repository's tracked sources — so we assume the v2 step executor is not public. Two questions:

    1. Which resolution do you actually want: accept by: 'target' in text.rewrite, or narrow the type and the schema so the gap surfaces at compile time instead of at runtime?
    2. If it is the former — is the executor in a package we can send a PR to? If it is not, we are happy to do the type/schema half and leave the runtime to you, but we would rather not open a PR that turns out mid-way to be able to fix only one side.

    #3971 — allow writing jc="distribute"

    This one looks self-contained in public code. PARAGRAPH_ALIGNMENTS (packages/document-api/src/paragraphs/paragraphs.types.ts) is the single gate — both the validator in paragraphs.ts and the schema enum derive from it — while ST_JUSTIFICATION (styles/registry.ts) already lists distribute, and the read model already reports distributed (types/paragraph.types.ts). So the value can be read but not written.

    We would send: the constant, the write path down to w:jc w:val="distribute", and a round-trip test. The naming call is yours — 'distribute' to match OOXML, or 'distributed' to match what the read model returns today. Would you take that PR?

    #3970 — read-only layout query API

    This is the big one, and the one we would least like to design on our own. What we need is read-only: lines per paragraph, page boundaries, and a signal for "pagination has settled". If you would accept it in principle, we would like a steer on the shape before we write anything — a promise-based accessor on the SuperDoc instance, an event, or something you already have in mind. We would rather fit whatever the layout packages already model than invent a new public surface next to it.

    A "no" or a "not like that" on any of these is genuinely useful to us — much better now than after the PR is written. And if there is a CLA step beyond what we did for #3950, tell us and we will take care of it.

  4. ghost added
    status: investigating
    on Sep 11, 2026
  5. ghost removed
    status: triage
    on Sep 11, 2026
  6. ghost added
    status: queued
    on Sep 11, 2026
  7. ghost removed
    status: investigating
    on Sep 11, 2026
  8. caio-pizzol commented on Sep 11, 2026

    @caio-pizzol
    Contributor

    @palmoni5 @Nathaniel-260 We confirmed the text.rewrite mismatch: the public API accepts explicit selection targets, but the v2 runtime rejects them. We also tested range references; they work for a single rewrite but are rejected in multi-step plans, so they don’t solve your batch-editing case.

    We’ve opened an engineering issue to address this. The rejecting code lives in the private v2 runtime, so a PR changing only the public types or schema wouldn’t resolve it. Thanks for the detailed reproduction—it helped us verify the issue and the batch-editing limitation.

  9. ghost added
    status: in-progress
    on Sep 18, 2026
  10. ghost removed
    status: queued
    on Sep 18, 2026
  11. ghost added
    status: awaiting-release
    on Sep 21, 2026
  12. ghost removed
    status: in-progress
    on Sep 21, 2026
  13. ghost added
    status: ready-for-validation
    on Sep 21, 2026
  14. ghost removed
    status: awaiting-release
    on Sep 21, 2026
  15. ghost added
    status: done
    on Sep 22, 2026
  16. ghost removed
    status: ready-for-validation
    on Sep 22, 2026
  17. teo-azzollini commented on Sep 24, 2026

    @teo-azzollini
    Collaborator

    @palmoni5 @Nathaniel-260 , quick update: this is now fixed in 2.16.1-next.7 and beyond. text.rewrite now accepts explicit selection targets in batched mutation plans, so your offset-addressed edits can be applied atomically without falling back to separate doc.replace() calls. Thanks again for the detailed reproduction—if you’re able to test it against the Otzaria workflow, we’d appreciate your confirmation.

  18. ghost added theissue type on Sep 24, 2026
  19. palmoni5 commented on Sep 24, 2026

    @palmoni5
    Author

    @teo-azzollini thanks! We tested it against superdoc@2.17.0 (@superdoc/docx-engine@0.16.0) on the real engine: built app in Chromium, results checked against the exported word/document.xml.

    Confirmed working: one by: 'target' step per block, across several blocks in one atomic plan. It applies correctly, one Ctrl+Z reverts the whole plan, and mixed run formatting (a bold run next to the edit) is preserved. by: 'target' combined with by: 'select' in the same block also works.

    Still blocked: two by: 'target' steps in the same block, which was the case that motivated this issue (the same pattern getting two different replacements in one paragraph). It is rejected in any step order, and even when every replacement keeps its range's length:

    DocumentApiValidationError: step "s1" shares a block with another by:"target" text-shifting step in this plan; explicit offsets are not re-derived between steps, so an earlier same-block step can shift this one's offsets. Split same-block edits into separate mutations.apply calls, or use by:"select" for later occurrences in the same block.
    
    // paragraph text: "ab . cd . ef"
    const id = (await doc.blocks.list({ includeText: true })).blocks[0].nodeId;
    const t = (s, e) => ({ kind: 'selection', start: { kind: 'text', blockId: id, offset: s }, end: { kind: 'text', blockId: id, offset: e } });
    await doc.mutations.apply({
      atomic: true,
      changeMode: 'direct',
      steps: [
        { id: 's1', op: 'text.rewrite', where: { by: 'target', target: t(2, 4) }, args: { replacement: { text: '.' } } },
        { id: 's2', op: 'text.rewrite', where: { by: 'target', target: t(7, 9) }, args: { replacement: { text: '. ' } } },
      ],
    });
    // -> rejected; expected "ab. cd.  ef"

    The suggested workarounds don't cover a "fix all" tool, where several fixes per paragraph are the norm:

    • Separate calls: the undo count becomes the largest number of fixes in any one paragraph instead of 1.
    • by: 'select': addresses by pattern, so it cannot express different replacements for the same pattern in the same paragraph.
    • One by: 'target' range from a block's first fix to its last: re-styles the untouched text in between with the first run's formatting.

    Suggestion: a follow-up issue for same-block targets, since the explicit-offset guard looks like a deliberate design decision rather than a leftover. Two shapes would work for us, and which one is up to you:

    1. Resolve all by: 'target' steps against the pre-plan state, applying same-block steps in descending offset order (or re-mapping them through the accumulated shifts). Overlapping targets are rejected. This matches how callers compute offsets: all of them from one blocks.list snapshot.
    2. One text.rewrite step with several ranges, e.g. where: { by: 'targets', targets: [...] } with a replacement per range.

    Happy to open it with the full write-up, or would you prefer to track it here?

    One minor thing from the same measurement: a by: 'target' rewrite whose range ends inside a formatted run leaves an empty run carrying that formatting. Paragraph ab . cd . ef with cd bold, target [4, 8) → "QQQQ":

    <w:r><w:t>ab .</w:t><w:t>QQQQ</w:t></w:r><w:r><w:rPr><w:b/></w:rPr></w:r><w:r><w:t>. ef</w:t></w:r>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: done

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions