/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils/internal";
import { withSchemaValidation, } from "../codec.js";
import { Versioned } from "./format.js";
export function makeVersionedCodec(supportedVersions, { jsonValidator: validator }, inner) {
    const codec = {
        encode: (data, context) => {
            const encoded = inner.encode(data, context);
            assert(supportedVersions.has(encoded.version), 0x88b /* version being encoded should be supported */);
            return encoded;
        },
        decode: (data, context) => {
            const versioned = data; // Validated by withSchemaValidation
            assert(supportedVersions.has(versioned.version), 0x88c /* version being decoded is not supported */);
            const decoded = inner.decode(data, context);
            return decoded;
        },
    };
    return supportedVersions.has(undefined)
        ? codec
        : withSchemaValidation(Versioned, codec, validator);
}
export function makeVersionedValidatedCodec(options, supportedVersions, schema, codec) {
    return makeVersionedCodec(supportedVersions, options, withSchemaValidation(schema, codec, options.jsonValidator));
}
/**
 * Creates a codec which dispatches to the appropriate member of a codec family based on the version of
 * data it encounters.
 * Each member of the codec family must write an explicit version number into the data it encodes.
 */
export function makeVersionDispatchingCodec(family, options) {
    const writeCodec = family.resolve(options.writeVersion).json;
    const supportedVersions = new Set(family.getSupportedFormats());
    return makeVersionedCodec(supportedVersions, options, {
        encode(data, context) {
            return writeCodec.encode(data, context);
        },
        decode(data, context) {
            const codec = family.resolve(data.version);
            return codec.json.decode(data, context);
        },
    });
}
//# sourceMappingURL=codec.js.map