"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.customizeSchemaTyping = exports.CustomizedTyping = exports.UnsafeUnknownSchema = exports.markSchemaMostDerived = exports.evaluateLazySchema = exports.areFieldSchemaEqual = exports.areImplicitFieldSchemaEqual = exports.normalizeAllowedTypes = exports.normalizeFieldSchema = exports.FieldSchema = exports.createFieldSchema = exports.getDefaultProvider = exports.extractFieldProvider = exports.isConstant = exports.getExplicitStoredKey = exports.getStoredKey = exports.FieldKind = exports.isTreeNodeSchemaClass = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const internal_2 = require("@fluidframework/telemetry-utils/internal");
const index_js_1 = require("../util/index.js");
const index_js_2 = require("./core/index.js");
const flexList_js_1 = require("./flexList.js");
const leafNodeSchema_js_1 = require("./leafNodeSchema.js");
const treeNodeValid_js_1 = require("./treeNodeValid.js");
/**
 * Returns true if the given schema is a {@link TreeNodeSchemaClass}, or otherwise false if it is a {@link TreeNodeSchemaNonClass}.
 * @internal
 */
function isTreeNodeSchemaClass(schema) {
    return schema.constructor !== undefined;
}
exports.isTreeNodeSchemaClass = isTreeNodeSchemaClass;
/**
 * Kind of a field on a node.
 * @remarks
 * More kinds may be added over time, so do not assume this is an exhaustive set.
 * @public
 */
var FieldKind;
(function (FieldKind) {
    /**
     * A field which can be empty or filled.
     * @remarks
     * Allows 0 or one child.
     */
    FieldKind[FieldKind["Optional"] = 0] = "Optional";
    /**
     * A field which must always be filled.
     * @remarks
     * Only allows exactly one child.
     */
    FieldKind[FieldKind["Required"] = 1] = "Required";
    /**
     * A special field used for node identifiers.
     * @remarks
     * Only allows exactly one child.
     */
    FieldKind[FieldKind["Identifier"] = 2] = "Identifier";
})(FieldKind || (exports.FieldKind = FieldKind = {}));
/**
 * Maps from a property key to its corresponding {@link FieldProps.key | stored key} for the provided
 * {@link ImplicitFieldSchema | field schema}.
 *
 * @remarks
 * If an explicit stored key was specified in the schema, it will be used.
 * Otherwise, the stored key is the same as the property key.
 */
function getStoredKey(propertyKey, fieldSchema) {
    return (0, index_js_1.brand)(getExplicitStoredKey(fieldSchema) ?? propertyKey);
}
exports.getStoredKey = getStoredKey;
/**
 * Gets the {@link FieldProps.key | stored key} specified by the schema, if one was explicitly specified.
 * Otherwise, returns undefined.
 */
function getExplicitStoredKey(fieldSchema) {
    return fieldSchema instanceof FieldSchema ? fieldSchema.props?.key : undefined;
}
exports.getExplicitStoredKey = getExplicitStoredKey;
/**
 * Returns true if the given {@link FieldProvider} is a {@link ConstantFieldProvider}
 */
function isConstant(fieldProvider) {
    return fieldProvider.length === 0;
}
exports.isConstant = isConstant;
function extractFieldProvider(input) {
    return input;
}
exports.extractFieldProvider = extractFieldProvider;
function getDefaultProvider(input) {
    return input;
}
exports.getDefaultProvider = getDefaultProvider;
/**
 * All policy for a specific field,
 * including functionality that does not have to be kept consistent across versions or deterministic.
 *
 * This can include policy for how to use this schema for "view" purposes, and well as how to expose editing APIs.
 * Use {@link SchemaFactory} to create the FieldSchema instances, for example {@link schemaStatics.optional}.
 * @privateRemarks
 * Public access to the constructor is removed to prevent creating expressible but unsupported (or not stable) configurations.
 * {@link createFieldSchema} can be used internally to create instances.
 *
 * @typeParam TCustomMetadata - Custom metadata properties to associate with the field.
 * See {@link FieldSchemaMetadata.custom}.
 *
 * @sealed @public
 */
class FieldSchema {
    /**
     * What types of tree nodes are allowed in this field.
     * @remarks Counterpart to {@link FieldSchema.allowedTypes}, with any lazy definitions evaluated.
     */
    get allowedTypeSet() {
        return this.lazyTypes.value;
    }
    /**
     * {@inheritDoc FieldProps.metadata}
     */
    get metadata() {
        return this.props?.metadata;
    }
    constructor(
    /**
     * The {@link https://en.wikipedia.org/wiki/Kind_(type_theory) | kind } of this field.
     * Determines the multiplicity, viewing and editing APIs as well as the merge resolution policy.
     */
    kind, 
    /**
     * What types of tree nodes are allowed in this field.
     */
    allowedTypes, 
    /**
     * Optional properties associated with the field.
     */
    props) {
        this.kind = kind;
        this.allowedTypes = allowedTypes;
        this.props = props;
        this.lazyTypes = new internal_1.Lazy(() => normalizeAllowedTypes(this.allowedTypes));
        // TODO: optional fields should (by default) get a default provider that returns undefined, removing the need to special case them here:
        this.requiresValue =
            this.props?.defaultProvider === undefined && this.kind !== FieldKind.Optional;
    }
}
exports.FieldSchema = FieldSchema;
(() => {
    exports.createFieldSchema = (kind, allowedTypes, props) => new FieldSchema(kind, allowedTypes, props);
})();
/**
 * Normalizes a {@link ImplicitFieldSchema} to a {@link FieldSchema}.
 */
function normalizeFieldSchema(schema) {
    return schema instanceof FieldSchema
        ? schema
        : (0, exports.createFieldSchema)(FieldKind.Required, schema);
}
exports.normalizeFieldSchema = normalizeFieldSchema;
/**
 * Normalizes a {@link ImplicitAllowedTypes} to a set of {@link TreeNodeSchema}s, by eagerly evaluating any
 * lazy schema declarations.
 *
 * @remarks Note: this must only be called after all required schemas have been declared, otherwise evaluation of
 * recursive schemas may fail.
 *
 * @internal
 */
function normalizeAllowedTypes(types) {
    const normalized = new Set();
    if ((0, index_js_1.isReadonlyArray)(types)) {
        // Types array must not be modified after it is normalized since that would result if the user of the normalized data having wrong (out of date) content.
        Object.freeze(types);
        for (const lazyType of types) {
            normalized.add(evaluateLazySchema(lazyType));
        }
    }
    else {
        normalized.add(evaluateLazySchema(types));
    }
    return normalized;
}
exports.normalizeAllowedTypes = normalizeAllowedTypes;
/**
 * Returns true if the given {@link ImplicitFieldSchema} are equivalent, otherwise false.
 * @remarks Two ImplicitFieldSchema are considered equivalent if all of the following are true:
 * 1. They have the same {@link FieldKind | kinds}.
 * 2. They have {@link areFieldPropsEqual | equivalent FieldProps}.
 * 3. They have the same exact set of allowed types. The allowed types must be (respectively) reference equal.
 *
 * For example, comparing an ImplicitFieldSchema that is a {@link TreeNodeSchema} to an ImplicitFieldSchema that is a {@link FieldSchema}
 * will return true if they are the same kind, the FieldSchema has exactly one allowed type (the TreeNodeSchema), and they have equivalent FieldProps.
 */
function areImplicitFieldSchemaEqual(a, b) {
    return areFieldSchemaEqual(normalizeFieldSchema(a), normalizeFieldSchema(b));
}
exports.areImplicitFieldSchemaEqual = areImplicitFieldSchemaEqual;
/**
 * Returns true if the given {@link FieldSchema} are equivalent, otherwise false.
 * @remarks Two FieldSchema are considered equivalent if all of the following are true:
 * 1. They have the same {@link FieldKind | kinds}.
 * 2. They have {@link areFieldPropsEqual | equivalent FieldProps}.
 * 3. They have the same exact set of allowed types. The allowed types must be reference equal.
 */
function areFieldSchemaEqual(a, b) {
    if (a === b) {
        return true;
    }
    if (a.kind !== b.kind) {
        return false;
    }
    if (!areFieldPropsEqual(a.props, b.props)) {
        return false;
    }
    return (0, index_js_1.compareSets)({ a: a.allowedTypeSet, b: b.allowedTypeSet });
}
exports.areFieldSchemaEqual = areFieldSchemaEqual;
/**
 * Returns true if the given {@link FieldProps} are equivalent, otherwise false.
 * @remarks FieldProps are considered equivalent if their keys and default providers are reference equal, and their metadata are {@link areMetadataEqual | equivalent}.
 */
function areFieldPropsEqual(a, b) {
    if (a === b) {
        return true;
    }
    if (a?.key !== b?.key || a?.defaultProvider !== b?.defaultProvider) {
        return false;
    }
    if (!areMetadataEqual(a?.metadata, b?.metadata)) {
        return false;
    }
    return true;
}
/**
 * Returns true if the given {@link FieldSchemaMetadata} are equivalent, otherwise false.
 * @remarks FieldSchemaMetadata are considered equivalent if their custom data and descriptions are (respectively) reference equal.
 */
function areMetadataEqual(a, b) {
    if (a === b) {
        return true;
    }
    return a?.custom === b?.custom && a?.description === b?.description;
}
const cachedLazyItem = new WeakMap();
/**
 * Returns the schema referenced by the {@link LazyItem}.
 * @remarks
 * Caches results to handle {@link LazyItem} which compute their resulting schema.
 * @alpha
 */
function evaluateLazySchema(value) {
    const evaluatedSchema = (0, flexList_js_1.isLazy)(value)
        ? (0, index_js_1.getOrCreate)(cachedLazyItem, value, value)
        : value;
    if (evaluatedSchema === undefined) {
        throw new internal_2.UsageError(`Encountered an undefined schema. This could indicate that some referenced schema has not yet been instantiated.`);
    }
    markSchemaMostDerived(evaluatedSchema);
    return evaluatedSchema;
}
exports.evaluateLazySchema = evaluateLazySchema;
/**
 * Indicates that a schema is the "most derived" version which is allowed to be used, see {@link MostDerivedData}.
 * Calling helps with error messages about invalid schema usage (using more than one type from single schema factor produced type,
 * and thus calling this for one than one subclass).
 * @remarks
 * Helper for invoking {@link TreeNodeValid.markMostDerived} for any {@link TreeNodeSchema} if it needed.
 */
function markSchemaMostDerived(schema, oneTimeInitialize = false) {
    if (schema instanceof leafNodeSchema_js_1.LeafNodeSchema) {
        return;
    }
    if (!(0, index_js_2.inPrototypeChain)(schema, treeNodeValid_js_1.TreeNodeValid)) {
        // Use JSON.stringify to quote and escape identifier string.
        throw new internal_2.UsageError(`Schema for ${JSON.stringify(schema.identifier)} does not extend a SchemaFactory generated class. This is invalid.`);
    }
    const schemaValid = schema;
    if (oneTimeInitialize) {
        schemaValid.oneTimeInitialize();
    }
    else {
        schemaValid.markMostDerived();
    }
}
exports.markSchemaMostDerived = markSchemaMostDerived;
/**
 * {@inheritdoc (UnsafeUnknownSchema:type)}
 * @alpha
 */
exports.UnsafeUnknownSchema = Symbol("UnsafeUnknownSchema");
/**
 * {@inheritdoc (CustomizedTyping:type)}
 * @system @public
 */
exports.CustomizedTyping = Symbol("CustomizedTyping");
/**
 * Customizes the types associated with `TSchema`
 * @remarks
 * By default, the types used when constructing, reading and writing tree nodes are derived from the schema.
 * In some cases, it may be desirable to override these types with carefully selected alternatives.
 * This utility allows for that customization.
 * Note that this customization is only used for typing, and does not affect the runtime behavior at all.
 *
 * This can be used for a wide variety of purposes, including (but not limited to):
 *
 * 1. Implementing better typing for a runtime extensible set of types (e.g. a polymorphic collection).
 * This is commonly needed when implementing containers which don't directly reference their child types, and can be done using {@link Customizer.simplified}.
 * 2. Adding type brands to specific values to increase type safety.
 * This can be done using {@link Customizer.simplified}.
 * 3. Adding some (compile time only) constraints to values, like enum style unions.
 * This can be done using {@link Customizer.simplified}.
 * 4. Making fields readonly (for the current client).
 * This can be done using {@link Customizer.custom} with `{ readWrite: never; }`.
 * 5. Opting into more [compleat and less sound](https://en.wikipedia.org/wiki/Soundness#Relation_to_completeness) typing.
 * {@link Customizer.relaxed} is an example of this.
 *
 * For this customization to be used, the resulting schema must be used as `ImplicitAllowedTypes`.
 * For example applying this to a single type, then using that type in an array of allowed types will have no effect:
 * in such a case the customization must instead be applied to the array of allowed types.
 * @privateRemarks
 * Once this API is more stable/final, the examples in tests such as openPolymorphism.spec.ts and schemaFactory.examples.spec.ts
 * should be copied into examples here, or somehow linked.
 * @alpha
 */
function customizeSchemaTyping(schema) {
    // This function just does type branding, and duplicating the typing here to avoid any would just make it harder to maintain not easier:
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const f = () => schema;
    return { strict: f, relaxed: f, simplified: f, simplifiedUnrestricted: f, custom: f };
}
exports.customizeSchemaTyping = customizeSchemaTyping;
//# sourceMappingURL=schemaTypes.js.map