// src/actions/packman/convert.ts
import {
  existsSync as existsSync10,
  readdirSync,
  statSync
} from "node:fs";
import PATH10 from "node:path";
import chalk12 from "chalk";

// src/lib/packageManagerRuntime.ts
import fs from "node:fs";
import chalk from "chalk";

// src/lib/crossSpawn.ts
import crossSpawn from "cross-spawn";
function spawnSync(command, args, options) {
  return crossSpawn.sync(command, args, options);
}

// src/lib/packageManagerRuntime.ts
var DISPLAY_NAMES = {
  bun: "Bun",
  npm: "npm",
  pnpm: "pnpm",
  yarn: "Yarn"
};
var MAC_INSTALL_COMMANDS = {
  bun: "brew install oven-sh/bun/bun",
  npm: "brew install node",
  pnpm: "brew install pnpm",
  yarn: "brew install yarn"
};
function currentPlatform() {
  if (process.platform === "darwin" || process.platform === "linux" || process.platform === "win32") {
    return process.platform;
  }
  return "unknown";
}
function askYesNo(question) {
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
    return false;
  }
  process.stdout.write(question);
  const buffer = Buffer.alloc(1024);
  const bytesRead = fs.readSync(process.stdin.fd, buffer, 0, buffer.length, null);
  const answer = buffer.toString("utf8", 0, bytesRead).trim().toLowerCase();
  return answer === "y" || answer === "yes";
}
function isCommandInstalled(command) {
  const result = spawnSync(command, ["--version"], {
    encoding: "utf8",
    stdio: "ignore"
  });
  return !result.error && result.status === 0;
}
function isPackageManagerInstalled(pm) {
  return isCommandInstalled(pm);
}
function getPackageManagerInstallPlan(pm, platform = currentPlatform()) {
  const displayName = DISPLAY_NAMES[pm];
  if (platform === "darwin") {
    const command = MAC_INSTALL_COMMANDS[pm];
    return {
      command,
      manualInstructions: [
        `Install ${displayName} with: ${command}`
      ],
      packageManager: pm,
      platform,
      supported: true
    };
  }
  if (platform === "linux") {
    return {
      manualInstructions: [
        `Automatic installation for ${displayName} is not implemented on Linux yet.`,
        `Install ${displayName} manually and re-run the command.`
      ],
      packageManager: pm,
      platform,
      supported: false
    };
  }
  if (platform === "win32") {
    return {
      manualInstructions: [
        `Automatic installation for ${displayName} is not implemented on Windows yet.`,
        `Install ${displayName} manually and re-run the command.`
      ],
      packageManager: pm,
      platform,
      supported: false
    };
  }
  return {
    manualInstructions: [
      `Automatic installation for ${displayName} is not implemented on ${platform} yet.`,
      `Install ${displayName} manually and re-run the command.`
    ],
    packageManager: pm,
    platform,
    supported: false
  };
}
function printManualInstructions(plan, context) {
  console.error(chalk.yellow(`${DISPLAY_NAMES[plan.packageManager]} is required for "${context.operation}".`));
  for (const line of plan.manualInstructions) {
    console.error(chalk.gray(`  ${line}`));
  }
}
function installWithHomebrew(pm, cwd) {
  const command = MAC_INSTALL_COMMANDS[pm];
  const result = spawnSync("brew", command.replace("brew ", "").split(" "), {
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  return result.status === 0;
}
function ensurePackageManagerInstalled(pm, context) {
  if (isPackageManagerInstalled(pm)) return true;
  const plan = getPackageManagerInstallPlan(pm, context.platform ?? currentPlatform());
  const displayName = DISPLAY_NAMES[pm];
  console.error(chalk.yellow(`${context.operation} requires ${displayName}, but it is not installed.`));
  if (!plan.supported) {
    printManualInstructions(plan, context);
    return false;
  }
  if (!isCommandInstalled("brew")) {
    console.error(chalk.yellow("Homebrew is not installed, so automatic installation is unavailable."));
    console.error(chalk.gray("  Install Homebrew from https://brew.sh and then run:"));
    console.error(chalk.gray(`  ${plan.command}`));
    return false;
  }
  const confirmed = askYesNo(chalk.cyan(`Install ${displayName} with Homebrew now? [y/N] `));
  if (!confirmed) {
    console.error(chalk.gray(`Skipping install. Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk.cyan(`Installing ${displayName} via Homebrew...
`));
  if (!installWithHomebrew(pm, context.cwd)) {
    console.error(chalk.red(`Homebrew failed to install ${displayName}.`));
    console.error(chalk.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  if (!isPackageManagerInstalled(pm)) {
    console.error(chalk.red(`${displayName} still does not appear to be installed after Homebrew completed.`));
    console.error(chalk.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk.green(`${displayName} installed successfully.`));
  return true;
}
function failureResult() {
  return {
    output: ["", ""],
    pid: 0,
    signal: null,
    status: 1,
    stderr: "",
    stdout: ""
  };
}
function spawnPackageManagerSync(pm, args, options) {
  if (!ensurePackageManagerInstalled(pm, options.context)) {
    return failureResult();
  }
  return spawnSync(pm, args, { encoding: "utf8", ...options });
}

// src/pm/workspaces.ts
import { existsSync, readFileSync } from "node:fs";
import PATH from "node:path";
import { globSync } from "glob";
function readJsonFile(path) {
  if (!existsSync(path)) return void 0;
  try {
    return JSON.parse(readFileSync(path, "utf8"));
  } catch {
    return void 0;
  }
}
function readRootPackageJson(cwd = process.cwd()) {
  return readJsonFile(PATH.resolve(cwd, "package.json"));
}
function readWorkspacePatternsFromPackageJson(cwd = process.cwd()) {
  const pkg = readRootPackageJson(cwd);
  if (!pkg?.workspaces) return [];
  if (Array.isArray(pkg.workspaces)) return [...pkg.workspaces];
  return pkg.workspaces.packages ? [...pkg.workspaces.packages] : [];
}
function readPnpmWorkspacePatterns(cwd = process.cwd()) {
  const wsPath = PATH.resolve(cwd, "pnpm-workspace.yaml");
  if (!existsSync(wsPath)) return [];
  const content = readFileSync(wsPath, "utf8");
  const patterns = [];
  let inPackages = false;
  for (const line of content.split("\n")) {
    if (/^packages\s*:/.test(line.trim())) {
      inPackages = true;
      continue;
    }
    if (inPackages) {
      const match = /^\s+-\s+['"]?([^'"]+)['"]?\s*$/.exec(line);
      if (match) {
        patterns.push(match[1]);
      } else if (line.trim() !== "" && !/^\s/.test(line)) {
        break;
      }
    }
  }
  return patterns;
}
function readWorkspacePatterns(cwd = process.cwd()) {
  const fromPackageJson = readWorkspacePatternsFromPackageJson(cwd);
  return fromPackageJson.length > 0 ? fromPackageJson : readPnpmWorkspacePatterns(cwd);
}
function detectPackageManagerFromPackageJson(cwd = process.cwd()) {
  const packageManager = readRootPackageJson(cwd)?.packageManager;
  if (!packageManager) return void 0;
  return packageManager.split("@")[0];
}

// src/pm/detectPackageManager.ts
import { existsSync as existsSync2 } from "node:fs";
var knownPackageManagers = /* @__PURE__ */ new Set(["bun", "npm", "pnpm", "yarn"]);
function detectPackageManager() {
  const packageManager = detectPackageManagerFromPackageJson();
  if (packageManager && knownPackageManagers.has(packageManager)) {
    return packageManager;
  }
  if (existsSync2("pnpm-lock.yaml") || existsSync2("pnpm-workspace.yaml")) return "pnpm";
  if (existsSync2("bun.lock") || existsSync2("bun.lockb")) return "bun";
  if (existsSync2("yarn.lock") || existsSync2(".yarnrc.yml")) return "yarn";
  if (existsSync2("package-lock.json") || existsSync2("npm-shrinkwrap.json")) return "npm";
  return "yarn";
}

// src/pm/registry.ts
var implementations = /* @__PURE__ */ new Map();
function getPackageManager(name) {
  const pmName = name ?? detectPackageManager();
  const pm = implementations.get(pmName);
  if (!pm) {
    throw new Error(
      `No package manager implementation registered for "${pmName}". Ensure registerPackageManager() has been called before getPackageManager().`
    );
  }
  return pm;
}

// src/actions/package-lint.ts
import { readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "node:fs";
import PATH4 from "node:path";
import chalk5 from "chalk";
import picomatch from "picomatch";
import semver2 from "semver";

// src/lib/toolchainVersion.ts
import { readFileSync as readFileSync2 } from "node:fs";
import { createRequire } from "node:module";
var require2 = createRequire(import.meta.url);
function bundledToolchainVersion() {
  const pkgPath = require2.resolve("@xylabs/toolchain/package.json");
  const pkg = JSON.parse(readFileSync2(pkgPath, "utf8"));
  if (!pkg.version) throw new Error("Could not read @xylabs/toolchain version");
  return pkg.version;
}
function bundledToolchainRange() {
  return `^${bundledToolchainVersion()}`;
}

// src/lib/initCwd.ts
function INIT_CWD() {
  return process.env.INIT_CWD ?? process.cwd();
}

// src/lib/latestVersions.ts
var latestVersions = {
  node: "24.14.1",
  nodeLtsCodename: "Krypton",
  npm: "11.11.0",
  pnpm: "10.33.0",
  yarn: "4.13.0"
};

// src/lib/npmLatestVersion.ts
var REGISTRY_BASE = "https://registry.npmjs.org";
var cache = /* @__PURE__ */ new Map();
async function fetchUncached(packageName) {
  try {
    const url = `${REGISTRY_BASE}/${encodeURIComponent(packageName)}/latest`;
    const res = await fetch(url, { headers: { Accept: "application/vnd.npm.install-v1+json" } });
    if (!res.ok) return void 0;
    const data = await res.json();
    return data.version;
  } catch {
    return void 0;
  }
}
function fetchLatestPackageVersion(packageName) {
  const existing = cache.get(packageName);
  if (existing) return existing;
  const pending = fetchUncached(packageName);
  cache.set(packageName, pending);
  return pending;
}

// src/lib/runInstall.ts
import chalk2 from "chalk";
function runInstall(cwd) {
  const pm = detectPackageManager();
  console.log(chalk2.gray(`Running ${pm} install...`));
  const result = spawnPackageManagerSync(pm, ["install"], {
    context: { cwd, operation: `Run ${pm} install` },
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (result.status !== 0) {
    console.warn(chalk2.yellow(`${pm} install failed`));
    return false;
  }
  console.log(chalk2.green("Dependencies installed"));
  return true;
}

// src/actions/package-lint-deps.ts
import { readFileSync as readFileSync3, writeFileSync } from "node:fs";
import PATH2 from "node:path";
import chalk3 from "chalk";
import semver from "semver";
function readWorkspacePackageJson(cwd, location) {
  const pkgPath = PATH2.resolve(cwd, location, "package.json");
  try {
    return JSON.parse(readFileSync3(pkgPath, "utf8"));
  } catch {
    return void 0;
  }
}
function writeWorkspacePackageJson(cwd, location, pkg) {
  const pkgPath = PATH2.resolve(cwd, location, "package.json");
  writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
}
function buildWorkspaceVersionMap(cwd, workspaces) {
  const map = /* @__PURE__ */ new Map();
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    const version = pkg.version;
    if (version) map.set(name, version);
  }
  return map;
}
function expectedPeerRange(devDepVersion, targetVersion) {
  const parsed = semver.parse(targetVersion);
  if (!parsed) return `~${targetVersion}`;
  if (devDepVersion === "workspace:^") {
    return `^${parsed.major}`;
  }
  return `~${parsed.major}.${parsed.minor}`;
}
function checkVersionConsistency(cwd, rootPkg, workspaces) {
  const result = {
    errors: [],
    fixable: [],
    warnings: []
  };
  if (rootPkg.version !== void 0) {
    result.fixable.push('Root package.json should not have a "version" field in a monorepo');
  }
  const versions = /* @__PURE__ */ new Map();
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    const version = pkg.version;
    if (version) {
      versions.set(name, version);
    } else {
      result.errors.push(`${name} (${location}) is missing a "version" field`);
    }
  }
  const uniqueVersions = new Set(versions.values());
  if (uniqueVersions.size > 1) {
    const versionList = [...uniqueVersions].toSorted(semver.rcompare);
    for (const [name, version] of versions) {
      if (version !== versionList[0]) {
        result.fixable.push(`${name} has version ${version} (expected ${versionList[0]})`);
      }
    }
  }
  return result;
}
function fixVersionConsistency(cwd, rootPkg, writeRootPackageJson2, workspaces) {
  if (rootPkg.version !== void 0) {
    delete rootPkg.version;
    writeRootPackageJson2(cwd, rootPkg);
    console.log(chalk3.green('  \u2714 Fixed: removed "version" from root package.json'));
  }
  const versions = [];
  for (const { location } of workspaces) {
    if (location === ".") continue;
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    const version = pkg.version;
    if (version && semver.valid(version)) {
      versions.push(version);
    }
  }
  if (versions.length === 0) return;
  const highest = versions.toSorted(semver.rcompare)[0];
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    if (pkg.version !== highest) {
      pkg.version = highest;
      writeWorkspacePackageJson(cwd, location, pkg);
      console.log(chalk3.green(`  \u2714 Fixed: set version to ${highest} in ${name} (${location})`));
    }
  }
}
function expectedDepVersion(targetVersion) {
  const parsed = semver.parse(targetVersion);
  if (!parsed) return `~${targetVersion}`;
  return `~${targetVersion}`;
}
function checkInternalDepVersions(cwd, workspaces) {
  const result = {
    errors: [],
    fixable: [],
    warnings: []
  };
  const workspaceVersions = buildWorkspaceVersionMap(cwd, workspaces);
  for (const { location, name } of workspaces) {
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    for (const depField of ["dependencies", "devDependencies"]) {
      const deps = pkg[depField];
      if (!deps) continue;
      for (const [dep, version] of Object.entries(deps)) {
        const targetVersion = workspaceVersions.get(dep);
        if (!targetVersion) continue;
        const expected = expectedDepVersion(targetVersion);
        if (version.startsWith("workspace:")) {
          result.fixable.push(
            `${name} (${location}) ${depField}.${dep} is "${version}" \u2014 should be "${expected}" (not workspace: protocol)`
          );
        } else if (version !== expected) {
          result.fixable.push(
            `${name} (${location}) ${depField}.${dep} is "${version}" \u2014 should be "${expected}"`
          );
        }
      }
    }
  }
  return result;
}
function fixInternalDepVersions(cwd, workspaces) {
  const workspaceVersions = buildWorkspaceVersionMap(cwd, workspaces);
  for (const { location, name } of workspaces) {
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    let modified = false;
    for (const depField of ["dependencies", "devDependencies"]) {
      const deps = pkg[depField];
      if (!deps) continue;
      for (const [dep, version] of Object.entries(deps)) {
        const targetVersion = workspaceVersions.get(dep);
        if (!targetVersion) continue;
        const expected = expectedDepVersion(targetVersion);
        if (version !== expected) {
          deps[dep] = expected;
          console.log(chalk3.green(`  \u2714 Fixed: set ${depField}.${dep} to "${expected}" in ${name} (${location})`));
          modified = true;
        }
      }
    }
    if (modified) {
      writeWorkspacePackageJson(cwd, location, pkg);
    }
  }
}
function checkWorkspaceProtocol(cwd, workspaces) {
  const result = {
    errors: [],
    fixable: [],
    warnings: []
  };
  const workspaceNames = new Set(workspaces.map((w) => w.name));
  for (const { location, name } of workspaces) {
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    for (const depField of ["dependencies", "devDependencies"]) {
      const deps = pkg[depField];
      if (!deps) continue;
      for (const [dep, version] of Object.entries(deps)) {
        if (!workspaceNames.has(dep)) continue;
        if (!version.startsWith("workspace:")) {
          result.fixable.push(
            `${name} (${location}) ${depField}.${dep} is "${version}" \u2014 should use workspace: protocol`
          );
        }
      }
    }
  }
  return result;
}
function fixWorkspaceProtocol(cwd, workspaces) {
  const workspaceNames = new Set(workspaces.map((w) => w.name));
  for (const { location, name } of workspaces) {
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    let modified = false;
    for (const depField of ["dependencies", "devDependencies"]) {
      const deps = pkg[depField];
      if (!deps) continue;
      for (const [dep, version] of Object.entries(deps)) {
        if (!workspaceNames.has(dep)) continue;
        if (!version.startsWith("workspace:")) {
          deps[dep] = "workspace:~";
          console.log(chalk3.green(`  \u2714 Fixed: set ${depField}.${dep} to "workspace:~" in ${name} (${location})`));
          modified = true;
        }
      }
    }
    if (modified) {
      writeWorkspacePackageJson(cwd, location, pkg);
    }
  }
}
function checkInternalPeerVersions(cwd, workspaces) {
  const result = {
    errors: [],
    fixable: [],
    warnings: []
  };
  const workspaceVersions = buildWorkspaceVersionMap(cwd, workspaces);
  const pmName = getPackageManager().name;
  const rewritesWorkspaceProtocol = pmName === "pnpm" || pmName === "bun";
  for (const { location, name } of workspaces) {
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    const peerDeps = pkg.peerDependencies;
    if (!peerDeps) continue;
    const devDeps = pkg.devDependencies;
    for (const [dep, version] of Object.entries(peerDeps)) {
      const targetVersion = workspaceVersions.get(dep);
      if (!targetVersion) continue;
      if (version.startsWith("workspace:")) {
        if (rewritesWorkspaceProtocol) continue;
        const expected2 = expectedPeerRange(devDeps?.[dep], targetVersion);
        result.fixable.push(
          `${name} (${location}) peerDependencies.${dep} uses workspace: protocol \u2014 should be "${expected2}"`
        );
        continue;
      }
      const expected = expectedPeerRange(devDeps?.[dep], targetVersion);
      if (version !== expected && !semver.satisfies(targetVersion, version)) {
        result.fixable.push(
          `${name} (${location}) peerDependencies.${dep} is "${version}" \u2014 current version ${targetVersion} is not satisfied; expected "${expected}"`
        );
      }
    }
  }
  return result;
}
function fixInternalPeerVersions(cwd, workspaces) {
  const workspaceVersions = buildWorkspaceVersionMap(cwd, workspaces);
  const pmName = getPackageManager().name;
  const rewritesWorkspaceProtocol = pmName === "pnpm" || pmName === "bun";
  for (const { location, name } of workspaces) {
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    const peerDeps = pkg.peerDependencies;
    if (!peerDeps) continue;
    const devDeps = pkg.devDependencies;
    let modified = false;
    for (const [dep, version] of Object.entries(peerDeps)) {
      const targetVersion = workspaceVersions.get(dep);
      if (!targetVersion) continue;
      if (rewritesWorkspaceProtocol && version.startsWith("workspace:")) continue;
      const expected = expectedPeerRange(devDeps?.[dep], targetVersion);
      if (version !== expected) {
        peerDeps[dep] = expected;
        console.log(chalk3.green(`  \u2714 Fixed: set peerDependencies.${dep} to "${expected}" in ${name} (${location})`));
        modified = true;
      }
    }
    if (modified) {
      writeWorkspacePackageJson(cwd, location, pkg);
    }
  }
}

// src/actions/package-lint-pnpm.ts
import {
  existsSync as existsSync3,
  readFileSync as readFileSync4,
  writeFileSync as writeFileSync2
} from "node:fs";
import PATH3 from "node:path";
import chalk4 from "chalk";
import * as yaml from "yaml";
function emptyResult() {
  return {
    errors: [],
    fixable: [],
    warnings: []
  };
}
function pnpmWorkspacePath(cwd) {
  return PATH3.resolve(cwd, "pnpm-workspace.yaml");
}
function readPnpmWorkspaceDocument(cwd) {
  const wsPath = pnpmWorkspacePath(cwd);
  if (!existsSync3(wsPath)) return void 0;
  try {
    return yaml.parseDocument(readFileSync4(wsPath, "utf8"));
  } catch {
    return void 0;
  }
}
function readPnpmWorkspaceGlobs(cwd) {
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return void 0;
  const packages = doc.get("packages");
  if (!yaml.isSeq(packages)) return void 0;
  const globs = [];
  for (const item of packages.items) {
    const value = yaml.isScalar(item) ? item.value : item;
    if (typeof value === "string") globs.push(value);
  }
  return globs.length > 0 ? globs : void 0;
}
var PNPM_RELEASE_AGE_REQUIRED_EXCLUDES = ["@xylabs/*", "@xyo-network/*"];
function readSequenceStrings(node) {
  if (!yaml.isSeq(node)) return [];
  const out = [];
  for (const item of node.items) {
    const value = yaml.isScalar(item) ? item.value : item;
    if (typeof value === "string") out.push(value);
  }
  return out;
}
function checkPnpmReleaseAgeExcludes(cwd, pm) {
  const result = emptyResult();
  if (pm !== "pnpm") return result;
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return result;
  const existing = readSequenceStrings(doc.get("minimumReleaseAgeExclude"));
  for (const required of PNPM_RELEASE_AGE_REQUIRED_EXCLUDES) {
    if (!existing.includes(required)) {
      result.fixable.push(`pnpm-workspace.yaml minimumReleaseAgeExclude is missing '${required}'`);
    }
  }
  return result;
}
function fixPnpmReleaseAgeExcludes(cwd) {
  const doc = readPnpmWorkspaceDocument(cwd);
  if (!doc) return;
  if (!yaml.isMap(doc.contents)) {
    console.log(chalk4.yellow("  \u26A0 pnpm-workspace.yaml has no top-level map; skipping fix"));
    return;
  }
  let seq = doc.get("minimumReleaseAgeExclude");
  if (!yaml.isSeq(seq)) {
    seq = new yaml.YAMLSeq();
    doc.set("minimumReleaseAgeExclude", seq);
  }
  const seqNode = seq;
  const existing = new Set(readSequenceStrings(seqNode));
  let added = false;
  for (const required of PNPM_RELEASE_AGE_REQUIRED_EXCLUDES) {
    if (existing.has(required)) continue;
    seqNode.add(required);
    existing.add(required);
    added = true;
  }
  if (!added) return;
  writeFileSync2(pnpmWorkspacePath(cwd), String(doc), "utf8");
  console.log(chalk4.green("  \u2714 Fixed: added @xylabs/* and @xyo-network/* to minimumReleaseAgeExclude in pnpm-workspace.yaml"));
}

// src/actions/package-lint.ts
function emptyResult2() {
  return {
    errors: [],
    fixable: [],
    warnings: []
  };
}
function readRootPackageJson2(cwd) {
  const raw = readFileSync5(PATH4.resolve(cwd, "package.json"), "utf8");
  return JSON.parse(raw);
}
function writeRootPackageJson(cwd, pkg) {
  const path = PATH4.resolve(cwd, "package.json");
  writeFileSync3(path, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
}
function isMonorepo(pkg, cwd) {
  const workspaces = pkg.workspaces;
  if (Array.isArray(workspaces) && workspaces.length > 0) return true;
  return readPnpmWorkspaceGlobs(cwd) !== void 0;
}
function checkPackagesFolder(workspaces) {
  const result = emptyResult2();
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    if (!location.startsWith("packages/") && !location.startsWith("packages\\")) {
      result.errors.push(`${name} (${location}) is not inside a packages/ folder`);
    }
  }
  return result;
}
function checkRootPrivate(pkg) {
  const result = emptyResult2();
  if (!pkg.private) {
    result.fixable.push("Root package.json must be private to prevent accidental publishing");
  }
  return result;
}
function fixRootPrivate(cwd, pkg) {
  pkg.private = true;
  writeRootPackageJson(cwd, pkg);
  console.log(chalk5.green('  \u2714 Fixed: set "private": true in root package.json'));
}
function checkNoPublishConfigOnPrivate(pkg) {
  const result = emptyResult2();
  if (pkg.private && pkg.publishConfig) {
    result.fixable.push("Root package.json has publishConfig but is private \u2014 publishConfig is unnecessary");
  }
  return result;
}
function fixNoPublishConfigOnPrivate(cwd, pkg) {
  delete pkg.publishConfig;
  writeRootPackageJson(cwd, pkg);
  console.log(chalk5.green("  \u2714 Fixed: removed publishConfig from private root package.json"));
}
function checkNoPackageManagerInWorkspaces(cwd, workspaces) {
  const result = emptyResult2();
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH4.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync5(pkgPath, "utf8");
      const pkg = JSON.parse(raw);
      if (pkg.packageManager) {
        result.fixable.push(`${name} (${location}) has a packageManager field \u2014 only the root should define this`);
      }
    } catch {
    }
  }
  return result;
}
function fixNoPackageManagerInWorkspaces(cwd, _pkg, workspaces) {
  for (const { location } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH4.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync5(pkgPath, "utf8");
      const pkg = JSON.parse(raw);
      if (pkg.packageManager) {
        delete pkg.packageManager;
        writeFileSync3(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk5.green(`  \u2714 Fixed: removed packageManager from ${location}/package.json`));
      }
    } catch {
    }
  }
}
function checkWorkspacesFieldPlacement(cwd, pm, workspaces) {
  const result = emptyResult2();
  for (const { location, name } of workspaces) {
    if (pm === "pnpm" ? true : location !== ".") {
      const pkgPath = PATH4.resolve(cwd, location, "package.json");
      try {
        const pkg = JSON.parse(readFileSync5(pkgPath, "utf8"));
        if (pkg.workspaces) {
          const label = location === "." ? "Root" : `${name} (${location})`;
          const reason = pm === "pnpm" ? "pnpm uses pnpm-workspace.yaml instead" : "only the root should define workspaces";
          result.fixable.push(`${label} has a workspaces field \u2014 ${reason}`);
        }
      } catch {
      }
    }
  }
  return result;
}
function fixWorkspacesFieldPlacement(cwd, pm, workspaces) {
  for (const { location } of workspaces) {
    if (pm === "pnpm" ? true : location !== ".") {
      const pkgPath = PATH4.resolve(cwd, location, "package.json");
      try {
        const pkg = JSON.parse(readFileSync5(pkgPath, "utf8"));
        if (pkg.workspaces) {
          delete pkg.workspaces;
          writeFileSync3(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
          const label = location === "." ? "root" : location;
          console.log(chalk5.green(`  \u2714 Fixed: removed workspaces from ${label}/package.json`));
        }
      } catch {
      }
    }
  }
}
function checkWorkspaceGlobCoverage(pkg, cwd, pm, workspaces) {
  const result = emptyResult2();
  const globs = pm === "pnpm" ? readPnpmWorkspaceGlobs(cwd) ?? [] : Array.isArray(pkg.workspaces) ? pkg.workspaces : [];
  if (globs.length === 0) {
    const source = pm === "pnpm" ? "pnpm-workspace.yaml" : "root package.json workspaces";
    result.errors.push(`No workspace globs found in ${source}`);
    return result;
  }
  const matchers = globs.map((glob) => picomatch(glob));
  const isMatch = (location) => matchers.some((m) => m(location));
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    if (!isMatch(location)) {
      const source = pm === "pnpm" ? "pnpm-workspace.yaml" : "root package.json workspaces";
      result.errors.push(`${name} (${location}) is not matched by any glob in ${source}`);
    }
  }
  return result;
}
function logResults(label, result, fix) {
  let errors = 0;
  let fixed = 0;
  for (const error of result.errors) {
    console.log(chalk5.red(`  \u2717 ${error}`));
    errors++;
  }
  for (const fixable of result.fixable) {
    if (fix) {
      fixed++;
    } else {
      console.log(chalk5.red(`  \u2717 ${fixable} (fixable)`));
      errors++;
    }
  }
  for (const warning of result.warnings) {
    console.log(chalk5.yellow(`  \u26A0 ${warning}`));
  }
  if (errors === 0 && fixed === 0 && result.warnings.length === 0) {
    console.log(chalk5.green(`  \u2713 ${label}`));
  }
  return { errors, fixed };
}
function runChecks(entries, cwd, pkg, fix) {
  let totalErrors = 0;
  let totalFixed = 0;
  for (const entry of entries) {
    const result = entry.check();
    const log = logResults(entry.label, result, fix);
    if (fix && entry.fix && result.fixable.length > 0) {
      entry.fix(cwd, pkg);
    }
    totalErrors += log.errors;
    totalFixed += log.fixed;
  }
  return { errors: totalErrors, fixed: totalFixed };
}
function checkVoltaOnlyInRoot(cwd, workspaces) {
  const result = emptyResult2();
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH4.resolve(cwd, location, "package.json");
    try {
      const pkg = JSON.parse(readFileSync5(pkgPath, "utf8"));
      if (pkg.volta) {
        result.fixable.push(`${name} (${location}) has a volta field \u2014 only the root should define this`);
      }
    } catch {
    }
  }
  return result;
}
function fixVoltaOnlyInRoot(cwd, _pkg, workspaces) {
  for (const { location } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH4.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync5(pkgPath, "utf8");
      const pkg = JSON.parse(raw);
      if (pkg.volta) {
        delete pkg.volta;
        writeFileSync3(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk5.green(`  \u2714 Fixed: removed volta from ${location}/package.json`));
      }
    } catch {
    }
  }
}
function isTerminalPackage(pkg) {
  return pkg.private === true;
}
function checkEnginesOnlyInNonTerminal(cwd, workspaces) {
  const result = emptyResult2();
  const rootPkg = JSON.parse(readFileSync5(PATH4.resolve(cwd, "package.json"), "utf8"));
  if (rootPkg.engines) {
    result.fixable.push("Root package.json has engines \u2014 terminal packages should not declare engines (use volta instead)");
  }
  for (const { location, name } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH4.resolve(cwd, location, "package.json");
    try {
      const pkg = JSON.parse(readFileSync5(pkgPath, "utf8"));
      if (isTerminalPackage(pkg) && pkg.engines) {
        result.fixable.push(`${name} (${location}) is terminal (private) but has engines \u2014 terminal packages should not declare engines`);
      }
      if (!isTerminalPackage(pkg) && !pkg.engines) {
        result.fixable.push(`${name} (${location}) is a library but has no engines field`);
      }
    } catch {
    }
  }
  return result;
}
function fixEnginesOnlyInNonTerminal(cwd, _pkg, workspaces) {
  const rootPath = PATH4.resolve(cwd, "package.json");
  const rootRaw = readFileSync5(rootPath, "utf8");
  const rootPkg = JSON.parse(rootRaw);
  if (rootPkg.engines) {
    delete rootPkg.engines;
    writeFileSync3(rootPath, `${JSON.stringify(rootPkg, null, 2)}
`, "utf8");
    console.log(chalk5.green("  \u2714 Fixed: removed engines from root package.json"));
  }
  const enginesTemplate = resolveEnginesTemplate(cwd, workspaces);
  for (const { location } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH4.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync5(pkgPath, "utf8");
      const pkg = JSON.parse(raw);
      if (isTerminalPackage(pkg) && pkg.engines) {
        delete pkg.engines;
        writeFileSync3(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk5.green(`  \u2714 Fixed: removed engines from ${location}/package.json`));
      }
      if (!isTerminalPackage(pkg) && !pkg.engines && enginesTemplate) {
        pkg.engines = enginesTemplate;
        writeFileSync3(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk5.green(`  \u2714 Fixed: added engines to ${location}/package.json`));
      }
    } catch {
    }
  }
}
function resolveEnginesTemplate(cwd, workspaces) {
  for (const { location } of workspaces) {
    if (location === ".") continue;
    try {
      const pkg = JSON.parse(readFileSync5(PATH4.resolve(cwd, location, "package.json"), "utf8"));
      if (!isTerminalPackage(pkg) && pkg.engines) {
        return pkg.engines;
      }
    } catch {
    }
  }
  return void 0;
}
function checkVersionsIncludeLts(cwd, workspaces) {
  const result = emptyResult2();
  const toolVersions = {
    node: latestVersions.node,
    npm: latestVersions.npm,
    pnpm: latestVersions.pnpm,
    yarn: latestVersions.yarn
  };
  for (const { location, name } of workspaces) {
    const pkgPath = location === "." ? PATH4.resolve(cwd, "package.json") : PATH4.resolve(cwd, location, "package.json");
    try {
      const pkg = JSON.parse(readFileSync5(pkgPath, "utf8"));
      const label = location === "." ? "root" : `${name} (${location})`;
      const engines = pkg.engines;
      if (engines) {
        for (const [tool, range] of Object.entries(engines)) {
          const latest = toolVersions[tool];
          if (latest && !semver2.satisfies(latest, range)) {
            result.errors.push(
              `${label} engines.${tool} "${range}" does not include latest ${tool === "node" ? "LTS " : ""}version ${latest}`
            );
          }
        }
      }
      const volta = pkg.volta;
      if (volta) {
        for (const [tool, pinnedVersion] of Object.entries(volta)) {
          const latest = toolVersions[tool];
          if (latest && semver2.lt(pinnedVersion, latest)) {
            result.warnings.push(
              `${label} volta.${tool} "${pinnedVersion}" is older than latest ${tool === "node" ? "LTS " : ""}version ${latest}`
            );
          }
        }
      }
    } catch {
    }
  }
  return result;
}
function logSummary(errors, fixed) {
  if (fixed > 0) {
    console.log(chalk5.green(`
  Fixed ${fixed} issue(s)`));
  }
  if (errors > 0) {
    console.log(chalk5.red(`
  ${errors} error(s) found`));
  } else if (fixed === 0) {
    console.log(chalk5.green("\n  All checks passed"));
  }
}
function packageLintMonorepo(fix = false) {
  const cwd = INIT_CWD();
  let pkg;
  try {
    pkg = readRootPackageJson2(cwd);
  } catch {
    console.error(chalk5.red("Could not read package.json"));
    return 1;
  }
  if (!isMonorepo(pkg, cwd)) {
    console.log(chalk5.gray("Not a monorepo \u2014 skipping repo lint checks"));
    return 0;
  }
  console.log(chalk5.green("Repo Lint"));
  const pm = detectPackageManager();
  const workspaces = getPackageManager().listWorkspaces();
  const internalDepCheck = pm === "pnpm" ? {
    check: () => checkWorkspaceProtocol(cwd, workspaces),
    fix: () => fixWorkspaceProtocol(cwd, workspaces),
    label: "Internal deps/devDeps use workspace: protocol"
  } : {
    check: () => checkInternalDepVersions(cwd, workspaces),
    fix: () => fixInternalDepVersions(cwd, workspaces),
    label: "Internal deps/devDeps use correct version ranges"
  };
  const checks = [
    {
      check: () => checkRootPrivate(pkg),
      fix: fixRootPrivate,
      label: "Root package is private"
    },
    {
      check: () => checkNoPublishConfigOnPrivate(pkg),
      fix: fixNoPublishConfigOnPrivate,
      label: "No publishConfig on private root"
    },
    { check: () => checkPackagesFolder(workspaces), label: "All packages are in packages/ folder" },
    {
      check: () => checkWorkspacesFieldPlacement(cwd, pm, workspaces),
      fix: () => fixWorkspacesFieldPlacement(cwd, pm, workspaces),
      label: pm === "pnpm" ? "No workspaces field in package.json (use pnpm-workspace.yaml)" : "Workspaces field only in root package.json"
    },
    {
      check: () => checkWorkspaceGlobCoverage(pkg, cwd, pm, workspaces),
      label: "Workspace globs cover all packages"
    },
    {
      check: () => checkNoPackageManagerInWorkspaces(cwd, workspaces),
      fix: () => fixNoPackageManagerInWorkspaces(cwd, pkg, workspaces),
      label: "No packageManager in workspace packages"
    },
    {
      check: () => checkVoltaOnlyInRoot(cwd, workspaces),
      fix: () => fixVoltaOnlyInRoot(cwd, pkg, workspaces),
      label: "Volta only in root package.json"
    },
    {
      check: () => checkEnginesOnlyInNonTerminal(cwd, workspaces),
      fix: () => fixEnginesOnlyInNonTerminal(cwd, pkg, workspaces),
      label: "Engines only in non-terminal (library) packages"
    },
    {
      check: () => checkVersionsIncludeLts(cwd, workspaces),
      label: "Engine/volta versions include latest LTS"
    },
    {
      check: () => checkVersionConsistency(cwd, pkg, workspaces),
      fix: () => fixVersionConsistency(cwd, pkg, writeRootPackageJson, workspaces),
      label: "Consistent versions across packages"
    },
    internalDepCheck,
    {
      check: () => checkInternalPeerVersions(cwd, workspaces),
      fix: () => fixInternalPeerVersions(cwd, workspaces),
      label: "Internal peerDeps use semver ranges (not workspace: protocol)"
    },
    {
      check: () => checkPnpmReleaseAgeExcludes(cwd, pm),
      fix: () => fixPnpmReleaseAgeExcludes(cwd),
      label: "pnpm-workspace.yaml excludes @xylabs/* and @xyo-network/* from minimumReleaseAge"
    }
  ];
  const { errors, fixed } = runChecks(checks, cwd, pkg, fix);
  logSummary(errors, fixed);
  if (fix && fixed > 0) runInstall();
  return errors > 0 ? 1 : 0;
}

// src/actions/packman/convertToBun.ts
import {
  existsSync as existsSync6,
  readFileSync as readFileSync8,
  rmSync,
  writeFileSync as writeFileSync6
} from "node:fs";
import PATH6 from "node:path";
import chalk8 from "chalk";

// src/actions/packman/rewriteScripts.ts
function xyCommand(pm) {
  switch (pm) {
    case "bun": {
      return "bun run xy";
    }
    case "npm": {
      return "npm exec -- xy";
    }
    case "pnpm": {
      return "pnpm xy";
    }
    default: {
      return "yarn xy";
    }
  }
}
function rootRunCommand(pm, script, rest = "") {
  const suffix = rest.trim() ? ` ${rest.trim()}` : "";
  return `${pm} run ${script}${suffix}`;
}
function addCommand(pm) {
  switch (pm) {
    case "bun": {
      return "bun add";
    }
    case "npm": {
      return "npm install";
    }
    case "pnpm": {
      return "pnpm add";
    }
    default: {
      return "yarn add";
    }
  }
}
function removeCommand(pm) {
  switch (pm) {
    case "bun": {
      return "bun remove";
    }
    case "npm": {
      return "npm uninstall";
    }
    case "pnpm": {
      return "pnpm remove";
    }
    default: {
      return "yarn remove";
    }
  }
}
function installCommand(pm) {
  return `${pm} install`;
}
function outdatedCommand(pm) {
  return `${pm} outdated`;
}
function dedupeCommand(pm) {
  return pm === "npm" ? "npm dedupe" : `${pm} dedupe`;
}
function trimRest(rest) {
  if (!rest) return "";
  const normalized = rest.trim();
  return normalized ? ` ${normalized}` : "";
}
function workspaceRunCommand(pm, pkg, script, rest = "") {
  const suffix = trimRest(rest);
  switch (pm) {
    case "bun": {
      return `bun run --filter ${pkg} ${script}${suffix}`;
    }
    case "npm": {
      return `npm run ${script} --workspace=${pkg}${suffix}`;
    }
    case "pnpm": {
      return `pnpm --filter ${pkg} run ${script}${suffix}`;
    }
    default: {
      return `yarn workspace ${pkg} run ${script}${suffix}`;
    }
  }
}
function workspaceRunAllCommand(pm, script, rest = "") {
  const suffix = trimRest(rest);
  switch (pm) {
    case "bun": {
      return `bun run --workspaces --if-present ${script}${suffix}`;
    }
    case "npm": {
      return `npm run ${script} --workspaces --if-present${suffix}`;
    }
    case "pnpm": {
      return `pnpm -r run ${script}${suffix}`;
    }
    default: {
      return `yarn workspaces foreach -Apt run ${script}${suffix}`;
    }
  }
}
function normalizeWorkspaceCommands(script, target) {
  let result = script;
  result = result.replaceAll(/\byarn workspace (\S+) run (\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\byarn workspace (\S+) (package-\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bpnpm --filter (\S+) run (\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bpnpm --filter (\S+) (package-\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bnpm run (\S+) --workspace(?:=|\s+)(\S+)(?:\s+(.*))?$/g, (_, command, pkg, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bnpm --workspace(?:=|\s+)(\S+) run (\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bnpm run (\S+) -w (\S+)(?:\s+(.*))?$/g, (_, command, pkg, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bbun run --filter (\S+) (\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\bbun --filter (\S+) run (\S+)(?:\s+(.*))?$/g, (_, pkg, command, rest) => workspaceRunCommand(target, pkg, command, rest));
  result = result.replaceAll(/\byarn workspaces foreach\s+(?:[^\s]+\s+)*run (\S+)(?:\s+(.*))?$/g, (_, command, rest) => workspaceRunAllCommand(target, command, rest));
  result = result.replaceAll(/\bpnpm -r(?:\s+[^\s]+)* run (\S+)(?:\s+(.*))?$/g, (_, command, rest) => workspaceRunAllCommand(target, command, rest));
  result = result.replaceAll(/\bnpm run (\S+) --workspaces(?: --if-present)?(?:\s+(.*))?$/g, (_, command, rest) => workspaceRunAllCommand(target, command, rest));
  result = result.replaceAll(/\bbun run(?:\s+--[^\s]+)* --workspaces(?: --if-present)? (\S+)(?:\s+(.*))?$/g, (_, command, rest) => workspaceRunAllCommand(target, command, rest));
  return result;
}
function normalizeRootRunCommands(script, target) {
  let result = script;
  result = result.replaceAll(/\byarn run (\S+)(?:\s+(.*))?$/g, (_, command, rest) => rootRunCommand(target, command, rest));
  result = result.replaceAll(/\bpnpm run (\S+)(?:\s+(.*))?$/g, (_, command, rest) => rootRunCommand(target, command, rest));
  result = result.replaceAll(/\bnpm run (\S+)(?!\s+(?:--workspace(?:=|\s)|-w\s|--workspaces)\b)(?:\s+(.*))?$/g, (_, command, rest) => rootRunCommand(target, command, rest));
  result = result.replaceAll(/\bbun run (\S+)(?!\s+(?:--filter|--workspaces)\b)(?:\s+(.*))?$/g, (_, command, rest) => rootRunCommand(target, command, rest));
  return result;
}
function normalizeXyCommands(script, target) {
  return script.replaceAll(/\byarn xy\b/g, xyCommand(target)).replaceAll(/\bpnpm xy\b/g, xyCommand(target)).replaceAll(/\bnpm exec(?: --)? xy\b/g, xyCommand(target)).replaceAll(/\bnpx(?: --no-install)? xy\b/g, xyCommand(target)).replaceAll(/\bbun run xy\b/g, xyCommand(target)).replaceAll(/\bbun x xy\b/g, xyCommand(target));
}
function rewriteScript(script, target) {
  let result = normalizeWorkspaceCommands(script, target);
  result = normalizeRootRunCommands(result, target);
  result = normalizeXyCommands(result, target);
  result = result.replaceAll(/\byarn add\b/g, addCommand(target));
  result = result.replaceAll(/\bpnpm add\b/g, addCommand(target));
  result = result.replaceAll(/\bbun add\b/g, addCommand(target));
  result = result.replaceAll(/\byarn remove\b/g, removeCommand(target));
  result = result.replaceAll(/\bpnpm remove\b/g, removeCommand(target));
  result = result.replaceAll(/\bbun remove\b/g, removeCommand(target));
  result = result.replaceAll(/\bnpm uninstall\b/g, removeCommand(target));
  result = result.replaceAll(/\byarn install\b/g, installCommand(target));
  result = result.replaceAll(/\bpnpm install\b/g, installCommand(target));
  result = result.replaceAll(/\bbun install\b/g, installCommand(target));
  result = result.replaceAll(/\bnpm install\b/g, installCommand(target));
  result = result.replaceAll(/\byarn dedupe\b/g, dedupeCommand(target));
  result = result.replaceAll(/\bpnpm dedupe\b/g, dedupeCommand(target));
  result = result.replaceAll(/\bnpm dedupe\b/g, dedupeCommand(target));
  result = result.replaceAll(/\byarn outdated\b/g, outdatedCommand(target));
  result = result.replaceAll(/\bpnpm outdated\b/g, outdatedCommand(target));
  result = result.replaceAll(/\bbun outdated\b/g, outdatedCommand(target));
  result = result.replaceAll(/\bnpm outdated\b/g, outdatedCommand(target));
  return result;
}
function rewriteScriptsInPackageJson(pkg, target) {
  const scripts = pkg.scripts;
  if (!scripts) return pkg;
  const rewritten = {};
  for (const [name, script] of Object.entries(scripts)) {
    rewritten[name] = rewriteScript(script, target);
  }
  return { ...pkg, scripts: rewritten };
}

// src/actions/packman/rewriteSourceImports.ts
import {
  existsSync as existsSync4,
  readFileSync as readFileSync6,
  writeFileSync as writeFileSync4
} from "node:fs";
import chalk6 from "chalk";
import { globSync as globSync2 } from "glob";
var SWAPS = [
  ["@xylabs/toolchain", "@xylabs/toolchain"],
  ["@xylabs/toolchain", "@xylabs/toolchain"]
];
var SOURCE_GLOBS = [
  "**/*.ts",
  "**/*.tsx",
  "**/*.mts",
  "**/*.cts",
  "**/*.js",
  "**/*.mjs"
];
var IGNORE_PATTERNS = [
  "**/node_modules/**",
  "**/dist/**",
  "**/build/**",
  "**/.yarn/**"
];
function rewriteSourceImports(cwd) {
  const files = globSync2(SOURCE_GLOBS, {
    cwd,
    absolute: true,
    ignore: IGNORE_PATTERNS
  });
  let count = 0;
  for (const file of files) {
    if (!existsSync4(file)) continue;
    const original = readFileSync6(file, "utf8");
    let content = original;
    for (const [from, to] of SWAPS) {
      content = content.replaceAll(from, to);
    }
    if (content !== original) {
      writeFileSync4(file, content, "utf8");
      count++;
    }
  }
  if (count > 0) {
    console.log(chalk6.green(`  Rewrote toolchain imports in ${count} source file(s)`));
  }
}

// src/actions/packman/swapTsScriptsDependency.ts
import {
  existsSync as existsSync5,
  readFileSync as readFileSync7,
  writeFileSync as writeFileSync5
} from "node:fs";
import PATH5 from "node:path";
import chalk7 from "chalk";
var TARGET_PACKAGE = "@xylabs/toolchain";
var managedPackages = [
  "@xylabs/toolchain",
  "@xylabs/toolchain",
  "@xylabs/toolchain"
];
function setToolchainInPackageJson(pkgPath, range) {
  if (!existsSync5(pkgPath)) return false;
  const raw = readFileSync7(pkgPath, "utf8");
  const pkg = JSON.parse(raw);
  let changed = false;
  let foundInDepsField;
  for (const depField of ["dependencies", "devDependencies"]) {
    const deps = pkg[depField];
    if (!deps) continue;
    let removed = false;
    for (const name of managedPackages) {
      if (deps[name]) {
        delete deps[name];
        removed = true;
        changed = true;
      }
    }
    if (removed) {
      foundInDepsField = depField;
      deps[TARGET_PACKAGE] = range;
    }
  }
  if (foundInDepsField) {
    const targetDeps = pkg[foundInDepsField];
    if (targetDeps[TARGET_PACKAGE] !== range) {
      targetDeps[TARGET_PACKAGE] = range;
      changed = true;
    }
  } else {
    const devDeps = pkg.devDependencies ?? {};
    if (devDeps[TARGET_PACKAGE] !== range) {
      devDeps[TARGET_PACKAGE] = range;
      pkg.devDependencies = devDeps;
      changed = true;
    }
  }
  if (changed) {
    writeFileSync5(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
  }
  return changed;
}
function swapTsScriptsDependency(cwd, workspacePackageJsonPaths) {
  const range = bundledToolchainRange();
  let count = 0;
  if (setToolchainInPackageJson(PATH5.join(cwd, "package.json"), range)) {
    count++;
  }
  for (const pkgPath of workspacePackageJsonPaths) {
    const fullPath = PATH5.resolve(cwd, pkgPath, "package.json");
    if (setToolchainInPackageJson(fullPath, range)) {
      count++;
    }
  }
  if (count > 0) {
    console.log(chalk7.green(`  Set toolchain dependency to ${TARGET_PACKAGE}@${range} in ${count} package(s)`));
  }
}

// src/actions/packman/convertToBun.ts
var BUN_VERSION = "1.3.3";
function updateRootPackageJson(cwd) {
  const pkgPath = PATH6.join(cwd, "package.json");
  const pkg = JSON.parse(readFileSync8(pkgPath, "utf8"));
  pkg.packageManager = `bun@${BUN_VERSION}`;
  const updated = rewriteScriptsInPackageJson(pkg, "bun");
  writeFileSync6(pkgPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
  console.log(chalk8.green("  Updated root package.json"));
}
function deleteArtifacts(cwd) {
  for (const relativePath of ["package-lock.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", "yarn.lock", ".yarnrc.yml"]) {
    const fullPath = PATH6.join(cwd, relativePath);
    if (existsSync6(fullPath)) {
      rmSync(fullPath, { force: true, recursive: true });
      console.log(chalk8.gray(`  Deleted ${relativePath}`));
    }
  }
  const yarnDir = PATH6.join(cwd, ".yarn");
  if (existsSync6(yarnDir)) {
    rmSync(yarnDir, { force: true, recursive: true });
    console.log(chalk8.gray("  Deleted .yarn/"));
  }
}
function convertToBun(cwd, workspacePackageJsonPaths) {
  console.log(chalk8.blue("\nConverting to bun...\n"));
  updateRootPackageJson(cwd);
  for (const pkgPath of workspacePackageJsonPaths) {
    const fullPath = PATH6.resolve(cwd, pkgPath, "package.json");
    if (!existsSync6(fullPath)) continue;
    const pkg = JSON.parse(readFileSync8(fullPath, "utf8"));
    const updated = rewriteScriptsInPackageJson(pkg, "bun");
    if (JSON.stringify(pkg) !== JSON.stringify(updated)) {
      writeFileSync6(fullPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
    }
  }
  console.log(chalk8.green(`  Rewrote scripts in ${workspacePackageJsonPaths.length} workspace package(s)`));
  swapTsScriptsDependency(cwd, workspacePackageJsonPaths);
  rewriteSourceImports(cwd);
  deleteArtifacts(cwd);
  console.log(chalk8.blue("\nRunning bun install..."));
  const install = spawnPackageManagerSync("bun", ["install"], {
    context: { cwd, operation: "Convert repo to bun and install dependencies" },
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (install.status !== 0) {
    console.error(chalk8.red("bun install failed"));
    return 1;
  }
  console.log(chalk8.blue("\nConversion complete.\n"));
  return 0;
}

// src/actions/packman/convertToNpm.ts
import {
  existsSync as existsSync7,
  readFileSync as readFileSync9,
  rmSync as rmSync2,
  writeFileSync as writeFileSync7
} from "node:fs";
import PATH7 from "node:path";
import chalk9 from "chalk";
var NPM_VERSION = "10.9.4";
function readWorkspacePatterns2(cwd) {
  const pkgPath = PATH7.join(cwd, "package.json");
  const pkg = JSON.parse(readFileSync9(pkgPath, "utf8"));
  return pkg.workspaces ?? [];
}
function updateRootPackageJson2(cwd) {
  const pkgPath = PATH7.join(cwd, "package.json");
  const pkg = JSON.parse(readFileSync9(pkgPath, "utf8"));
  pkg.packageManager = `npm@${NPM_VERSION}`;
  const updated = rewriteScriptsInPackageJson(pkg, "npm");
  writeFileSync7(pkgPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
  console.log(chalk9.green("  Updated root package.json"));
}
function deleteArtifacts2(cwd) {
  for (const relativePath of ["bun.lock", "bun.lockb", "pnpm-lock.yaml", "pnpm-workspace.yaml", "yarn.lock", ".yarnrc.yml"]) {
    const fullPath = PATH7.join(cwd, relativePath);
    if (existsSync7(fullPath)) {
      rmSync2(fullPath, { force: true, recursive: true });
      console.log(chalk9.gray(`  Deleted ${relativePath}`));
    }
  }
  const yarnDir = PATH7.join(cwd, ".yarn");
  if (existsSync7(yarnDir)) {
    rmSync2(yarnDir, { force: true, recursive: true });
    console.log(chalk9.gray("  Deleted .yarn/"));
  }
}
function convertToNpm(cwd, workspacePackageJsonPaths) {
  console.log(chalk9.blue("\nConverting to npm...\n"));
  const workspacePatterns = readWorkspacePatterns2(cwd);
  if (workspacePatterns.length === 0) {
    console.warn(chalk9.yellow("  No root package.json workspaces found; npm monorepo support relies on the workspaces field"));
  }
  updateRootPackageJson2(cwd);
  for (const pkgPath of workspacePackageJsonPaths) {
    const fullPath = PATH7.resolve(cwd, pkgPath, "package.json");
    if (!existsSync7(fullPath)) continue;
    const pkg = JSON.parse(readFileSync9(fullPath, "utf8"));
    const updated = rewriteScriptsInPackageJson(pkg, "npm");
    if (JSON.stringify(pkg) !== JSON.stringify(updated)) {
      writeFileSync7(fullPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
    }
  }
  console.log(chalk9.green(`  Rewrote scripts in ${workspacePackageJsonPaths.length} workspace package(s)`));
  swapTsScriptsDependency(cwd, workspacePackageJsonPaths);
  rewriteSourceImports(cwd);
  deleteArtifacts2(cwd);
  console.log(chalk9.blue("\nRunning npm install..."));
  const install = spawnPackageManagerSync("npm", ["install"], {
    context: { cwd, operation: "Convert repo to npm and install dependencies" },
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (install.status !== 0) {
    console.error(chalk9.red("npm install failed"));
    return 1;
  }
  console.log(chalk9.blue("\nConversion complete.\n"));
  return 0;
}

// src/actions/packman/convertToPnpm.ts
import {
  existsSync as existsSync8,
  mkdirSync,
  readFileSync as readFileSync10,
  rmSync as rmSync3,
  writeFileSync as writeFileSync8
} from "node:fs";
import PATH8 from "node:path";
import chalk10 from "chalk";
function createPnpmWorkspaceYaml(cwd, workspacePatterns) {
  const lines = ["packages:"];
  for (const pattern of workspacePatterns) {
    lines.push(`  - '${pattern}'`);
  }
  writeFileSync8(PATH8.join(cwd, "pnpm-workspace.yaml"), lines.join("\n") + "\n", "utf8");
  console.log(chalk10.green("  Created pnpm-workspace.yaml"));
}
function readPnpmWorkspacePatterns2(cwd) {
  const wsPath = PATH8.join(cwd, "pnpm-workspace.yaml");
  if (!existsSync8(wsPath)) return [];
  const content = readFileSync10(wsPath, "utf8");
  const patterns = [];
  const lines = content.split("\n");
  let inPackages = false;
  for (const line of lines) {
    if (line.trim() === "packages:") {
      inPackages = true;
      continue;
    }
    if (inPackages && /^\s+-\s+/.test(line)) {
      const pattern = line.replace(/^\s+-\s+/, "").replaceAll(/['"]/g, "").trim();
      if (pattern) patterns.push(pattern);
    } else if (inPackages && !/^\s/.test(line) && line.trim()) {
      inPackages = false;
    }
  }
  return patterns;
}
function updateRootPackageJson3(cwd, pnpmVersion) {
  const pkgPath = PATH8.join(cwd, "package.json");
  const pkg = JSON.parse(readFileSync10(pkgPath, "utf8"));
  const workspacePatterns = pkg.workspaces ?? readPnpmWorkspacePatterns2(cwd);
  delete pkg.workspaces;
  pkg.packageManager = `pnpm@${pnpmVersion}`;
  const updated = rewriteScriptsInPackageJson(pkg, "pnpm");
  writeFileSync8(pkgPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
  console.log(chalk10.green("  Updated root package.json"));
  return workspacePatterns;
}
function updateGitignore(cwd) {
  const gitignorePath = PATH8.join(cwd, ".gitignore");
  if (!existsSync8(gitignorePath)) return;
  let content = readFileSync10(gitignorePath, "utf8");
  const yarnLines = [
    ".pnp.*",
    ".pnp",
    ".yarn/*",
    "!.yarn/patches",
    "!.yarn/plugins",
    "!.yarn/releases",
    "!.yarn/sdks",
    "!.yarn/versions"
  ];
  for (const line of yarnLines) {
    content = content.replaceAll(new RegExp(String.raw`^${line.replaceAll(".", String.raw`\.`).replaceAll("*", String.raw`\*`).replaceAll("!", String.raw`\!`)}\s*$`, "gm"), "");
  }
  content = content.replaceAll(/\n{3,}/g, "\n\n");
  writeFileSync8(gitignorePath, content, "utf8");
  console.log(chalk10.green("  Updated .gitignore"));
}
function deleteYarnArtifacts(cwd) {
  const yarnLock = PATH8.join(cwd, "yarn.lock");
  const yarnrc = PATH8.join(cwd, ".yarnrc.yml");
  const yarnDir = PATH8.join(cwd, ".yarn");
  if (existsSync8(yarnLock)) {
    rmSync3(yarnLock);
    console.log(chalk10.gray("  Deleted yarn.lock"));
  }
  if (existsSync8(yarnrc)) {
    rmSync3(yarnrc);
    console.log(chalk10.gray("  Deleted .yarnrc.yml"));
  }
  if (existsSync8(yarnDir)) {
    rmSync3(yarnDir, { force: true, recursive: true });
    console.log(chalk10.gray("  Deleted .yarn/"));
  }
}
function createNpmrc(cwd) {
  const npmrcPath = PATH8.join(cwd, ".npmrc");
  if (existsSync8(npmrcPath)) return;
  mkdirSync(PATH8.dirname(npmrcPath), { recursive: true });
  writeFileSync8(npmrcPath, "", "utf8");
  console.log(chalk10.green("  Created .npmrc"));
}
async function resolvePnpmVersion() {
  const latest = await fetchLatestPackageVersion("pnpm");
  if (latest) return latest;
  console.warn(chalk10.yellow(`  Unable to reach npm for pnpm latest; falling back to bundled pnpm version ${latestVersions.pnpm}`));
  return latestVersions.pnpm;
}
async function convertToPnpm(cwd, workspacePackageJsonPaths) {
  console.log(chalk10.blue("\nConverting to pnpm...\n"));
  const pnpmVersion = await resolvePnpmVersion();
  const workspacePatterns = updateRootPackageJson3(cwd, pnpmVersion);
  createPnpmWorkspaceYaml(cwd, workspacePatterns);
  for (const pkgPath of workspacePackageJsonPaths) {
    const fullPath = PATH8.resolve(cwd, pkgPath, "package.json");
    if (!existsSync8(fullPath)) continue;
    const pkg = JSON.parse(readFileSync10(fullPath, "utf8"));
    const updated = rewriteScriptsInPackageJson(pkg, "pnpm");
    if (JSON.stringify(pkg) !== JSON.stringify(updated)) {
      writeFileSync8(fullPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
    }
  }
  console.log(chalk10.green(`  Rewrote scripts in ${workspacePackageJsonPaths.length} workspace package(s)`));
  updateGitignore(cwd);
  createNpmrc(cwd);
  swapTsScriptsDependency(cwd, workspacePackageJsonPaths);
  rewriteSourceImports(cwd);
  deleteYarnArtifacts(cwd);
  console.log(chalk10.blue("\nRunning pnpm install..."));
  const install = spawnPackageManagerSync("pnpm", ["install"], {
    context: { cwd, operation: "Convert repo to pnpm and install dependencies" },
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (install.status !== 0) {
    console.error(chalk10.red("pnpm install failed"));
    return 1;
  }
  console.log(chalk10.blue("\nConversion complete.\n"));
  return 0;
}

// src/actions/packman/convertToYarn.ts
import {
  existsSync as existsSync9,
  readFileSync as readFileSync11,
  rmSync as rmSync4,
  writeFileSync as writeFileSync9
} from "node:fs";
import PATH9 from "node:path";
import chalk11 from "chalk";
var YARN_VERSION = "4.13.0";
var YARNRC_TEMPLATE = `compressionLevel: mixed

enableGlobalCache: true

enableInlineBuilds: true

nmHoistingLimits: none

nodeLinker: node-modules
`;
var YARN_GITIGNORE_ENTRIES = `
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
`;
function readPnpmWorkspacePatterns3(cwd) {
  const wsPath = PATH9.join(cwd, "pnpm-workspace.yaml");
  if (!existsSync9(wsPath)) return [];
  const content = readFileSync11(wsPath, "utf8");
  const patterns = [];
  const lines = content.split("\n");
  let inPackages = false;
  for (const line of lines) {
    if (line.trim() === "packages:") {
      inPackages = true;
      continue;
    }
    if (inPackages && /^\s+-\s+/.test(line)) {
      const pattern = line.replace(/^\s+-\s+/, "").replaceAll(/['"]/g, "").trim();
      if (pattern) patterns.push(pattern);
    } else if (inPackages && !/^\s/.test(line) && line.trim()) {
      inPackages = false;
    }
  }
  return patterns;
}
function updateRootPackageJson4(cwd, workspacePatterns) {
  const pkgPath = PATH9.join(cwd, "package.json");
  const pkg = JSON.parse(readFileSync11(pkgPath, "utf8"));
  pkg.workspaces = workspacePatterns;
  pkg.packageManager = `yarn@${YARN_VERSION}`;
  const updated = rewriteScriptsInPackageJson(pkg, "yarn");
  writeFileSync9(pkgPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
  console.log(chalk11.green("  Updated root package.json"));
}
function updateGitignore2(cwd) {
  const gitignorePath = PATH9.join(cwd, ".gitignore");
  let content = existsSync9(gitignorePath) ? readFileSync11(gitignorePath, "utf8") : "";
  if (!content.includes(".yarn/*")) {
    content = content.trimEnd() + "\n" + YARN_GITIGNORE_ENTRIES;
  }
  writeFileSync9(gitignorePath, content, "utf8");
  console.log(chalk11.green("  Updated .gitignore"));
}
function deletePnpmArtifacts(cwd) {
  const lockfile = PATH9.join(cwd, "pnpm-lock.yaml");
  const workspaceYaml = PATH9.join(cwd, "pnpm-workspace.yaml");
  const npmrc = PATH9.join(cwd, ".npmrc");
  if (existsSync9(lockfile)) {
    rmSync4(lockfile);
    console.log(chalk11.gray("  Deleted pnpm-lock.yaml"));
  }
  if (existsSync9(workspaceYaml)) {
    rmSync4(workspaceYaml);
    console.log(chalk11.gray("  Deleted pnpm-workspace.yaml"));
  }
  if (existsSync9(npmrc)) {
    const content = readFileSync11(npmrc, "utf8");
    if (content.trim() === "" || content.includes("shamefully-hoist") || content.includes("node-linker")) {
      rmSync4(npmrc);
      console.log(chalk11.gray("  Deleted .npmrc"));
    }
  }
}
function createYarnrc(cwd) {
  const yarnrcPath = PATH9.join(cwd, ".yarnrc.yml");
  if (existsSync9(yarnrcPath)) return;
  writeFileSync9(yarnrcPath, YARNRC_TEMPLATE, "utf8");
  console.log(chalk11.green("  Created .yarnrc.yml"));
}
function readWorkspacePatternsFromPackageJson2(cwd) {
  const pkgPath = PATH9.join(cwd, "package.json");
  if (!existsSync9(pkgPath)) return [];
  const pkg = JSON.parse(readFileSync11(pkgPath, "utf8"));
  return pkg.workspaces ?? [];
}
function convertToYarn(cwd, workspacePackageJsonPaths) {
  console.log(chalk11.blue("\nConverting to yarn...\n"));
  const workspacePatterns = readPnpmWorkspacePatterns3(cwd);
  if (workspacePatterns.length === 0) {
    const fromPkg = readWorkspacePatternsFromPackageJson2(cwd);
    if (fromPkg.length > 0) {
      workspacePatterns.push(...fromPkg);
    } else {
      console.warn(chalk11.yellow("  No workspace patterns found"));
    }
  }
  updateRootPackageJson4(cwd, workspacePatterns);
  for (const pkgPath of workspacePackageJsonPaths) {
    const fullPath = PATH9.resolve(cwd, pkgPath, "package.json");
    if (!existsSync9(fullPath)) continue;
    const pkg = JSON.parse(readFileSync11(fullPath, "utf8"));
    const updated = rewriteScriptsInPackageJson(pkg, "yarn");
    if (JSON.stringify(pkg) !== JSON.stringify(updated)) {
      writeFileSync9(fullPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
    }
  }
  console.log(chalk11.green(`  Rewrote scripts in ${workspacePackageJsonPaths.length} workspace package(s)`));
  updateGitignore2(cwd);
  createYarnrc(cwd);
  swapTsScriptsDependency(cwd, workspacePackageJsonPaths);
  rewriteSourceImports(cwd);
  deletePnpmArtifacts(cwd);
  console.log(chalk11.blue("\nRunning yarn install..."));
  const install = spawnPackageManagerSync("yarn", ["install"], {
    context: { cwd, operation: "Convert repo to yarn and install dependencies" },
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (install.status !== 0) {
    console.error(chalk11.red("yarn install failed"));
    return 1;
  }
  console.log(chalk11.blue("\nConversion complete.\n"));
  return 0;
}

// src/actions/packman/convert.ts
function detectCurrentPM(cwd) {
  const packageManager = detectPackageManagerFromPackageJson(cwd);
  if (packageManager === "bun" || packageManager === "npm" || packageManager === "pnpm" || packageManager === "yarn") {
    return packageManager;
  }
  if (existsSync10(PATH10.join(cwd, "pnpm-lock.yaml")) || existsSync10(PATH10.join(cwd, "pnpm-workspace.yaml"))) {
    return "pnpm";
  }
  if (existsSync10(PATH10.join(cwd, "bun.lock")) || existsSync10(PATH10.join(cwd, "bun.lockb"))) {
    return "bun";
  }
  if (existsSync10(PATH10.join(cwd, "yarn.lock")) || existsSync10(PATH10.join(cwd, ".yarnrc.yml"))) {
    return "yarn";
  }
  if (existsSync10(PATH10.join(cwd, "package-lock.json")) || existsSync10(PATH10.join(cwd, "npm-shrinkwrap.json"))) {
    return "npm";
  }
  return "unknown";
}
function findWorkspacePackagePaths(cwd) {
  const patterns = readWorkspacePatterns(cwd);
  const dirs = [];
  for (const pattern of patterns) {
    const resolved = resolveWorkspaceGlob(cwd, pattern);
    dirs.push(...resolved);
  }
  return dirs;
}
function resolveWorkspaceGlob(cwd, pattern) {
  const parts = pattern.split("/");
  return walkGlob(cwd, parts, "");
}
function walkGlob(basePath, parts, currentPath) {
  if (parts.length === 0) {
    const fullPath = PATH10.join(basePath, currentPath);
    if (existsSync10(PATH10.join(fullPath, "package.json"))) {
      return [currentPath];
    }
    return [];
  }
  const [part, ...rest] = parts;
  const dirPath = PATH10.join(basePath, currentPath);
  if (!existsSync10(dirPath) || !statSync(dirPath).isDirectory()) {
    return [];
  }
  if (part === "*" || part === "**") {
    const entries = readdirSync(dirPath, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules" && e.name !== "dist");
    const results = [];
    if (part === "**") {
      results.push(...walkGlob(basePath, rest, currentPath));
    }
    for (const entry of entries) {
      const subPath2 = currentPath ? `${currentPath}/${entry.name}` : entry.name;
      if (part === "**") {
        results.push(
          ...walkGlob(basePath, rest, subPath2),
          ...walkGlob(basePath, parts, subPath2)
        );
      } else {
        results.push(...walkGlob(basePath, rest, subPath2));
      }
    }
    return results;
  }
  const subPath = currentPath ? `${currentPath}/${part}` : part;
  return walkGlob(basePath, rest, subPath);
}
async function convert({ target, verbose }) {
  const validTargets = ["bun", "npm", "pnpm", "yarn"];
  if (!validTargets.includes(target)) {
    console.error(chalk12.red(`Invalid target "${target}". Must be one of: ${validTargets.join(", ")}`));
    return 1;
  }
  const cwd = process.cwd();
  const currentPM = detectCurrentPM(cwd);
  if (verbose) {
    console.log(chalk12.gray(`Current package manager: ${currentPM}`));
    console.log(chalk12.gray(`Target package manager: ${target}`));
  }
  if (currentPM === target) {
    console.log(chalk12.yellow(`Already using ${target}. Re-applying conversion to fix any incomplete steps...`));
  }
  if (currentPM === "unknown") {
    console.error(chalk12.red("Could not detect current package manager. No packageManager field or known lockfile found."));
    return 1;
  }
  const workspacePaths = findWorkspacePackagePaths(cwd);
  if (verbose) {
    console.log(chalk12.gray(`Found ${workspacePaths.length} workspace packages`));
  }
  const result = target === "pnpm" ? await convertToPnpm(cwd, workspacePaths) : target === "yarn" ? convertToYarn(cwd, workspacePaths) : target === "npm" ? convertToNpm(cwd, workspacePaths) : convertToBun(cwd, workspacePaths);
  if (result !== 0) return result;
  console.log(chalk12.green("\nRunning repo lint --fix..."));
  packageLintMonorepo(true);
  return result;
}
export {
  convert,
  detectCurrentPM,
  findWorkspacePackagePaths
};
//# sourceMappingURL=convert.mjs.map
