"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.markContentType = exports.extractFactoryContent = exports.prepareContentForInsert = exports.getOrCreateNodeProxy = exports.getProxyForField = exports.isTreeNode = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const index_js_1 = require("../core/index.js");
const index_js_2 = require("../feature-libraries/index.js");
const index_js_3 = require("../util/index.js");
const proxyBinding_js_1 = require("./proxyBinding.js");
const rawNode_js_1 = require("./rawNode.js");
const schemaCaching_js_1 = require("./schemaCaching.js");
const schemaTypes_js_1 = require("./schemaTypes.js");
/**
 * Detects if the given 'candidate' is a TreeNode.
 *
 * @remarks
 * Supports both Hydrated and {@link Unhydrated} TreeNodes, both of which return true.
 *
 * Because the common usage is to check if a value being inserted/set is a TreeNode,
 * this function permits calling with primitives as well as objects.
 *
 * Primitives will always return false (as they are copies of data, not references to nodes).
 *
 * @param candidate - Value which may be a TreeNode
 * @returns true if the given 'candidate' is a hydrated TreeNode.
 */
function isTreeNode(candidate) {
    return (0, proxyBinding_js_1.tryGetFlexNode)(candidate) !== undefined;
}
exports.isTreeNode = isTreeNode;
/**
 * Retrieve the associated proxy for the given field.
 * */
function getProxyForField(field) {
    switch (field.schema.kind) {
        case index_js_2.FieldKinds.required: {
            const asValue = field;
            // TODO: Ideally, we would return leaves without first boxing them.  However, this is not
            //       as simple as calling '.content' since this skips the node and returns the FieldNode's
            //       inner field.
            return getOrCreateNodeProxy(asValue.boxedContent);
        }
        case index_js_2.FieldKinds.optional: {
            const asValue = field;
            // TODO: Ideally, we would return leaves without first boxing them.  However, this is not
            //       as simple as calling '.content' since this skips the node and returns the FieldNode's
            //       inner field.
            const maybeContent = asValue.boxedContent;
            // Normally, empty fields are unreachable due to the behavior of 'tryGetField'.  However, the
            // root field is a special case where the field is always present (even if empty).
            return maybeContent === undefined ? undefined : getOrCreateNodeProxy(maybeContent);
        }
        // TODO: Remove if/when 'FieldNode' is removed.
        case index_js_2.FieldKinds.sequence: {
            // 'getProxyForNode' handles FieldNodes by unconditionally creating a array node proxy, making
            // this case unreachable as long as users follow the 'array recipe'.
            (0, index_js_3.fail)("'sequence' field is unexpected.");
        }
        default:
            (0, index_js_3.fail)("invalid field kind");
    }
}
exports.getProxyForField = getProxyForField;
function getOrCreateNodeProxy(flexNode) {
    const cachedProxy = (0, proxyBinding_js_1.tryGetProxy)(flexNode);
    if (cachedProxy !== undefined) {
        return cachedProxy;
    }
    const schema = flexNode.schema;
    const classSchema = (0, schemaCaching_js_1.tryGetSimpleNodeSchema)(schema);
    (0, internal_1.assert)(classSchema !== undefined, "node without schema");
    if (typeof classSchema === "function") {
        const simpleSchema = classSchema;
        return new simpleSchema(flexNode);
    }
    else {
        return classSchema.create(flexNode);
    }
}
exports.getOrCreateNodeProxy = getOrCreateNodeProxy;
/**
 * Records any proxies in the given content tree and does the necessary bookkeeping to ensure they are synchronized with subsequent reads of the tree.
 * @remarks If the content tree contains any proxies, this function must be called just prior to inserting the content into the tree.
 * Specifically, no other content may be inserted into the tree between the invocation of this function and the insertion of `content`.
 * The insertion of `content` must occur or else this function will cause memory leaks.
 * @param content - the tree of content to be inserted, of which any of its object/map/array nodes might be a proxy
 * @param anchors - the {@link AnchorSet} for the tree
 * @returns The content after having all proxies replaced inline with plain javascript objects.
 * See {@link extractFactoryContent} for more details.
 */
function prepareContentForInsert(content, forest) {
    if ((0, index_js_3.isReadonlyArray)(content)) {
        return prepareArrayContentForInsert(content, forest);
    }
    const proxies = {
        rootPath: { parent: undefined, parentField: index_js_1.EmptyKey, parentIndex: 0 },
        proxyPaths: [],
    };
    const extractedContent = extractFactoryContent(content, {
        path: proxies.rootPath,
        onVisitProxy: (p, proxy) => {
            proxies.proxyPaths.push({ path: p, proxy });
        },
    });
    bindProxies([proxies], forest);
    return extractedContent;
}
exports.prepareContentForInsert = prepareContentForInsert;
function prepareArrayContentForInsert(content, forest) {
    const proxies = [];
    const extractedContent = [];
    for (let i = 0; i < content.length; i++) {
        proxies.push({
            rootPath: {
                parent: undefined,
                parentField: index_js_1.EmptyKey,
                parentIndex: 0,
            },
            proxyPaths: [],
        });
        extractedContent.push(extractFactoryContent(content[i], {
            path: proxies[i].rootPath,
            onVisitProxy: (p, proxy) => {
                proxies[i].proxyPaths.push({ path: p, proxy });
            },
        }));
    }
    bindProxies(proxies, forest);
    return extractedContent;
}
function bindProxies(proxies, forest) {
    // Only subscribe to the event if there is at least one proxy tree to hydrate - this is not the case when inserting an empty array [].
    if (proxies.length > 0) {
        // Creating a new array emits one event per element in the array, so listen to the event once for each element
        let i = 0;
        const off = forest.on("afterRootFieldCreated", (fieldKey) => {
            proxies[i].rootPath.parentField = fieldKey;
            for (const { path, proxy } of proxies[i].proxyPaths) {
                (0, proxyBinding_js_1.anchorProxy)(forest.anchors, path, proxy);
            }
            if (++i === proxies.length) {
                off();
            }
        });
    }
}
/**
 * Given a content tree that is to be inserted into the shared tree, replace all subtrees that were created by factories
 * (via {@link SharedTreeObjectFactory.create}) with the content that was passed to those factories.
 * @param content - the content being inserted which may be, and/or may contain, factory-created content
 * @param onVisitProxy - an optional callback that will run for each proxy (i.e. object created by a factory) found in the inserted content
 * @param insertedAtIndex - if the content being inserted is array node content, this must be the index in the array node at which the content is being inserted
 * @returns the result of the content replacement and a {@link ExtractedFactoryContent.hydrateProxies} function which must be invoked if present.
 * @remarks
 * This functions works recursively.
 * Factory-created objects that are nested inside of the content passed to other factory-created objects, and so on, will be in-lined.
 * This function also adds the hidden {@link typeNameSymbol} of each object schema to the output.
 * @example
 * ```ts
 * const x = foo.create({
 *   a: 3, b: bar.create({
 *     c: [baz.create({ d: 5 })]
 *   })
 * });
 * const y = extractFactoryContent(x);
 * y === {
 *   [typeNameSymbol]: "foo", a: 3, b: {
 *     [typeNameSymbol]: "bar", c: [{ [typeNameSymbol]: "baz", d: 5 }]
 *  }
 * }
 * ```
 */
function extractFactoryContent(input, visitProxies) {
    let content;
    const rawFlexNode = (0, proxyBinding_js_1.tryGetFlexNode)(input);
    if (rawFlexNode !== undefined) {
        const factoryContent = (0, rawNode_js_1.extractRawNodeContent)(rawFlexNode);
        if (factoryContent === undefined) {
            // We were passed a proxy, but that proxy doesn't have any raw content.
            throw new Error("Cannot insert a node that is already in the tree");
        }
        visitProxies?.onVisitProxy(visitProxies.path, input);
        content = factoryContent;
    }
    else {
        content = input;
    }
    (0, internal_1.assert)(!isTreeNode(content), 0x844 /* Unhydrated insertion content should have FlexNode */);
    let type;
    let extractedContent;
    if ((0, index_js_3.isReadonlyArray)(content)) {
        type = schemaTypes_js_1.NodeKind.Array;
        extractedContent = extractContentArray(content, visitProxies);
    }
    else if (content instanceof Map) {
        type = schemaTypes_js_1.NodeKind.Map;
        extractedContent = extractContentMap(content, visitProxies);
    }
    else if (typeof content === "object" && content !== null && !(0, index_js_2.isFluidHandle)(content)) {
        type = schemaTypes_js_1.NodeKind.Object;
        extractedContent = extractContentObject(content, visitProxies);
    }
    else {
        extractedContent = content;
        type = schemaTypes_js_1.NodeKind.Leaf;
    }
    if (rawFlexNode !== undefined) {
        const kindFromSchema = (0, schemaCaching_js_1.tryGetSimpleNodeSchema)(rawFlexNode.schema)?.kind ??
            (0, index_js_3.fail)("NodeBase should always have class schema");
        (0, internal_1.assert)(kindFromSchema === type, 0x845 /* kind of data should match kind of schema */);
    }
    return extractedContent;
}
exports.extractFactoryContent = extractFactoryContent;
function extractContentArray(input, visitProxies) {
    const output = [];
    if (index_js_2.typeNameSymbol in input) {
        Object.defineProperty(output, index_js_2.typeNameSymbol, { value: input[index_js_2.typeNameSymbol] });
    }
    for (let i = 0; i < input.length; i++) {
        const childContent = extractFactoryContent(input[i], visitProxies !== undefined
            ? {
                path: {
                    parent: visitProxies.path,
                    parentField: index_js_1.EmptyKey,
                    parentIndex: i,
                },
                onVisitProxy: visitProxies?.onVisitProxy,
            }
            : undefined);
        output.push(childContent);
    }
    return output;
}
function extractContentMap(input, visitProxies) {
    const output = new Map();
    if (index_js_2.typeNameSymbol in input) {
        Object.defineProperty(output, index_js_2.typeNameSymbol, { value: input[index_js_2.typeNameSymbol] });
    }
    for (const [key, value] of input) {
        const childContent = extractFactoryContent(value, visitProxies !== undefined
            ? {
                path: {
                    parent: visitProxies.path,
                    parentField: (0, index_js_3.brand)(key),
                    parentIndex: 0,
                },
                onVisitProxy: visitProxies?.onVisitProxy,
            }
            : undefined);
        output.set(key, childContent);
    }
    return output;
}
function extractContentObject(input, visitProxies) {
    const output = {};
    if (index_js_2.typeNameSymbol in input) {
        Object.defineProperty(output, index_js_2.typeNameSymbol, { value: input[index_js_2.typeNameSymbol] });
    }
    for (const [key, value] of Object.entries(input)) {
        // Treat undefined fields and missing fields the same.
        // Generally tree does not require explicit undefined values at runtime despite some of the schema aware type checking currently requiring it.
        if (value !== undefined) {
            const childContent = extractFactoryContent(value, visitProxies !== undefined
                ? {
                    path: {
                        parent: visitProxies.path,
                        parentField: (0, index_js_3.brand)(key),
                        parentIndex: 0,
                    },
                    onVisitProxy: visitProxies?.onVisitProxy,
                }
                : undefined);
            output[key] = childContent;
        }
    }
    return output;
}
/**
 * Brand `copy` with the type (under {@link typeNameSymbol}) to avoid ambiguity when inferring types from this data.
 */
function markContentType(typeName, copy) {
    Object.defineProperty(copy, index_js_2.typeNameSymbol, { value: typeName });
}
exports.markContentType = markContentType;
//# sourceMappingURL=proxies.js.map