"use strict";
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports._decryptStream = void 0;
const material_management_node_1 = require("@aws-crypto/material-management-node");
const parse_header_stream_1 = require("./parse_header_stream");
const verify_stream_1 = require("./verify_stream");
const decipher_stream_1 = require("./decipher_stream");
const duplexify_1 = __importDefault(require("duplexify"));
// @ts-ignore
const readable_stream_1 = require("readable-stream");
function _decryptStream(decryptParameters, cmm, { maxBodySize } = {}) {
    /* If the cmm is a Keyring, wrap it with NodeDefaultCMM. */
    cmm =
        cmm instanceof material_management_node_1.KeyringNode
            ? new material_management_node_1.NodeDefaultCryptographicMaterialsManager(cmm)
            : cmm;
    const parseHeaderStream = new parse_header_stream_1.ParseHeaderStream(decryptParameters.signaturePolicy, decryptParameters.clientOptions, cmm);
    const verifyStream = new verify_stream_1.VerifyStream({ maxBodySize });
    const decipherStream = (0, decipher_stream_1.getDecipherStream)();
    const stream = new duplexify_1.default(parseHeaderStream, decipherStream);
    /* pipeline will _either_ stream.destroy or the callback.
     * decipherStream uses destroy to dispose the material.
     * So I tack a pass though stream onto the end.
     */
    (0, readable_stream_1.pipeline)(parseHeaderStream, verifyStream, decipherStream, new readable_stream_1.PassThrough(), (err) => {
        if (err)
            stream.emit('error', err);
    });
    // Forward header events
    parseHeaderStream.once('MessageHeader', (header) => stream.emit('MessageHeader', header));
    return stream;
}
exports._decryptStream = _decryptStream;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVjcnlwdF9zdHJlYW0uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvZGVjcnlwdF9zdHJlYW0udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc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