"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTreeNodeSchemaInitializedData = exports.getUnhydratedContext = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const index_js_1 = require("../feature-libraries/index.js");
const index_js_2 = require("../util/index.js");
const index_js_3 = require("./core/index.js");
const fieldSchema_js_1 = require("./fieldSchema.js");
const toStoredSchema_js_1 = require("./toStoredSchema.js");
const contextCache = new WeakMap();
/**
 * See note in {@link getUnhydratedContext}.
 */
let getUnhydratedContextIsRunning = false;
/**
 * Utility for creating {@link Context}s for unhydrated nodes.
 * @remarks
 * The resulting context will not allow any unknown optional fields.
 */
function getUnhydratedContext(schema) {
    // Due to caching, calling this reentrantly can cause issues.
    // Due to recursive schema, and generally lots of lazy initialization code depending on this, bugs with this going reentrant are not uncommon.
    // To make debugging such cases much easier, we assert that this is not called reentrantly.
    (0, internal_1.assert)(!getUnhydratedContextIsRunning, 0xca7 /* getUnhydratedContext should not be reentrant */);
    getUnhydratedContextIsRunning = true;
    try {
        return (0, index_js_2.getOrCreate)(contextCache, schema, (s) => {
            const normalized = (0, fieldSchema_js_1.normalizeFieldSchema)(schema);
            const flexContext = new index_js_3.UnhydratedContext(index_js_1.defaultSchemaPolicy, (0, toStoredSchema_js_1.toStoredSchema)(schema, toStoredSchema_js_1.toUnhydratedSchema));
            return new index_js_3.Context(flexContext, index_js_3.Context.schemaMapFromRootSchema(normalized.allowedTypesFull.evaluate()));
        });
    }
    finally {
        getUnhydratedContextIsRunning = false;
    }
}
exports.getUnhydratedContext = getUnhydratedContext;
/**
 * Utility for creating {@link TreeNodeSchemaInitializedData}.
 */
function getTreeNodeSchemaInitializedData(schema, handler) {
    const data = (0, index_js_3.getTreeNodeSchemaPrivateData)(schema);
    return {
        ...handler,
        context: getUnhydratedContext(schema),
        childAllowedTypes: data.childAllowedTypes.map((t) => t.evaluate()),
    };
}
exports.getTreeNodeSchemaInitializedData = getTreeNodeSchemaInitializedData;
//# sourceMappingURL=createContext.js.map