"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.runSynchronous = exports.TreeCheckout = exports.createTreeCheckout = void 0;
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
const core_utils_1 = require("@fluidframework/core-utils");
const core_1 = require("../core");
const events_1 = require("../events");
const feature_libraries_1 = require("../feature-libraries");
const shared_tree_core_1 = require("../shared-tree-core");
const util_1 = require("../util");
const codec_1 = require("../codec");
/**
 * Creates a {@link TreeCheckout}.
 * @param args - an object containing optional components that will be used to build the view.
 * Any components not provided will be created by default.
 * @remarks This does not create a {@link SharedTree}, but rather a view with the minimal state
 * and functionality required to implement {@link ITreeCheckout}.
 */
function createTreeCheckout(args) {
    const schema = args?.schema ?? new core_1.InMemoryStoredSchemaRepository();
    const forest = args?.forest ?? (0, feature_libraries_1.buildForest)();
    const changeFamily = args?.changeFamily ?? new feature_libraries_1.DefaultChangeFamily({ jsonValidator: codec_1.noopValidator });
    const branch = args?.branch ??
        new shared_tree_core_1.SharedTreeBranch({
            change: changeFamily.rebaser.compose([]),
            revision: (0, core_1.assertIsRevisionTag)("00000000-0000-4000-8000-000000000000"),
        }, changeFamily);
    const events = args?.events ?? (0, events_1.createEmitter)();
    const transaction = new Transaction(branch);
    return new TreeCheckout(transaction, branch, changeFamily, schema, forest, events, args?.removedRoots);
}
exports.createTreeCheckout = createTreeCheckout;
class Transaction {
    constructor(branch) {
        this.branch = branch;
    }
    start() {
        this.branch.startTransaction();
        this.branch.editor.enterTransaction();
    }
    commit() {
        this.branch.commitTransaction();
        this.branch.editor.exitTransaction();
        return util_1.TransactionResult.Commit;
    }
    abort() {
        this.branch.abortTransaction();
        this.branch.editor.exitTransaction();
        return util_1.TransactionResult.Abort;
    }
    inProgress() {
        return this.branch.isTransacting();
    }
}
/**
 * An implementation of {@link ITreeCheckoutFork}.
 */
class TreeCheckout {
    constructor(transaction, branch, changeFamily, storedSchema, forest, events, removedRoots = (0, core_1.makeDetachedFieldIndex)("repair")) {
        this.transaction = transaction;
        this.branch = branch;
        this.changeFamily = changeFamily;
        this.storedSchema = storedSchema;
        this.forest = forest;
        this.events = events;
        this.removedRoots = removedRoots;
        // We subscribe to `beforeChange` rather than `afterChange` here because it's possible that the change is invalid WRT our forest.
        // For example, a bug in the editor might produce a malformed change object and thus applying the change to the forest will throw an error.
        // In such a case we will crash here, preventing the change from being added to the commit graph, and preventing `afterChange` from firing.
        // One important consequence of this is that we will not submit the op containing the invalid change, since op submissions happens in response to `afterChange`.
        branch.on("beforeChange", (event) => {
            if (event.change !== undefined) {
                const delta = (0, feature_libraries_1.intoDelta)(event.change);
                const anchorVisitor = this.forest.anchors.acquireVisitor();
                const combinedVisitor = (0, core_1.combineVisitors)([this.forest.acquireVisitor(), anchorVisitor], [anchorVisitor]);
                (0, core_1.visitDelta)(delta, combinedVisitor, this.removedRoots);
                combinedVisitor.free();
                this.events.emit("afterBatch");
            }
            if (event.type === "replace" && (0, shared_tree_core_1.getChangeReplaceType)(event) === "transactionCommit") {
                const transactionRevision = event.newCommits[0].revision;
                for (const transactionStep of event.removedCommits) {
                    this.removedRoots.updateMajor(transactionStep.revision, transactionRevision);
                }
            }
        });
        branch.on("revertible", (revertible) => {
            // if there are no listeners, discard the revertible to avoid memory leaks
            if (!this.events.hasListeners("revertible")) {
                revertible.discard();
            }
            else {
                this.events.emit("revertible", revertible);
            }
        });
    }
    get rootEvents() {
        return this.forest.anchors;
    }
    get editor() {
        return this.branch.editor;
    }
    locate(anchor) {
        return this.forest.anchors.locate(anchor);
    }
    fork() {
        const anchors = new core_1.AnchorSet();
        // TODO: ensure editing this clone of the schema does the right thing.
        const storedSchema = new core_1.InMemoryStoredSchemaRepository(this.storedSchema);
        const forest = this.forest.clone(storedSchema, anchors);
        const branch = this.branch.fork();
        const transaction = new Transaction(branch);
        return new TreeCheckout(transaction, branch, this.changeFamily, storedSchema, forest, (0, events_1.createEmitter)(), this.removedRoots.clone());
    }
    rebase(view) {
        view.branch.rebaseOnto(this.branch);
    }
    rebaseOnto(view) {
        view.rebase(this);
    }
    merge(view, disposeView = true) {
        (0, core_utils_1.assert)(!this.transaction.inProgress() || disposeView, 0x710 /* A view that is merged into an in-progress transaction must be disposed */);
        while (view.transaction.inProgress()) {
            view.transaction.commit();
        }
        this.branch.merge(view.branch);
        if (disposeView) {
            view.dispose();
        }
    }
    /**
     * Dispose this view, freezing its state and allowing the SharedTree to release resources required by it.
     * Attempts to further mutate or dispose this view will error.
     */
    dispose() {
        this.branch.dispose();
    }
}
exports.TreeCheckout = TreeCheckout;
/**
 * Run a synchronous transaction on the given shared tree view.
 * This is a convenience helper around the {@link SharedTreeFork#transaction} APIs.
 * @param view - the view on which to run the transaction
 * @param transaction - the transaction function. This will be executed immediately. It is passed `view` as an argument for convenience.
 * If this function returns an `Abort` result then the transaction will be aborted. Otherwise, it will be committed.
 * @returns whether or not the transaction was committed or aborted
 * @alpha
 */
function runSynchronous(view, transaction) {
    view.transaction.start();
    const result = transaction(view);
    return result === util_1.TransactionResult.Abort
        ? view.transaction.abort()
        : view.transaction.commit();
}
exports.runSynchronous = runSynchronous;
//# sourceMappingURL=treeCheckout.js.map