"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPossibleTypes = exports.fieldDataToMapTrees = exports.nodeDataToMapTree = exports.cursorFromFieldData = exports.cursorFromNodeData = void 0;
const core_utils_1 = require("@fluidframework/core-utils");
const telemetry_utils_1 = require("@fluidframework/telemetry-utils");
const index_js_1 = require("../core/index.js");
// Drilling into `domains` to reduce the magnitude of cycles introduced here
// eslint-disable-next-line import/no-internal-modules
const leafDomain_js_1 = require("../domains/leafDomain.js");
const index_js_2 = require("../feature-libraries/index.js");
const index_js_3 = require("../util/index.js");
/**
 * Module notes:
 *
 * The flow of the below code is in terms of the structure of the input data. We then verify that the associated
 * schema is appropriate for that kind of data. This is fine while we have a 1:1 mapping of kind of input data to
 * the kind of schema we expect for it (e.g. an input that is an array always need to be associated with a sequence in
 * the schema). If/when we begin accepting kinds of input data that are ambiguous (e.g. accepting an input that is an
 * array of key/value tuples to instantiate a map) we may need to rethink the structure here to be based more on the
 * schema than on the input data.
 */
/**
 * Transforms an input {@link TypedNode} tree to a {@link MapTree}, and wraps the tree in a {@link CursorWithNode}.
 * @param data - The input tree to be converted.
 * @param globalSchema - Schema for the whole tree for interperting `Any`.
 * @param typeSet - The set of types allowed by the parent context. Used to validate the input tree.
 *
 * @returns A cursor (in nodes mode) for the mapped tree if the input data was defined. Otherwise, returns `undefined`.
 */
function cursorFromNodeData(data, globalSchema, typeSet) {
    if (data === undefined) {
        return undefined;
    }
    const mappedContent = nodeDataToMapTree(data, globalSchema, typeSet);
    return (0, index_js_2.cursorForMapTreeNode)(mappedContent);
}
exports.cursorFromNodeData = cursorFromNodeData;
/**
 * Transforms an input {@link TreeField} tree to an array of {@link MapTree}s, and wraps the tree in a {@link CursorWithNode}.
 * @param data - The input tree to be converted.
 * @param globalSchema - Schema for the whole tree for interperting `Any`.
 */
function cursorFromFieldData(data, globalSchema, fieldSchema) {
    const mappedContent = fieldDataToMapTrees(data, globalSchema, fieldSchema);
    return (0, index_js_2.cursorForMapTreeField)(mappedContent);
}
exports.cursorFromFieldData = cursorFromFieldData;
/**
 * Transforms an input {@link TypedNode} tree to a {@link MapTree}.
 * @param data - The input tree to be converted.
 * If the data is an unsupported value (e.g. NaN), a fallback value will be used when supported,
 * otherwise an error will be thrown.
 *
 * Fallbacks:
 *
 * * `NaN` =\> `null`
 *
 * * `+/-∞` =\> `null`
 *
 * * `-0` =\> `+0`
 *
 * @param globalSchema - Schema for the whole tree for interperting `Any`.
 * @param typeSet - The set of types allowed by the parent context. Used to validate the input tree.
 */
function nodeDataToMapTree(data, globalSchema, typeSet) {
    (0, core_utils_1.assert)(data !== undefined, 0x846 /* Cannot map undefined tree. */);
    if (data === null) {
        return valueToMapTree(data, globalSchema, typeSet);
    }
    switch (typeof data) {
        case "number":
        case "string":
        case "boolean":
            return valueToMapTree(data, globalSchema, typeSet);
        default: {
            if ((0, index_js_2.isFluidHandle)(data)) {
                return valueToMapTree(data, globalSchema, typeSet);
            }
            else if (Array.isArray(data)) {
                return arrayToMapTree(data, globalSchema, typeSet);
            }
            else if (data instanceof Map) {
                return mapToMapTree(data, globalSchema, typeSet);
            }
            else {
                // Assume record-like object
                return recordToMapTree(data, globalSchema, typeSet);
            }
        }
    }
}
exports.nodeDataToMapTree = nodeDataToMapTree;
/**
 * Transforms an input {@link TreeField} tree to an array of {@link MapTree}s.
 * @param data - The input tree to be converted.
 * If the input is a sequence containing 1 or more `undefined` values, those values will be mapped as `null` if supported.
 * Othewise, an error will be thrown.
 * @param globalSchema - Schema for the whole tree. Used to select the valid types when encountering `any`.
 */
function fieldDataToMapTrees(data, globalSchema, fieldSchema) {
    const multiplicity = fieldSchema.kind.multiplicity;
    if (data === undefined) {
        (0, core_utils_1.assert)(multiplicity === index_js_2.Multiplicity.Forbidden || multiplicity === index_js_2.Multiplicity.Optional, 0x847 /* `undefined` provided for a field that does not support `undefined` */);
        return [];
    }
    const typeSet = fieldSchema.allowedTypeSet;
    if (multiplicity === index_js_2.Multiplicity.Sequence) {
        (0, core_utils_1.assert)(Array.isArray(data), 0x848 /* Expected an array as sequence input. */);
        const children = Array.from(data, (child) => {
            // We do not support undefined sequence entries.
            // If we encounter an undefined entry, use null instead if supported by the schema, otherwise throw.
            let childWithFallback = child;
            if (child === undefined) {
                if (typeSet === index_js_2.Any || typeSet.has(leafDomain_js_1.leaf.null)) {
                    childWithFallback = null;
                }
                else {
                    throw new TypeError(`Received unsupported array entry value: ${child}.`);
                }
            }
            return nodeDataToMapTree(childWithFallback, globalSchema, typeSet);
        });
        return children;
    }
    (0, core_utils_1.assert)(multiplicity === index_js_2.Multiplicity.Single || multiplicity === index_js_2.Multiplicity.Optional, 0x849 /* A single value was provided for an unsupported field */);
    return [nodeDataToMapTree(data, globalSchema, typeSet)];
}
exports.fieldDataToMapTrees = fieldDataToMapTrees;
function valueToMapTree(
// eslint-disable-next-line @rushstack/no-new-null
value, globalSchema, typeSet) {
    const mappedValue = mapValueWithFallbacks(value, typeSet);
    const schema = getType(mappedValue, globalSchema, typeSet);
    (0, core_utils_1.assert)(schema instanceof index_js_2.LeafNodeSchema && (0, index_js_2.allowsValue)(schema.leafValue, mappedValue), 0x84a /* Unsupported schema for provided primitive. */);
    return {
        value: mappedValue,
        type: schema.name,
        fields: new Map(),
    };
}
/**
 * Checks an incoming value to ensure it is compatible with our serialization format.
 * For unsupported values with a schema-compatible replacement, return the replacement value.
 * For unsupported values without a schema-compatible replacement, throw.
 * For supported values, return the input.
 */
function mapValueWithFallbacks(
// eslint-disable-next-line @rushstack/no-new-null
value, typeSet) {
    switch (typeof value) {
        case "number": {
            if (Object.is(value, -0)) {
                // Our serialized data format does not support -0.
                // Map such input to +0.
                return 0;
            }
            else if (Number.isNaN(value) || !Number.isFinite(value)) {
                // Our serialized data format does not support NaN nor +/-∞.
                // If the schema supports `null`, fall back to that. Otherwise, throw.
                // This is intended to match JSON's behavior for such values.
                if (typeSet === index_js_2.Any || typeSet.has(leafDomain_js_1.leaf.null)) {
                    return null;
                }
                else {
                    throw new TypeError(`Received unsupported numeric value: ${value}.`);
                }
            }
            else {
                return value;
            }
        }
        default:
            return value;
    }
}
function arrayToMapTree(data, globalSchema, typeSet) {
    const schema = getType(data, globalSchema, typeSet);
    (0, core_utils_1.assert)(schema instanceof index_js_2.FlexFieldNodeSchema, 0x84b /* Array data reported comparable with the schema without a primary field. */);
    const mappedChildren = fieldDataToMapTrees(data, globalSchema, schema.info);
    const fieldsEntries = mappedChildren.length === 0 ? [] : [[index_js_1.EmptyKey, mappedChildren]];
    // Array node children are represented as a single field entry denoted with `EmptyKey`
    const fields = new Map(fieldsEntries);
    return {
        type: schema.name,
        fields,
    };
}
function mapToMapTree(data, globalSchema, typeSet) {
    const schema = getType(data, globalSchema, typeSet);
    const fields = new Map();
    for (const [key, value] of data) {
        (0, core_utils_1.assert)(!fields.has((0, index_js_3.brand)(key)), 0x84c /* Keys should not be duplicated */);
        // Omit undefined record entries - an entry with an undefined key is equivalent to no entry
        if (value !== undefined) {
            const childSchema = schema.getFieldSchema((0, index_js_3.brand)(key));
            const mappedField = fieldDataToMapTrees(value, globalSchema, childSchema);
            fields.set((0, index_js_3.brand)(key), mappedField);
        }
    }
    return {
        type: schema.name,
        fields,
    };
}
function recordToMapTree(data, globalSchema, typeSet) {
    const schema = getType(data, globalSchema, typeSet);
    const fields = new Map();
    // Filter keys to only those that are strings - our trees do not support symbol or numeric property keys
    const keys = Reflect.ownKeys(data).filter((key) => typeof key === "string");
    for (const key of keys) {
        (0, core_utils_1.assert)(!fields.has(key), 0x84d /* Keys should not be duplicated */);
        const value = data[key];
        // Omit undefined record entries - an entry with an undefined key is equivalent to no entry
        if (value !== undefined) {
            const childSchema = schema.getFieldSchema(key);
            const mappedChildTree = fieldDataToMapTrees(value, globalSchema, childSchema);
            fields.set((0, index_js_3.brand)(key), mappedChildTree);
        }
    }
    return {
        type: schema.name,
        fields,
    };
}
function getType(data, globalSchema, typeSet) {
    const possibleTypes = getPossibleTypes(globalSchema, typeSet, data);
    (0, core_utils_1.assert)(possibleTypes.length !== 0, 0x84e /* data is incompatible with all types allowed by the schema */);
    checkInput(possibleTypes.length === 1, () => `The provided data is compatible with more than one type allowed by the schema.
The set of possible types is ${JSON.stringify([...possibleTypes.map((n) => n.name)], undefined)}.
Explicitly construct an unhydrated node of the desired type to disambiguate.
For class-based schema, this can be done by replacing an expression like "{foo: 1}" with "new MySchema({foo: 1})".`);
    return possibleTypes[0];
}
/**
 * An invalid tree has been provided, presumably by the user of this package.
 * Throw and an error that properly preserves the message (unlike asserts which will get hard to read short codes intended for package internal logic errors).
 */
function invalidInput(message) {
    throw new telemetry_utils_1.UsageError(message);
}
function checkInput(condition, message) {
    if (!condition) {
        invalidInput(typeof message === "string" ? message : message());
    }
}
/**
 * @returns all types for which the data is schema-compatible.
 */
function getPossibleTypes(globalSchema, typeSet, data) {
    // All types allowed by schema
    const allowedTypes = (0, index_js_2.getAllowedTypes)(globalSchema, typeSet);
    const possibleTypes = [];
    for (const allowed of allowedTypes) {
        if (shallowCompatibilityTest(allowed, data)) {
            possibleTypes.push(allowed);
        }
    }
    return possibleTypes;
}
exports.getPossibleTypes = getPossibleTypes;
/**
 * Checks if data might be schema-compatible.
 *
 * @returns false if `data` is incompatible with `type` based on a cheap/shallow check.
 *
 * Note that this may return true for cases where data is incompatible, but it must not return false in cases where the data is compatible.
 */
function shallowCompatibilityTest(schema, data) {
    (0, core_utils_1.assert)(data !== undefined, 0x889 /* undefined cannot be used as contextually typed data. Use ContextuallyTypedFieldData. */);
    if ((0, index_js_2.isTreeValue)(data)) {
        return schema instanceof index_js_2.LeafNodeSchema && (0, index_js_2.allowsValue)(schema.leafValue, data);
    }
    if (schema instanceof index_js_2.LeafNodeSchema) {
        return false;
    }
    if (index_js_2.typeNameSymbol in data) {
        return data[index_js_2.typeNameSymbol] === schema.name;
    }
    if ((0, index_js_3.isReadonlyArray)(data)) {
        if (schema instanceof index_js_2.FlexFieldNodeSchema) {
            const field = schema.getFieldSchema();
            return field.kind.multiplicity === index_js_2.Multiplicity.Sequence;
        }
        else {
            return false;
        }
    }
    if (data instanceof Map) {
        return schema instanceof index_js_2.FlexMapNodeSchema;
    }
    // For now, consider all not explicitly typed objects shallow compatible.
    // This will require explicit differentiation in polymorphic cases rather than automatic structural differentiation.
    return true;
}
//# sourceMappingURL=toMapTree.js.map