"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 });
const git = __importStar(require("../git"));
const fs_1 = __importDefault(require("fs"));
const constants_1 = require("./constants");
const constantsNode_1 = require("./constantsNode");
const getBundledAxeCoreVersions_1 = require("./getBundledAxeCoreVersions");
const validateAxeRunOptions_1 = require("./validateAxeRunOptions");
const createDebugger_1 = __importDefault(require("../createDebugger"));
const initializeSession_1 = __importDefault(require("./initializeSession"));
const validateAxeRunContext_1 = require("./validateAxeRunContext");
const isValidExcludePattern_1 = __importDefault(require("./isValidExcludePattern"));
const writeExtensionManifest_1 = __importDefault(require("./writeExtensionManifest"));
const isCI_1 = require("./isCI");
const debugLogger = (0, createDebugger_1.default)('config:writeVariables');
const { version } = require('../../package.json');
const allowedAccessibilityStandards = [
    'All',
    'WCAG 2.2 AAA',
    'WCAG 2.2 AA',
    'WCAG 2.2 A',
    'WCAG 2.1 AAA',
    'WCAG 2.1 AA',
    'WCAG 2.1 A',
    'WCAG 2.0 AAA',
    'WCAG 2.0 AA',
    'WCAG 2.0 A',
    'Trusted Tester v5',
    'EN-301-549',
    'RGAAv4'
];
const DEFAULT_TIMEOUT = {
    start: 2000,
    stop: 5000,
    analyze: 5000,
    flush: 5000
};
function writeVariables({ apiKey, autoAnalyze, configurationOverrides, cypress, isPlaywrightTest, isWdioTestrunner, serverURL, sessionId, runContext, runOptions, excludeUrlPatterns, buildID, timeout = {}, takeScreenshots, screenshotDir, experimentalAdvancedRules, projectId, git: gitConfig }) {
    const screenshotsEnabled = !!takeScreenshots;
    debugLogger('Received configuration:', {
        apiKey: '<redacted>',
        ...(autoAnalyze !== undefined && { autoAnalyze }),
        ...(serverURL !== undefined && { serverURL }),
        ...(sessionId !== undefined && { sessionId }),
        ...(runContext !== undefined && { runContext }),
        ...(runOptions !== undefined && { runOptions }),
        ...(configurationOverrides !== undefined && { configurationOverrides }),
        ...(excludeUrlPatterns !== undefined && { excludeUrlPatterns }),
        ...(buildID !== undefined && { buildID }),
        ...(projectId !== undefined && { projectId }),
        ...(gitConfig !== undefined && { git: gitConfig }),
        ...(takeScreenshots !== undefined && { takeScreenshots }),
        ...(screenshotDir !== undefined && { screenshotDir })
    });
    if (configurationOverrides && runOptions?.runOnly) {
        throw new Error('You cannot use `configurationOverrides` and `runOptions.runOnly` together. These configuration options are mutually exclusive.');
    }
    if (!serverURL) {
        serverURL = constants_1.DEFAULT_SERVER_URL;
    }
    let urlString;
    try {
        urlString = new URL(serverURL).toString();
    }
    catch (err) {
        throw new Error(`Error when converting serverURL to URL. Ensure it is formatted properly: ${err}`);
    }
    if (typeof runContext !== 'undefined') {
        (0, validateAxeRunContext_1.validateAxeRunContext)(runContext);
        debugLogger('Validated runContext:', runContext);
    }
    if (typeof runOptions !== 'undefined') {
        (0, validateAxeRunOptions_1.validateAxeRunOptions)(runOptions);
        debugLogger('Validated runOptions:', runOptions);
    }
    if (configurationOverrides) {
        debugLogger('configurationOverrides:', configurationOverrides);
        const hasInvalidAccessibilityStandard = configurationOverrides.accessibilityStandard &&
            !allowedAccessibilityStandards.includes(configurationOverrides.accessibilityStandard);
        if (hasInvalidAccessibilityStandard) {
            throw new Error(`Invalid accessibility standard: ${configurationOverrides.accessibilityStandard}. Allowed options: ${allowedAccessibilityStandards.join(', ')}`);
        }
    }
    const gitData = {};
    if (typeof gitConfig === 'object' && gitConfig !== null) {
        debugLogger('Using user-provided git config with keys:', Object.keys(gitConfig));
        gitData.git_branch = gitConfig.branch ?? null;
        gitData.git_tag = gitConfig.tag ?? null;
        gitData.git_default_branch = gitConfig.defaultBranch ?? null;
        gitData.git_url = gitConfig.url ?? null;
        gitData.git_is_dirty = gitConfig.isDirty ?? false;
        gitData.git_commit_sha = gitConfig.commitSha ?? null;
        gitData.git_commit_author = gitConfig.commitAuthor ?? null;
        gitData.git_commit_email = gitConfig.commitEmail ?? null;
        gitData.git_commit_message = gitConfig.commitMessage ?? null;
    }
    else if (gitConfig !== false) {
        const isGitRepo = git.isRepository();
        if (isGitRepo) {
            debugLogger('Is this a git project?', { isGitRepo });
            gitData.git_branch = git.getBranchName();
            gitData.git_tag = git.getTag();
            gitData.git_default_branch = git.getDefaultBranchName();
            gitData.git_url = git.getRemoteURL();
            gitData.git_is_dirty = git.isDirty();
            const info = git.getCommitInfo();
            gitData.git_commit_sha = info?.hash;
            gitData.git_commit_author = info?.author;
            gitData.git_commit_email = info?.email;
            gitData.git_commit_message = info?.message;
        }
    }
    if (!buildID && (isPlaywrightTest || isWdioTestrunner)) {
        if (!sessionId && fs_1.default.existsSync(constantsNode_1.PATH_TO_SESSION_FILE)) {
            debugLogger('Reading session ID from file');
            try {
                const data = JSON.parse(fs_1.default.readFileSync(constantsNode_1.PATH_TO_SESSION_FILE, 'utf8'));
                sessionId = data.id;
            }
            catch (error) {
                throw new Error(`Unable to read session configuration: ${error}`);
            }
        }
    }
    if (!projectId) {
        console.warn('Warning: `projectId` within axe configuration will become a mandatory field in a future release. Please supply your `projectId` found on your projects page');
    }
    debugLogger('Initializing axe Watcher session');
    const projectIdValue = projectId || null;
    const bundledAxeCoreVersions = (0, getBundledAxeCoreVersions_1.getBundledAxeCoreVersions)();
    const { axe_core_settings, session_id } = (0, initializeSession_1.default)({
        apiKey,
        projectId: projectIdValue,
        serverURL: urlString,
        watcherVersion: version,
        sessionID: sessionId || null,
        buildID: buildID || null,
        gitCommitSha: gitData.git_commit_sha || null,
        gitUrl: gitData.git_url || null,
        gitBranch: gitData.git_branch || null,
        gitCommitAuthor: gitData.git_commit_author || null,
        gitIsDirty: gitData.git_is_dirty || false,
        gitDefaultBranch: gitData.git_default_branch || null,
        gitCommitMessage: gitData.git_commit_message || null,
        gitTag: gitData.git_tag || null,
        gitCommitEmail: gitData.git_commit_email || null,
        configOverrides: configurationOverrides || null,
        runOptions: runOptions || null,
        isCanonicalSource: (0, isCI_1.isCI)(),
        bundledAxeCoreVersions
    });
    if (typeof autoAnalyze === 'undefined') {
        autoAnalyze = true;
    }
    if (excludeUrlPatterns?.length) {
        (0, isValidExcludePattern_1.default)(excludeUrlPatterns);
    }
    const variables = {
        api_key: apiKey,
        project_id: projectIdValue,
        server_url: urlString,
        session_id: session_id || sessionId,
        take_screenshots: screenshotsEnabled,
        screenshot_dir: screenshotsEnabled ? screenshotDir : undefined,
        auto_analyze: !!autoAnalyze,
        cypress: !!cypress,
        experimental_advanced_rules: !!experimentalAdvancedRules,
        run_context: runContext || null,
        run_options: runOptions || null,
        git_data: gitData,
        exclude_url_patterns: excludeUrlPatterns || null,
        axe_core_settings: axe_core_settings || null,
        timeout: {
            ...DEFAULT_TIMEOUT,
            ...timeout
        }
    };
    fs_1.default.writeFileSync(constantsNode_1.PATH_TO_EXTENSION_VARIABLES, JSON.stringify(variables));
    if (axe_core_settings?.axe_core_version) {
        (0, writeExtensionManifest_1.default)({
            js: [
                `axe-versions/axe-core@${axe_core_settings?.axe_core_version}/axe.min.js`,
                'content.js'
            ]
        });
    }
}
exports.default = writeVariables;
//# sourceMappingURL=writeVariables.js.map