// src/actions/packman/swapTsScriptsDependency.ts
import {
  existsSync,
  readFileSync as readFileSync2,
  writeFileSync
} from "node:fs";
import PATH from "node:path";
import chalk from "chalk";

// src/lib/toolchainVersion.ts
import { readFileSync } 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(readFileSync(pkgPath, "utf8"));
  if (!pkg.version) throw new Error("Could not read @xylabs/toolchain version");
  return pkg.version;
}
function bundledToolchainRange() {
  return `^${bundledToolchainVersion()}`;
}

// src/actions/packman/swapTsScriptsDependency.ts
var TARGET_PACKAGE = "@xylabs/toolchain";
var managedPackages = [
  "@xylabs/toolchain",
  "@xylabs/toolchain",
  "@xylabs/toolchain"
];
function setToolchainInPackageJson(pkgPath, range) {
  if (!existsSync(pkgPath)) return false;
  const raw = readFileSync2(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) {
    writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
  }
  return changed;
}
function swapTsScriptsDependency(cwd, workspacePackageJsonPaths) {
  const range = bundledToolchainRange();
  let count = 0;
  if (setToolchainInPackageJson(PATH.join(cwd, "package.json"), range)) {
    count++;
  }
  for (const pkgPath of workspacePackageJsonPaths) {
    const fullPath = PATH.resolve(cwd, pkgPath, "package.json");
    if (setToolchainInPackageJson(fullPath, range)) {
      count++;
    }
  }
  if (count > 0) {
    console.log(chalk.green(`  Set toolchain dependency to ${TARGET_PACKAGE}@${range} in ${count} package(s)`));
  }
}
export {
  swapTsScriptsDependency
};
//# sourceMappingURL=swapTsScriptsDependency.mjs.map
