import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import yaml from "js-yaml";
import { logger } from "../logger.js";
export const CRITICAL_BUILD_DEPS = [
    "deno",
    "workerd",
    "esbuild",
    "@swc/core",
    "protobufjs",
];
const MODULES_YAML = path.join("node_modules", ".modules.yaml");
export function isPnpmDlx(somePath) {
    const normalized = somePath.replace(/\\/g, "/");
    return (normalized.includes("/pnpm/dlx/") || normalized.includes("/pnpm-cache/dlx/"));
}
export function formatCommand(argv) {
    if (!Array.isArray(argv._) || argv._.length === 0) {
        return "<cmd>";
    }
    return argv._.map(String).map(shellQuote).join(" ");
}
function shellQuote(arg) {
    if (/^[a-zA-Z0-9_./@:=+-]+$/.test(arg)) {
        return arg;
    }
    return JSON.stringify(arg);
}
export function findCliModulesYaml(startDir) {
    let current = path.resolve(startDir);
    while (true) {
        const candidate = path.join(current, MODULES_YAML);
        if (existsSync(candidate)) {
            return candidate;
        }
        const parent = path.dirname(current);
        if (parent === current) {
            return null;
        }
        current = parent;
    }
}
export function readBlockedBuilds(modulesYamlPath) {
    let raw;
    try {
        raw = readFileSync(modulesYamlPath, "utf-8");
    }
    catch (cause) {
        logger.debug({ cause, modulesYamlPath }, "Could not read .modules.yaml");
        return [];
    }
    let parsed;
    try {
        parsed = yaml.load(raw);
    }
    catch (cause) {
        logger.debug({ cause, modulesYamlPath }, "Could not parse .modules.yaml");
        return [];
    }
    if (!parsed || typeof parsed !== "object") {
        return [];
    }
    const record = parsed;
    const ignored = Array.isArray(record.ignoredBuilds)
        ? record.ignoredBuilds
        : [];
    const pending = Array.isArray(record.pendingBuilds)
        ? record.pendingBuilds
        : [];
    const names = new Set();
    for (const entry of [...ignored, ...pending]) {
        if (typeof entry !== "string") {
            continue;
        }
        names.add(stripVersion(entry));
    }
    return [...names];
}
export function getBlockedCriticalDeps(cliModuleDir) {
    try {
        const modulesYaml = findCliModulesYaml(cliModuleDir);
        if (!modulesYaml) {
            return [];
        }
        const blocked = new Set(readBlockedBuilds(modulesYaml));
        return CRITICAL_BUILD_DEPS.filter((name) => blocked.has(name));
    }
    catch (cause) {
        logger.debug({ cause, cliModuleDir }, "pnpm lifecycle detection failed");
        return [];
    }
}
function stripVersion(entry) {
    const at = entry.lastIndexOf("@");
    if (at <= 0) {
        return entry;
    }
    return entry.slice(0, at);
}
//# sourceMappingURL=pnpm-lifecycle.js.map