"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.forestCodecBuilder = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const internal_2 = require("@fluidframework/runtime-utils/internal");
const index_js_1 = require("../../codec/index.js");
const index_js_2 = require("../chunked-forest/index.js");
const formatCommon_js_1 = require("./formatCommon.js");
function makeForestSummarizerCodec(options, version) {
    // Performance: Since multiple places (including multiple versions of this codec) use the field batch codec,
    // we may end up with multiple copies of it, including compiling its format validation multiple times.
    // This is not ideal, but is not too bad as it is a small fixed number of copies and thus should not be too expensive.
    // If this becomes problematic a cache could be added for options to codec instances somewhere.
    const fieldBatchCodec = index_js_2.fieldBatchCodecBuilder.build(options);
    const formatSchema = formatCommon_js_1.FormatCommon;
    return {
        encode: (data, context) => {
            const keys = [];
            const fields = [];
            for (const [key, value] of data) {
                keys.push(key);
                fields.push(value);
            }
            return {
                keys,
                fields: fieldBatchCodec.encode(fields, context),
                version,
            };
        },
        decode: (data, context) => {
            const out = new Map();
            const fields = fieldBatchCodec.decode(data.fields, context);
            (0, internal_1.assert)(data.keys.length === fields.length, 0x891 /* mismatched lengths */);
            for (const [index, field] of fields.entries()) {
                out.set(data.keys[index] ?? (0, internal_1.oob)(), field);
            }
            return out;
        },
        schema: formatSchema,
    };
}
/**
 * {@link ClientVersionDispatchingCodecBuilder} for forest summarizer codecs.
 */
exports.forestCodecBuilder = index_js_1.ClientVersionDispatchingCodecBuilder.build("Forest", [
    {
        minVersionForCollab: internal_2.lowestMinVersionForCollab,
        formatVersion: formatCommon_js_1.ForestFormatVersion.v1,
        codec: (options) => makeForestSummarizerCodec(options, formatCommon_js_1.ForestFormatVersion.v1),
    },
    {
        minVersionForCollab: index_js_1.FluidClientVersion.v2_74,
        formatVersion: formatCommon_js_1.ForestFormatVersion.v2,
        codec: (options) => makeForestSummarizerCodec(options, formatCommon_js_1.ForestFormatVersion.v2),
    },
]);
//# sourceMappingURL=codec.js.map