"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.EditManager = exports.minimumPossibleSequenceNumber = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const client_utils_1 = require("@fluid-internal/client-utils");
const sorted_btree_es6_1 = require("@tylerbu/sorted-btree-es6");
const index_js_1 = require("../core/index.js");
const index_js_2 = require("../util/index.js");
const branch_js_1 = require("./branch.js");
const sequenceIdUtils_js_1 = require("./sequenceIdUtils.js");
const internal_2 = require("@fluidframework/telemetry-utils/internal");
exports.minimumPossibleSequenceNumber = (0, index_js_2.brand)(Number.MIN_SAFE_INTEGER);
const minimumPossibleSequenceId = {
    sequenceNumber: exports.minimumPossibleSequenceNumber,
};
/**
 * A special revision tag for the initial {@link EditManager.trunkBase} commit.
 * @remarks This tag is used to supply the _initial_ trunk base with a known revision.
 * The trunk base may advance over time, after which point the trunk base will have a different revision.
 * When {@link EditManager.getSummaryData | serializing} and deserializing, peer branches that include the trunk base commit in their history will always use this tag.
 */
const rootRevision = "root";
/**
 * Max number of telemetry log call that may be aggregated before being sent.
 */
const maxRebaseStatsAggregationCount = 1000;
/**
 * Represents a local branch of a document and interprets the effect on the document of adding sequenced changes,
 * which were based on a given session's branch, to the document history
 */
// TODO: Try to reduce this to a single type parameter
class EditManager {
    /**
     * @param changeFamily - the change family of changes on the trunk and local branch
     * @param localSessionId - the id of the local session that will be used for local commits
     */
    constructor(changeFamily, localSessionId, mintRevisionTag, logger) {
        this.changeFamily = changeFamily;
        this.localSessionId = localSessionId;
        this.mintRevisionTag = mintRevisionTag;
        this._events = (0, client_utils_1.createEmitter)();
        /**
         * Records extra data associated with commits in the {@link trunk}.
         * This does not include an entry for the {@link trunkBase}.
         */
        this.trunkMetadata = new Map();
        /**
         * A map from a sequence id to the commit in the {@link trunk} which has that sequence id.
         * This also includes an entry for the {@link trunkBase} which always has the lowest key in the map.
         */
        this.sequenceMap = new sorted_btree_es6_1.BTree(undefined, sequenceIdUtils_js_1.sequenceIdComparator);
        /**
         * Branches are maintained to represent the local change list that the issuing client had
         * at the time of submitting the latest known edit on the branch.
         * This means the head commit of each branch is always in its original (non-rebased) form.
         */
        this.peerLocalBranches = new Map();
        /**
         * Tracks where on the trunk all registered branches are based. Each key is the sequence id of a commit on
         * the trunk, and the value is the set of all branches who have that commit as their common ancestor with the trunk.
         *
         * @remarks
         * This does not include the local branch.
         */
        this.trunkBranches = new sorted_btree_es6_1.BTree(undefined, sequenceIdUtils_js_1.sequenceIdComparator);
        /**
         * The sequence number of the newest commit on the trunk that has been received by all peers.
         * Defaults to {@link minimumPossibleSequenceNumber} if no commits have been received.
         *
         * @remarks If there are more than one commit with the same sequence number we assume this refers to the last commit in the batch.
         */
        this.minimumSequenceNumber = exports.minimumPossibleSequenceNumber;
        /**
         * The list of commits (from oldest to most recent) that are on the local branch but not on the trunk.
         * When a local commit is sequenced, the first commit in this list shifted onto the tip of the trunk.
         */
        this.localCommits = [];
        this.trunkBase = {
            revision: rootRevision,
            change: changeFamily.rebaser.compose([]),
        };
        this.sequenceMap.set(minimumPossibleSequenceId, this.trunkBase);
        if (logger !== undefined) {
            this.telemetryEventBatcher = new internal_2.TelemetryEventBatcher({
                eventName: "rebaseProcessing",
                category: "performance",
            }, logger, maxRebaseStatsAggregationCount);
        }
        this.trunk = new branch_js_1.SharedTreeBranch(this.trunkBase, changeFamily, mintRevisionTag, this._events, this.telemetryEventBatcher);
        this.localBranch = new branch_js_1.SharedTreeBranch(this.trunk.getHead(), changeFamily, mintRevisionTag, this._events, this.telemetryEventBatcher);
        this.localBranch.events.on("afterChange", (event) => {
            if (event.type === "append") {
                for (const commit of event.newCommits) {
                    this.localCommits.push(commit);
                }
            }
            else {
                this.localCommits.length = 0;
                (0, index_js_1.findCommonAncestor)([this.localBranch.getHead(), this.localCommits], this.trunk.getHead());
            }
        });
        // Track all forks of the local branch for purposes of trunk eviction. Unlike the local branch, they have
        // an unknown lifetime and rebase frequency, so we can not make any assumptions about which trunk commits
        // they require and therefore we monitor them explicitly.
        (0, branch_js_1.onForkTransitive)(this.localBranch, (fork) => this.registerBranch(fork));
    }
    /**
     * Make the given branch known to the `EditManager`. The `EditManager` will ensure that all registered
     * branches remain usable even as the minimum sequence number advances.
     *
     * TODO#AB6926: Refactor local branch management into a separate class that encapsulates `trunkBranches` and everything
     * that touches it.
     * TODO#AB6925: Maintain the divergence point between each branch and the trunk so that we don't have to recompute
     * it so often.
     */
    registerBranch(branch) {
        this.trackBranch(branch);
        // Whenever the branch is rebased, update our record of its base trunk commit
        const offBeforeRebase = branch.events.on("beforeChange", (args) => {
            if (args.type === "rebase") {
                this.untrackBranch(branch);
            }
        });
        const offAfterRebase = branch.events.on("afterChange", (args) => {
            if (args.type === "rebase") {
                this.trackBranch(branch);
                this.trimTrunk();
            }
        });
        // When the branch is disposed, update our branch set and trim the trunk
        const offDispose = branch.events.on("dispose", () => {
            this.untrackBranch(branch);
            this.trimTrunk();
            offBeforeRebase();
            offAfterRebase();
            offDispose();
        });
    }
    trackBranch(b) {
        const trunkCommit = (0, index_js_1.findCommonAncestor)(this.trunk.getHead(), b.getHead()) ??
            (0, internal_1.fail)(0xad2 /* Expected branch to be related to trunk */);
        const sequenceId = this.getCommitSequenceId(trunkCommit);
        const branches = (0, index_js_2.getOrCreate)(this.trunkBranches, sequenceId, () => new Set());
        (0, internal_1.assert)(!branches.has(b), 0x670 /* Branch was registered more than once */);
        branches.add(b);
    }
    untrackBranch(b) {
        const trunkCommit = (0, index_js_1.findCommonAncestor)(this.trunk.getHead(), b.getHead()) ??
            (0, internal_1.fail)(0xad3 /* Expected branch to be related to trunk */);
        const sequenceId = this.getCommitSequenceId(trunkCommit);
        const branches = this.trunkBranches.get(sequenceId) ?? (0, internal_1.fail)(0xad4 /* Expected branch to be tracked */);
        (0, internal_1.assert)(branches.delete(b), 0x671 /* Expected branch to be tracked */);
        if (branches.size === 0) {
            this.trunkBranches.delete(sequenceId);
        }
    }
    /**
     * Promote the oldest un-sequenced commit on the local branch to the head of the trunk.
     * @param sequenceId - The sequence id of the new trunk commit
     * @remarks This method is a performance optimization for the scenario where this client receives its own change back after sequencing.
     * The normal (not optimized) process in this case would be to apply the new sequenced commit to the trunk and then rebase the local branch over the trunk.
     * The first commit will be "the same" (as in, it will have the same revision) as the commit that was just sequenced, so the rebase will be a no-op.
     * Because the rebase is a no-op, we can skip it entirely and simply remove the commit from the local branch and append it to the trunk.
     * Avoiding the overhead of the rebase process, even when it's a no-op, has real measured performance benefits and is worth the added complexity here.
     */
    fastForwardNextLocalCommit(sequenceId) {
        // First, push the local commit to the trunk.
        // We are mutating our `localCommits` cache here, but there is no need to actually change the `localBranch` itself because it will simply catch up later if/when it next rebases.
        const firstLocalCommit = this.localCommits.shift();
        (0, internal_1.assert)(firstLocalCommit !== undefined, 0x6b5 /* Received a sequenced change from the local session despite having no local changes */);
        const previousSequenceId = this.getCommitSequenceId(this.trunk.getHead());
        this.pushGraphCommitToTrunk(sequenceId, firstLocalCommit, this.localSessionId);
        // Next, we need to update the sequence IDs that our local branches (user's branches, not peer branches) are associated with.
        // In particular, if a local branch is based on the previous trunk head (the branch's first ancestor in the trunk is the commit that was the head before we pushed the new commit)
        // and also branches off of the local branch (it has an ancestor that is part of the local branch), it needs to have its sequence number advanced to be that of the new trunk head.
        // Intuitively, this makes sense because:
        // 1. The trunk's head just advanced forward by some (sequence) amount.
        // 2. The local branch is always rebased to be branching off of the head of the trunk (not literally in this case, because of the optimization, but in effect).
        // 3. Therefore, the entire local branch just advanced forward by some (sequence) amount, and any commits downstream of it which track the sequence numbers of their base commits on the trunk should also advance.
        // This update is not necessarily required for all local branches, since some may have fallen behind the local branch and are based on older trunk commits (such branches do not need updating).
        const currentBranches = this.trunkBranches.get(previousSequenceId);
        if (currentBranches !== undefined) {
            const newBranches = (0, index_js_2.getOrCreate)(this.trunkBranches, sequenceId, () => new Set());
            for (const branch of currentBranches) {
                // Check every branch associated with the old sequence ID and advance it if it is based on the local branch (specifically, on the local branch as it was before we pushed its first commit to the trunk).
                // We validate this by checking if the branch's head is a descendant of the local commit that we just pushed.
                if ((0, index_js_1.findAncestor)(branch.getHead(), (c) => c === firstLocalCommit) !== undefined) {
                    newBranches.add(branch);
                    currentBranches.delete(branch);
                }
            }
            // Clean up our trunk branches map by removing any empty sets.
            if (currentBranches.size === 0) {
                this.trunkBranches.delete(previousSequenceId);
            }
            if (newBranches.size === 0) {
                this.trunkBranches.delete(sequenceId);
            }
        }
    }
    /**
     * Return the sequence number at which the given commit was sequenced on the trunk, or undefined if the commit is not part of the trunk.
     */
    getSequenceNumber(trunkCommit) {
        return this.trunkMetadata.get(trunkCommit.revision)?.sequenceId.sequenceNumber;
    }
    /**
     * Advances the minimum sequence number, and removes all commits from the trunk which lie outside the collaboration window,
     * if they are not retained by revertibles or local branches.
     * @param minimumSequenceNumber - the sequence number of the newest commit that all peers (including this one) have received and applied to their trunks.
     *
     * @remarks If there are more than one commit with the same sequence number we assume this refers to the last commit in the batch.
     */
    advanceMinimumSequenceNumber(minimumSequenceNumber, trimTrunk = true) {
        if (minimumSequenceNumber === this.minimumSequenceNumber) {
            return;
        }
        (0, internal_1.assert)(minimumSequenceNumber > this.minimumSequenceNumber, 0x476 /* number must be larger or equal to current minimumSequenceNumber. */);
        this.minimumSequenceNumber = minimumSequenceNumber;
        if (trimTrunk) {
            this.trimTrunk();
        }
    }
    /**
     * Examines the latest known minimum sequence number and the trunk bases of any registered branches to determine
     * if any commits on the trunk are unreferenced and unneeded for future computation; those found are evicted from the trunk.
     */
    trimTrunk() {
        /** The sequence id of the most recent commit on the trunk that will be trimmed */
        let trunkTailSequenceId = {
            sequenceNumber: this.minimumSequenceNumber,
            indexInBatch: Number.POSITIVE_INFINITY,
        };
        // If there are any outstanding registered branches, get the one that is the oldest (has the "most behind" trunk base)
        const minimumBranchBaseSequenceId = this.trunkBranches.minKey();
        if (minimumBranchBaseSequenceId !== undefined) {
            // If that branch is behind the minimum sequence id, we only want to evict commits older than it,
            // even if those commits are behind the minimum sequence id
            const sequenceIdBeforeMinimumBranchBase = (0, sequenceIdUtils_js_1.getUpperBoundOfPreviousSequenceId)(minimumBranchBaseSequenceId);
            trunkTailSequenceId = (0, sequenceIdUtils_js_1.minSequenceId)(trunkTailSequenceId, sequenceIdBeforeMinimumBranchBase);
        }
        const [sequenceId, latestEvicted] = this.getClosestTrunkCommit((0, sequenceIdUtils_js_1.maxSequenceId)(trunkTailSequenceId, this.sequenceMap.minKey() ?? minimumPossibleSequenceId));
        // Don't do any work if the commit found by the search is already the tail of the trunk
        if (latestEvicted !== this.trunkBase) {
            // The minimum sequence number informs us that all peer branches are at least caught up to the tail commit,
            // so rebase them accordingly. This is necessary to prevent peer branches from referencing any evicted commits.
            for (const [, branch] of this.peerLocalBranches) {
                branch.rebaseOnto(this.trunk, latestEvicted);
            }
            // This mutation is a performance hack. If commits are truly immutable, then changing the trunk's tail requires
            // regenerating the entire commit graph. Instead, we can simply chop off the tail like this if we're certain
            // that there are no outstanding references to any of the commits being removed (other than the references via
            // the trunk). The peer branches have been rebased to the head of the trunk, the local branch is already rebased
            // to the head of the trunk, and all other branches are tracked by `trunkBranches` and known to be ahead of or at
            // `newTrunkBase`. Therefore, no branches should have unique references to any of the commits being evicted here.
            // We mutate the most recent of the evicted commits to become the new trunk base. That way, any other commits that
            // have parent pointers to the latest evicted commit will stay linked, even though that it is no longer part of the trunk.
            const newTrunkBase = latestEvicted;
            // The metadata for new trunk base revision needs to be deleted before modifying it.
            this.trunkMetadata.delete(newTrunkBase.revision);
            // collect the revisions that will be trimmed to send as part of the branch trimmed event
            const trimmedRevisions = getPathFromBase(newTrunkBase, this.trunkBase).map((c) => c.revision);
            // Dropping the parent field removes (transitively) all references to the evicted commits so they can be garbage collected.
            delete newTrunkBase.parent;
            this.trunkBase = newTrunkBase;
            // Update any state that is derived from trunk commits
            this.sequenceMap.editRange(minimumPossibleSequenceId, sequenceId, true, (s, commit) => {
                // Cleanup look-aside data for each evicted commit
                this.trunkMetadata.delete(commit.revision);
                // Delete all evicted commits from `sequenceMap` except for the latest one, which is the new `trunkBase`
                if ((0, sequenceIdUtils_js_1.equalSequenceIds)(s, sequenceId)) {
                    (0, internal_1.assert)(commit === newTrunkBase, 0x729 /* Expected last evicted commit to be new trunk base */);
                }
                else {
                    Reflect.defineProperty(commit, "change", {
                        get: () => (0, internal_1.assert)(false, 0xa5e /* Should not access 'change' property of an evicted commit */),
                    });
                    Reflect.defineProperty(commit, "revision", {
                        get: () => (0, internal_1.assert)(false, 0xa5f /* Should not access 'revision' property of an evicted commit */),
                    });
                    Reflect.defineProperty(commit, "parent", {
                        get: () => (0, internal_1.assert)(false, 0xa60 /* Should not access 'parent' property of an evicted commit */),
                    });
                    return { delete: true };
                }
            });
            const trunkSize = getPathFromBase(this.trunk.getHead(), this.trunkBase).length;
            (0, internal_1.assert)(this.sequenceMap.size === trunkSize + 1, 0x744 /* The size of the sequenceMap must have one element more than the trunk */);
            (0, internal_1.assert)(this.trunkMetadata.size === trunkSize, 0x745 /* The size of the trunkMetadata must be the same as the trunk */);
            this._events.emit("ancestryTrimmed", trimmedRevisions);
        }
    }
    isEmpty() {
        return (this.trunk.getHead() === this.trunkBase &&
            this.peerLocalBranches.size === 0 &&
            this.localBranch.getHead() === this.trunk.getHead() &&
            this.minimumSequenceNumber === exports.minimumPossibleSequenceNumber);
    }
    getSummaryData() {
        // The assert below is acceptable at present because summarization only ever occurs on a client with no
        // local/in-flight changes.
        // In the future we may wish to relax this constraint. For that to work, the current implementation of
        // `EditManager` would have to be amended in one of two ways:
        // A) Changes made by the local session should be represented by a branch in `EditManager.branches`.
        // B) The contents of such a branch should be computed on demand based on the trunk.
        // Note that option (A) would be a simple change to `addSequencedChanges` whereas (B) would likely require
        // rebasing trunk changes over the inverse of trunk changes.
        (0, internal_1.assert)(this.localBranch.getHead() === this.trunk.getHead(), 0x428 /* Clients with local changes cannot be used to generate summaries */);
        // Trimming the trunk before serializing ensures that the trunk data in the summary is as minimal as possible.
        this.trimTrunk();
        let oldestCommitInCollabWindow = this.getClosestTrunkCommit(this.minimumSequenceNumber)[1];
        (0, internal_1.assert)(oldestCommitInCollabWindow.parent !== undefined ||
            oldestCommitInCollabWindow === this.trunkBase, 0x8c7 /* Expected oldest commit in collab window to have a parent or be the trunk base */);
        // Path construction is exclusive, so we need to use the parent of the oldest commit in the window if it exists
        oldestCommitInCollabWindow =
            oldestCommitInCollabWindow.parent ?? oldestCommitInCollabWindow;
        const trunk = getPathFromBase(this.trunk.getHead(), oldestCommitInCollabWindow).map((c) => {
            (0, internal_1.assert)(c !== this.trunkBase, 0xa61 /* Serialized trunk should not include the trunk base */);
            const metadata = this.trunkMetadata.get(c.revision) ??
                (0, internal_1.fail)(0xad5 /* Expected metadata for trunk commit */);
            const commit = {
                change: c.change,
                revision: c.revision,
                sequenceNumber: metadata.sequenceId.sequenceNumber,
                sessionId: metadata.sessionId,
            };
            if (metadata.sequenceId.indexInBatch !== undefined) {
                commit.indexInBatch = metadata.sequenceId.indexInBatch;
            }
            return commit;
        });
        const peerLocalBranches = new Map((0, index_js_2.mapIterable)(this.peerLocalBranches.entries(), ([sessionId, branch]) => {
            const branchPath = [];
            const ancestor = (0, index_js_1.findCommonAncestor)([branch.getHead(), branchPath], this.trunk.getHead()) ??
                (0, internal_1.fail)(0xad6 /* Expected branch to be based on trunk */);
            const base = ancestor === this.trunkBase ? rootRevision : ancestor.revision;
            return [
                sessionId,
                {
                    base,
                    commits: branchPath.map((c) => {
                        (0, internal_1.assert)(c !== this.trunkBase, 0xa62 /* Serialized branch should not include the trunk base */);
                        const commit = {
                            change: c.change,
                            revision: c.revision,
                            sessionId,
                        };
                        return commit;
                    }),
                },
            ];
        }));
        return { trunk, peerLocalBranches };
    }
    loadSummaryData(data) {
        (0, internal_1.assert)(this.isEmpty(), 0x68a /* Attempted to load from summary after edit manager was already mutated */);
        // Record the tags of each trunk commit as we generate the trunk so they can be looked up quickly
        // when hydrating the peer branches below
        const trunkRevisionCache = new Map();
        trunkRevisionCache.set(this.trunkBase.revision, this.trunkBase);
        this.trunk.setHead(data.trunk.reduce((base, c) => {
            const sequenceId = c.indexInBatch === undefined
                ? {
                    sequenceNumber: c.sequenceNumber,
                }
                : {
                    sequenceNumber: c.sequenceNumber,
                    indexInBatch: c.indexInBatch,
                };
            const commit = (0, index_js_1.mintCommit)(base, c);
            this.sequenceMap.set(sequenceId, commit);
            this.trunkMetadata.set(c.revision, {
                sequenceId,
                sessionId: c.sessionId,
            });
            trunkRevisionCache.set(c.revision, commit);
            return commit;
        }, this.trunkBase));
        this.localBranch.setHead(this.trunk.getHead());
        for (const [sessionId, branch] of data.peerLocalBranches) {
            const commit = trunkRevisionCache.get(branch.base) ??
                (0, internal_1.fail)(0xad7 /* Expected summary branch to be based off of a revision in the trunk */);
            this.peerLocalBranches.set(sessionId, new branch_js_1.SharedTreeBranch(branch.commits.reduce(index_js_1.mintCommit, commit), this.changeFamily, this.mintRevisionTag));
        }
    }
    getCommitSequenceId(trunkCommitOrTrunkBase) {
        const id = this.trunkMetadata.get(trunkCommitOrTrunkBase.revision)?.sequenceId;
        if (id === undefined) {
            (0, internal_1.assert)(trunkCommitOrTrunkBase === this.trunkBase, 0xa63 /* Commit must be either be on the trunk or be the trunk base */);
            return minimumPossibleSequenceId;
        }
        return id;
    }
    getTrunkChanges() {
        return this.getTrunkCommits().map((c) => c.change);
    }
    getTrunkCommits() {
        return getPathFromBase(this.trunk.getHead(), this.trunkBase);
    }
    getTrunkHead() {
        return this.trunk.getHead();
    }
    getLocalChanges() {
        return this.getLocalCommits().map((c) => c.change);
    }
    getLocalCommits() {
        return this.localCommits;
    }
    /**
     * Gets the length of the longest branch maintained by this `EditManager`.
     * This may be the length of a peer branch or the local branch.
     *
     * @remarks
     * The length is counted from the lowest common ancestor with the trunk such that a fully sequenced branch would
     * have length zero.
     */
    getLongestBranchLength() {
        let max = 0;
        const trunkHead = this.trunk.getHead();
        for (const branch of this.peerLocalBranches.values()) {
            const branchPath = getPathFromBase(branch.getHead(), trunkHead);
            if (branchPath.length > max) {
                max = branchPath.length;
            }
        }
        const localPath = getPathFromBase(this.localBranch.getHead(), trunkHead);
        return Math.max(max, localPath.length);
    }
    /* eslint-disable jsdoc/check-indentation */
    /**
     * Add a bunch of sequenced changes. A bunch is a group of sequenced commits that have the following properties:
     * - They are not interleaved with messages from other DDSes in the container.
     * - They are all part of the same batch, which entails:
     *   - They are contiguous in sequencing order.
     *   - They are all from the same client.
     *   - They are all based on the same reference sequence number.
     *   - They are not interleaved with messages from other clients.
     */
    /* eslint-enable jsdoc/check-indentation */
    addSequencedChanges(newCommits, sessionId, sequenceNumber, referenceSequenceNumber) {
        (0, internal_1.assert)(newCommits.length > 0, 0xad8 /* Expected at least one sequenced change */);
        (0, internal_1.assert)(sequenceNumber > this.minimumSequenceNumber, 0x713 /* Expected change sequence number to exceed the last known minimum sequence number */);
        (0, internal_1.assert)(sequenceNumber >= // This is ">=", not ">" because changes in the same batch will have the same sequence number
            (this.sequenceMap.maxKey()?.sequenceNumber ?? exports.minimumPossibleSequenceNumber), 0xa64 /* Attempted to sequence change with an outdated sequence number */);
        // Returns the sequence id for the next commit to be processed in the bunch. Since all the commits have the
        // same sequence number, only the index in the batch needs to be incremented.
        const getNextSequenceId = (sequenceId) => {
            return {
                sequenceNumber: sequenceId.sequenceNumber,
                indexInBatch: (sequenceId.indexInBatch ?? 0) + 1,
            };
        };
        const commitsSequenceNumber = this.getBatch(sequenceNumber);
        // The sequence id for the next commit to be processed in the bunch.
        let nextSequenceId = commitsSequenceNumber.length === 0
            ? {
                sequenceNumber,
            }
            : {
                sequenceNumber,
                indexInBatch: commitsSequenceNumber.length,
            };
        // Local changes, i.e., changes from this client are applied by fast forwarding the local branch commit onto
        // the trunk.
        if (sessionId === this.localSessionId) {
            for (const _ of newCommits) {
                this.fastForwardNextLocalCommit(nextSequenceId);
                nextSequenceId = getNextSequenceId(nextSequenceId);
            }
            return;
        }
        // Remote changes, i.e., changes from remote clients are applied in three steps.
        // Step 1 - Recreate the peer remote client's local environment.
        // Get the revision that the remote change is based on and rebase that peer local branch over the part of the
        // trunk up to the base revision. This will be a no-op if the sending client has not advanced since the last
        // time we received an edit from it
        const [, baseRevisionInTrunk] = this.getClosestTrunkCommit(referenceSequenceNumber);
        const peerLocalBranch = (0, index_js_2.getOrCreate)(this.peerLocalBranches, sessionId, () => new branch_js_1.SharedTreeBranch(baseRevisionInTrunk, this.changeFamily, this.mintRevisionTag));
        peerLocalBranch.rebaseOnto(this.trunk, baseRevisionInTrunk);
        // Step 2 - Append the changes to the peer branch and rebase the changes to the tip of the trunk.
        if (peerLocalBranch.getHead() === this.trunk.getHead()) {
            // If the peer local branch is fully caught up and empty (no changes relative to the trunk) after being
            // rebased, then push changes to the trunk directly and update the peer branch to the trunk's head.
            for (const newCommit of newCommits) {
                this.pushCommitToTrunk(nextSequenceId, { ...newCommit, sessionId });
                nextSequenceId = getNextSequenceId(nextSequenceId);
            }
            peerLocalBranch.setHead(this.trunk.getHead());
        }
        else {
            // Otherwise, push the changes to the peer local branch and merge the branch into the trunk.
            for (const newCommit of newCommits) {
                peerLocalBranch.apply((0, index_js_1.tagChange)(newCommit.change, newCommit.revision));
            }
            const result = this.trunk.merge(peerLocalBranch);
            if (result !== undefined) {
                // If the merge resulted in any changes to the trunk, update the sequence map and trunk metadata
                // with the rebased commits.
                for (const sourceCommit of result.sourceCommits) {
                    this.sequenceMap.set(nextSequenceId, sourceCommit);
                    this.trunkMetadata.set(sourceCommit.revision, {
                        sequenceId: nextSequenceId,
                        sessionId,
                    });
                    nextSequenceId = getNextSequenceId(nextSequenceId);
                }
            }
        }
        // Step 3 - Rebase the local branch over the updated trunk.
        this.localBranch.rebaseOnto(this.trunk);
    }
    findLocalCommit(revision) {
        const commits = [];
        const commit = (0, index_js_1.findAncestor)([this.localBranch.getHead(), commits], (c) => c.revision === revision);
        (0, internal_1.assert)(commit !== undefined, 0x599 /* Expected local branch to contain revision */);
        return [commit, commits];
    }
    pushCommitToTrunk(sequenceId, commit) {
        const mintedCommit = (0, index_js_1.mintCommit)(this.trunk.getHead(), commit);
        this.pushGraphCommitToTrunk(sequenceId, mintedCommit, commit.sessionId);
    }
    pushGraphCommitToTrunk(sequenceId, graphCommit, sessionId) {
        this.trunk.setHead(graphCommit);
        const trunkHead = this.trunk.getHead();
        this.sequenceMap.set(sequenceId, trunkHead);
        this.trunkMetadata.set(trunkHead.revision, { sequenceId, sessionId });
    }
    getClosestTrunkCommit(searchBy) {
        const sequenceId = typeof searchBy === "number"
            ? {
                // This is to make sure that the correct commit is selected in this 2 scenarios:
                // 1) The commit is unique for that sequence number
                // 2) There are more than one commit for the same sequence number, in this case we need to select the last one.
                sequenceNumber: searchBy,
                indexInBatch: Number.POSITIVE_INFINITY,
            }
            : searchBy;
        const commit = this.sequenceMap.getPairOrNextLower(sequenceId);
        (0, internal_1.assert)(commit !== undefined, 0x746 /* sequence id has been evicted */);
        return commit;
    }
    getBatch(sequenceNumber) {
        const startSequenceId = {
            sequenceNumber,
        };
        const endSequenceId = {
            sequenceNumber: (0, index_js_2.brand)(sequenceNumber + 1),
        };
        return this.sequenceMap.getRange(startSequenceId, endSequenceId, false);
    }
}
exports.EditManager = EditManager;
/**
 * Gets the path from the base of a branch to its head.
 */
function getPathFromBase(branchHead, baseBranchHead) {
    const path = [];
    (0, internal_1.assert)((0, index_js_1.findCommonAncestor)([branchHead, path], baseBranchHead) !== undefined, 0x573 /* Expected branches to be related */);
    return path;
}
//# sourceMappingURL=editManager.js.map