"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.mergeExecutionConfiguration = exports.parsePipelineVariableNames = exports.publishExecutionVariables = exports.getExecutionVariables = exports.setAzureVariable = exports.toSafeAzureVariableName = exports.statusMap = exports.getAzureApiBasicAuth = exports.getAzureApiToken = exports.toBase64 = exports.getAzureApiUrl = exports.getAzureProject = exports.getEaApiAuth = exports.initDevOpsApi = exports.initEaApi = exports.getEaApiUrl = exports.wait = void 0;
const taskLib = __importStar(require("azure-pipelines-task-lib/task"));
const types_1 = require("./types");
const logger_1 = __importDefault(require("./logger"));
const eaApi_1 = __importDefault(require("./eaApi"));
const devOpsTestApi_1 = __importDefault(require("./devOpsTestApi"));
let eaApiUrl;
const wait = (ms) => {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
};
exports.wait = wait;
const getEaApiUrl = () => {
    if (eaApiUrl)
        return eaApiUrl;
    const connectedEaService = taskLib.getInput("EA", true);
    if (!connectedEaService) {
        throw new Error("EA service connection is not configured");
    }
    const eaUrl = taskLib.getEndpointUrl(connectedEaService, true);
    if (!eaUrl) {
        throw new Error("EA service URL is not configured");
    }
    eaApiUrl = eaUrl;
    return eaApiUrl;
};
exports.getEaApiUrl = getEaApiUrl;
const initEaApi = async () => {
    const url = (0, exports.getEaApiUrl)();
    const ea = await (0, eaApi_1.default)(url, (0, exports.getEaApiAuth)());
    logger_1.default.info(`Executing on EA system ${url}`);
    return ea;
};
exports.initEaApi = initEaApi;
const initDevOpsApi = async () => {
    const devOpsApi = await (0, devOpsTestApi_1.default)(taskLib.getVariable("System.TeamFoundationCollectionUri"), (0, exports.getAzureApiToken)(), (0, exports.getAzureProject)());
    logger_1.default.info(`Executing on Azure DevOps system ${(0, exports.getAzureApiUrl)()}`);
    return devOpsApi;
};
exports.initDevOpsApi = initDevOpsApi;
const getEaApiAuth = () => {
    const connectedEaService = taskLib.getInput("EA", true);
    if (!connectedEaService) {
        throw new Error("EA service connection is not configured");
    }
    const enpointAuth = taskLib.getEndpointAuthorizationParameter(connectedEaService, "apitoken", true);
    if (!enpointAuth) {
        throw new Error("EA service API token is not configured");
    }
    return enpointAuth;
};
exports.getEaApiAuth = getEaApiAuth;
const getAzureProject = () => taskLib.getVariable("system.teamProject");
exports.getAzureProject = getAzureProject;
const getAzureApiUrl = () => {
    const teamProject = (0, exports.getAzureProject)();
    const teamFoundationCollectionUri = taskLib.getVariable("System.TeamFoundationCollectionUri");
    return `${teamFoundationCollectionUri}${teamProject}/_apis/`;
};
exports.getAzureApiUrl = getAzureApiUrl;
const toBase64 = (text) => {
    const buff = Buffer.from(text);
    const base64data = buff.toString("base64");
    return base64data;
};
exports.toBase64 = toBase64;
const getAzureApiToken = () => {
    const tfsService = taskLib.getInput("AzureDevops", true);
    if (!tfsService) {
        throw new Error("Azure DevOps service connection is not configured");
    }
    return taskLib.getEndpointAuthorizationParameter(tfsService, "apitoken", true);
};
exports.getAzureApiToken = getAzureApiToken;
const getAzureApiBasicAuth = () => `Basic ${(0, exports.toBase64)(`${(0, exports.getAzureApiToken)()}:`)}`;
exports.getAzureApiBasicAuth = getAzureApiBasicAuth;
exports.statusMap = {
    [types_1.ExecutionStatus.ERROR]: "Failed",
    [types_1.ExecutionStatus.SUCCESS]: "Passed",
    [types_1.ExecutionStatus.WARNING]: "Warning",
};
const toSafeAzureVariableName = (name) => {
    const sanitized = name
        .replace(/[^A-Za-z0-9_.]/g, "_")
        .replace(/^[^A-Za-z_]+/, "")
        .replace(/_+/g, "_");
    return sanitized;
};
exports.toSafeAzureVariableName = toSafeAzureVariableName;
const setAzureVariable = (name, value) => {
    taskLib.setVariable(name, value, false);
};
exports.setAzureVariable = setAzureVariable;
const getExecutionVariables = (executionOutput) => {
    const variables = {};
    executionOutput.forEach((scriptOutput) => {
        if (scriptOutput.usedVariables) {
            scriptOutput.usedVariables.forEach((variable) => {
                if (variable.type !== undefined ||
                    variable.lastValue === undefined ||
                    variable.lastValue === null ||
                    !/^[A-Za-z_][A-Za-z0-9_.]*$/.test(variable.name)) {
                    return;
                }
                variables[variable.name] = variable.lastValue;
            });
        }
    });
    return variables;
};
exports.getExecutionVariables = getExecutionVariables;
const publishExecutionVariables = (executionOutput) => {
    const variables = (0, exports.getExecutionVariables)(executionOutput);
    let publishedCount = 0;
    Object.keys(variables).forEach((rawName) => {
        const name = (0, exports.toSafeAzureVariableName)(rawName);
        const value = String(variables[name]);
        (0, exports.setAzureVariable)(name, value);
        publishedCount += 1;
    });
    if (publishedCount > 0) {
        logger_1.default.info(`Published ${publishedCount} Azure pipeline variables from EA execution`);
    }
};
exports.publishExecutionVariables = publishExecutionVariables;
const parsePipelineVariableNames = () => {
    const raw = taskLib.getInput("pipelineVariables") || "";
    return raw
        .split(/[\n,]/)
        .map((name) => name.trim())
        .filter(Boolean);
};
exports.parsePipelineVariableNames = parsePipelineVariableNames;
const mergeExecutionConfiguration = (testConfig) => {
    const valuesByName = {};
    (testConfig?.values || []).forEach((variable) => {
        if (variable.name) {
            valuesByName[variable.name] = variable.value ?? "";
        }
    });
    const applyPipelineValue = (name) => {
        const pipelineValue = taskLib.getVariable(name) ?? taskLib.getVariable((0, exports.toSafeAzureVariableName)(name));
        if (pipelineValue !== undefined) {
            valuesByName[name] = pipelineValue;
        }
    };
    Object.keys(valuesByName).forEach(applyPipelineValue);
    (0, exports.parsePipelineVariableNames)().forEach(applyPipelineValue);
    const values = Object.keys(valuesByName).map((name) => ({
        name,
        value: valuesByName[name],
    }));
    if (values.length === 0) {
        return testConfig;
    }
    logger_1.default.info(`Merged execution variables: ${JSON.stringify(values)}`);
    return {
        id: testConfig?.id ?? 0,
        name: testConfig?.name ?? "",
        description: testConfig?.description ?? "",
        values,
    };
};
exports.mergeExecutionConfiguration = mergeExecutionConfiguration;
//# sourceMappingURL=helpers.js.map