"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.MergeTree = exports.clientSeqComparer = void 0;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable @typescript-eslint/consistent-type-assertions */
/* eslint-disable @typescript-eslint/prefer-optional-chain, no-bitwise */
const common_utils_1 = require("@fluidframework/common-utils");
const container_utils_1 = require("@fluidframework/container-utils");
const attributionCollection_1 = require("./attributionCollection");
const collections_1 = require("./collections");
const constants_1 = require("./constants");
const localReference_1 = require("./localReference");
const mergeTreeNodes_1 = require("./mergeTreeNodes");
const mergeTreeDeltaCallback_1 = require("./mergeTreeDeltaCallback");
const opBuilder_1 = require("./opBuilder");
const ops_1 = require("./ops");
const partialLengths_1 = require("./partialLengths");
const properties_1 = require("./properties");
const referencePositions_1 = require("./referencePositions");
const segmentPropertiesManager_1 = require("./segmentPropertiesManager");
const mergeTreeNodeWalk_1 = require("./mergeTreeNodeWalk");
const zamboni_1 = require("./zamboni");
const minListenerComparer = {
    min: {
        minRequired: Number.MIN_VALUE,
        onMinGE: () => {
            (0, common_utils_1.assert)(false, 0x048 /* "onMinGE()" */);
        },
    },
    compare: (a, b) => a.minRequired - b.minRequired,
};
function isRemoved(segment) {
    return (0, mergeTreeNodes_1.toRemovalInfo)(segment) !== undefined;
}
function isRemovedAndAcked(segment) {
    const removalInfo = (0, mergeTreeNodes_1.toRemovalInfo)(segment);
    return removalInfo !== undefined && removalInfo.removedSeq !== constants_1.UnassignedSequenceNumber;
}
function nodeTotalLength(mergeTree, node) {
    if (!node.isLeaf()) {
        return node.cachedLength;
    }
    return mergeTree.localNetLength(node);
}
const LRUSegmentComparer = {
    min: { maxSeq: -2 },
    compare: (a, b) => a.maxSeq - b.maxSeq,
};
function applyLeafRangeMarker(marker, searchInfo) {
    for (const rangeLabel of searchInfo.rangeLabels) {
        if ((0, referencePositions_1.refHasRangeLabel)(marker, rangeLabel)) {
            let currentStack = searchInfo.stacks[rangeLabel];
            if (currentStack === undefined) {
                currentStack = new collections_1.Stack();
                searchInfo.stacks[rangeLabel] = currentStack;
            }
            applyRangeReference(currentStack, marker);
        }
    }
}
function recordRangeLeaf(segment, segpos, refSeq, clientId, start, end, searchInfo) {
    if (mergeTreeNodes_1.Marker.is(segment)) {
        if (segment.refType & (ops_1.ReferenceType.NestBegin | ops_1.ReferenceType.NestEnd)) {
            applyLeafRangeMarker(segment, searchInfo);
        }
    }
    return false;
}
function rangeShift(node, segpos, refSeq, clientId, offset, end, searchInfo) {
    var _a;
    if (node.isLeaf()) {
        const seg = node;
        if (((_a = searchInfo.mergeTree.localNetLength(seg)) !== null && _a !== void 0 ? _a : 0) > 0 && mergeTreeNodes_1.Marker.is(seg)) {
            if (seg.refType & (ops_1.ReferenceType.NestBegin | ops_1.ReferenceType.NestEnd)) {
                applyLeafRangeMarker(seg, searchInfo);
            }
        }
    }
    else {
        const block = node;
        applyStackDelta(searchInfo.stacks, block.rangeStacks);
    }
    return true;
}
function recordTileStart(segment, segpos, refSeq, clientId, start, end, searchInfo) {
    if (mergeTreeNodes_1.Marker.is(segment)) {
        if ((0, referencePositions_1.refHasTileLabel)(segment, searchInfo.tileLabel)) {
            searchInfo.tile = segment;
        }
    }
    return false;
}
function tileShift(node, segpos, refSeq, clientId, offset, end, searchInfo) {
    var _a;
    if (node.isLeaf()) {
        const seg = node;
        if (((_a = searchInfo.mergeTree.localNetLength(seg)) !== null && _a !== void 0 ? _a : 0) > 0 && mergeTreeNodes_1.Marker.is(seg)) {
            if ((0, referencePositions_1.refHasTileLabel)(seg, searchInfo.tileLabel)) {
                searchInfo.tile = seg;
            }
        }
    }
    else {
        const block = node;
        const marker = searchInfo.tilePrecedesPos
            ? block.rightmostTiles[searchInfo.tileLabel]
            : block.leftmostTiles[searchInfo.tileLabel];
        if (marker !== undefined) {
            searchInfo.tile = marker;
        }
    }
    return true;
}
function addTile(tile, tiles) {
    const tileLabels = (0, referencePositions_1.refGetTileLabels)(tile);
    if (tileLabels) {
        for (const tileLabel of tileLabels) {
            tiles[tileLabel] = tile;
        }
    }
}
function addTileIfNotPresent(tile, tiles) {
    const tileLabels = (0, referencePositions_1.refGetTileLabels)(tile);
    if (tileLabels) {
        for (const tileLabel of tileLabels) {
            if (tiles[tileLabel] === undefined) {
                tiles[tileLabel] = tile;
            }
        }
    }
}
function applyStackDelta(currentStackMap, deltaStackMap) {
    // eslint-disable-next-line guard-for-in, no-restricted-syntax
    for (const label in deltaStackMap) {
        const deltaStack = deltaStackMap[label];
        if (!deltaStack.empty()) {
            let currentStack = currentStackMap[label];
            if (currentStack === undefined) {
                currentStack = new collections_1.Stack();
                currentStackMap[label] = currentStack;
            }
            for (const delta of deltaStack.items) {
                applyRangeReference(currentStack, delta);
            }
        }
    }
}
function applyRangeReference(stack, delta) {
    if ((0, referencePositions_1.refTypeIncludesFlag)(delta, ops_1.ReferenceType.NestBegin)) {
        stack.push(delta);
        return true;
    }
    else {
        // Assume delta is end reference
        const top = stack.top();
        // TODO: match end with begin
        if (top && (0, referencePositions_1.refTypeIncludesFlag)(top, ops_1.ReferenceType.NestBegin)) {
            stack.pop();
        }
        else {
            stack.push(delta);
        }
        return false;
    }
}
function addNodeReferences(mergeTree, node, rightmostTiles, leftmostTiles, rangeStacks) {
    var _a;
    function updateRangeInfo(label, refPos) {
        let stack = rangeStacks[label];
        if (stack === undefined) {
            stack = new collections_1.Stack();
            rangeStacks[label] = stack;
        }
        applyRangeReference(stack, refPos);
    }
    if (node.isLeaf()) {
        const segment = node;
        if (((_a = mergeTree.localNetLength(segment)) !== null && _a !== void 0 ? _a : 0) > 0) {
            if (mergeTreeNodes_1.Marker.is(segment)) {
                const markerId = segment.getId();
                // Also in insertMarker but need for reload segs case
                // can add option for this only from reload segs
                if (markerId) {
                    mergeTree.mapIdToSegment(markerId, segment);
                }
                if ((0, referencePositions_1.refTypeIncludesFlag)(segment, ops_1.ReferenceType.Tile)) {
                    addTile(segment, rightmostTiles);
                    addTileIfNotPresent(segment, leftmostTiles);
                }
                if (segment.refType & (ops_1.ReferenceType.NestBegin | ops_1.ReferenceType.NestEnd)) {
                    const rangeLabels = (0, referencePositions_1.refGetRangeLabels)(segment);
                    if (rangeLabels) {
                        for (const label of rangeLabels) {
                            updateRangeInfo(label, segment);
                        }
                    }
                }
            }
            else {
                const baseSegment = node;
                if (baseSegment.localRefs &&
                    baseSegment.localRefs.hierRefCount !== undefined &&
                    baseSegment.localRefs.hierRefCount > 0) {
                    for (const lref of baseSegment.localRefs) {
                        if ((0, referencePositions_1.refTypeIncludesFlag)(lref, ops_1.ReferenceType.Tile)) {
                            addTile(lref, rightmostTiles);
                            addTileIfNotPresent(lref, leftmostTiles);
                        }
                        if (lref.refType & (ops_1.ReferenceType.NestBegin | ops_1.ReferenceType.NestEnd)) {
                            for (const label of (0, referencePositions_1.refGetRangeLabels)(lref)) {
                                updateRangeInfo(label, lref);
                            }
                        }
                    }
                }
            }
        }
    }
    else {
        const block = node;
        applyStackDelta(rangeStacks, block.rangeStacks);
        (0, properties_1.extend)(rightmostTiles, block.rightmostTiles);
        extendIfUndefined(leftmostTiles, block.leftmostTiles);
    }
}
function extendIfUndefined(base, extension) {
    if (extension !== undefined) {
        // eslint-disable-next-line no-restricted-syntax
        for (const key in extension) {
            if (base[key] === undefined) {
                base[key] = extension[key];
            }
        }
    }
    return base;
}
class HierMergeBlock extends mergeTreeNodes_1.MergeBlock {
    constructor(childCount) {
        super(childCount);
        this.rightmostTiles = (0, properties_1.createMap)();
        this.leftmostTiles = (0, properties_1.createMap)();
        this.rangeStacks = (0, properties_1.createMap)();
    }
    hierBlock() {
        return this;
    }
    hierToString(indentCount) {
        let strbuf = "";
        // eslint-disable-next-line guard-for-in, no-restricted-syntax
        for (const key in this.rangeStacks) {
            const stack = this.rangeStacks[key];
            strbuf += (0, mergeTreeNodes_1.internedSpaces)(indentCount);
            strbuf += `${key}: `;
            for (const item of stack.items) {
                strbuf += `${item.toString()} `;
            }
            strbuf += "\n";
        }
        return strbuf;
    }
}
/**
 * @deprecated For internal use only. public export will be removed.
 * @internal
 */
exports.clientSeqComparer = {
    min: { refSeq: -1, clientId: "" },
    compare: (a, b) => a.refSeq - b.refSeq,
};
/**
 * @internal
 */
class MergeTree {
    constructor(options) {
        this.options = options;
        this.blockUpdateActions = MergeTree.initBlockUpdateActions;
        this.collabWindow = new mergeTreeNodes_1.CollaborationWindow();
        /**
         * Whether or not all blocks in the mergeTree currently have information about local partial lengths computed.
         * This information is only necessary on reconnect, and otherwise costly to bookkeep.
         * This field enables tracking whether partials need to be recomputed using localSeq information.
         */
        this.localPartialsComputed = false;
        // TODO: add remove on segment remove
        // for now assume only markers have ids and so point directly at the Segment
        // if we need to have pointers to non-markers, we can change to point at local refs
        this.idToSegment = new Map();
        this.splitLeafSegment = (segment, pos) => {
            var _a;
            if (!(pos > 0 && segment)) {
                return {};
            }
            const next = segment.splitAt(pos);
            (_a = this.mergeTreeMaintenanceCallback) === null || _a === void 0 ? void 0 : _a.call(this, {
                operation: mergeTreeDeltaCallback_1.MergeTreeMaintenanceType.SPLIT,
                deltaSegments: [{ segment }, { segment: next }],
            }, undefined);
            return { next };
        };
        this._root = this.makeBlock(0);
        this._root.mergeTree = this;
    }
    get getSegmentsToScour() {
        return this.segmentsToScour;
    }
    get root() {
        return this._root;
    }
    set root(value) {
        this._root = value;
        value.mergeTree = this;
    }
    makeBlock(childCount) {
        const block = new HierMergeBlock(childCount);
        block.ordinal = "";
        return block;
    }
    clone() {
        const b = new MergeTree(this.options);
        // For now assume that b will not collaborate
        b.root = b.blockClone(this.root);
    }
    blockClone(block, segments) {
        const bBlock = this.makeBlock(block.childCount);
        for (let i = 0; i < block.childCount; i++) {
            const child = block.children[i];
            if (child.isLeaf()) {
                const segment = this.segmentClone(child);
                bBlock.assignChild(segment, i);
                if (segments) {
                    segments.push(segment);
                }
            }
            else {
                bBlock.assignChild(this.blockClone(child, segments), i);
            }
        }
        this.nodeUpdateLengthNewStructure(bBlock);
        this.nodeUpdateOrdinals(bBlock);
        return bBlock;
    }
    segmentClone(segment) {
        const b = segment.clone();
        return b;
    }
    /**
     * Compute the net length of this segment from a local perspective.
     * @param segment - Segment whose length to find
     * @param localSeq - localSeq at which to find the length of this segment. If not provided,
     * default is to consider the local client's current perspective. Only local sequence
     * numbers corresponding to un-acked operations give valid results.
     */
    localNetLength(segment, refSeq, localSeq) {
        var _a;
        const removalInfo = (0, mergeTreeNodes_1.toRemovalInfo)(segment);
        if (localSeq === undefined) {
            if (removalInfo !== undefined) {
                if (((_a = this.options) === null || _a === void 0 ? void 0 : _a.mergeTreeUseNewLengthCalculations) !== true) {
                    const normalizedRemovedSeq = removalInfo.removedSeq === constants_1.UnassignedSequenceNumber
                        ? Number.MAX_SAFE_INTEGER
                        : removalInfo.removedSeq;
                    if (normalizedRemovedSeq > this.collabWindow.minSeq) {
                        return 0;
                    }
                    // this segment removed and outside the collab window which means it is zamboni eligible
                    // this also means the segment could not exist, so we should not consider it
                    // when making decisions about conflict resolutions
                    return undefined;
                }
                return 0;
            }
            else {
                return segment.cachedLength;
            }
        }
        (0, common_utils_1.assert)(refSeq !== undefined, 0x398 /* localSeq provided for local length without refSeq */);
        (0, common_utils_1.assert)(segment.seq !== undefined, 0x399 /* segment with no seq in mergeTree */);
        const { seq, removedSeq, localRemovedSeq } = segment;
        if (seq !== constants_1.UnassignedSequenceNumber) {
            // inserted remotely
            if (seq > refSeq ||
                (removedSeq !== undefined &&
                    removedSeq !== constants_1.UnassignedSequenceNumber &&
                    removedSeq <= refSeq) ||
                (localRemovedSeq !== undefined && localRemovedSeq <= localSeq)) {
                return 0;
            }
            return segment.cachedLength;
        }
        else {
            (0, common_utils_1.assert)(segment.localSeq !== undefined, 0x39a /* unacked segment with undefined localSeq */);
            // inserted locally, still un-acked
            if (segment.localSeq > localSeq ||
                (localRemovedSeq !== undefined && localRemovedSeq <= localSeq)) {
                return 0;
            }
            return segment.cachedLength;
        }
    }
    // TODO: remove id when segment removed
    mapIdToSegment(id, segment) {
        this.idToSegment.set(id, segment);
    }
    addNode(block, node) {
        const index = block.childCount++;
        block.assignChild(node, index, false);
        return index;
    }
    reloadFromSegments(segments) {
        // This code assumes that a later call to `startCollaboration()` will initialize partial lengths.
        (0, common_utils_1.assert)(!this.collabWindow.collaborating, 0x049 /* "Trying to reload from segments while collaborating!" */);
        const maxChildren = mergeTreeNodes_1.MaxNodesInBlock - 1;
        // Starting with the leaf segments, recursively builds the B-Tree layer by layer from the bottom up.
        const buildMergeBlock = (nodes) => {
            const blockCount = Math.ceil(nodes.length / maxChildren); // Compute # blocks require for this level of B-Tree
            const blocks = new Array(blockCount); // Pre-alloc array to collect nodes
            // For each block in this level of the B-Tree...
            for (let nodeIndex = 0, blockIndex = 0; // Start with the first block and first node
             blockIndex < blockCount; // If we have more blocks, we also have more nodes to insert
             blockIndex++ // Advance to next block in this layer.
            ) {
                const block = (blocks[blockIndex] = this.makeBlock(0));
                // For each child of the current block, insert a node (while we have nodes left)
                // and update the block's info.
                for (let childIndex = 0; childIndex < maxChildren && nodeIndex < nodes.length; // While we still have children & nodes left
                 childIndex++, nodeIndex++ // Advance to next child & node
                ) {
                    // Insert the next node into the current block
                    this.addNode(block, nodes[nodeIndex]);
                }
                // Calculate this block's info.  Previously this was inlined into the above loop as a micro-optimization,
                // but it turns out to be negligible in practice since `reloadFromSegments()` is only invoked for the
                // snapshot header.  The bulk of the segments in long documents are inserted via `insertSegments()`.
                this.blockUpdate(block);
            }
            // eslint-disable-next-line @typescript-eslint/no-unsafe-return
            return blocks.length === 1 // If there is only one block at this layer...
                ? blocks[0] // ...then we're done.  Return the root.
                : buildMergeBlock(blocks); // ...otherwise recursively build the next layer above blocks.
        };
        if (segments.length > 0) {
            this.root = buildMergeBlock(segments);
            this.nodeUpdateOrdinals(this.root);
        }
        else {
            this.root = this.makeBlock(0);
        }
    }
    // For now assume min starts at zero
    startCollaboration(localClientId, minSeq, currentSeq) {
        this.collabWindow.clientId = localClientId;
        this.collabWindow.minSeq = minSeq;
        this.collabWindow.collaborating = true;
        this.collabWindow.currentSeq = currentSeq;
        this.segmentsToScour = new collections_1.Heap([], LRUSegmentComparer);
        this.pendingSegments = new collections_1.List();
        this.nodeUpdateLengthNewStructure(this.root, true);
    }
    addToLRUSet(segment, seq) {
        // If the parent node has not yet been marked for scour (i.e., needsScour is not false or undefined),
        // add the segment and mark the mark the node now.
        // TODO: 'seq' may be less than the current sequence number when inserting pre-ACKed
        //       segments from a snapshot.  We currently skip these for now.
        if (segment.parent.needsScour !== true && seq > this.collabWindow.currentSeq) {
            segment.parent.needsScour = true;
            this.segmentsToScour.add({ segment, maxSeq: seq });
        }
    }
    getCollabWindow() {
        return this.collabWindow;
    }
    getLength(refSeq, clientId) {
        return this.blockLength(this.root, refSeq, clientId);
    }
    /**
     * Returns the current length of the MergeTree for the local client.
     */
    get length() {
        return this.root.cachedLength;
    }
    getPosition(node, refSeq, clientId, localSeq) {
        var _a;
        let totalOffset = 0;
        let parent = node.parent;
        let prevParent;
        while (parent) {
            const children = parent.children;
            for (let childIndex = 0; childIndex < parent.childCount; childIndex++) {
                const child = children[childIndex];
                if ((prevParent && child === prevParent) || child === node) {
                    break;
                }
                totalOffset += (_a = this.nodeLength(child, refSeq, clientId, localSeq)) !== null && _a !== void 0 ? _a : 0;
            }
            prevParent = parent;
            parent = parent.parent;
        }
        return totalOffset;
    }
    getContainingSegment(pos, refSeq, clientId, localSeq) {
        (0, common_utils_1.assert)(localSeq === undefined || clientId === this.collabWindow.clientId, 0x39b /* localSeq provided for non-local client */);
        let segment;
        let offset;
        const leaf = (leafSeg, segpos, _refSeq, _clientId, start) => {
            segment = leafSeg;
            offset = start;
            return false;
        };
        this.nodeMap(refSeq, clientId, leaf, undefined, undefined, pos, pos + 1, localSeq);
        return { segment, offset };
    }
    /**
     * @remarks Must only be used by client.
     * @param segment - The segment to slide from.
     * @returns The segment to.
     * @internal
     */
    _getSlideToSegment(segment) {
        if (!segment || !isRemovedAndAcked(segment)) {
            return segment;
        }
        let slideToSegment;
        const goFurtherToFindSlideToSegment = (seg) => {
            if (seg.seq !== constants_1.UnassignedSequenceNumber && !isRemovedAndAcked(seg)) {
                slideToSegment = seg;
                return false;
            }
            return true;
        };
        // Slide to the next farthest valid segment in the tree.
        (0, mergeTreeNodeWalk_1.forwardExcursion)(segment, goFurtherToFindSlideToSegment);
        if (slideToSegment) {
            return slideToSegment;
        }
        // If no such segment is found, slide to the last valid segment.
        (0, mergeTreeNodeWalk_1.backwardExcursion)(segment, goFurtherToFindSlideToSegment);
        return slideToSegment;
    }
    /**
     * This method should only be called when the current client sequence number is
     * max(remove segment sequence number, add reference sequence number).
     * Otherwise eventual consistency is not guaranteed.
     * See `packages\dds\merge-tree\REFERENCEPOSITIONS.md`
     */
    slideAckedRemovedSegmentReferences(segment) {
        var _a, _b, _c, _d, _e, _f, _g;
        (0, common_utils_1.assert)(isRemovedAndAcked(segment), 0x2f1 /* slideReferences from a segment which has not been removed and acked */);
        if (((_a = segment.localRefs) === null || _a === void 0 ? void 0 : _a.empty) !== false) {
            return;
        }
        const newSegment = this._getSlideToSegment(segment);
        if (newSegment) {
            const localRefs = ((_b = newSegment.localRefs) !== null && _b !== void 0 ? _b : (newSegment.localRefs = new localReference_1.LocalReferenceCollection(newSegment)));
            if (newSegment.ordinal < segment.ordinal) {
                localRefs.addAfterTombstones(segment.localRefs);
            }
            else {
                localRefs.addBeforeTombstones(segment.localRefs);
            }
        }
        else {
            for (const ref of segment.localRefs) {
                if (!(0, referencePositions_1.refTypeIncludesFlag)(ref, ops_1.ReferenceType.StayOnRemove)) {
                    (_d = (_c = ref.callbacks) === null || _c === void 0 ? void 0 : _c.beforeSlide) === null || _d === void 0 ? void 0 : _d.call(_c, ref);
                    (_e = segment.localRefs) === null || _e === void 0 ? void 0 : _e.removeLocalRef(ref);
                    (_g = (_f = ref.callbacks) === null || _f === void 0 ? void 0 : _f.afterSlide) === null || _g === void 0 ? void 0 : _g.call(_f, ref);
                }
            }
        }
        // TODO is it required to update the path lengths?
        if (newSegment) {
            this.blockUpdatePathLengths(newSegment.parent, constants_1.TreeMaintenanceSequenceNumber, constants_1.LocalClientId);
        }
    }
    blockLength(node, refSeq, clientId) {
        return this.collabWindow.collaborating && clientId !== this.collabWindow.clientId
            ? node.partialLengths.getPartialLength(refSeq, clientId)
            : node.cachedLength;
    }
    /**
     * Compute local partial length information
     *
     * Public only for use by internal tests
     *
     * @internal
     */
    computeLocalPartials(refSeq) {
        if (this.localPartialsComputed) {
            return;
        }
        const rebaseCollabWindow = new mergeTreeNodes_1.CollaborationWindow();
        rebaseCollabWindow.loadFrom(this.collabWindow);
        if (refSeq < this.collabWindow.minSeq) {
            rebaseCollabWindow.minSeq = refSeq;
        }
        this.root.partialLengths = partialLengths_1.PartialSequenceLengths.combine(this.root, rebaseCollabWindow, true, true);
        this.localPartialsComputed = true;
    }
    nodeLength(node, refSeq, clientId, localSeq) {
        var _a, _b;
        if (!this.collabWindow.collaborating || this.collabWindow.clientId === clientId) {
            if (node.isLeaf()) {
                return this.localNetLength(node, refSeq, localSeq);
            }
            else if (localSeq === undefined) {
                // Local client sees all segments, even when collaborating
                return node.cachedLength;
            }
            else {
                this.computeLocalPartials(refSeq);
                // Local client should see all segments except those after localSeq.
                return node.partialLengths.getPartialLength(refSeq, clientId, localSeq);
            }
        }
        else {
            // Sequence number within window
            if (!node.isLeaf()) {
                return node.partialLengths.getPartialLength(refSeq, clientId);
            }
            else {
                const segment = node;
                const removalInfo = (0, mergeTreeNodes_1.toRemovalInfo)(segment);
                if (((_a = this.options) === null || _a === void 0 ? void 0 : _a.mergeTreeUseNewLengthCalculations) === true) {
                    // normalize the seq numbers
                    // if the remove is local (UnassignedSequenceNumber) give it the highest possible
                    // seq for comparison, as it will get a seq higher than any other seq once sequenced
                    // if the segments seq is local (UnassignedSequenceNumber) give it the second highest
                    // possible seq, as the highest is reserved for the remove.
                    const seq = node.seq === constants_1.UnassignedSequenceNumber
                        ? Number.MAX_SAFE_INTEGER - 1
                        : (_b = node.seq) !== null && _b !== void 0 ? _b : 0;
                    if (removalInfo !== undefined) {
                        const removedSeq = removalInfo.removedSeq === constants_1.UnassignedSequenceNumber
                            ? Number.MAX_SAFE_INTEGER
                            : removalInfo === null || removalInfo === void 0 ? void 0 : removalInfo.removedSeq;
                        if (removedSeq <= this.collabWindow.minSeq) {
                            return undefined;
                        }
                        if (removedSeq <= refSeq ||
                            removalInfo.removedClientIds.includes(clientId)) {
                            return 0;
                        }
                    }
                    return seq <= refSeq || segment.clientId === clientId
                        ? segment.cachedLength
                        : 0;
                }
                if (removalInfo !== undefined &&
                    removalInfo.removedSeq !== constants_1.UnassignedSequenceNumber &&
                    removalInfo.removedSeq <= refSeq) {
                    // this segment is a tombstone eligible for zamboni
                    // so should never be considered, as it may not exist
                    // on other clients
                    return undefined;
                }
                if (segment.clientId === clientId ||
                    (segment.seq !== constants_1.UnassignedSequenceNumber && segment.seq <= refSeq)) {
                    // Segment happened by reference sequence number or segment from requesting client
                    if (removalInfo !== undefined) {
                        return removalInfo.removedClientIds.includes(clientId)
                            ? 0
                            : segment.cachedLength;
                    }
                    else {
                        return segment.cachedLength;
                    }
                }
                else {
                    // the segment was inserted and removed before the
                    // this context, so it will never exist for this
                    // context
                    if (removalInfo !== undefined &&
                        removalInfo.removedSeq !== constants_1.UnassignedSequenceNumber) {
                        return undefined;
                    }
                    // Segment invisible to client at reference sequence number/branch id/client id of op
                    return 0;
                }
            }
        }
    }
    addMinSeqListener(minRequired, onMinGE) {
        if (!this.minSeqListeners) {
            this.minSeqListeners = new collections_1.Heap([], minListenerComparer);
        }
        this.minSeqListeners.add({ minRequired, onMinGE });
    }
    notifyMinSeqListeners() {
        if (this.minSeqListeners) {
            while (this.minSeqListeners.count() > 0 &&
                this.minSeqListeners.peek().minRequired <= this.collabWindow.minSeq) {
                const minListener = this.minSeqListeners.get();
                minListener.onMinGE(this.collabWindow.minSeq);
            }
        }
    }
    setMinSeq(minSeq) {
        (0, common_utils_1.assert)(minSeq <= this.collabWindow.currentSeq, 0x04e /* "Trying to set minSeq above currentSeq of collab window!" */);
        // Only move forward
        (0, common_utils_1.assert)(this.collabWindow.minSeq <= minSeq, 0x04f /* "minSeq of collab window > target minSeq!" */);
        if (minSeq > this.collabWindow.minSeq) {
            this.collabWindow.minSeq = minSeq;
            if (MergeTree.options.zamboniSegments) {
                (0, zamboni_1.zamboniSegments)(this);
            }
            this.notifyMinSeqListeners();
        }
    }
    referencePositionToLocalPosition(refPos, refSeq = this.collabWindow.currentSeq, clientId = this.collabWindow.clientId) {
        var _a;
        const seg = refPos.getSegment();
        if ((seg === null || seg === void 0 ? void 0 : seg.parent) === undefined) {
            return referencePositions_1.DetachedReferencePosition;
        }
        if (refPos.isLeaf()) {
            return this.getPosition(refPos, refSeq, clientId);
        }
        if ((0, referencePositions_1.refTypeIncludesFlag)(refPos, ops_1.ReferenceType.Transient) || ((_a = seg.localRefs) === null || _a === void 0 ? void 0 : _a.has(refPos))) {
            const offset = isRemoved(seg) ? 0 : refPos.getOffset();
            return offset + this.getPosition(seg, refSeq, clientId);
        }
        return referencePositions_1.DetachedReferencePosition;
    }
    getStackContext(startPos, clientId, rangeLabels) {
        const searchInfo = {
            mergeTree: this,
            stacks: (0, properties_1.createMap)(),
            rangeLabels,
        };
        this.search(startPos, constants_1.UniversalSequenceNumber, clientId, { leaf: recordRangeLeaf, shift: rangeShift }, searchInfo);
        return searchInfo.stacks;
    }
    // TODO: filter function
    /**
     * Finds the nearest reference with ReferenceType.Tile to `startPos` in the direction dictated by `tilePrecedesPos`.
     *
     * @param startPos - Position at which to start the search
     * @param clientId - clientId dictating the perspective to search from
     * @param tileLabel - Label of the tile to search for
     * @param tilePrecedesPos - Whether the desired tile comes before (true) or after (false) `startPos`
     */
    findTile(startPos, clientId, tileLabel, tilePrecedesPos = true) {
        const searchInfo = {
            mergeTree: this,
            tilePrecedesPos,
            tileLabel,
        };
        if (tilePrecedesPos) {
            this.search(startPos, constants_1.UniversalSequenceNumber, clientId, { leaf: recordTileStart, shift: tileShift }, searchInfo);
        }
        else {
            this.backwardSearch(startPos, constants_1.UniversalSequenceNumber, clientId, { leaf: recordTileStart, shift: tileShift }, searchInfo);
        }
        if (searchInfo.tile) {
            let pos;
            if (searchInfo.tile.isLeaf()) {
                const marker = searchInfo.tile;
                pos = this.getPosition(marker, constants_1.UniversalSequenceNumber, clientId);
            }
            else {
                const localRef = searchInfo.tile;
                pos = this.referencePositionToLocalPosition(localRef, constants_1.UniversalSequenceNumber, clientId);
            }
            return { tile: searchInfo.tile, pos };
        }
        return undefined;
    }
    search(pos, refSeq, clientId, actions, clientData) {
        return this.searchBlock(this.root, pos, 0, refSeq, clientId, actions, clientData);
    }
    searchBlock(block, pos, segpos, refSeq, clientId, actions, clientData, localSeq) {
        var _a;
        let _pos = pos;
        let _segpos = segpos;
        const children = block.children;
        if (actions && actions.pre) {
            actions.pre(block, _segpos, refSeq, clientId, undefined, undefined, clientData);
        }
        const contains = actions && actions.contains;
        for (let childIndex = 0; childIndex < block.childCount; childIndex++) {
            const child = children[childIndex];
            const len = (_a = this.nodeLength(child, refSeq, clientId, localSeq)) !== null && _a !== void 0 ? _a : 0;
            if ((!contains && _pos < len) ||
                (contains &&
                    contains(child, _pos, refSeq, clientId, undefined, undefined, clientData))) {
                // Found entry containing pos
                if (!child.isLeaf()) {
                    return this.searchBlock(child, _pos, _segpos, refSeq, clientId, actions, clientData, localSeq);
                }
                else {
                    if (actions && actions.leaf) {
                        actions.leaf(child, _segpos, refSeq, clientId, _pos, -1, clientData);
                    }
                    return child;
                }
            }
            else {
                if (actions && actions.shift) {
                    actions.shift(child, _segpos, refSeq, clientId, _pos, undefined, clientData);
                }
                _pos -= len;
                _segpos += len;
            }
        }
        if (actions && actions.post) {
            actions.post(block, _segpos, refSeq, clientId, undefined, undefined, clientData);
        }
    }
    backwardSearch(pos, refSeq, clientId, actions, clientData) {
        const len = this.getLength(refSeq, clientId);
        if (pos > len) {
            return undefined;
        }
        return this.backwardSearchBlock(this.root, pos, len, refSeq, clientId, actions, clientData);
    }
    backwardSearchBlock(block, pos, segEnd, refSeq, clientId, actions, clientData) {
        var _a;
        let _segEnd = segEnd;
        const children = block.children;
        if (actions && actions.pre) {
            actions.pre(block, _segEnd, refSeq, clientId, undefined, undefined, clientData);
        }
        const contains = actions && actions.contains;
        for (let childIndex = block.childCount - 1; childIndex >= 0; childIndex--) {
            const child = children[childIndex];
            const len = (_a = this.nodeLength(child, refSeq, clientId)) !== null && _a !== void 0 ? _a : 0;
            const segpos = _segEnd - len;
            if ((!contains && pos >= segpos) ||
                (contains &&
                    contains(child, pos, refSeq, clientId, undefined, undefined, clientData))) {
                // Found entry containing pos
                if (!child.isLeaf()) {
                    return this.backwardSearchBlock(child, pos, _segEnd, refSeq, clientId, actions, clientData);
                }
                else {
                    if (actions && actions.leaf) {
                        actions.leaf(child, segpos, refSeq, clientId, pos, -1, clientData);
                    }
                    return child;
                }
            }
            else {
                if (actions && actions.shift) {
                    actions.shift(child, segpos, refSeq, clientId, pos, undefined, clientData);
                }
                _segEnd = segpos;
            }
        }
        if (actions && actions.post) {
            actions.post(block, _segEnd, refSeq, clientId, undefined, undefined, clientData);
        }
    }
    updateRoot(splitNode) {
        if (splitNode !== undefined) {
            const newRoot = this.makeBlock(2);
            newRoot.assignChild(this.root, 0, false);
            newRoot.assignChild(splitNode, 1, false);
            this.root = newRoot;
            this.nodeUpdateOrdinals(this.root);
            this.nodeUpdateLengthNewStructure(this.root);
        }
    }
    /**
     * Assign sequence number to existing segment; update partial lengths to reflect the change
     * @param seq - sequence number given by server to pending segment
     */
    ackPendingSegment(opArgs) {
        var _a, _b;
        const seq = opArgs.sequencedMessage.sequenceNumber;
        const pendingSegmentGroup = (_a = this.pendingSegments.shift()) === null || _a === void 0 ? void 0 : _a.data;
        const nodesToUpdate = [];
        let overwrite = false;
        if (pendingSegmentGroup !== undefined) {
            const deltaSegments = [];
            pendingSegmentGroup.segments.map((pendingSegment) => {
                var _a, _b;
                const overlappingRemove = !pendingSegment.ack(pendingSegmentGroup, opArgs);
                // TODO: This work should likely be done as part of the above `ack` call. However the exact format
                // of the argument to pass isn't obvious given some planned extensibility points around customizing
                // what types of operations are attributed and how. Since `ack` is in the public API, leaving it
                // here for now should reduce future breaking changes.
                if (opArgs.op.type === ops_1.MergeTreeDeltaType.INSERT &&
                    ((_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.attribution) === null || _b === void 0 ? void 0 : _b.track)) {
                    pendingSegment.attribution = new attributionCollection_1.AttributionCollection({ type: "op", seq }, pendingSegment.cachedLength);
                }
                overwrite = overlappingRemove || overwrite;
                if (!overlappingRemove && opArgs.op.type === ops_1.MergeTreeDeltaType.REMOVE) {
                    this.slideAckedRemovedSegmentReferences(pendingSegment);
                }
                if (MergeTree.options.zamboniSegments) {
                    this.addToLRUSet(pendingSegment, seq);
                }
                if (!nodesToUpdate.includes(pendingSegment.parent)) {
                    nodesToUpdate.push(pendingSegment.parent);
                }
                deltaSegments.push({
                    segment: pendingSegment,
                });
            });
            (_b = this.mergeTreeMaintenanceCallback) === null || _b === void 0 ? void 0 : _b.call(this, {
                deltaSegments,
                operation: mergeTreeDeltaCallback_1.MergeTreeMaintenanceType.ACKNOWLEDGED,
            }, opArgs);
            const clientId = this.collabWindow.clientId;
            for (const node of nodesToUpdate) {
                this.blockUpdatePathLengths(node, seq, clientId, overwrite);
                // NodeUpdatePathLengths(node, seq, clientId, true);
            }
        }
        if (MergeTree.options.zamboniSegments) {
            (0, zamboni_1.zamboniSegments)(this);
        }
    }
    addToPendingList(segment, segmentGroup, localSeq, previousProps) {
        let _segmentGroup = segmentGroup;
        if (_segmentGroup === undefined) {
            // TODO: review the cast
            _segmentGroup = {
                segments: [],
                localSeq,
                refSeq: this.collabWindow.currentSeq,
            };
            if (previousProps) {
                _segmentGroup.previousProps = [];
            }
            this.pendingSegments.push(_segmentGroup);
        }
        if ((!_segmentGroup.previousProps && previousProps) ||
            (_segmentGroup.previousProps && !previousProps)) {
            throw new Error("All segments in group should have previousProps or none");
        }
        if (previousProps) {
            _segmentGroup.previousProps.push(previousProps);
        }
        segment.segmentGroups.enqueue(_segmentGroup);
        return _segmentGroup;
    }
    // TODO: error checking
    getMarkerFromId(id) {
        return this.idToSegment.get(id);
    }
    /**
     * Given a position specified relative to a marker id, lookup the marker
     * and convert the position to a character position.
     * @param relativePos - Id of marker (may be indirect) and whether position is before or after marker.
     * @param refseq - The reference sequence number at which to compute the position.
     * @param clientId - The client id with which to compute the position.
     */
    posFromRelativePos(relativePos, refseq = this.collabWindow.currentSeq, clientId = this.collabWindow.clientId) {
        let pos = -1;
        let marker;
        if (relativePos.id) {
            marker = this.getMarkerFromId(relativePos.id);
        }
        if (marker) {
            pos = this.getPosition(marker, refseq, clientId);
            if (!relativePos.before) {
                pos += marker.cachedLength;
                if (relativePos.offset !== undefined) {
                    pos += relativePos.offset;
                }
            }
            else {
                if (relativePos.offset !== undefined) {
                    pos -= relativePos.offset;
                }
            }
        }
        return pos;
    }
    insertSegments(pos, segments, refSeq, clientId, seq, opArgs) {
        var _a;
        this.ensureIntervalBoundary(pos, refSeq, clientId);
        const localSeq = seq === constants_1.UnassignedSequenceNumber ? ++this.collabWindow.localSeq : undefined;
        this.blockInsert(pos, refSeq, clientId, seq, localSeq, segments);
        // opArgs == undefined => loading snapshot or test code
        if (opArgs !== undefined) {
            (_a = this.mergeTreeDeltaCallback) === null || _a === void 0 ? void 0 : _a.call(this, opArgs, {
                operation: ops_1.MergeTreeDeltaType.INSERT,
                deltaSegments: segments.map((segment) => ({ segment })),
            });
        }
        if (this.collabWindow.collaborating &&
            MergeTree.options.zamboniSegments &&
            seq !== constants_1.UnassignedSequenceNumber) {
            (0, zamboni_1.zamboniSegments)(this);
        }
    }
    insertAtReferencePosition(referencePosition, insertSegment, opArgs) {
        var _a;
        if (insertSegment.cachedLength === 0) {
            return;
        }
        if (insertSegment.parent ||
            insertSegment.removedSeq ||
            insertSegment.seq !== constants_1.UniversalSequenceNumber) {
            throw new Error("Cannot insert segment that has already been inserted.");
        }
        const rebalanceTree = (segment) => {
            // Blocks should never be left full
            // if the inserts makes the block full
            // then we need to walk up the chain of parents
            // and split the blocks until we find a block with
            // room
            let block = segment.parent;
            let ordinalUpdateNode = block;
            while (block !== undefined) {
                if (block.childCount >= mergeTreeNodes_1.MaxNodesInBlock) {
                    const splitNode = this.split(block);
                    if (block === this.root) {
                        this.updateRoot(splitNode);
                        // Update root already updates all its children ordinals
                        ordinalUpdateNode = undefined;
                    }
                    else {
                        this.insertChildNode(block.parent, splitNode, block.index + 1);
                        ordinalUpdateNode = splitNode.parent;
                        this.blockUpdateLength(block.parent, constants_1.UnassignedSequenceNumber, clientId);
                    }
                }
                else {
                    this.blockUpdateLength(block, constants_1.UnassignedSequenceNumber, clientId);
                }
                block = block.parent;
            }
            // Only update ordinals once, for all children,
            // on the path
            if (ordinalUpdateNode) {
                this.nodeUpdateOrdinals(ordinalUpdateNode);
            }
        };
        const clientId = this.collabWindow.clientId;
        const refSegment = referencePosition.getSegment();
        const refOffset = referencePosition.getOffset();
        const refSegLen = this.nodeLength(refSegment, this.collabWindow.currentSeq, clientId);
        let startSeg = refSegment;
        // if the change isn't at a boundary, we need to split the segment
        if (refOffset !== 0 && refSegLen !== undefined && refSegLen !== 0) {
            const splitSeg = this.splitLeafSegment(refSegment, refOffset);
            (0, common_utils_1.assert)(!!splitSeg.next, 0x050 /* "Next segment changes are undefined!" */);
            this.insertChildNode(refSegment.parent, splitSeg.next, refSegment.index + 1);
            rebalanceTree(splitSeg.next);
            startSeg = splitSeg.next;
        }
        // walk back from the segment, to see if there is a previous tie break seg
        (0, mergeTreeNodeWalk_1.backwardExcursion)(startSeg, (backSeg) => {
            if (!backSeg.isLeaf()) {
                return true;
            }
            const backLen = this.nodeLength(backSeg, this.collabWindow.currentSeq, clientId);
            // ignore removed segments
            if (backLen === undefined) {
                return true;
            }
            // Find the nearest 0 length seg we can insert over, as all other inserts
            // go near to far
            if (backLen === 0) {
                if (this.breakTie(0, backSeg, constants_1.UnassignedSequenceNumber)) {
                    startSeg = backSeg;
                }
                return true;
            }
            return false;
        });
        if (this.collabWindow.collaborating) {
            insertSegment.localSeq = ++this.collabWindow.localSeq;
            insertSegment.seq = constants_1.UnassignedSequenceNumber;
        }
        else {
            insertSegment.seq = constants_1.UniversalSequenceNumber;
        }
        insertSegment.clientId = clientId;
        if (mergeTreeNodes_1.Marker.is(insertSegment)) {
            const markerId = insertSegment.getId();
            if (markerId) {
                this.mapIdToSegment(markerId, insertSegment);
            }
        }
        this.insertChildNode(startSeg.parent, insertSegment, startSeg.index);
        rebalanceTree(insertSegment);
        (_a = this.mergeTreeDeltaCallback) === null || _a === void 0 ? void 0 : _a.call(this, opArgs, {
            deltaSegments: [{ segment: insertSegment }],
            operation: ops_1.MergeTreeDeltaType.INSERT,
        });
        if (this.collabWindow.collaborating) {
            this.addToPendingList(insertSegment, undefined, insertSegment.localSeq);
        }
    }
    /**
     * Resolves a remote client's position against the local sequence
     * and returns the remote client's position relative to the local
     * sequence. The client ref seq must be above the minimum sequence number
     * or the return value will be undefined.
     * Generally this method is used in conjunction with signals which provide
     * point in time values for the below parameters, and is useful for things
     * like displaying user position. It should not be used with persisted values
     * as persisted values will quickly become invalid as the remoteClientRefSeq
     * moves below the minimum sequence number
     * @param remoteClientPosition - The remote client's position to resolve
     * @param remoteClientRefSeq - The reference sequence number of the remote client
     * @param remoteClientId - The client id of the remote client
     */
    resolveRemoteClientPosition(remoteClientPosition, remoteClientRefSeq, remoteClientId) {
        if (remoteClientRefSeq < this.collabWindow.minSeq) {
            return undefined;
        }
        const segmentInfo = this.getContainingSegment(remoteClientPosition, remoteClientRefSeq, remoteClientId);
        const { currentSeq, clientId } = this.collabWindow;
        if (segmentInfo && segmentInfo.segment) {
            const segmentPosition = this.getPosition(segmentInfo.segment, currentSeq, clientId);
            return segmentPosition + segmentInfo.offset;
        }
        else {
            if (remoteClientPosition === this.getLength(remoteClientRefSeq, remoteClientId)) {
                return this.getLength(currentSeq, clientId);
            }
        }
    }
    insertChildNode(block, child, childIndex) {
        (0, common_utils_1.assert)(block.childCount < mergeTreeNodes_1.MaxNodesInBlock, 0x051 /* "Too many children on merge block!" */);
        for (let i = block.childCount; i > childIndex; i--) {
            block.children[i] = block.children[i - 1];
            block.children[i].index = i;
        }
        block.childCount++;
        block.assignChild(child, childIndex, false);
    }
    blockInsert(pos, refSeq, clientId, seq, localSeq, newSegments) {
        var _a, _b, _c;
        let segIsLocal = false;
        const checkSegmentIsLocal = (segment) => {
            if (segment.seq === constants_1.UnassignedSequenceNumber) {
                segIsLocal = true;
            }
            // Only need to look at first segment that follows finished node
            return false;
        };
        const continueFrom = (node) => {
            segIsLocal = false;
            (0, mergeTreeNodeWalk_1.forwardExcursion)(node, checkSegmentIsLocal);
            return segIsLocal;
        };
        let segmentGroup;
        const saveIfLocal = (locSegment) => {
            // Save segment so can assign sequence number when acked by server
            if (this.collabWindow.collaborating) {
                if (locSegment.seq === constants_1.UnassignedSequenceNumber &&
                    clientId === this.collabWindow.clientId) {
                    segmentGroup = this.addToPendingList(locSegment, segmentGroup, localSeq);
                }
                // LocSegment.seq === 0 when coming from SharedSegmentSequence.loadBody()
                // In all other cases this has to be true (checked by addToLRUSet):
                // locSegment.seq > this.collabWindow.currentSeq
                else if (locSegment.seq > this.collabWindow.minSeq &&
                    MergeTree.options.zamboniSegments) {
                    this.addToLRUSet(locSegment, locSegment.seq);
                }
            }
        };
        const onLeaf = (segment, _pos, context) => {
            const segmentChanges = {};
            if (segment) {
                // Insert before segment
                segmentChanges.replaceCurrent = context.candidateSegment;
                segmentChanges.next = segment;
            }
            else {
                segmentChanges.next = context.candidateSegment;
            }
            return segmentChanges;
        };
        // TODO: build tree from segs and insert all at once
        let insertPos = pos;
        for (const newSegment of newSegments) {
            segIsLocal = false;
            if (newSegment.cachedLength > 0) {
                newSegment.seq = seq;
                newSegment.localSeq = localSeq;
                newSegment.clientId = clientId;
                if (((_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.attribution) === null || _b === void 0 ? void 0 : _b.track) && seq !== constants_1.UnassignedSequenceNumber) {
                    (_c = newSegment.attribution) !== null && _c !== void 0 ? _c : (newSegment.attribution = new attributionCollection_1.AttributionCollection({ type: "op", seq }, newSegment.cachedLength));
                }
                if (mergeTreeNodes_1.Marker.is(newSegment)) {
                    const markerId = newSegment.getId();
                    if (markerId) {
                        this.mapIdToSegment(markerId, newSegment);
                    }
                }
                const splitNode = this.insertingWalk(this.root, insertPos, refSeq, clientId, seq, {
                    leaf: onLeaf,
                    candidateSegment: newSegment,
                    continuePredicate: continueFrom,
                });
                if (newSegment.parent === undefined) {
                    throw new Error(`MergeTree insert failed: ${JSON.stringify({
                        currentSeq: this.collabWindow.currentSeq,
                        minSeq: this.collabWindow.minSeq,
                        segSeq: newSegment.seq,
                    })}`);
                }
                this.updateRoot(splitNode);
                saveIfLocal(newSegment);
                insertPos += newSegment.cachedLength;
            }
        }
    }
    ensureIntervalBoundary(pos, refSeq, clientId) {
        const splitNode = this.insertingWalk(this.root, pos, refSeq, clientId, constants_1.TreeMaintenanceSequenceNumber, { leaf: this.splitLeafSegment });
        this.updateRoot(splitNode);
    }
    // Assume called only when pos == len
    breakTie(pos, node, seq) {
        var _a;
        if (node.isLeaf()) {
            if (pos === 0) {
                // normalize the seq numbers
                // if the new seg is local (UnassignedSequenceNumber) give it the highest possible
                // seq for comparison, as it will get a seq higher than any other seq once sequences
                // if the current seg is local (UnassignedSequenceNumber) give it the second highest
                // possible seq, as the highest is reserved for the previous.
                const newSeq = seq === constants_1.UnassignedSequenceNumber ? Number.MAX_SAFE_INTEGER : seq;
                const segSeq = node.seq === constants_1.UnassignedSequenceNumber
                    ? Number.MAX_SAFE_INTEGER - 1
                    : (_a = node.seq) !== null && _a !== void 0 ? _a : 0;
                return newSeq > segSeq;
            }
            return false;
        }
        else {
            return true;
        }
    }
    insertingWalk(block, pos, refSeq, clientId, seq, context) {
        let _pos = pos;
        const children = block.children;
        let childIndex;
        let child;
        let newNode;
        let fromSplit;
        for (childIndex = 0; childIndex < block.childCount; childIndex++) {
            child = children[childIndex];
            const len = this.nodeLength(child, refSeq, clientId);
            if (len === undefined) {
                // if the seg len in undefined, the segment
                // will be removed, so should just be skipped for now
                continue;
            }
            else {
                (0, common_utils_1.assert)(len >= 0, 0x4bc /* Length should not be negative */);
            }
            if (_pos < len || (_pos === len && this.breakTie(_pos, child, seq))) {
                // Found entry containing pos
                if (!child.isLeaf()) {
                    const childBlock = child;
                    // Internal node
                    const splitNode = this.insertingWalk(childBlock, _pos, refSeq, clientId, seq, context);
                    if (splitNode === undefined) {
                        if (context.structureChange) {
                            this.nodeUpdateLengthNewStructure(block);
                        }
                        else {
                            this.blockUpdateLength(block, seq, clientId);
                        }
                        return undefined;
                    }
                    else if (splitNode === MergeTree.theUnfinishedNode) {
                        _pos -= len; // Act as if shifted segment
                        continue;
                    }
                    else {
                        newNode = splitNode;
                        fromSplit = splitNode;
                        childIndex++; // Insert after
                    }
                }
                else {
                    const segment = child;
                    const segmentChanges = context.leaf(segment, _pos, context);
                    if (segmentChanges.replaceCurrent) {
                        block.assignChild(segmentChanges.replaceCurrent, childIndex, false);
                        segmentChanges.replaceCurrent.ordinal = child.ordinal;
                    }
                    if (segmentChanges.next) {
                        newNode = segmentChanges.next;
                        childIndex++; // Insert after
                    }
                    else {
                        // No change
                        if (context.structureChange) {
                            this.nodeUpdateLengthNewStructure(block);
                        }
                        return undefined;
                    }
                }
                break;
            }
            else {
                _pos -= len;
            }
        }
        if (!newNode) {
            if (_pos === 0) {
                if (seq !== constants_1.UnassignedSequenceNumber &&
                    context.continuePredicate &&
                    context.continuePredicate(block)) {
                    return MergeTree.theUnfinishedNode;
                }
                else {
                    const segmentChanges = context.leaf(undefined, _pos, context);
                    newNode = segmentChanges.next;
                    // Assert segmentChanges.replaceCurrent === undefined
                }
            }
        }
        if (newNode) {
            for (let i = block.childCount; i > childIndex; i--) {
                block.children[i] = block.children[i - 1];
                block.children[i].index = i;
            }
            block.assignChild(newNode, childIndex, false);
            block.childCount++;
            block.setOrdinal(newNode, childIndex);
            if (block.childCount < mergeTreeNodes_1.MaxNodesInBlock) {
                if (fromSplit) {
                    this.nodeUpdateOrdinals(fromSplit);
                }
                if (context.structureChange) {
                    this.nodeUpdateLengthNewStructure(block);
                }
                else {
                    this.blockUpdateLength(block, seq, clientId);
                }
                return undefined;
            }
            else {
                // Don't update ordinals because higher block will do it
                return this.split(block);
            }
        }
        else {
            return undefined;
        }
    }
    split(node) {
        const halfCount = mergeTreeNodes_1.MaxNodesInBlock / 2;
        const newNode = this.makeBlock(halfCount);
        node.childCount = halfCount;
        // Update ordinals to reflect lowered child count
        this.nodeUpdateOrdinals(node);
        for (let i = 0; i < halfCount; i++) {
            newNode.assignChild(node.children[halfCount + i], i, false);
            node.children[halfCount + i] = undefined;
        }
        this.nodeUpdateLengthNewStructure(node);
        this.nodeUpdateLengthNewStructure(newNode);
        return newNode;
    }
    nodeUpdateOrdinals(block) {
        for (let i = 0; i < block.childCount; i++) {
            const child = block.children[i];
            block.setOrdinal(child, i);
            if (!child.isLeaf()) {
                this.nodeUpdateOrdinals(child);
            }
        }
    }
    /**
     * Annotate a range with properties
     * @param start - The inclusive start position of the range to annotate
     * @param end - The exclusive end position of the range to annotate
     * @param props - The properties to annotate the range with
     * @param combiningOp - Optional. Specifies how to combine values for the property, such as "incr" for increment.
     * @param refSeq - The reference sequence number to use to apply the annotate
     * @param clientId - The id of the client making the annotate
     * @param seq - The sequence number of the annotate operation
     * @param opArgs - The op args for the annotate op. this is passed to the merge tree callback if there is one
     * @param rollback - Whether this is for a local rollback and what kind
     */
    annotateRange(start, end, props, combiningOp, refSeq, clientId, seq, opArgs, rollback = segmentPropertiesManager_1.PropertiesRollback.None) {
        var _a;
        this.ensureIntervalBoundary(start, refSeq, clientId);
        this.ensureIntervalBoundary(end, refSeq, clientId);
        const deltaSegments = [];
        const localSeq = seq === constants_1.UnassignedSequenceNumber ? ++this.collabWindow.localSeq : undefined;
        let segmentGroup;
        const annotateSegment = (segment) => {
            const propertyDeltas = segment.addProperties(props, combiningOp, seq, this.collabWindow, rollback);
            deltaSegments.push({ segment, propertyDeltas });
            if (this.collabWindow.collaborating) {
                if (seq === constants_1.UnassignedSequenceNumber) {
                    segmentGroup = this.addToPendingList(segment, segmentGroup, localSeq, propertyDeltas ? propertyDeltas : {});
                }
                else {
                    if (MergeTree.options.zamboniSegments) {
                        this.addToLRUSet(segment, seq);
                    }
                }
            }
            return true;
        };
        this.nodeMap(refSeq, clientId, annotateSegment, undefined, undefined, start, end);
        // OpArgs == undefined => test code
        if (deltaSegments.length > 0) {
            (_a = this.mergeTreeDeltaCallback) === null || _a === void 0 ? void 0 : _a.call(this, opArgs, {
                operation: ops_1.MergeTreeDeltaType.ANNOTATE,
                deltaSegments,
            });
        }
        if (this.collabWindow.collaborating && seq !== constants_1.UnassignedSequenceNumber) {
            if (MergeTree.options.zamboniSegments) {
                (0, zamboni_1.zamboniSegments)(this);
            }
        }
    }
    markRangeRemoved(start, end, refSeq, clientId, seq, overwrite = false, opArgs) {
        var _a;
        let _overwrite = overwrite;
        this.ensureIntervalBoundary(start, refSeq, clientId);
        this.ensureIntervalBoundary(end, refSeq, clientId);
        let segmentGroup;
        const removedSegments = [];
        const localOverlapWithRefs = [];
        const localSeq = seq === constants_1.UnassignedSequenceNumber ? ++this.collabWindow.localSeq : undefined;
        const markRemoved = (segment, pos, _start, _end) => {
            var _a;
            const existingRemovalInfo = (0, mergeTreeNodes_1.toRemovalInfo)(segment);
            if (existingRemovalInfo !== undefined) {
                _overwrite = true;
                if (existingRemovalInfo.removedSeq === constants_1.UnassignedSequenceNumber) {
                    // we removed this locally, but someone else removed it first
                    // so put them at the head of the list
                    // The list isn't ordered, but we keep the first removal at the head
                    // for partialLengths bookkeeping purposes
                    existingRemovalInfo.removedClientIds.unshift(clientId);
                    existingRemovalInfo.removedSeq = seq;
                    if (((_a = segment.localRefs) === null || _a === void 0 ? void 0 : _a.empty) === false) {
                        localOverlapWithRefs.push(segment);
                    }
                }
                else {
                    // Do not replace earlier sequence number for remove
                    existingRemovalInfo.removedClientIds.push(clientId);
                }
            }
            else {
                segment.removedClientIds = [clientId];
                segment.removedSeq = seq;
                segment.localRemovedSeq = localSeq;
                removedSegments.push({ segment });
            }
            // Save segment so can assign removed sequence number when acked by server
            if (this.collabWindow.collaborating) {
                if (segment.removedSeq === constants_1.UnassignedSequenceNumber &&
                    clientId === this.collabWindow.clientId) {
                    segmentGroup = this.addToPendingList(segment, segmentGroup, localSeq);
                }
                else {
                    if (MergeTree.options.zamboniSegments) {
                        this.addToLRUSet(segment, seq);
                    }
                }
            }
            return true;
        };
        const afterMarkRemoved = (node, pos, _start, _end) => {
            if (_overwrite) {
                this.nodeUpdateLengthNewStructure(node);
            }
            else {
                this.blockUpdateLength(node, seq, clientId);
            }
            return true;
        };
        this.nodeMap(refSeq, clientId, markRemoved, undefined, afterMarkRemoved, start, end);
        // these segments are already viewed as being removed locally and are not event-ed
        // so can slide non-StayOnRemove refs immediately
        localOverlapWithRefs.forEach((s) => this.slideAckedRemovedSegmentReferences(s));
        // opArgs == undefined => test code
        if (removedSegments.length > 0) {
            (_a = this.mergeTreeDeltaCallback) === null || _a === void 0 ? void 0 : _a.call(this, opArgs, {
                operation: ops_1.MergeTreeDeltaType.REMOVE,
                deltaSegments: removedSegments,
            });
        }
        // these events are newly removed
        // so we slide after eventing in case the consumer wants to make reference
        // changes at remove time, like add a ref to track undo redo.
        if (!this.collabWindow.collaborating || clientId !== this.collabWindow.clientId) {
            removedSegments.forEach((rSeg) => {
                this.slideAckedRemovedSegmentReferences(rSeg.segment);
            });
        }
        if (this.collabWindow.collaborating && seq !== constants_1.UnassignedSequenceNumber) {
            if (MergeTree.options.zamboniSegments) {
                (0, zamboni_1.zamboniSegments)(this);
            }
        }
    }
    /**
     * Revert an unacked local op
     */
    rollback(op, localOpMetadata) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
        if (op.type === ops_1.MergeTreeDeltaType.REMOVE) {
            const pendingSegmentGroup = (_c = (_b = (_a = this.pendingSegments) === null || _a === void 0 ? void 0 : _a.pop) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.data;
            if (pendingSegmentGroup === undefined || pendingSegmentGroup !== localOpMetadata) {
                throw new Error("Rollback op doesn't match last edit");
            }
            for (const segment of pendingSegmentGroup.segments) {
                const segmentSegmentGroup = (_e = (_d = segment.segmentGroups) === null || _d === void 0 ? void 0 : _d.pop) === null || _e === void 0 ? void 0 : _e.call(_d);
                (0, common_utils_1.assert)(segmentSegmentGroup === pendingSegmentGroup, 0x3ee /* Unexpected segmentGroup in segment */);
                (0, common_utils_1.assert)(segment.removedClientIds !== undefined &&
                    segment.removedClientIds[0] === this.collabWindow.clientId, 0x39d /* Rollback segment removedClientId does not match local client */);
                segment.removedClientIds = undefined;
                segment.removedSeq = undefined;
                segment.localRemovedSeq = undefined;
                // Note: optional chaining short-circuits:
                // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining#short-circuiting
                (_f = this.mergeTreeDeltaCallback) === null || _f === void 0 ? void 0 : _f.call(this, { op: (0, opBuilder_1.createInsertSegmentOp)(this.findRollbackPosition(segment), segment) }, {
                    operation: ops_1.MergeTreeDeltaType.INSERT,
                    deltaSegments: [{ segment }],
                });
                for (let updateNode = segment.parent; updateNode !== undefined; updateNode = updateNode.parent) {
                    this.blockUpdateLength(updateNode, constants_1.UnassignedSequenceNumber, this.collabWindow.clientId);
                }
            }
        }
        else if (op.type === ops_1.MergeTreeDeltaType.INSERT ||
            op.type === ops_1.MergeTreeDeltaType.ANNOTATE) {
            const pendingSegmentGroup = (_j = (_h = (_g = this.pendingSegments) === null || _g === void 0 ? void 0 : _g.pop) === null || _h === void 0 ? void 0 : _h.call(_g)) === null || _j === void 0 ? void 0 : _j.data;
            if (pendingSegmentGroup === undefined ||
                pendingSegmentGroup !== localOpMetadata ||
                (op.type === ops_1.MergeTreeDeltaType.ANNOTATE && !pendingSegmentGroup.previousProps)) {
                throw new Error("Rollback op doesn't match last edit");
            }
            let i = 0;
            for (const segment of pendingSegmentGroup.segments) {
                const segmentSegmentGroup = (_l = (_k = segment.segmentGroups).pop) === null || _l === void 0 ? void 0 : _l.call(_k);
                (0, common_utils_1.assert)(segmentSegmentGroup === pendingSegmentGroup, 0x3ef /* Unexpected segmentGroup in segment */);
                const start = this.findRollbackPosition(segment);
                if (op.type === ops_1.MergeTreeDeltaType.INSERT) {
                    segment.seq = constants_1.UniversalSequenceNumber;
                    segment.localSeq = undefined;
                    const removeOp = (0, opBuilder_1.createRemoveRangeOp)(start, start + segment.cachedLength);
                    this.markRangeRemoved(start, start + segment.cachedLength, constants_1.UniversalSequenceNumber, this.collabWindow.clientId, constants_1.UniversalSequenceNumber, false, { op: removeOp });
                } /* op.type === MergeTreeDeltaType.ANNOTATE */
                else {
                    const props = pendingSegmentGroup.previousProps[i];
                    const rollbackType = op.combiningOp && op.combiningOp.name === "rewrite"
                        ? segmentPropertiesManager_1.PropertiesRollback.Rewrite
                        : segmentPropertiesManager_1.PropertiesRollback.Rollback;
                    const annotateOp = (0, opBuilder_1.createAnnotateRangeOp)(start, start + segment.cachedLength, props, undefined);
                    this.annotateRange(start, start + segment.cachedLength, props, undefined, constants_1.UniversalSequenceNumber, this.collabWindow.clientId, constants_1.UniversalSequenceNumber, { op: annotateOp }, rollbackType);
                    i++;
                }
            }
        }
        else {
            throw new Error("Unsupported op type for rollback");
        }
    }
    /**
     * Walk the segments up to the current segment and calculate its position
     */
    findRollbackPosition(segment) {
        let segmentPosition = 0;
        (0, mergeTreeNodeWalk_1.walkAllChildSegments)(this.root, (seg) => {
            // If we've found the desired segment, terminate the walk and return 'segmentPosition'.
            if (seg === segment) {
                return false;
            }
            // If not removed, increase position
            if (seg.removedSeq === undefined) {
                segmentPosition += seg.cachedLength;
            }
            return true;
        });
        return segmentPosition;
    }
    nodeUpdateLengthNewStructure(node, recur = false) {
        this.blockUpdate(node);
        if (this.collabWindow.collaborating) {
            this.localPartialsComputed = false;
            node.partialLengths = partialLengths_1.PartialSequenceLengths.combine(node, this.collabWindow, recur);
        }
    }
    removeLocalReferencePosition(lref) {
        var _a;
        const segment = lref.getSegment();
        if (segment) {
            const removedRefs = (_a = segment === null || segment === void 0 ? void 0 : segment.localRefs) === null || _a === void 0 ? void 0 : _a.removeLocalRef(lref);
            if (removedRefs !== undefined) {
                this.blockUpdatePathLengths(segment.parent, constants_1.TreeMaintenanceSequenceNumber, constants_1.LocalClientId);
            }
            return removedRefs;
        }
    }
    createLocalReferencePosition(segment, offset, refType, properties) {
        var _a;
        if (isRemovedAndAcked(segment) &&
            !(0, referencePositions_1.refTypeIncludesFlag)(refType, ops_1.ReferenceType.SlideOnRemove | ops_1.ReferenceType.Transient)) {
            throw new container_utils_1.UsageError("Can only create SlideOnRemove or Transient local reference position on a removed segment");
        }
        const localRefs = (_a = segment.localRefs) !== null && _a !== void 0 ? _a : new localReference_1.LocalReferenceCollection(segment);
        segment.localRefs = localRefs;
        const segRef = localRefs.createLocalRef(offset, refType, properties);
        this.blockUpdatePathLengths(segment.parent, constants_1.TreeMaintenanceSequenceNumber, constants_1.LocalClientId);
        return segRef;
    }
    // Segments should either be removed remotely, removed locally, or inserted locally
    normalizeAdjacentSegments(affectedSegments) {
        // Eagerly demand this since we're about to shift elements in the list around
        const currentOrder = Array.from(affectedSegments, ({ data: seg }) => ({
            parent: seg.parent,
            index: seg.index,
            ordinal: seg.ordinal,
        }));
        // Last segment which was not affected locally.
        let lastLocalSegment = affectedSegments.last;
        while (lastLocalSegment !== undefined && isRemovedAndAcked(lastLocalSegment.data)) {
            lastLocalSegment = lastLocalSegment.prev;
        }
        if (!lastLocalSegment) {
            return;
        }
        for (let segmentToSlide = lastLocalSegment, nearerSegment = lastLocalSegment === null || lastLocalSegment === void 0 ? void 0 : lastLocalSegment.prev; segmentToSlide !== undefined; segmentToSlide = nearerSegment, nearerSegment = nearerSegment === null || nearerSegment === void 0 ? void 0 : nearerSegment.prev) {
            // Slide iterCur forward as far as possible
            if (isRemovedAndAcked(segmentToSlide.data)) {
                // Slide past all segments that are not also remotely removed
                affectedSegments.remove(segmentToSlide);
                affectedSegments.insertAfter(lastLocalSegment, segmentToSlide.data);
            }
            else if (isRemoved(segmentToSlide.data)) {
                (0, common_utils_1.assert)(segmentToSlide.data.localRemovedSeq !== undefined, 0x54d /* Removed segment that hasnt had its removal acked should be locally removed */);
                // Slide each locally removed item past all segments that have localSeq > lremoveItem.localSeq
                // but not past remotely removed segments;
                let cur = segmentToSlide;
                let scan = cur.next;
                while (scan !== undefined &&
                    !isRemovedAndAcked(scan.data) &&
                    scan.data.localSeq !== undefined &&
                    scan.data.localSeq > segmentToSlide.data.localRemovedSeq) {
                    cur = scan;
                    scan = scan.next;
                }
                if (cur !== segmentToSlide) {
                    affectedSegments.remove(segmentToSlide);
                    affectedSegments.insertAfter(cur, segmentToSlide.data);
                }
            }
        }
        const newOrder = Array.from(affectedSegments.map(({ data }) => data));
        newOrder.forEach((seg) => { var _a; return (_a = seg.localRefs) === null || _a === void 0 ? void 0 : _a.walkReferences((lref) => { var _a, _b; return (_b = (_a = lref.callbacks) === null || _a === void 0 ? void 0 : _a.beforeSlide) === null || _b === void 0 ? void 0 : _b.call(_a, lref); }); });
        const perSegmentTrackingGroups = new Map();
        for (const segment of newOrder) {
            const { trackingCollection } = segment;
            const trackingGroups = Array.from(trackingCollection.trackingGroups);
            perSegmentTrackingGroups.set(segment, trackingGroups);
            for (const group of trackingCollection.trackingGroups) {
                trackingCollection.unlink(group);
            }
        }
        for (let i = 0; i < newOrder.length; i++) {
            const seg = newOrder[i];
            const { parent, index, ordinal } = currentOrder[i];
            parent === null || parent === void 0 ? void 0 : parent.assignChild(seg, index, false);
            seg.ordinal = ordinal;
        }
        for (const [segment, groups] of perSegmentTrackingGroups.entries()) {
            for (const group of groups) {
                segment.trackingCollection.link(group);
            }
        }
        // Finally, update internal node bookkeeping on ancestors of the swapped nodes.
        // Toposort would improve this by a log factor, but probably not worth the added code size
        const depths = new Map();
        const computeDepth = (block) => {
            if (!depths.has(block)) {
                depths.set(block, block.parent === undefined ? 0 : 1 + computeDepth(block.parent));
            }
            return depths.get(block);
        };
        newOrder.forEach(computeDepth);
        for (const [node] of Array.from(depths.entries()).sort((a, b) => b[1] - a[1])) {
            if (!node.isLeaf()) {
                this.nodeUpdateLengthNewStructure(node, false);
            }
        }
        newOrder.forEach((seg) => { var _a; return (_a = seg.localRefs) === null || _a === void 0 ? void 0 : _a.walkReferences((lref) => { var _a, _b; return (_b = (_a = lref.callbacks) === null || _a === void 0 ? void 0 : _a.afterSlide) === null || _b === void 0 ? void 0 : _b.call(_a, lref); }); });
    }
    /**
     * Normalizes the segments nearby `segmentGroup` to be ordered as they would if the op submitting `segmentGroup`
     * is rebased to the current sequence number.
     * This primarily affects the ordering of adjacent segments that were removed between the original submission of
     * the local ops and now.
     * Consider the following sequence of events:
     * Initial state: "hi my friend" (seq: 0)
     * - Client 1 inserts "good " to make "hi my good friend" (op1, refSeq: 0)
     * - Client 2 deletes "my " to make "hi friend" (op2, refSeq: 0)
     * - op2 is sequenced giving seq 1
     * - Client 1 disconnects and reconnects at seq: 1.
     *
     * At this point in time, client 1 will have segments ["hi ", Removed"my ", Local"good ", "friend"].
     * However, the rebased op that it submits will cause client 2 to have segments
     * ["hi ", Local"good ", Removed"my ", "friend"].
     *
     * The difference in ordering can be problematic for tie-breaking concurrently inserted segments in some scenarios.
     * Rather than incur extra work tie-breaking these scenarios for all clients, when client 1 rebases its operation,
     * it can fix up its local state to align with what would be expected of the op it resubmits.
     */
    normalizeSegmentsOnRebase() {
        let currentRangeToNormalize = new collections_1.List();
        let rangeContainsLocalSegs = false;
        let rangeContainsRemoteRemovedSegs = false;
        const normalize = () => {
            if (rangeContainsLocalSegs &&
                rangeContainsRemoteRemovedSegs &&
                currentRangeToNormalize.length > 1) {
                this.normalizeAdjacentSegments(currentRangeToNormalize);
            }
        };
        (0, mergeTreeNodeWalk_1.walkAllChildSegments)(this.root, (seg) => {
            if (isRemoved(seg) || seg.seq === constants_1.UnassignedSequenceNumber) {
                if (isRemovedAndAcked(seg)) {
                    rangeContainsRemoteRemovedSegs = true;
                }
                if (seg.seq === constants_1.UnassignedSequenceNumber) {
                    rangeContainsLocalSegs = true;
                }
                currentRangeToNormalize.push(seg);
            }
            else {
                normalize();
                currentRangeToNormalize = new collections_1.List();
                rangeContainsLocalSegs = false;
                rangeContainsRemoteRemovedSegs = false;
            }
            return true;
        });
        normalize();
    }
    blockUpdate(block) {
        var _a;
        let len = 0;
        const hierBlock = block.hierBlock();
        if (hierBlock) {
            hierBlock.rightmostTiles = (0, properties_1.createMap)();
            hierBlock.leftmostTiles = (0, properties_1.createMap)();
            hierBlock.rangeStacks = {};
        }
        for (let i = 0; i < block.childCount; i++) {
            const child = block.children[i];
            len += (_a = nodeTotalLength(this, child)) !== null && _a !== void 0 ? _a : 0;
            if (hierBlock) {
                addNodeReferences(this, child, hierBlock.rightmostTiles, hierBlock.leftmostTiles, hierBlock.rangeStacks);
            }
            if (this.blockUpdateActions) {
                this.blockUpdateActions.child(block, i);
            }
        }
        block.cachedLength = len;
    }
    blockUpdatePathLengths(startBlock, seq, clientId, newStructure = false) {
        let block = startBlock;
        while (block !== undefined) {
            if (newStructure) {
                this.nodeUpdateLengthNewStructure(block);
            }
            else {
                this.blockUpdateLength(block, seq, clientId);
            }
            block = block.parent;
        }
    }
    blockUpdateLength(node, seq, clientId) {
        this.blockUpdate(node);
        this.localPartialsComputed = false;
        if (this.collabWindow.collaborating &&
            seq !== constants_1.UnassignedSequenceNumber &&
            seq !== constants_1.TreeMaintenanceSequenceNumber) {
            if (node.partialLengths !== undefined &&
                MergeTree.options.incrementalUpdate &&
                clientId !== constants_1.NonCollabClient) {
                node.partialLengths.update(node, seq, clientId, this.collabWindow);
            }
            else {
                node.partialLengths = partialLengths_1.PartialSequenceLengths.combine(node, this.collabWindow);
            }
        }
    }
    mapRange(handler, refSeq, clientId, accum, start, end, splitRange = false) {
        if (splitRange) {
            if (start) {
                this.ensureIntervalBoundary(start, refSeq, clientId);
            }
            if (end) {
                this.ensureIntervalBoundary(end, refSeq, clientId);
            }
        }
        this.nodeMap(refSeq, clientId, handler, accum, undefined, start, end);
    }
    incrementalBlockMap(stateStack) {
        var _a;
        while (!stateStack.empty()) {
            // We already check the stack is not empty
            const state = stateStack.top();
            if (state.op !== mergeTreeNodes_1.IncrementalExecOp.Go) {
                return;
            }
            if (state.childIndex === 0) {
                if (state.start === undefined) {
                    state.start = 0;
                }
                if (state.end === undefined) {
                    state.end = this.blockLength(state.block, state.refSeq, state.clientId);
                }
                if (state.actions.pre) {
                    state.actions.pre(state);
                }
            }
            if (state.op === mergeTreeNodes_1.IncrementalExecOp.Go && state.childIndex < state.block.childCount) {
                const child = state.block.children[state.childIndex];
                const len = (_a = this.nodeLength(child, state.refSeq, state.clientId)) !== null && _a !== void 0 ? _a : 0;
                if (len > 0 && state.start < len && state.end > 0) {
                    if (!child.isLeaf()) {
                        const childState = new mergeTreeNodes_1.IncrementalMapState(child, state.actions, state.pos, state.refSeq, state.clientId, state.context, state.start, state.end, 0);
                        stateStack.push(childState);
                    }
                    else {
                        state.actions.leaf(child, state);
                    }
                }
                state.pos += len;
                state.start -= len;
                state.end -= len;
                state.childIndex++;
            }
            else {
                if (state.childIndex === state.block.childCount) {
                    if (state.op === mergeTreeNodes_1.IncrementalExecOp.Go && state.actions.post) {
                        state.actions.post(state);
                    }
                    stateStack.pop();
                }
            }
        }
    }
    nodeMap(refSeq, clientId, leaf, accum, post, start = 0, end, localSeq) {
        var _a;
        const endPos = (_a = end !== null && end !== void 0 ? end : this.nodeLength(this.root, refSeq, clientId, localSeq)) !== null && _a !== void 0 ? _a : 0;
        if (endPos === start) {
            return;
        }
        let pos = 0;
        (0, mergeTreeNodeWalk_1.depthFirstNodeWalk)(this.root, this.root.children[0], (node) => {
            if (endPos <= pos) {
                return mergeTreeNodeWalk_1.NodeAction.Exit;
            }
            const len = this.nodeLength(node, refSeq, clientId, localSeq);
            if (len === undefined || len === 0) {
                return mergeTreeNodeWalk_1.NodeAction.Skip;
            }
            const nextPos = pos + len;
            // start is beyond the current node, so we can skip it
            if (start >= nextPos) {
                pos = nextPos;
                return mergeTreeNodeWalk_1.NodeAction.Skip;
            }
            if (node.isLeaf()) {
                if (leaf(node, pos, refSeq, clientId, start - pos, endPos - pos, accum) ===
                    false) {
                    return mergeTreeNodeWalk_1.NodeAction.Exit;
                }
                pos = nextPos;
            }
        }, undefined, post === undefined
            ? undefined
            : (block) => post(block, pos, refSeq, clientId, start - pos, endPos - pos, accum));
    }
}
exports.MergeTree = MergeTree;
MergeTree.options = {
    incrementalUpdate: true,
    insertAfterRemovedSegs: true,
    zamboniSegments: true,
};
MergeTree.theUnfinishedNode = { childCount: -1 };
//# sourceMappingURL=mergeTree.js.map