// src/actions/package-lint-deps.ts
import { readFileSync as readFileSync2, writeFileSync } from "fs";
import PATH2 from "path";
import chalk from "chalk";
import semver from "semver";

// src/pm/workspaces.ts
import { existsSync, readFileSync } from "fs";
import PATH from "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 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 "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/lib/initCwd.ts
function INIT_CWD() {
  return process.env.INIT_CWD ?? process.cwd();
}

// src/actions/package-lint-deps.ts
function readWorkspacePackageJson(cwd, location) {
  const pkgPath = PATH2.resolve(cwd, location, "package.json");
  try {
    return JSON.parse(readFileSync2(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, writeRootPackageJson, workspaces) {
  if (rootPkg.version !== void 0) {
    delete rootPkg.version;
    writeRootPackageJson(cwd, rootPkg);
    console.log(chalk.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(chalk.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(chalk.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(chalk.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);
  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:")) {
        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);
  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;
      const expected = expectedPeerRange(devDeps?.[dep], targetVersion);
      if (version !== expected) {
        peerDeps[dep] = expected;
        console.log(chalk.green(`  \u2714 Fixed: set peerDependencies.${dep} to "${expected}" in ${name} (${location})`));
        modified = true;
      }
    }
    if (modified) {
      writeWorkspacePackageJson(cwd, location, pkg);
    }
  }
}
function syncInternalPeerVersions({ verbose = false } = {}) {
  const cwd = INIT_CWD();
  const workspaces = getPackageManager().listWorkspaces();
  if (verbose) {
    console.log(chalk.gray(`Publish pre-check: syncing internal peer versions across ${workspaces.length} workspaces\u2026`));
  }
  const workspaceVersions = buildWorkspaceVersionMap(cwd, workspaces);
  let updated = 0;
  let scanned = 0;
  for (const { location, name } of workspaces) {
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    scanned++;
    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;
      const expected = expectedPeerRange(devDeps?.[dep], targetVersion);
      if (version !== expected) {
        peerDeps[dep] = expected;
        console.log(chalk.green(`Publish: updated ${name} peerDependencies.${dep} to "${expected}"`));
        modified = true;
        updated++;
      }
    }
    if (modified) {
      writeWorkspacePackageJson(cwd, location, pkg);
    }
  }
  if (verbose) {
    console.log(chalk.gray(`Publish pre-check: scanned ${scanned} workspaces, updated ${updated} peerDependency range${updated === 1 ? "" : "s"}.`));
  }
  return updated;
}
function logMonorepoVersion() {
  const cwd = INIT_CWD();
  const workspaces = getPackageManager().listWorkspaces();
  for (const { location } of workspaces) {
    if (location === ".") continue;
    const pkg = readWorkspacePackageJson(cwd, location);
    if (!pkg) continue;
    const version = pkg.version;
    if (version) {
      console.log(chalk.green(`
Deployed version: ${chalk.bold(version)}`));
      return;
    }
  }
}
export {
  checkInternalDepVersions,
  checkInternalPeerVersions,
  checkVersionConsistency,
  checkWorkspaceProtocol,
  fixInternalDepVersions,
  fixInternalPeerVersions,
  fixVersionConsistency,
  fixWorkspaceProtocol,
  logMonorepoVersion,
  syncInternalPeerVersions
};
//# sourceMappingURL=package-lint-deps.mjs.map