"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.signXmlResponse = exports.signXml = exports.assertRequired = void 0;
const xml_crypto_1 = require("xml-crypto");
const algorithms = require("./algorithms");
function assertRequired(value, error) {
    if (value === undefined || value === null || (typeof value === "string" && value.length === 0)) {
        throw new TypeError(error !== null && error !== void 0 ? error : "value does not exist");
    }
    else {
        return value;
    }
}
exports.assertRequired = assertRequired;
function signXml(samlMessage, xpath, options) {
    const defaultTransforms = [
        "http://www.w3.org/2000/09/xmldsig#enveloped-signature",
        "http://www.w3.org/2001/10/xml-exc-c14n#",
    ];
    if (!samlMessage)
        throw new Error("samlMessage is required");
    if (!xpath)
        throw new Error("xpath is required");
    if (!options) {
        options = {};
    }
    if (!options.privateKey)
        throw new Error("options.privateKey is required");
    const transforms = options.xmlSignatureTransforms || defaultTransforms;
    const sig = new xml_crypto_1.SignedXml();
    if (options.signatureAlgorithm) {
        sig.signatureAlgorithm = algorithms.getSigningAlgorithm(options.signatureAlgorithm);
    }
    sig.addReference(xpath, transforms, algorithms.getDigestAlgorithm(options.digestAlgorithm));
    sig.signingKey = options.privateKey;
    sig.computeSignature(samlMessage, {
        location: { reference: xpath, action: "append" },
    });
    return sig.getSignedXml();
}
exports.signXml = signXml;
function signXmlResponse(samlMessage, options) {
    const responseXpath = '//*[local-name(.)="Response" and namespace-uri(.)="urn:oasis:names:tc:SAML:2.0:protocol"]';
    return signXml(samlMessage, responseXpath, options);
}
exports.signXmlResponse = signXmlResponse;
//# sourceMappingURL=utility.js.map