"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.SchemaFactoryAlpha = void 0;
const index_js_1 = require("../core/index.js");
// These imports prevent a large number of type references in the API reports from showing up as *_2.
/* eslint-disable unused-imports/no-unused-imports, @typescript-eslint/no-unused-vars, import-x/no-duplicates */
const fieldSchema_js_1 = require("../fieldSchema.js");
const index_js_2 = require("../node-kinds/index.js");
const unhydratedFlexTreeFromInsertable_js_1 = require("../unhydratedFlexTreeFromInsertable.js");
const schemaFactory_js_1 = require("./schemaFactory.js");
const schemaFactoryBeta_js_1 = require("./schemaFactoryBeta.js");
const schemaStatics_js_1 = require("./schemaStatics.js");
const treeBeta_js_1 = require("./treeBeta.js");
const withDefault = (fieldSchema, defaultValue) => {
    const typedFieldSchema = fieldSchema;
    // create the default provider function, it is called eagerly during node construction
    const defaultProvider = (0, fieldSchema_js_1.getDefaultProvider)(() => {
        // Resolve the value: if it's a function, call it; otherwise use it directly
        let insertableValue = typeof defaultValue === "function" ? defaultValue() : defaultValue;
        // If the value is an already-constructed TreeNode (e.g., from a generator function that
        // returns the same instance repeatedly), clone it to ensure each use gets a fresh instance.
        // This prevents multi-parenting errors.
        if ((0, index_js_1.isTreeNode)(insertableValue)) {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            insertableValue = treeBeta_js_1.TreeBeta.clone(insertableValue);
        }
        // For optional fields with an undefined default, return an empty array (no value).
        if (insertableValue === undefined) {
            return [];
        }
        // Convert the insertable value to an unhydrated flex tree.
        // For insertable data, this creates a fresh tree structure.
        const allowedTypeSet = (0, index_js_1.normalizeAllowedTypes)(typedFieldSchema.allowedTypes).evaluateSet();
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        return [(0, unhydratedFlexTreeFromInsertable_js_1.unhydratedFlexTreeFromInsertableNode)(insertableValue, allowedTypeSet)];
    });
    // create a new field schema with the default provider
    const propsWithDefault = {
        ...typedFieldSchema.props,
        defaultProvider,
    };
    return (0, fieldSchema_js_1.createFieldSchema)(typedFieldSchema.kind, typedFieldSchema.allowedTypes, propsWithDefault);
};
const stagedOptional = (t, props) => {
    return (0, fieldSchema_js_1.createFieldSchema)(fieldSchema_js_1.FieldKind.Optional, t, {
        defaultProvider: (0, fieldSchema_js_1.getDefaultProvider)(() => []),
        ...props,
        stagedOptionalUpgrade: (0, index_js_1.createSchemaUpgrade)(),
    });
};
const schemaStaticsAlpha = {
    withDefault,
    withDefaultRecursive: withDefault,
    stagedOptional,
    stagedOptionalRecursive: stagedOptional,
};
/**
 * {@link SchemaFactory} with additional alpha APIs.
 *
 * @alpha
 * @privateRemarks
 * When building schema, when `options` is not provided, `TCustomMetadata` is inferred as `unknown`.
 * If desired, this could be made to infer `undefined` instead by adding overloads for everything,
 * but currently it is not worth the maintenance overhead as there is no use case which this is known to be helpful for.
 */
class SchemaFactoryAlpha extends schemaFactoryBeta_js_1.SchemaFactoryBeta {
    constructor() {
        super(...arguments);
        /**
         * {@inheritDoc SchemaStatics.leaves}
         */
        this.leaves = schemaStatics_js_1.schemaStatics.leaves;
        /**
         * {@inheritDoc SchemaStatics.optional}
         */
        this.optional = schemaStatics_js_1.schemaStatics.optional;
        /**
         * {@inheritDoc SchemaStatics.required}
         */
        this.required = schemaStatics_js_1.schemaStatics.required;
        /**
         * {@inheritDoc SchemaStatics.optionalRecursive}
         */
        this.optionalRecursive = schemaStatics_js_1.schemaStatics.optionalRecursive;
        /**
         * {@inheritDoc SchemaStatics.requiredRecursive}
         */
        this.requiredRecursive = schemaStatics_js_1.schemaStatics.requiredRecursive;
        /**
         * {@inheritdoc SchemaStaticsAlpha.withDefault}
         */
        this.withDefault = schemaStaticsAlpha.withDefault;
        /**
         * {@inheritdoc SchemaStaticsAlpha.withDefault}
         */
        this.withDefaultRecursive = schemaStaticsAlpha.withDefaultRecursive;
        /**
         * {@inheritdoc SchemaStaticsAlpha.stagedOptional}
         */
        this.stagedOptional = schemaStaticsAlpha.stagedOptional;
        /**
         * {@inheritdoc SchemaStaticsAlpha.stagedOptionalRecursive}
         */
        this.stagedOptionalRecursive = schemaStaticsAlpha.stagedOptionalRecursive;
    }
    /**
     * Define a {@link TreeNodeSchemaClass} for a {@link TreeObjectNode}.
     *
     * @param name - Unique identifier for this schema within this factory's scope.
     * @param fields - Schema for fields of the object node's schema. Defines what children can be placed under each key.
     * @param options - Additional options for the schema.
     */
    objectAlpha(name, fields, options) {
        return (0, index_js_2.objectSchema)((0, schemaFactory_js_1.scoped)(this, name), fields, true, {
            ...schemaFactory_js_1.defaultSchemaFactoryObjectOptions,
            ...options,
        });
    }
    /**
     * {@inheritdoc SchemaFactory.objectRecursive}
     */
    objectRecursive(name, t, options) {
        return this.objectAlpha(name, t, options);
    }
    /**
     * Alpha version of {@link SchemaFactory.objectRecursive} that supports field defaults via {@link SchemaStaticsAlpha.withDefaultRecursive}.
     * Use with {@link ValidateRecursiveSchema} for improved type safety.
     * @remarks
     * Use this instead of {@link SchemaFactory.objectRecursive} when fields use {@link SchemaStaticsAlpha.withDefaultRecursive}.
     * See {@link ValidateRecursiveSchema} for additional information about using recursive schema.
     */
    objectRecursiveAlpha(name, t, options) {
        return this.objectAlpha(name, t, options);
    }
    /**
     * Define a {@link TreeNodeSchema} for a {@link TreeMapNodeAlpha}.
     *
     * @param name - Unique identifier for this schema within this factory's scope.
     * @param allowedTypes - The types that may appear as values in the map.
     * @param options - Additional options for the schema.
     *
     * @example
     * ```typescript
     * class NamedMap extends factory.map("name", factory.number, {
     * 	metadata: { description: "A map of numbers" }
     * }) {}
     * ```
     */
    mapAlpha(name, allowedTypes, options) {
        return (0, index_js_2.mapSchema)((0, schemaFactory_js_1.scoped)(this, name), allowedTypes, true, true, options);
    }
    /**
     * {@inheritDoc SchemaFactory.objectRecursive}
     */
    // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
    mapRecursive(name, allowedTypes, options) {
        return this.mapAlpha(name, allowedTypes, options);
    }
    /**
     * Define a {@link TreeNodeSchemaClass} for a {@link (TreeArrayNode:interface)}.
     *
     * @param name - Unique identifier for this schema within this factory's scope.
     * @param allowedTypes - The types that may appear in the array.
     * @param options - Additional options for the schema.
     *
     * @example
     * ```typescript
     * class NamedArray extends factory.arrayAlpha("name", factory.number) {}
     * ```
     */
    arrayAlpha(name, allowedTypes, options) {
        return (0, index_js_2.arraySchema)((0, schemaFactory_js_1.scoped)(this, name), allowedTypes, true, true, options ?? {});
    }
    /**
     * {@link SchemaFactory.arrayRecursive} but with support for some alpha features.
     */
    // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
    arrayRecursive(name, allowedTypes, options) {
        return this.arrayAlpha(name, allowedTypes, options);
    }
    /**
     * Define (and add to this library) a {@link TreeNodeSchemaClass} for a {@link (TreeRecordNode:interface)}.
     *
     * @param name - Unique identifier for this schema within this factory's scope.
     * @param allowedTypes - The types that may appear in the record.
     * @param options - Additional options for the schema.
     *
     * @example
     * ```typescript
     * class NamedRecord extends factory.recordAlpha("name", factory.number) {}
     * ```
     */
    recordAlpha(name, allowedTypes, options) {
        return (0, index_js_2.recordSchema)({
            identifier: (0, schemaFactory_js_1.scoped)(this, name),
            info: allowedTypes,
            customizable: true,
            implicitlyConstructable: true,
            nodeOptions: options,
        });
    }
    /**
     * {@link SchemaFactoryBeta.(record:2)} except tweaked to work better for recursive types.
     * Use with {@link ValidateRecursiveSchema} for improved type safety.
     * @remarks
     * This version of `SchemaFactory.record` uses the same workarounds as {@link SchemaFactory.objectRecursive}.
     * See {@link ValidateRecursiveSchema} for additional information about using recursive schema.
     */
    // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
    recordRecursive(name, allowedTypes, options) {
        const RecordSchema = (0, index_js_2.recordSchema)({
            identifier: (0, schemaFactory_js_1.scoped)(this, name),
            info: allowedTypes,
            customizable: true,
            // Setting this to true seems to work ok currently, but not for other node kinds.
            // Supporting this could be fragile and might break other future changes, so it's being kept as false for now.
            implicitlyConstructable: false,
            nodeOptions: options,
        });
        return RecordSchema;
    }
    /**
     * {@inheritDoc SchemaFactoryBeta.scopedFactory}
     */
    scopedFactoryAlpha(name) {
        return new SchemaFactoryAlpha((0, schemaFactory_js_1.scoped)(this, name));
    }
}
exports.SchemaFactoryAlpha = SchemaFactoryAlpha;
/**
 * {@inheritDoc SchemaStatics.leaves}
 */
SchemaFactoryAlpha.leaves = schemaStatics_js_1.schemaStatics.leaves;
/**
 * {@inheritDoc SchemaStatics.optional}
 */
SchemaFactoryAlpha.optional = schemaStatics_js_1.schemaStatics.optional;
/**
 * {@inheritDoc SchemaStatics.required}
 */
SchemaFactoryAlpha.required = schemaStatics_js_1.schemaStatics.required;
/**
 * {@inheritDoc SchemaStatics.optionalRecursive}
 */
SchemaFactoryAlpha.optionalRecursive = schemaStatics_js_1.schemaStatics.optionalRecursive;
/**
 * {@inheritDoc SchemaStatics.requiredRecursive}
 */
SchemaFactoryAlpha.requiredRecursive = schemaStatics_js_1.schemaStatics.requiredRecursive;
/**
 * Like {@link SchemaFactory.identifier} but static and a factory function that can be provided {@link FieldProps}.
 */
SchemaFactoryAlpha.identifier = schemaStatics_js_1.schemaStatics.identifier;
/**
 * {@inheritdoc SchemaStaticsAlpha.withDefault}
 */
SchemaFactoryAlpha.withDefault = schemaStaticsAlpha.withDefault;
/**
 * {@inheritdoc SchemaStaticsAlpha.withDefault}
 */
SchemaFactoryAlpha.withDefaultRecursive = schemaStaticsAlpha.withDefaultRecursive;
/**
 * {@inheritdoc SchemaStaticsAlpha.stagedOptional}
 */
SchemaFactoryAlpha.stagedOptional = schemaStaticsAlpha.stagedOptional;
/**
 * {@inheritdoc SchemaStaticsAlpha.stagedOptionalRecursive}
 */
SchemaFactoryAlpha.stagedOptionalRecursive = schemaStaticsAlpha.stagedOptionalRecursive;
//# sourceMappingURL=schemaFactoryAlpha.js.map