"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AssumeRoleCredentialsProvider = void 0;
const client_sts_1 = require("@aws-sdk/client-sts");
class AssumeRoleCredentialsProvider {
    constructor(options) {
        this.options = Object.assign(Object.assign({}, options), { region: options.region || process.env.AWS_REGION, expirationMarginSec: options.expirationMarginSec || 5, roleSessionName: options.roleSessionName || "axios" });
        this.sts = new client_sts_1.STSClient({ region: this.options.region });
    }
    getCredentials() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.credentials || this.areCredentialsExpired()) {
                const stsCredentials = yield this.assumeRole();
                this.credentials = {
                    accessKeyId: stsCredentials.AccessKeyId || "",
                    secretAccessKey: stsCredentials.SecretAccessKey || "",
                    sessionToken: stsCredentials.SessionToken,
                };
                this.expiration = stsCredentials.Expiration;
            }
            return this.credentials;
        });
    }
    areCredentialsExpired() {
        return (this.expiration !== undefined &&
            new Date().getTime() + this.options.expirationMarginSec * 1000 >=
                this.expiration.getTime());
    }
    assumeRole() {
        return __awaiter(this, void 0, void 0, function* () {
            const res = yield this.sts.send(new client_sts_1.AssumeRoleCommand({
                RoleArn: this.options.roleArn,
                RoleSessionName: this.options.roleSessionName,
            }));
            if (!res.Credentials) {
                throw new Error("Failed to get credentials from the assumed role");
            }
            return res.Credentials;
        });
    }
}
exports.AssumeRoleCredentialsProvider = AssumeRoleCredentialsProvider;
