// src/actions/publint.ts
import chalk6 from "chalk";

// src/lib/concurrency.ts
import { AsyncLocalStorage } from "async_hooks";
var outputStorage = new AsyncLocalStorage();
var captureInstalled = false;
function installOutputCapture() {
  if (captureInstalled) return;
  captureInstalled = true;
  const originalStdoutWrite = process.stdout.write.bind(process.stdout);
  const originalStderrWrite = process.stderr.write.bind(process.stderr);
  function intercept(original) {
    return function(chunk, ...args) {
      const buffer = outputStorage.getStore();
      if (buffer) {
        buffer.push(typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk));
        return true;
      }
      return original(chunk, ...args);
    };
  }
  process.stdout.write = intercept(originalStdoutWrite);
  process.stderr.write = intercept(originalStderrWrite);
}
async function runWithConcurrency(items, concurrency, fn) {
  let next = 0;
  async function worker() {
    while (next < items.length) {
      const i = next++;
      await fn(items[i]);
    }
  }
  await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, () => worker()));
}

// src/lib/packageManagerRuntime.ts
import { spawnSync } from "child_process";
import fs from "fs";
import chalk from "chalk";
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",
    shell: false,
    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",
    shell: false,
    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 "fs";
import PATH from "path";
import { globSync } from "glob";
function readJsonFile(path2) {
  if (!existsSync(path2)) return void 0;
  try {
    return JSON.parse(readFileSync(path2, "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/lib/loadConfig.ts
import chalk2 from "chalk";
import { cosmiconfig } from "cosmiconfig";
import { TypeScriptLoader } from "cosmiconfig-typescript-loader";
import deepmerge from "deepmerge";
var config;
var rootConfigPath;
var workspaceConfigCache = /* @__PURE__ */ new Map();
var deprecationWarned = /* @__PURE__ */ new Set();
function createExplorer() {
  return cosmiconfig("xy", { cache: true, loaders: { ".ts": TypeScriptLoader() } });
}
var loadConfig = async (params) => {
  if (config === void 0) {
    const cosmicConfigResult = await createExplorer().search();
    config = cosmicConfigResult?.config ?? {};
    rootConfigPath = cosmicConfigResult?.filepath;
    const configFilePath = cosmicConfigResult?.filepath;
    if (configFilePath !== void 0) {
      console.log(chalk2.green(`Loaded config from ${configFilePath}`));
      if (config.verbose) {
        console.log(chalk2.gray(`${JSON.stringify(config, null, 2)}`));
      }
    }
  }
  return deepmerge(config, params ?? {});
};
async function loadWorkspaceConfig(workspaceDir) {
  const cached = workspaceConfigCache.get(workspaceDir);
  if (cached !== void 0) return cached;
  const result = await createExplorer().search(workspaceDir);
  if (!result || result.filepath === rootConfigPath) {
    workspaceConfigCache.set(workspaceDir, {});
    return {};
  }
  const wsConfig = result.config ?? {};
  workspaceConfigCache.set(workspaceDir, wsConfig);
  return wsConfig;
}
var DEPRECATED_COMMAND_FIELDS = /* @__PURE__ */ new Set(["deplint", "publint"]);
function resolveCommandField(cfg, commandName, configPath) {
  const commands = cfg.commands;
  const fromCommands = commands?.[commandName];
  const fromTopLevel = cfg[commandName];
  if (fromCommands !== void 0 && typeof fromCommands === "object") {
    return fromCommands;
  }
  if (fromTopLevel !== void 0 && typeof fromTopLevel === "object" && DEPRECATED_COMMAND_FIELDS.has(commandName)) {
    const key = `${configPath ?? "unknown"}:${commandName}`;
    if (!deprecationWarned.has(key)) {
      deprecationWarned.add(key);
      console.warn(chalk2.yellow(
        `[xy] Deprecated: top-level "${commandName}" in ${configPath ?? "xy.config"} \u2014 move to "commands.${commandName}"`
      ));
    }
    return fromTopLevel;
  }
  return {};
}
async function loadWorkspaceCommandConfig(workspaceDir, commandName) {
  const root = await loadConfig();
  const rootCmd = resolveCommandField(root, commandName, rootConfigPath);
  const wsConfig = await loadWorkspaceConfig(workspaceDir);
  const wsConfigPath = workspaceConfigCache.has(workspaceDir) ? workspaceDir : void 0;
  const wsCmd = resolveCommandField(wsConfig, commandName, wsConfigPath);
  return deepmerge(rootCmd, wsCmd);
}

// src/lib/runInstall.ts
import chalk3 from "chalk";
function runInstall(cwd) {
  const pm = detectPackageManager();
  console.log(chalk3.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(chalk3.yellow(`${pm} install failed`));
    return false;
  }
  console.log(chalk3.green("Dependencies installed"));
  return true;
}

// src/actions/package/compile/XyConfig.ts
var ALL_PUBLINT_CHECKS = [
  "files",
  "importToDefault",
  "main",
  "module",
  "peerDeps",
  "publint",
  "resolutions",
  "rootSource",
  "rootTypes",
  "sideEffects",
  "source",
  "types"
];
var PUBLISH_ONLY_CHECKS = [
  "files",
  "importToDefault",
  "main",
  "module",
  "publint",
  "rootSource",
  "rootTypes",
  "sideEffects",
  "source",
  "types"
];

// src/actions/package/publint.ts
import { promises as fs2 } from "fs";
import path from "path";
import chalk4 from "chalk";
import { glob } from "glob";
import sortPackageJson from "sort-package-json";
var removeSourceFromExports = (exports) => {
  let removed = false;
  for (const [key, value] of Object.entries(exports)) {
    if (key === "source") {
      delete exports[key];
      removed = true;
    } else if (typeof value === "object" && value !== null && removeSourceFromExports(value)) removed = true;
  }
  return removed;
};
var hasSourceInExports = (exports) => {
  for (const [key, value] of Object.entries(exports)) {
    if (key === "source") return true;
    if (typeof value === "object" && value !== null && hasSourceInExports(value)) return true;
  }
  return false;
};
var hasImportKeyInExports = (exports) => {
  for (const [key, value] of Object.entries(exports)) {
    if (key === "import" && typeof value === "string" && value.endsWith(".mjs")) return true;
    if (typeof value === "object" && value !== null && hasImportKeyInExports(value)) return true;
  }
  return false;
};
var replaceImportWithDefault = (exports) => {
  let modified = false;
  for (const [key, value] of Object.entries(exports)) {
    if (key === "import" && typeof value === "string" && value.endsWith(".mjs")) {
      if (exports.default === void 0) {
        exports.default = value;
      }
      delete exports.import;
      if (exports.types === void 0) {
        exports.types = value.replace(/\.mjs$/, ".d.ts");
      }
      modified = true;
    } else if (typeof value === "object" && value !== null && replaceImportWithDefault(value)) modified = true;
  }
  return modified;
};
var hasTypesInExports = (exports) => {
  for (const [key, value] of Object.entries(exports)) {
    if (key === "types") return true;
    if (typeof value === "object" && value !== null && hasTypesInExports(value)) return true;
  }
  return false;
};
function ensureExportsPath(value) {
  if (value.startsWith("./") || value.startsWith("../")) return value;
  return `./${value}`;
}
function emptyCustomResult() {
  return {
    errors: 0,
    modified: false,
    warnings: 0
  };
}
function mergeResults(target, source) {
  target.errors += source.errors;
  target.warnings += source.warnings;
  target.modified = target.modified || source.modified;
}
function checkFiles(pkg, fix) {
  const result = emptyCustomResult();
  const files = pkg.files;
  if (files === void 0) {
    console.warn(chalk4.yellow('Publint [custom]: "files" field is missing'));
    result.warnings++;
  }
  if (Array.isArray(files) && !files.includes("README.md")) {
    files.push("README.md");
    console.warn(chalk4.yellow('Publint [custom]: added "README.md" to "files"'));
    result.modified = true;
    result.warnings++;
  }
  if (Array.isArray(files) && files.includes("src")) {
    if (fix) {
      pkg.files = files.filter((f) => f !== "src");
      console.warn(chalk4.yellow('Publint [custom]: removed "src" from "files"'));
      result.modified = true;
    } else {
      console.warn(chalk4.yellow('Publint [custom]: "src" should not be in "files" (use --fix to remove)'));
    }
    result.warnings++;
  }
  return result;
}
function checkExportsSource(pkg, fix) {
  const result = emptyCustomResult();
  const exports = pkg.exports;
  if (exports && typeof exports === "object" && hasSourceInExports(exports)) {
    if (fix) {
      removeSourceFromExports(exports);
      console.warn(chalk4.yellow('Publint [custom]: removed "source" entries from "exports"'));
      result.modified = true;
    } else {
      console.warn(chalk4.yellow('Publint [custom]: "source" entries should not be in "exports" (use --fix to remove)'));
    }
    result.warnings++;
  }
  return result;
}
function migrateFieldToExports(pkg, field, exportKey, fix) {
  const result = emptyCustomResult();
  if (pkg[field] === void 0) return result;
  const fieldValue = pkg[field];
  if (!fieldValue.endsWith(".js") && !fieldValue.endsWith(".mjs") && !fieldValue.endsWith(".cjs")) return result;
  if (fix) {
    const exportValue = ensureExportsPath(fieldValue);
    const exports = pkg.exports;
    if (exports && typeof exports === "object") {
      const dot = exports["."];
      if (dot && typeof dot === "object" && !dot[exportKey]) {
        dot[exportKey] = exportValue;
        console.warn(chalk4.yellow(`Publint [custom]: migrated "${field}" to "exports['.'].${exportKey}" (${fieldValue})`));
      }
    } else if (!pkg.exports) {
      pkg.exports = { ".": { [exportKey]: exportValue } };
      console.warn(chalk4.yellow(`Publint [custom]: migrated "${field}" to "exports" (.\u2192${fieldValue})`));
    }
    delete pkg[field];
    console.warn(chalk4.yellow(`Publint [custom]: removed deprecated "${field}" field`));
    result.modified = true;
  } else {
    console.warn(chalk4.yellow(`Publint [custom]: "${field}" field is deprecated, use "exports" instead (use --fix to remove)`));
  }
  result.warnings++;
  return result;
}
function checkSideEffects(pkg) {
  const result = emptyCustomResult();
  if (pkg.sideEffects !== false) {
    console.warn(chalk4.yellow('Publint [custom]: "sideEffects" field should be set to false'));
    result.warnings++;
  }
  return result;
}
function checkRootSource(pkg, fix) {
  const result = emptyCustomResult();
  for (const field of ["source", "src"]) {
    if (pkg[field] !== void 0) {
      if (fix) {
        delete pkg[field];
        console.warn(chalk4.yellow(`Publint [custom]: removed root-level "${field}" field`));
        result.modified = true;
      } else {
        console.warn(chalk4.yellow(`Publint [custom]: root-level "${field}" field should not be in package.json (use --fix to remove)`));
      }
      result.warnings++;
    }
  }
  return result;
}
function checkResolutions(pkg) {
  const result = emptyCustomResult();
  if (pkg.resolutions !== void 0) {
    console.warn(chalk4.yellow('Publint [custom]: "resolutions" in use'));
    console.warn(chalk4.gray(JSON.stringify(pkg.resolutions, null, 2)));
    result.warnings++;
  }
  return result;
}
function checkImportToDefault(pkg, fix) {
  const result = emptyCustomResult();
  const exports = pkg.exports;
  if (!exports || typeof exports !== "object") return result;
  if (!hasImportKeyInExports(exports)) return result;
  if (fix) {
    replaceImportWithDefault(exports);
    console.warn(chalk4.yellow('Publint [custom]: renamed "import" to "default" in "exports" and ensured "types" siblings'));
    result.modified = true;
  } else {
    console.warn(chalk4.yellow('Publint [custom]: "import" entries in "exports" should use "default" instead (use --fix to rename)'));
  }
  result.warnings++;
  return result;
}
function checkRootTypes(pkg, fix) {
  const result = emptyCustomResult();
  if (pkg.types === void 0) return result;
  const exports = pkg.exports;
  if (!exports || typeof exports !== "object" || !hasTypesInExports(exports)) return result;
  if (fix) {
    delete pkg.types;
    console.warn(chalk4.yellow('Publint [custom]: removed redundant root "types" field (already defined in "exports")'));
    result.modified = true;
  } else {
    console.warn(chalk4.yellow('Publint [custom]: root "types" field is redundant when "exports" defines types (use --fix to remove)'));
  }
  result.warnings++;
  return result;
}
function customPubLint(pkg, fix = false, exclude = /* @__PURE__ */ new Set()) {
  const result = emptyCustomResult();
  if (!exclude.has("files")) mergeResults(result, checkFiles(pkg, fix));
  if (!exclude.has("source")) mergeResults(result, checkExportsSource(pkg, fix));
  if (!exclude.has("rootSource")) mergeResults(result, checkRootSource(pkg, fix));
  if (!exclude.has("main")) mergeResults(result, migrateFieldToExports(pkg, "main", "default", fix));
  if (!exclude.has("types")) mergeResults(result, migrateFieldToExports(pkg, "types", "types", fix));
  if (!exclude.has("module")) mergeResults(result, migrateFieldToExports(pkg, "module", "default", fix));
  if (!exclude.has("importToDefault")) mergeResults(result, checkImportToDefault(pkg, fix));
  if (!exclude.has("rootTypes")) mergeResults(result, checkRootTypes(pkg, fix));
  if (!exclude.has("sideEffects")) mergeResults(result, checkSideEffects(pkg));
  if (!exclude.has("resolutions")) mergeResults(result, checkResolutions(pkg));
  return [result.errors, result.warnings, result.modified];
}
var ALWAYS_INCLUDED_PATTERNS = [
  "package.json",
  "README",
  "README.*",
  "LICENCE",
  "LICENCE.*",
  "LICENSE",
  "LICENSE.*",
  "CHANGELOG",
  "CHANGELOG.*"
];
async function resolvePackFiles(pkgDir, filesField) {
  const patterns = [...ALWAYS_INCLUDED_PATTERNS];
  if (filesField) {
    for (const pattern of filesField) {
      if (pattern.startsWith("!")) {
        patterns.push(pattern);
      } else {
        patterns.push(pattern, `${pattern}/**`);
      }
    }
  }
  const matched = await glob(patterns, {
    cwd: pkgDir,
    nodir: true,
    dot: false
  });
  const files = await Promise.all(
    matched.map(async (rel) => {
      const abs = path.join(pkgDir, rel);
      const data = await fs2.readFile(abs, "utf8").catch(() => "");
      return { name: path.join(pkgDir, rel), data };
    })
  );
  return files;
}
async function runPublintLibrary(pkgDir, pkg, strict, pack) {
  const { publint: publint2 } = await import("publint");
  let packOption = false;
  if (pack) {
    const files = await resolvePackFiles(pkgDir, pkg.files);
    packOption = { files };
  }
  const { messages } = await publint2({
    level: "suggestion",
    pack: packOption,
    pkgDir,
    strict
  });
  const { formatMessage } = await import("publint/utils");
  for (const message of messages) {
    switch (message.type) {
      case "error": {
        console.error(chalk4.red(`[${message.code}] ${formatMessage(message, pkg)}`));
        break;
      }
      case "warning": {
        console.warn(chalk4.yellow(`[${message.code}] ${formatMessage(message, pkg)}`));
        break;
      }
      default: {
        console.log(chalk4.white(`[${message.code}] ${formatMessage(message, pkg)}`));
        break;
      }
    }
  }
  return {
    errors: messages.filter((message) => message.type === "error").length,
    total: messages.length
  };
}
var packagePublint = async ({
  exclude = /* @__PURE__ */ new Set(),
  fix = false,
  pack = true,
  pkgDir: pkgDirParam,
  strict = true,
  verbose: _verbose = false
} = {}) => {
  const pkgDir = pkgDirParam ?? INIT_CWD();
  const sortedPkg = sortPackageJson(await fs2.readFile(`${pkgDir}/package.json`, "utf8"));
  await fs2.writeFile(`${pkgDir}/package.json`, sortedPkg);
  const pkg = JSON.parse(await fs2.readFile(`${pkgDir}/package.json`, "utf8"));
  const effectiveExclude = pkg.private ? /* @__PURE__ */ new Set([...exclude, ...PUBLISH_ONLY_CHECKS]) : exclude;
  console.log(chalk4.green(`Publint: ${String(pkg.name)}${pkg.private ? chalk4.gray(" (private)") : ""}`));
  console.log(chalk4.gray(pkgDir));
  let libraryErrors = 0;
  if (!effectiveExclude.has("publint")) {
    const library = await runPublintLibrary(pkgDir, pkg, strict, pack);
    libraryErrors = library.errors;
  }
  const [errorCount, _warningCount, modified] = customPubLint(pkg, fix, effectiveExclude);
  if (modified) {
    const sorted = sortPackageJson(JSON.stringify(pkg, null, 2));
    await fs2.writeFile(`${pkgDir}/package.json`, sorted);
  }
  return libraryErrors + errorCount;
};

// src/actions/package-lint-deps.ts
import { readFileSync as readFileSync2, writeFileSync } from "fs";
import PATH2 from "path";
import chalk5 from "chalk";
import semver from "semver";
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 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(chalk5.green(`  \u2714 Fixed: set peerDependencies.${dep} to "${expected}" in ${name} (${location})`));
        modified = true;
      }
    }
    if (modified) {
      writeWorkspacePackageJson(cwd, location, pkg);
    }
  }
}

// src/actions/publint.ts
function resolveExclude(publintConfig, cliExclude, cliInclude) {
  const hasExclude = (publintConfig.exclude?.length ?? 0) > 0 || (cliExclude?.length ?? 0) > 0;
  const hasInclude = (publintConfig.include?.length ?? 0) > 0 || (cliInclude?.length ?? 0) > 0;
  if (hasExclude && hasInclude) {
    console.error(chalk6.red("Publint: --include and --exclude cannot be used together"));
    return void 0;
  }
  if (hasInclude) {
    const include = /* @__PURE__ */ new Set([
      ...publintConfig.include ?? [],
      ...cliInclude ?? []
    ]);
    return new Set(ALL_PUBLINT_CHECKS.filter((c) => !include.has(c)));
  }
  return /* @__PURE__ */ new Set([
    ...publintConfig.exclude ?? [],
    ...cliExclude ?? []
  ]);
}
function normalizePublintConfig(value) {
  if (typeof value === "object") return value;
  return {};
}
async function loadPublintOptions() {
  const config2 = await loadConfig();
  const publintConfig = normalizePublintConfig(config2.commands?.publint ?? config2.publint);
  const exclude = resolveExclude(publintConfig) ?? /* @__PURE__ */ new Set();
  return { exclude, pack: publintConfig.pack ?? true };
}
var publint = async ({
  cliExclude,
  cliInclude,
  fix,
  jobs,
  pack,
  verbose,
  pkg
}) => {
  return pkg === void 0 ? await publintAll({
    cliExclude,
    cliInclude,
    fix,
    jobs,
    pack,
    verbose
  }) : await publintSingle({
    cliExclude,
    cliInclude,
    fix,
    pack,
    pkg,
    verbose
  });
};
function logPublintSummary(packages, errors, ms) {
  const color = errors > 0 ? chalk6.red : chalk6.blue;
  console.log(color(`Checked ${packages} package(s) in ${ms.toFixed(0)}ms with ${errors} issue(s) found.`));
}
var publintSingle = async ({
  cliExclude,
  cliInclude,
  fix,
  pack,
  pkg,
  verbose
}) => {
  const start = performance.now();
  const pm = getPackageManager();
  const workspace = pm.findWorkspace(pkg);
  if (!workspace) {
    console.error(chalk6.red(`Publint: workspace "${pkg}" not found`));
    return 1;
  }
  const wsPublintConfig = normalizePublintConfig(
    await loadWorkspaceCommandConfig(workspace.location, "publint")
  );
  const exclude = resolveExclude(wsPublintConfig, cliExclude, cliInclude);
  if (!exclude) return 1;
  const shouldPack = pack ?? wsPublintConfig.pack ?? true;
  const errors = await packagePublint({
    exclude,
    fix,
    pack: shouldPack,
    pkgDir: workspace.location,
    verbose
  });
  logPublintSummary(1, errors, performance.now() - start);
  return errors;
};
var publintAll = async ({
  cliExclude,
  cliInclude,
  fix,
  jobs,
  pack,
  verbose
}) => {
  const start = performance.now();
  const pm = getPackageManager();
  const workspaces = pm.listWorkspaces();
  const concurrency = jobs;
  const results = Array.from({ length: workspaces.length }, () => ({ errors: 0, output: [] }));
  installOutputCapture();
  await runWithConcurrency(
    workspaces.map((ws, i) => ({ i, ws })),
    concurrency,
    async ({ i, ws }) => {
      const output = [];
      await outputStorage.run(output, async () => {
        try {
          const wsPublintConfig = normalizePublintConfig(
            await loadWorkspaceCommandConfig(ws.location, "publint")
          );
          const exclude = resolveExclude(wsPublintConfig, cliExclude, cliInclude) ?? /* @__PURE__ */ new Set();
          const shouldPack = pack ?? wsPublintConfig.pack ?? true;
          const errors = await packagePublint({
            exclude,
            fix,
            pack: shouldPack,
            pkgDir: ws.location,
            verbose
          });
          results[i] = { errors, output };
        } catch (ex) {
          output.push(chalk6.red(`Publint failed for ${ws.name}: ${ex.message}
`));
          results[i] = { errors: 1, output };
        }
      });
    }
  );
  let totalErrors = 0;
  for (const { errors, output } of results) {
    for (const line of output) {
      process.stdout.write(line);
    }
    totalErrors += errors;
  }
  const allExclude = resolveExclude({}, cliExclude, cliInclude) ?? /* @__PURE__ */ new Set();
  if (!allExclude.has("peerDeps")) {
    const cwd = INIT_CWD();
    const peerResult = checkInternalPeerVersions(cwd, workspaces);
    if (peerResult.fixable.length > 0) {
      if (fix) {
        fixInternalPeerVersions(cwd, workspaces);
        runInstall();
      } else {
        for (const msg of peerResult.fixable) {
          console.log(chalk6.red(`  \u2717 ${msg} (fixable)`));
        }
        totalErrors += peerResult.fixable.length;
      }
    }
    totalErrors += peerResult.errors.length;
  }
  logPublintSummary(workspaces.length, totalErrors, performance.now() - start);
  return totalErrors;
};
export {
  loadPublintOptions,
  publint,
  publintAll,
  publintSingle
};
//# sourceMappingURL=publint.mjs.map