#!/usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createProgram = createProgram;
exports.run = run;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const runtime_contract_1 = require("../lib/runtime/runtime-contract");
const runtime_contract_2 = require("../lib/runtime/runtime-contract");
const errors_1 = require("../lib/errors");
const output_1 = require("../lib/output");
const pagination_1 = require("../lib/output/pagination");
const budget_1 = require("../lib/output/budget");
const workspace_compatibility_1 = require("../lib/workspace-compatibility");
const runtime_state_1 = require("../lib/version-manager/runtime-state");
const commands_1 = require("./commands");
const output_lifecycle_1 = require("./commands/release/output-lifecycle");
const node_child_process_1 = require("node:child_process");
const automation_protocol_1 = require("../lib/automation-protocol");
const ROOT_HELP_INIT_WORKSPACE_LOCATION = [
    "",
    "Agent Orientation:",
    "  Use this guardrail before automation agents plan, edit, validate, summarize, or reconcile work:",
    "    day-shift agent",
    "",
    "  Automation agents should prefer the machine-readable command envelope:",
    "    day-shift agent --format json",
    "",
    "Initialize Workspace Location:",
    "  By default, Day Shift initializes workspace state at repository root:",
    "    day-shift init",
    "",
    "  Use --directory to initialize inside a specific subdirectory (target must remain inside repository root):",
    "    day-shift init --directory <path>",
    "",
    "  When --directory is provided, Day Shift creates .day-shift/ in the target directory.",
    ""
].join("\n");
async function createProgram() {
    const { Command } = await import("commander");
    const program = new Command();
    const capturedOutput = {
        stdout: "",
        stderr: ""
    };
    const explicitRoot = process.env.DAY_SHIFT_REPOSITORY_ROOT;
    const repositoryDetection = (0, runtime_contract_2.detectRepositoryRoot)({
        explicitRoot: explicitRoot && explicitRoot.trim().length > 0 ? explicitRoot : undefined
    });
    const repositoryContext = (0, runtime_contract_2.createRepositoryContext)(repositoryDetection, false);
    program
        .name(runtime_contract_1.CLI_NAME)
        .description(runtime_contract_1.CLI_DESCRIPTION)
        .version(runtime_contract_1.CLI_VERSION)
        .option("--format <format>", `Set output format for supported command output: ${output_1.OUTPUT_FORMATS.join(" or ")}.`, output_1.DEFAULT_OUTPUT_FORMAT)
        .option("--protocol-version <version>", "Select automation protocol version 1 or 2.")
        .option("--detail <detail>", "Set JSON detail: compact, summary, or full.")
        .option("--finding-code <code>", "Retain a stable non-blocking finding code. Repeat to include more codes.")
        .option("--severity <severity>", "Retain a non-blocking finding severity. Repeat to include more severities.")
        .option("--fields <fields>", "Select comma-separated top-level JSON data fields.")
        .option("--limit <lane=count>", "Limit a top-level JSON array lane. Repeat for independent lanes.")
        .option("--page-lane <lane>", "Page one top-level JSON array lane.")
        .option("--page-size <count>", "Set the positive number of entries in a JSON page.")
        .option("--page-cursor <cursor>", "Resume a JSON page from an opaque continuation cursor.")
        .option("--output-budget <bytes>", "Bound approved read-only JSON output to a safe byte count.")
        .option("--json-spacing <spacing>", "Set JSON serialization spacing: compact or pretty.")
        .configureOutput({
        writeOut: (text) => {
            capturedOutput.stdout += text;
        },
        writeErr: (text) => {
            capturedOutput.stderr += text;
        }
    })
        .showHelpAfterError()
        .showSuggestionAfterError()
        .exitOverride();
    program.addHelpText("after", ROOT_HELP_INIT_WORKSPACE_LOCATION);
    program.capturedOutput = capturedOutput;
    program.configRepositoryContext = repositoryContext;
    await (0, commands_1.registerCommands)(program);
    return program;
}
async function run(argv = process.argv) {
    const protocolInput = normalizeProtocolVersionInput(argv);
    const normalizedArgv = normalizeVersionOptionAliases(protocolInput.argv);
    const format = (0, output_1.detectRequestedOutputFormat)(normalizedArgv);
    const invalidGlobalFormat = (0, output_1.detectInvalidGlobalOutputFormat)(normalizedArgv);
    if (protocolInput.requested !== undefined && protocolInput.version === null) {
        (0, automation_protocol_1.selectAutomationProtocolVersion)(automation_protocol_1.AUTOMATION_PROTOCOL_VERSION);
        const runtimeError = (0, errors_1.createUsageError)(`Unsupported automation protocol version '${String(protocolInput.requested)}'.`, [
            "Supported protocol versions: 1, 2",
            "Pin compatibility output with --protocol-version 1.",
            "No command work was performed."
        ]);
        (0, output_1.emitError)({ command: runtime_contract_1.CLI_NAME, format, code: runtimeError.code, message: runtimeError.message, ...(0, errors_1.getRuntimeErrorEnvelopeFields)(runtimeError), details: runtimeError.details, findings: runtimeError.findings });
        return runtimeError.exitCode;
    }
    (0, automation_protocol_1.selectAutomationProtocolVersion)(protocolInput.version ?? automation_protocol_1.AUTOMATION_PROTOCOL_VERSION);
    const shimDispatchExitCode = dispatchManagedCliFromShimIfNeeded(normalizedArgv, format);
    if (shimDispatchExitCode !== null) {
        return shimDispatchExitCode;
    }
    if (invalidGlobalFormat !== null) {
        const runtimeError = (0, errors_1.createUnsupportedOutputFormatError)({
            received: invalidGlobalFormat,
            commandBoundary: `${runtime_contract_1.CLI_NAME} global --format option before command execution`
        });
        (0, output_1.emitError)({
            command: runtime_contract_1.CLI_NAME,
            format: output_1.DEFAULT_OUTPUT_FORMAT,
            code: runtimeError.code,
            message: runtimeError.message,
            ...(0, errors_1.getRuntimeErrorEnvelopeFields)(runtimeError),
            details: runtimeError.details,
            findings: runtimeError.findings
        });
        return runtimeError.exitCode;
    }
    try {
        const outputOptions = (0, output_1.detectOutputProjectionOptions)(normalizedArgv);
        if (outputOptions.pageLane !== undefined && !isPaginationReadCommand(normalizedArgv)) {
            throw new TypeError("Pagination is supported only on approved read-only discovery, inventory, validation, health, and context commands.");
        }
        if (outputOptions.outputBudget !== undefined
            && !(0, budget_1.isApprovedBoundedReadCommand)(detectCommandIdentity(normalizedArgv))) {
            throw new TypeError("Output budgets are supported only on approved read-only discovery, inventory, validation, health, and context commands.");
        }
    }
    catch (error) {
        const runtimeError = (0, errors_1.createUsageError)(error instanceof Error ? error.message : "Invalid output control.", [
            "Supported detail values: compact, summary, full",
            "Supported severities: informational, warning, error",
            "Limits use: --limit <lane>=<non-negative integer>",
            "No command work was performed."
        ]);
        (0, output_1.emitError)({
            command: runtime_contract_1.CLI_NAME,
            format,
            code: runtimeError.code,
            message: runtimeError.message,
            ...(0, errors_1.getRuntimeErrorEnvelopeFields)(runtimeError),
            details: runtimeError.details,
            findings: runtimeError.findings
        });
        return runtimeError.exitCode;
    }
    const compatibilityError = checkInstalledWorkspaceCompatibility(normalizedArgv);
    if (compatibilityError !== null) {
        (0, output_1.emitError)({
            command: runtime_contract_1.CLI_NAME,
            format,
            code: compatibilityError.code,
            message: compatibilityError.message,
            ...(0, errors_1.getRuntimeErrorEnvelopeFields)(compatibilityError),
            details: compatibilityError.details,
            findings: compatibilityError.findings
        });
        return compatibilityError.exitCode;
    }
    const program = await createProgram();
    try {
        await program.parseAsync(normalizedArgv);
        const requestedExitCode = program.runtimeExitCode;
        return typeof requestedExitCode === "number"
            ? requestedExitCode
            : errors_1.RuntimeExitCode.SUCCESS;
    }
    catch (error) {
        const capturedOutput = program.capturedOutput ?? { stdout: "", stderr: "" };
        if ((0, errors_1.isCommanderLifecycleSignal)(error)) {
            if (capturedOutput.stdout) {
                process.stdout.write(capturedOutput.stdout);
            }
            if (capturedOutput.stderr) {
                process.stderr.write(capturedOutput.stderr);
            }
            return errors_1.RuntimeExitCode.SUCCESS;
        }
        if ((0, errors_1.isCommanderUsageError)(error)) {
            const runtimeError = (0, errors_1.createCommanderUsageError)({
                error,
                capturedStderr: capturedOutput.stderr
            });
            if (format === "json") {
                (0, output_1.emitError)({
                    command: runtime_contract_1.CLI_NAME,
                    format,
                    code: runtimeError.code,
                    message: runtimeError.message,
                    ...(0, errors_1.getRuntimeErrorEnvelopeFields)(runtimeError),
                    details: runtimeError.details,
                    findings: runtimeError.findings
                });
            }
            else {
                if (capturedOutput.stdout) {
                    process.stdout.write(capturedOutput.stdout);
                }
                if (capturedOutput.stderr) {
                    process.stderr.write(capturedOutput.stderr);
                }
            }
            return runtimeError.exitCode;
        }
        if (error instanceof pagination_1.PaginationCursorError) {
            const runtimeError = (0, errors_1.createUsageError)(`${error.code}: ${error.message}`, [
                "Pagination cursor validation failed before output was accepted.",
                "No pagination write was performed; refresh the first page and use its returned next cursor."
            ]);
            (0, output_1.emitError)({
                command: runtime_contract_1.CLI_NAME,
                format,
                code: runtimeError.code,
                message: runtimeError.message,
                ...(0, errors_1.getRuntimeErrorEnvelopeFields)(runtimeError),
                details: runtimeError.details,
                findings: runtimeError.findings
            });
            return runtimeError.exitCode;
        }
        if (error instanceof budget_1.OutputBudgetError) {
            const runtimeError = (0, errors_1.createUsageError)(`${error.code}: ${error.message}`, [
                `Minimum safe budget: ${error.minimumBytes} bytes`,
                "Use fields, limits, pagination, compact detail, or a larger output budget.",
                "No partial JSON document was emitted."
            ]);
            (0, output_1.emitError)({
                command: runtime_contract_1.CLI_NAME,
                format,
                code: runtimeError.code,
                message: runtimeError.message,
                ...(0, errors_1.getRuntimeErrorEnvelopeFields)(runtimeError),
                details: runtimeError.details,
                findings: runtimeError.findings
            });
            return runtimeError.exitCode;
        }
        const runtimeError = (0, errors_1.createUnexpectedError)(error);
        (0, output_1.emitError)({
            command: runtime_contract_1.CLI_NAME,
            format,
            code: runtimeError.code,
            message: runtimeError.message,
            ...(0, errors_1.getRuntimeErrorEnvelopeFields)(runtimeError),
            details: runtimeError.details,
            findings: runtimeError.findings
        });
        return runtimeError.exitCode;
    }
}
function normalizeProtocolVersionInput(argv) {
    const normalized = [...argv];
    let requested;
    for (let index = 2; index < normalized.length; index += 1) {
        if (normalized[index] === "--protocol-version")
            requested = normalized[index + 1];
        else if (normalized[index].startsWith("--protocol-version="))
            requested = normalized[index].slice("--protocol-version=".length);
        if (normalized[index] === "--input-json" || normalized[index].startsWith("--input-json=")) {
            const inline = normalized[index].startsWith("--input-json=");
            const jsonIndex = inline ? index : index + 1;
            const json = inline ? normalized[index].slice("--input-json=".length) : normalized[jsonIndex];
            try {
                const parsed = JSON.parse(json);
                if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && Object.hasOwn(parsed, "protocolVersion")) {
                    if (requested !== undefined)
                        return { argv: normalized, requested: "multiple selections", version: null };
                    requested = parsed.protocolVersion;
                    delete parsed.protocolVersion;
                    const replacement = JSON.stringify(parsed);
                    normalized[jsonIndex] = inline ? `--input-json=${replacement}` : replacement;
                }
            }
            catch { /* command-specific structured-input handling owns malformed JSON */ }
        }
    }
    return { argv: normalized, ...(requested === undefined ? {} : { requested }), version: requested === undefined ? automation_protocol_1.AUTOMATION_PROTOCOL_VERSION : (0, automation_protocol_1.resolveAutomationProtocolVersion)(requested) };
}
function isPaginationReadCommand(argv) {
    return (0, budget_1.isApprovedBoundedReadCommand)(detectCommandIdentity(argv));
}
function detectCommandIdentity(argv) {
    const valueOptions = new Set([
        "--format",
        "--protocol-version",
        "--detail",
        "--finding-code",
        "--severity",
        "--fields",
        "--limit",
        "--page-lane",
        "--page-size",
        "--page-cursor",
        "--output-budget",
        "--json-spacing"
    ]);
    const commandTokens = [];
    for (let index = 2; index < argv.length; index += 1) {
        const token = argv[index];
        const optionName = token.split("=", 1)[0];
        if (valueOptions.has(optionName)) {
            if (!token.includes("=")) {
                index += 1;
            }
            continue;
        }
        if (token.startsWith("-")) {
            continue;
        }
        commandTokens.push(token);
        if (commandTokens.length === 2) {
            break;
        }
    }
    const nestedIdentity = commandTokens.join(" ");
    if ((0, budget_1.isApprovedBoundedReadCommand)(nestedIdentity)) {
        return nestedIdentity;
    }
    return commandTokens[0] ?? "";
}
function dispatchManagedCliFromShimIfNeeded(argv, format) {
    if (!(0, runtime_state_1.isVersionManagerShimMode)() || (0, runtime_state_1.isVersionManagerCommand)(argv)) {
        return null;
    }
    const resolution = (0, runtime_state_1.resolveSelectedManagedCli)({ currentExecutablePath: argv[1] });
    if (!resolution.ok) {
        (0, output_1.emitError)({
            command: "version shim dispatch",
            format,
            code: resolution.reason.toUpperCase().replace(/-/g, "_"),
            message: resolution.message,
            details: [
                ...resolution.details,
                "Recovery: run day-shift version doctor for local runtime context."
            ],
            findings: [
                (0, output_1.createBlockingValidationFinding)({
                    code: `VERSION_MANAGER_${resolution.reason.toUpperCase().replace(/-/g, "_")}`,
                    message: resolution.message,
                    blockingReason: "invalid-command-input",
                    recovery: "Inspect local version-manager state with day-shift version doctor, then repair selected metadata or managed package layout.",
                    evidence: {
                        category: "command-specific",
                        details: {
                            reason: resolution.reason,
                            details: resolution.details
                        }
                    }
                })
            ]
        });
        return errors_1.RuntimeExitCode.ERROR;
    }
    const spawnCommand = resolution.target.executablePath.endsWith(".js")
        ? "node"
        : resolution.target.executablePath;
    const spawnArgs = resolution.target.executablePath.endsWith(".js")
        ? [resolution.target.executablePath, ...argv.slice(2)]
        : argv.slice(2);
    const result = (0, node_child_process_1.spawnSync)(spawnCommand, spawnArgs, {
        stdio: "pipe",
        encoding: "utf8",
        env: {
            ...process.env,
            DAY_SHIFT_MANAGED_VERSION: resolution.target.selectedVersion,
            DAY_SHIFT_MANAGED_PACKAGE_ROOT: resolution.target.packageRoot
        }
    });
    if (result.stdout) {
        process.stdout.write(result.stdout);
    }
    if (result.stderr) {
        process.stderr.write(result.stderr);
    }
    if (result.error !== undefined) {
        if (result.error && result.error.code === "EPERM" &&
            resolution.target.executablePath.endsWith(".js")) {
            return runManagedJavaScriptInProcess(resolution.target.executablePath, argv.slice(2), {
                DAY_SHIFT_MANAGED_VERSION: resolution.target.selectedVersion,
                DAY_SHIFT_MANAGED_PACKAGE_ROOT: resolution.target.packageRoot
            });
        }
        (0, output_1.emitError)({
            command: "version shim dispatch",
            format,
            code: "MANAGED_CLI_SPAWN_FAILED",
            message: "Failed to spawn selected Day Shift managed executable.",
            details: [
                `Executable path: ${resolution.target.executablePath}`,
                result.error.message
            ],
            findings: [
                (0, output_1.createBlockingValidationFinding)({
                    code: "VERSION_MANAGER_MANAGED_CLI_SPAWN_FAILED",
                    message: "Failed to spawn selected Day Shift managed executable.",
                    blockingReason: "invalid-command-input",
                    recovery: "Verify that the managed executable exists, is executable, and is not blocked by the host environment.",
                    evidence: {
                        category: "command-specific",
                        details: {
                            executablePath: resolution.target.executablePath,
                            error: result.error.message
                        }
                    }
                })
            ]
        });
        return errors_1.RuntimeExitCode.ERROR;
    }
    return result.status ?? errors_1.RuntimeExitCode.ERROR;
}
function runManagedJavaScriptInProcess(executablePath, args, managedEnvironment) {
    const previousArgv = process.argv;
    const previousExitCode = process.exitCode;
    const previousEnvironment = {};
    const previousStdoutWrite = process.stdout.write;
    const previousStderrWrite = process.stderr.write;
    let capturedStdout = "";
    let capturedStderr = "";
    for (const key of Object.keys(managedEnvironment)) {
        previousEnvironment[key] = process.env[key];
        process.env[key] = managedEnvironment[key];
    }
    process.argv = [process.execPath, executablePath, ...args];
    process.exitCode = undefined;
    process.stdout.write = ((chunk, ...writeArgs) => {
        capturedStdout += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
        const callback = writeArgs.find((arg) => typeof arg === "function");
        callback?.();
        return true;
    });
    process.stderr.write = ((chunk, ...writeArgs) => {
        capturedStderr += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
        const callback = writeArgs.find((arg) => typeof arg === "function");
        callback?.();
        return true;
    });
    try {
        delete require.cache[require.resolve(executablePath)];
        require(executablePath);
        if (capturedStdout) {
            node_fs_1.default.writeSync(1, capturedStdout);
        }
        if (capturedStderr) {
            node_fs_1.default.writeSync(2, capturedStderr);
        }
        return typeof process.exitCode === "number" ? process.exitCode : errors_1.RuntimeExitCode.SUCCESS;
    }
    catch (error) {
        (0, output_1.emitError)({
            command: "version shim dispatch",
            format: output_1.DEFAULT_OUTPUT_FORMAT,
            code: "MANAGED_CLI_IN_PROCESS_FAILED",
            message: "Failed to run selected Day Shift managed JavaScript executable in-process.",
            details: [error instanceof Error ? error.message : String(error)]
        });
        return errors_1.RuntimeExitCode.ERROR;
    }
    finally {
        process.stdout.write = previousStdoutWrite;
        process.stderr.write = previousStderrWrite;
        process.argv = previousArgv;
        process.exitCode = previousExitCode;
        for (const [key, value] of Object.entries(previousEnvironment)) {
            if (value === undefined) {
                delete process.env[key];
            }
            else {
                process.env[key] = value;
            }
        }
    }
}
function checkInstalledWorkspaceCompatibility(argv) {
    if (shouldSkipInstalledWorkspaceCompatibilityGate(argv)) {
        return null;
    }
    const explicitRoot = process.env.DAY_SHIFT_REPOSITORY_ROOT;
    const repositoryDetection = (0, runtime_contract_2.detectRepositoryRoot)({
        explicitRoot: explicitRoot && explicitRoot.trim().length > 0 ? explicitRoot : undefined
    });
    const dayShiftDirectory = node_path_1.default.join(repositoryDetection.root, runtime_contract_1.DAY_SHIFT_DIRECTORY_NAME);
    if (!node_fs_1.default.existsSync(dayShiftDirectory) || !node_fs_1.default.statSync(dayShiftDirectory).isDirectory()) {
        return null;
    }
    if (!workspaceHasCompatibilityEvidence(repositoryDetection.root)) {
        return null;
    }
    const evidence = (0, workspace_compatibility_1.discoverWorkspaceCompatibilityVersions)({
        repositoryRoot: repositoryDetection.root
    });
    const checks = (0, workspace_compatibility_1.checkWorkspaceCompatibility)({
        evidence,
        compatibility: output_lifecycle_1.CURRENT_RELEASE_COMPATIBILITY
    });
    const diagnostics = (0, workspace_compatibility_1.createWorkspaceCompatibilityDiagnostics)({
        checks,
        evidence
    });
    if (diagnostics.length === 0) {
        return null;
    }
    const findings = (0, workspace_compatibility_1.createWorkspaceCompatibilityFindings)(diagnostics);
    return (0, errors_1.createInvalidConfigError)("Day Shift workspace compatibility check failed before command execution.", [
        "No-write boundary: no workspace files were changed.",
        "Recovery: use a CLI release compatible with the detected workspace metadata, or run an explicit migration with a compatible CLI before retrying.",
        (0, output_1.renderValidationFindingsText)(findings, "Compatibility findings")
    ], findings);
}
function workspaceHasCompatibilityEvidence(repositoryRoot) {
    return workspaceRootContainsMarkdownEvidence(node_path_1.default.join(repositoryRoot, ".day-shift", "specs"))
        || workspaceRootContainsMarkdownEvidence(node_path_1.default.join(repositoryRoot, ".day-shift", "planning"));
}
function workspaceRootContainsMarkdownEvidence(rootPath) {
    if (!node_fs_1.default.existsSync(rootPath) || !node_fs_1.default.statSync(rootPath).isDirectory()) {
        return false;
    }
    const entries = node_fs_1.default.readdirSync(rootPath, { withFileTypes: true });
    for (const entry of entries) {
        const childPath = node_path_1.default.join(rootPath, entry.name);
        if (entry.isFile() && entry.name.endsWith(".md")) {
            return true;
        }
        if (entry.isDirectory() && workspaceRootContainsMarkdownEvidence(childPath)) {
            return true;
        }
    }
    return false;
}
function shouldSkipInstalledWorkspaceCompatibilityGate(argv) {
    if (require.main !== module) {
        return true;
    }
    if (process.env.DAY_SHIFT_SKIP_WORKSPACE_COMPATIBILITY_GATE === "1") {
        return true;
    }
    const commandArgs = argv.slice(2);
    if (commandArgs.some((arg) => arg === "--help" || arg === "-h" || arg === "help")) {
        return true;
    }
    if (commandArgs.some((arg) => arg === "--version" || arg === "-V")) {
        return true;
    }
    const globalValueOptions = new Set([
        "--format",
        "--protocol-version",
        "--detail",
        "--finding-code",
        "--severity",
        "--fields",
        "--limit",
        "--page-lane",
        "--page-size",
        "--page-cursor",
        "--output-budget",
        "--json-spacing"
    ]);
    const commandTokens = [];
    for (let index = 0; index < commandArgs.length && commandTokens.length < 2; index += 1) {
        const token = commandArgs[index];
        const optionName = token.split("=", 1)[0];
        if (globalValueOptions.has(optionName)) {
            if (!token.includes("="))
                index += 1;
            continue;
        }
        if (!token.startsWith("-"))
            commandTokens.push(token);
    }
    const firstCommand = commandTokens[0];
    if (firstCommand === "workspace") {
        const workspaceSubcommand = commandTokens[1];
        return workspaceSubcommand === "migrate" || workspaceSubcommand === "upgrade";
    }
    return firstCommand === "about" || firstCommand === "completion" || firstCommand === "init" || firstCommand === "license";
}
function normalizeVersionOptionAliases(argv) {
    return normalizeVersionInstallVersionOption(normalizeReleaseVersionOption(argv));
}
function normalizeVersionInstallVersionOption(argv) {
    const versionIndex = argv.indexOf("version");
    const installIndex = argv.indexOf("install");
    if (versionIndex === -1 ||
        installIndex === -1 ||
        installIndex !== versionIndex + 1 ||
        installIndex >= argv.length - 1) {
        return argv;
    }
    let changed = false;
    const normalized = argv.map((arg, index) => {
        if (index <= installIndex) {
            return arg;
        }
        if (arg === "--version") {
            changed = true;
            return "--assert-version";
        }
        if (arg.startsWith("--version=")) {
            changed = true;
            return `--assert-version=${arg.slice("--version=".length)}`;
        }
        return arg;
    });
    return changed ? normalized : argv;
}
function normalizeReleaseVersionOption(argv) {
    const releaseIndex = argv.indexOf("release");
    if (releaseIndex === -1 || releaseIndex >= argv.length - 1) {
        return argv;
    }
    let changed = false;
    const normalized = argv.map((arg, index) => {
        if (index <= releaseIndex) {
            return arg;
        }
        if (arg === "--version") {
            changed = true;
            return "--release-version";
        }
        if (arg.startsWith("--version=")) {
            changed = true;
            return `--release-version=${arg.slice("--version=".length)}`;
        }
        return arg;
    });
    return changed ? normalized : argv;
}
if (require.main === module) {
    void run().then((exitCode) => {
        process.exitCode = exitCode;
    });
}
