// src/xy/common/checkCommand.ts
import chalk13 from "chalk";

// src/lib/concurrency.ts
import { AsyncLocalStorage } from "node:async_hooks";
var outputStorage = new AsyncLocalStorage();
var captureInstalled = false;
function installOutputCapture() {
  if (captureInstalled) return;
  captureInstalled = true;
  const originalStdoutWrite2 = 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(originalStdoutWrite2);
  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/crossSpawn.ts
import crossSpawn from "cross-spawn";
function spawnSync(command, args, options) {
  return crossSpawn.sync(command, args, options);
}

// src/lib/packageManagerRuntime.ts
import fs from "node: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",
    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(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 "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/lib/initCwd.ts
function INIT_CWD() {
  return process.env.INIT_CWD ?? process.cwd();
}

// src/lib/gitConfig.ts
import { execFileSync } from "node:child_process";
function getGitConfig(key) {
  try {
    const value = execFileSync("git", ["config", "--get", key], {
      encoding: "utf8",
      stdio: ["ignore", "pipe", "ignore"]
    }).trim();
    return value.length > 0 ? value : void 0;
  } catch {
    return void 0;
  }
}
function getGitConfigBool(key) {
  try {
    const value = execFileSync("git", ["config", "--bool", "--get", key], {
      encoding: "utf8",
      stdio: ["ignore", "pipe", "ignore"]
    }).trim();
    if (value === "true") return true;
    if (value === "false") return false;
    return void 0;
  } catch {
    return void 0;
  }
}
function setGitConfig(key, value) {
  execFileSync("git", ["config", key, value], { stdio: "inherit" });
}

// 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/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 isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
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 {};
}
function mergeRuleConfigs(target, source) {
  if (isRecord(target) && isRecord(source)) {
    return { ...target, ...source };
  }
  return source;
}
function mergeCommandConfig(rootCmd, workspaceCmd, commandName) {
  return deepmerge(rootCmd, workspaceCmd, { customMerge: (key) => commandName === "deplint" && key === "rules" ? mergeRuleConfigs : void 0 });
}
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 mergeCommandConfig(rootCmd, wsCmd, commandName);
}

// src/lib/reporting/runWithEnvelope.ts
import { performance as performance3 } from "node:perf_hooks";

// src/lib/reporting/xyReporter.ts
import { performance as performance2 } from "node:perf_hooks";
var jsonMode = false;
var strictMode = false;
var originalStdoutWrite;
var envelopeEmitted = false;
var currentCommand = "unknown";
var startTime = 0;
function isJsonMode() {
  return jsonMode;
}
function isStrictMode() {
  return strictMode || process.env.XY_STRICT === "1";
}
function setCurrentCommand(name) {
  currentCommand = name;
  startTime = performance2.now();
  envelopeEmitted = false;
}
function emitJson(envelope) {
  if (envelopeEmitted) return;
  envelopeEmitted = true;
  const json = JSON.stringify(envelope) + "\n";
  if (originalStdoutWrite) {
    originalStdoutWrite(json);
  } else {
    process.stdout.write(json);
  }
}

// src/lib/reporting/runWithEnvelope.ts
async function runWithEnvelope(command, action) {
  setCurrentCommand(command);
  const start = performance3.now();
  let exitCode;
  let envelope;
  try {
    const ret = await action();
    if (typeof ret === "number") {
      exitCode = ret;
    } else {
      exitCode = ret.exitCode;
      envelope = ret.envelope;
    }
  } catch (ex) {
    exitCode = 1;
    const message = ex instanceof Error ? ex.message : String(ex);
    envelope = {
      errorCount: 1,
      errors: [{ message }]
    };
    if (!isJsonMode()) {
      console.error(message);
    }
  }
  if (isJsonMode()) {
    emitJson({
      command,
      data: envelope?.data,
      durationMs: Math.round(performance3.now() - start),
      errorCount: envelope?.errorCount ?? (exitCode === 0 ? 0 : 1),
      errors: envelope?.errors,
      exitCode,
      schemaVersion: 1,
      success: exitCode === 0,
      warningCount: envelope?.warningCount ?? 0,
      warnings: envelope?.warnings
    });
  }
  return exitCode;
}
async function withEnvelope(command, action) {
  process.exitCode = await runWithEnvelope(command, action);
}

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

// src/actions/gitlint.ts
import chalk5 from "chalk";
function gitlint() {
  console.log(`
Gitlint Start [${process.cwd()}]
`);
  let valid = 0;
  let warnings = 0;
  const errors = 0;
  const warn = (message) => {
    console.warn(chalk5.yellow(`Warning: ${message}`));
    warnings++;
  };
  if (getGitConfigBool("core.ignorecase") === true) {
    warn("Please set core.ignorecase to FALSE in .git/config file [run yarn gitlint-fix]");
  } else {
    valid++;
  }
  if (getGitConfigBool("core.autocrlf") === false) {
    valid++;
  } else {
    warn("Please set core.autocrlf to FALSE in .git/config file [run yarn gitlint-fix]");
  }
  if (getGitConfig("core.eol") === "lf") {
    valid++;
  } else {
    warn('Please set core.eol to "lf" in .git/config file [run yarn gitlint-fix]');
  }
  const resultMessages = [];
  if (valid > 0) {
    resultMessages.push(chalk5.green(`Passed: ${valid}`));
  }
  if (warnings > 0) {
    resultMessages.push(chalk5.yellow(`Warnings: ${warnings}`));
  }
  if (errors > 0) {
    resultMessages.push(chalk5.red(` Errors: ${errors}`));
  }
  console.warn(`Gitlint Finish [ ${resultMessages.join(" | ")} ]
`);
  return errors + (isStrictMode() ? warnings : 0);
}

// src/actions/gitlint-fix.ts
import chalk6 from "chalk";
function gitlintFix() {
  console.log(`
Gitlint Fix Start [${process.cwd()}]
`);
  if (getGitConfigBool("core.ignorecase") === true) {
    setGitConfig("core.ignorecase", "false");
    console.warn(chalk6.yellow("\nGitlint Fix: Updated core.ignorecase to be false\n"));
  }
  if (getGitConfigBool("core.autocrlf") !== false) {
    setGitConfig("core.autocrlf", "false");
    console.warn(chalk6.yellow("\nGitlint Fix: Updated core.autocrlf to be false\n"));
  }
  if (getGitConfig("core.eol") !== "lf") {
    setGitConfig("core.eol", "lf");
    console.warn(chalk6.yellow('\nGitlint Fix: Updated core.eol to be "lf"\n'));
  }
  return 0;
}

// src/actions/lint-init.ts
import {
  existsSync as existsSync3,
  readFileSync as readFileSync3,
  unlinkSync,
  writeFileSync as writeFileSync2
} from "node:fs";
import PATH3 from "node:path";
import chalk7 from "chalk";
import { globSync as globSync2 } from "glob";
function hasReactDependency(packageJsonPath) {
  try {
    const content = readFileSync3(packageJsonPath, "utf8");
    const pkg = JSON.parse(content);
    const deps = pkg.dependencies;
    const devDeps = pkg.devDependencies;
    const peerDeps = pkg.peerDependencies;
    return deps?.react != null || devDeps?.react != null || peerDeps?.react != null;
  } catch {
    return false;
  }
}
function detectReactInMonorepo(cwd, verbose) {
  const rootPkgPath = PATH3.resolve(cwd, "package.json");
  if (hasReactDependency(rootPkgPath)) {
    if (verbose) console.log(chalk7.gray("  React detected in package.json"));
    return true;
  }
  const packageJsonPaths = globSync2("packages/**/package.json", {
    cwd,
    ignore: ["**/node_modules/**"]
  });
  for (const relPath of packageJsonPaths) {
    const fullPath = PATH3.resolve(cwd, relPath);
    if (hasReactDependency(fullPath)) {
      if (verbose) console.log(chalk7.gray(`  React detected in ${relPath}`));
      return true;
    }
  }
  return false;
}

// src/actions/lintlint.ts
import {
  existsSync as existsSync4,
  readFileSync as readFileSync4,
  writeFileSync as writeFileSync3
} from "node:fs";
import PATH4 from "node:path";
import chalk8 from "chalk";
import { findUp } from "find-up";
function parseRuleValue(value) {
  if (typeof value === "string") {
    return { level: value };
  }
  if (typeof value === "number") {
    return { level: String(value) };
  }
  if (Array.isArray(value) && value.length > 0) {
    return {
      level: String(value[0]),
      options: value.length > 1 ? value.slice(1) : void 0
    };
  }
  return void 0;
}
function normalizeLevel(level) {
  if (level === "0" || level === "off") return "off";
  if (level === "1" || level === "warn") return "warn";
  if (level === "2" || level === "error") return "error";
  return level;
}
function rulesMatch(a, b) {
  if (normalizeLevel(a.level) !== normalizeLevel(b.level)) return false;
  return JSON.stringify(a.options) === JSON.stringify(b.options);
}
function formatRule(entry) {
  if (entry.options) {
    return JSON.stringify([entry.level, ...entry.options]);
  }
  return JSON.stringify([entry.level]);
}
function mergeRulesFromBlocks(blocks) {
  const merged = /* @__PURE__ */ new Map();
  for (const block of blocks) {
    if (!block.rules) continue;
    for (const [name, value] of Object.entries(block.rules)) {
      const parsed = parseRuleValue(value);
      if (parsed) merged.set(name, parsed);
    }
  }
  return merged;
}
function detectSharedPackage(source) {
  if (source.includes("@xylabs/eslint-config-react-flat")) return "@xylabs/eslint-config-react-flat";
  if (source.includes("@xylabs/eslint-config-flat")) return "@xylabs/eslint-config-flat";
  return void 0;
}
function extractLocalRuleBlocks(source) {
  const blocks = [];
  const ruleBlockRegex = /\{\s*(?:files\s*:\s*\[.*?\]\s*,\s*)?rules\s*:\s*\{([^}]*(?:\{[^}]*\}[^}]*)*)\}/g;
  let match;
  while ((match = ruleBlockRegex.exec(source)) !== null) {
    blocks.push(match[1]);
  }
  return blocks;
}
function extractRulesFromSourceBlocks(blocks) {
  const rules = /* @__PURE__ */ new Map();
  for (const block of blocks) {
    const ruleRegex = /['"]([^'"]+)['"]\s*:\s*(\[[\s\S]*?\](?=\s*,|\s*$))/gm;
    let match;
    while ((match = ruleRegex.exec(block)) !== null) {
      rules.set(match[1], match[2]);
    }
  }
  return rules;
}
function extractConfigBlocks(sharedModule) {
  const config2 = sharedModule.config ?? sharedModule.default;
  if (Array.isArray(config2)) return config2;
  return [];
}
async function resolveSharedConfig(configDir, sharedPkg) {
  try {
    const sharedModule = await import(sharedPkg);
    return extractConfigBlocks(sharedModule);
  } catch {
    const distPath = PATH4.resolve(configDir, "node_modules", sharedPkg, "dist", "node", "index.mjs");
    try {
      const sharedModule = await import(distPath);
      return extractConfigBlocks(sharedModule);
    } catch {
      const neutralPath = PATH4.resolve(configDir, "node_modules", sharedPkg, "dist", "neutral", "index.mjs");
      const sharedModule = await import(neutralPath);
      return extractConfigBlocks(sharedModule);
    }
  }
}
async function loadSharedRules(configDir, sharedPkg, verbose) {
  const sharedBlocks = await resolveSharedConfig(configDir, sharedPkg);
  const sharedRules = mergeRulesFromBlocks(sharedBlocks);
  if (verbose) {
    console.log(chalk8.gray(`Shared config defines ${sharedRules.size} rules`));
  }
  if (sharedRules.size === 0) {
    console.error(chalk8.red("Could not load rules from shared config. Is it installed and built?"));
    return void 0;
  }
  return sharedRules;
}
async function loadLocalRules(eslintConfigPath, source, verbose) {
  const localModule = await import(eslintConfigPath);
  const localConfig = localModule.default ?? localModule;
  const localBlocks = Array.isArray(localConfig) ? localConfig : [localConfig];
  const resolved = mergeRulesFromBlocks(localBlocks);
  const localRuleBlocks = extractLocalRuleBlocks(source);
  const explicit = extractRulesFromSourceBlocks(localRuleBlocks);
  if (verbose) {
    console.log(chalk8.gray(`Local config has ${explicit.size} explicit rule setting(s)`));
  }
  return { explicit, resolved };
}
function compareRules(explicitRuleNames, allResolvedRules, sharedRules) {
  const redundant = [];
  const overrides = [];
  const additions = [];
  for (const ruleName of explicitRuleNames.keys()) {
    const resolvedEntry = allResolvedRules.get(ruleName);
    const sharedEntry = sharedRules.get(ruleName);
    if (!resolvedEntry) continue;
    if (!sharedEntry) {
      additions.push({ local: resolvedEntry, rule: ruleName });
    } else if (rulesMatch(resolvedEntry, sharedEntry)) {
      redundant.push({
        local: resolvedEntry,
        rule: ruleName,
        shared: sharedEntry
      });
    } else {
      overrides.push({
        local: resolvedEntry,
        rule: ruleName,
        shared: sharedEntry
      });
    }
  }
  return {
    additions,
    overrides,
    redundant
  };
}
function reportResults({
  additions,
  overrides,
  redundant
}, verbose) {
  if (redundant.length > 0) {
    console.log(chalk8.yellow(`
${redundant.length} redundant rule(s) (same as shared config \u2014 can be removed):`));
    for (const { rule, local } of redundant) {
      console.log(chalk8.yellow(`  ${rule}: ${formatRule(local)}`));
    }
  }
  if (overrides.length > 0) {
    console.log(chalk8.cyan(`
${overrides.length} rule override(s) (different from shared config):`));
    for (const {
      rule,
      local,
      shared
    } of overrides) {
      console.log(chalk8.cyan(`  ${rule}:`));
      console.log(chalk8.gray(`    shared: ${formatRule(shared)}`));
      console.log(chalk8.white(`    local:  ${formatRule(local)}`));
    }
  }
  if (additions.length > 0 && verbose) {
    console.log(chalk8.gray(`
${additions.length} local addition(s) (not in shared config):`));
    for (const { rule, local } of additions) {
      console.log(chalk8.gray(`  ${rule}: ${formatRule(local)}`));
    }
  }
  if (redundant.length === 0 && overrides.length === 0) {
    console.log(chalk8.green("No redundant or overridden rules found"));
  }
}
function fixRedundantRules(eslintConfigPath, redundant) {
  let updated = readFileSync4(eslintConfigPath, "utf8");
  const original = updated;
  for (const { rule } of redundant) {
    const escaped = rule.replaceAll("/", String.raw`\/`);
    const pattern = new RegExp(String.raw`[ \t]*['"]${escaped}['"]\s*:\s*\[[^\]]*\],?[ \t]*\n?`, "g");
    updated = updated.replace(pattern, "");
  }
  updated = updated.replaceAll(/\{\s*rules\s*:\s*\{\s*\}\s*,?\s*\}\s*,?/g, "");
  updated = updated.replaceAll(/\n{3,}/g, "\n\n");
  if (updated !== original) {
    writeFileSync3(eslintConfigPath, updated, "utf8");
    console.log(chalk8.green(`
Fixed: removed ${redundant.length} redundant rule(s)`));
  }
}
function formatConfigFile(eslintConfigPath) {
  spawnSync("eslint", ["--fix", eslintConfigPath], { stdio: "inherit" });
}
function fixConfigMismatch(eslintConfigPath, configDir, source, sharedPkg, expectedPkg) {
  const updated = source.replaceAll(sharedPkg, expectedPkg);
  writeFileSync3(eslintConfigPath, updated, "utf8");
  console.log(chalk8.green(`Fixed: replaced ${sharedPkg} with ${expectedPkg}`));
  const packageJsonPath = PATH4.resolve(configDir, "package.json");
  if (!existsSync4(packageJsonPath)) return;
  const content = readFileSync4(packageJsonPath, "utf8");
  const pkg = JSON.parse(content);
  const devDeps = pkg.devDependencies ?? {};
  const oldVersion = devDeps[sharedPkg];
  if (!oldVersion) return;
  delete devDeps[sharedPkg];
  devDeps[expectedPkg] = oldVersion;
  const sorted = Object.fromEntries(Object.entries(devDeps).toSorted(([a], [b]) => a.localeCompare(b)));
  pkg.devDependencies = sorted;
  writeFileSync3(packageJsonPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
  console.log(chalk8.green(`Updated package.json: ${sharedPkg} \u2192 ${expectedPkg}`));
  runInstall(configDir);
}
function checkConfigVariant(eslintConfigPath, configDir, source, sharedPkg, fix, verbose) {
  const hasReact = detectReactInMonorepo(configDir, verbose);
  const expectedPkg = hasReact ? "@xylabs/eslint-config-react-flat" : "@xylabs/eslint-config-flat";
  if (sharedPkg === expectedPkg) return false;
  console.log(chalk8.yellow(`
Config mismatch: using ${sharedPkg} but ${hasReact ? "React packages detected" : "no React packages found"}`));
  console.log(chalk8.yellow(`  Expected: ${expectedPkg}`));
  if (fix) {
    fixConfigMismatch(eslintConfigPath, configDir, source, sharedPkg, expectedPkg);
  }
  return true;
}
async function lintlint({ fix, verbose } = {}) {
  const eslintConfigPath = await findUp(["eslint.config.ts", "eslint.config.mjs"]);
  if (!eslintConfigPath) {
    console.error(chalk8.red("No eslint.config.ts found"));
    return 1;
  }
  const configDir = PATH4.dirname(eslintConfigPath);
  if (verbose) {
    console.log(chalk8.gray(`Found config: ${eslintConfigPath}`));
  }
  const source = readFileSync4(eslintConfigPath, "utf8");
  const sharedPkg = detectSharedPackage(source);
  if (!sharedPkg) {
    console.log(chalk8.yellow("No @xylabs/eslint-config-flat or @xylabs/eslint-config-react-flat imports found"));
    return 0;
  }
  if (verbose) {
    console.log(chalk8.gray(`Shared package: ${sharedPkg}`));
  }
  const hasMismatch = checkConfigVariant(eslintConfigPath, configDir, source, sharedPkg, !!fix, !!verbose);
  const currentSource = hasMismatch && fix ? readFileSync4(eslintConfigPath, "utf8") : source;
  const sharedRules = await loadSharedRules(configDir, sharedPkg, !!verbose);
  if (!sharedRules) return 1;
  const { explicit, resolved } = await loadLocalRules(eslintConfigPath, currentSource, !!verbose);
  const results = compareRules(explicit, resolved, sharedRules);
  reportResults(results, !!verbose);
  if (results.redundant.length > 0 && fix) {
    fixRedundantRules(eslintConfigPath, results.redundant);
  }
  const didFix = fix && (hasMismatch || results.redundant.length > 0);
  if (didFix) {
    formatConfigFile(eslintConfigPath);
  }
  const hasUnfixedIssues = !fix && (hasMismatch || results.redundant.length > 0);
  return hasUnfixedIssues && isStrictMode() ? 1 : 0;
}

// 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 "node:fs";
import path from "node:path";
import chalk9 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(chalk9.yellow('Publint [custom]: "files" field is missing'));
    result.warnings++;
  }
  if (Array.isArray(files) && !files.includes("README.md")) {
    files.push("README.md");
    console.warn(chalk9.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(chalk9.yellow('Publint [custom]: removed "src" from "files"'));
      result.modified = true;
    } else {
      console.warn(chalk9.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(chalk9.yellow('Publint [custom]: removed "source" entries from "exports"'));
      result.modified = true;
    } else {
      console.warn(chalk9.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(chalk9.yellow(`Publint [custom]: migrated "${field}" to "exports['.'].${exportKey}" (${fieldValue})`));
      }
    } else if (!pkg.exports) {
      pkg.exports = { ".": { [exportKey]: exportValue } };
      console.warn(chalk9.yellow(`Publint [custom]: migrated "${field}" to "exports" (.\u2192${fieldValue})`));
    }
    delete pkg[field];
    console.warn(chalk9.yellow(`Publint [custom]: removed deprecated "${field}" field`));
    result.modified = true;
  } else {
    console.warn(chalk9.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(chalk9.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(chalk9.yellow(`Publint [custom]: removed root-level "${field}" field`));
        result.modified = true;
      } else {
        console.warn(chalk9.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(chalk9.yellow('Publint [custom]: "resolutions" in use'));
    console.warn(chalk9.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(chalk9.yellow('Publint [custom]: renamed "import" to "default" in "exports" and ensured "types" siblings'));
    result.modified = true;
  } else {
    console.warn(chalk9.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(chalk9.yellow('Publint [custom]: removed redundant root "types" field (already defined in "exports")'));
    result.modified = true;
  } else {
    console.warn(chalk9.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(chalk9.red(`[${message.code}] ${formatMessage(message, pkg)}`));
        break;
      }
      case "warning": {
        console.warn(chalk9.yellow(`[${message.code}] ${formatMessage(message, pkg)}`));
        break;
      }
      default: {
        console.log(chalk9.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 = isStrictMode(),
  verbose: _verbose = false
} = {}) => {
  const pkgDir = path.resolve(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(chalk9.green(`Publint: ${String(pkg.name)}${pkg.private ? chalk9.gray(" (private)") : ""}`));
  console.log(chalk9.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.ts
import { readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "node:fs";
import PATH6 from "node:path";
import chalk11 from "chalk";
import picomatch from "picomatch";
import semver2 from "semver";

// src/actions/package-lint-pnpm.ts
import {
  existsSync as existsSync5,
  readFileSync as readFileSync5,
  writeFileSync as writeFileSync4
} from "node:fs";
import PATH5 from "node:path";
import chalk10 from "chalk";
import * as yaml from "yaml";
function emptyResult() {
  return {
    errors: [],
    fixable: [],
    warnings: []
  };
}
function pnpmWorkspacePath(cwd) {
  return PATH5.resolve(cwd, "pnpm-workspace.yaml");
}
function readPnpmWorkspaceDocument(cwd) {
  const wsPath = pnpmWorkspacePath(cwd);
  if (!existsSync5(wsPath)) return void 0;
  try {
    return yaml.parseDocument(readFileSync5(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(chalk10.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;
  writeFileSync4(pnpmWorkspacePath(cwd), String(doc), "utf8");
  console.log(chalk10.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 = readFileSync6(PATH6.resolve(cwd, "package.json"), "utf8");
  return JSON.parse(raw);
}
function writeRootPackageJson(cwd, pkg) {
  const path2 = PATH6.resolve(cwd, "package.json");
  writeFileSync5(path2, `${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(chalk11.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(chalk11.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 = PATH6.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync6(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 = PATH6.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync6(pkgPath, "utf8");
      const pkg = JSON.parse(raw);
      if (pkg.packageManager) {
        delete pkg.packageManager;
        writeFileSync5(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk11.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 = PATH6.resolve(cwd, location, "package.json");
      try {
        const pkg = JSON.parse(readFileSync6(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 = PATH6.resolve(cwd, location, "package.json");
      try {
        const pkg = JSON.parse(readFileSync6(pkgPath, "utf8"));
        if (pkg.workspaces) {
          delete pkg.workspaces;
          writeFileSync5(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
          const label = location === "." ? "root" : location;
          console.log(chalk11.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((glob2) => picomatch(glob2));
  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(chalk11.red(`  \u2717 ${error}`));
    errors++;
  }
  for (const fixable of result.fixable) {
    if (fix) {
      fixed++;
    } else {
      console.log(chalk11.red(`  \u2717 ${fixable} (fixable)`));
      errors++;
    }
  }
  for (const warning of result.warnings) {
    console.log(chalk11.yellow(`  \u26A0 ${warning}`));
  }
  if (errors === 0 && fixed === 0 && result.warnings.length === 0) {
    console.log(chalk11.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 = PATH6.resolve(cwd, location, "package.json");
    try {
      const pkg = JSON.parse(readFileSync6(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 = PATH6.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync6(pkgPath, "utf8");
      const pkg = JSON.parse(raw);
      if (pkg.volta) {
        delete pkg.volta;
        writeFileSync5(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk11.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(readFileSync6(PATH6.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 = PATH6.resolve(cwd, location, "package.json");
    try {
      const pkg = JSON.parse(readFileSync6(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 = PATH6.resolve(cwd, "package.json");
  const rootRaw = readFileSync6(rootPath, "utf8");
  const rootPkg = JSON.parse(rootRaw);
  if (rootPkg.engines) {
    delete rootPkg.engines;
    writeFileSync5(rootPath, `${JSON.stringify(rootPkg, null, 2)}
`, "utf8");
    console.log(chalk11.green("  \u2714 Fixed: removed engines from root package.json"));
  }
  const enginesTemplate = resolveEnginesTemplate(cwd, workspaces);
  for (const { location } of workspaces) {
    if (location === ".") continue;
    const pkgPath = PATH6.resolve(cwd, location, "package.json");
    try {
      const raw = readFileSync6(pkgPath, "utf8");
      const pkg = JSON.parse(raw);
      if (isTerminalPackage(pkg) && pkg.engines) {
        delete pkg.engines;
        writeFileSync5(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk11.green(`  \u2714 Fixed: removed engines from ${location}/package.json`));
      }
      if (!isTerminalPackage(pkg) && !pkg.engines && enginesTemplate) {
        pkg.engines = enginesTemplate;
        writeFileSync5(pkgPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
        console.log(chalk11.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(readFileSync6(PATH6.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 === "." ? PATH6.resolve(cwd, "package.json") : PATH6.resolve(cwd, location, "package.json");
    try {
      const pkg = JSON.parse(readFileSync6(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(chalk11.green(`
  Fixed ${fixed} issue(s)`));
  }
  if (errors > 0) {
    console.log(chalk11.red(`
  ${errors} error(s) found`));
  } else if (fixed === 0) {
    console.log(chalk11.green("\n  All checks passed"));
  }
}
function packageLintMonorepo(fix = false) {
  const cwd = INIT_CWD();
  let pkg;
  try {
    pkg = readRootPackageJson2(cwd);
  } catch {
    console.error(chalk11.red("Could not read package.json"));
    return 1;
  }
  if (!isMonorepo(pkg, cwd)) {
    console.log(chalk11.gray("Not a monorepo \u2014 skipping repo lint checks"));
    return 0;
  }
  console.log(chalk11.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/publint.ts
import chalk12 from "chalk";
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(chalk12.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 {};
}
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 ? chalk12.red : chalk12.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(chalk12.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(chalk12.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 {
        const strict = isStrictMode();
        for (const msg of peerResult.fixable) {
          console.log(strict ? chalk12.red(`  \u2717 ${msg} (fixable)`) : chalk12.yellow(`  \u26A0 ${msg} (fixable)`));
        }
        if (strict) totalErrors += peerResult.fixable.length;
      }
    }
    totalErrors += peerResult.errors.length;
  }
  logPublintSummary(workspaces.length, totalErrors, performance.now() - start);
  return totalErrors;
};

// src/xy/common/checkCommand.ts
var checkCommand = {
  command: "check",
  describe: "Check - Run gitlint, publint, repo lint, and lintlint",
  builder: (yargs) => {
    return yargs.option("fix", {
      default: false,
      description: "Auto-fix fixable issues",
      type: "boolean"
    });
  },
  handler: async (argv) => {
    const verbose = !!argv.verbose;
    const fix = !!argv.fix;
    const jobs = argv.jobs;
    if (verbose) console.log("Check");
    await withEnvelope("check", async () => {
      let errors = 0;
      console.log(chalk13.blue("\n\u2014 gitlint \u2014"));
      errors += fix ? gitlintFix() : gitlint();
      console.log(chalk13.blue("\n\u2014 publint \u2014"));
      errors += await publint({
        fix,
        jobs,
        verbose
      });
      console.log(chalk13.blue("\n\u2014 repo lint \u2014"));
      errors += packageLintMonorepo(fix);
      console.log(chalk13.blue("\n\u2014 lintlint \u2014"));
      errors += await lintlint({ fix, verbose });
      if (errors > 0) {
        console.log(chalk13.red(`${errors} issue(s) found`));
      } else {
        console.log(chalk13.green("All checks passed"));
      }
      return {
        envelope: { errorCount: errors },
        exitCode: errors > 0 ? 1 : 0
      };
    });
  }
};
export {
  checkCommand
};
//# sourceMappingURL=checkCommand.mjs.map
