Editor replaceRange transaction out of range

Hi, I have been trying to call the replaceRange transaction method on positions that should definitely be in range, but continue to get a RangeError: Position X out of range.

When running this:

      const from = range.range.start.index + 1;
      const to = range.range.end.index + 1;
      const expression = initialValue.expressions[range.code];
      const node = getExpressionNode(expression);
      transaction.replaceRangeWith(from, to, node);

The ranges I am providing above are valid ranges in the editorState.doc.textContent that I am calculating based on regex patterns.

That code throws the error above, and when console logging first the end value and then also calculating the last position using const lastPos = Selection.atEnd(editorState.doc)?.anchor; My end position is lower than the lastPost, i.e: end = 177, lastPos = 185.

Trying to figure out why it’s complaining about being out of range when everything leads me to believe it is in fact in range. Any help is appreciated, thanks in advance!

Could it be that the document is corrupted somehow? Can you create a stand-alone example script that reproduces the error?

I can put together more of an example but it will take me a bit.

One thing that comes to mind now, is I am mapping through an array of ranges to then call replaceRangeWith the nodes. Once the first one happens would my document content length then be shorter so that the second replacement step now has invalid ranges that I gave it first. All of this is happening in steps of a transaction dispatched at once.

Yes, subsequent steps act on tr.doc, which may have a different size than the start doc if you deleted/inserted stuff.