// src/xy/lint/fixCommand.ts
import chalk6 from "chalk";

// src/lib/checkResult.ts
import chalk from "chalk";
var checkResult = (name, result, level = "error", exitOnFail = false) => {
  if (result) {
    const exiting = exitOnFail ? "[Exiting Process]" : "[Continuing]";
    const chalkFunc = level === "error" ? chalk.red : chalk.yellow;
    console[level](chalkFunc(`${name} had ${result} failures ${exiting}`));
    if (exitOnFail) {
      process.exit(result);
    }
  }
};

// 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 chalk2 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(chalk2.yellow(`${DISPLAY_NAMES[plan.packageManager]} is required for "${context.operation}".`));
  for (const line of plan.manualInstructions) {
    console.error(chalk2.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(chalk2.yellow(`${context.operation} requires ${displayName}, but it is not installed.`));
  if (!plan.supported) {
    printManualInstructions(plan, context);
    return false;
  }
  if (!isCommandInstalled("brew")) {
    console.error(chalk2.yellow("Homebrew is not installed, so automatic installation is unavailable."));
    console.error(chalk2.gray("  Install Homebrew from https://brew.sh and then run:"));
    console.error(chalk2.gray(`  ${plan.command}`));
    return false;
  }
  const confirmed = askYesNo(chalk2.cyan(`Install ${displayName} with Homebrew now? [y/N] `));
  if (!confirmed) {
    console.error(chalk2.gray(`Skipping install. Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk2.cyan(`Installing ${displayName} via Homebrew...
`));
  if (!installWithHomebrew(pm, context.cwd)) {
    console.error(chalk2.red(`Homebrew failed to install ${displayName}.`));
    console.error(chalk2.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  if (!isPackageManagerInstalled(pm)) {
    console.error(chalk2.red(`${displayName} still does not appear to be installed after Homebrew completed.`));
    console.error(chalk2.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk2.green(`${displayName} installed successfully.`));
  return true;
}

// src/pm/workspaces.ts
import { existsSync, readFileSync } from "fs";
import PATH from "path";
import { globSync } from "glob";
function readJsonFile(path3) {
  if (!existsSync(path3)) return void 0;
  try {
    return JSON.parse(readFileSync(path3, "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/processEx.ts
import chalk3 from "chalk";

// src/lib/withError.ts
var withError = (ex, closure, predicate = (ex2) => !!ex2.name && !!ex2.message) => {
  return predicate(ex) ? closure(ex) : void 0;
};

// src/lib/withErrnoException.ts
var withErrnoException = (ex, closure) => {
  return withError(ex, closure, (ex2) => ex2.errno !== void 0);
};

// src/lib/processEx.ts
var processEx = (ex) => {
  const error = typeof ex === "string" ? new Error(ex) : ex;
  const exitCode = withErrnoException(error, (error2) => {
    if (error2.code === "ENOENT") {
      console.error(chalk3.red(`'${error2.path}' not found.`));
    } else {
      console.error(chalk3.red(`Errno: ${error2.code}`));
    }
    return error2.errno ?? -1;
  }) ?? withError(error, (error2) => {
    console.error(chalk3.red(`${error2.name}: ${error2.message}`));
    return -1;
  }) ?? (() => {
    console.error(chalk3.red(`Unexpected Error: ${JSON.stringify(ex, null, 2)}`));
    return -1;
  })();
  process.exit(process.exitCode ?? exitCode);
};

// src/lib/safeExit.ts
var safeExit = (func, exitOnFail = true) => {
  try {
    const result = func();
    if (result && exitOnFail) {
      process.exit(result);
    }
    return result;
  } catch (ex) {
    return processEx(ex);
  }
};

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

// src/lib/packageName.ts
import { readFileSync as readFileSync2 } from "fs";
import path from "path";
function packageName() {
  if (process.env.npm_package_name) {
    return process.env.npm_package_name;
  }
  try {
    const pkgPath = path.join(INIT_CWD(), "package.json");
    const pkg = JSON.parse(readFileSync2(pkgPath, "utf8"));
    return pkg.name;
  } catch {
    return void 0;
  }
}

// src/lib/runSteps.ts
import { spawnSync as spawnSync2 } from "child_process";
import { existsSync as existsSync3 } from "fs";
import chalk4 from "chalk";
var packageManagers = /* @__PURE__ */ new Set(["bun", "npm", "pnpm", "yarn"]);
var runSteps = (name, steps, exitOnFail = true, messages) => {
  return safeExit(() => {
    const pkgName = packageName();
    console.log(chalk4.green(`${name} [${pkgName}]`));
    let totalStatus = 0;
    for (const [i, [command, args, config]] of steps.entries()) {
      if (messages?.[i]) {
        console.log(chalk4.gray(messages?.[i]));
      }
      const argList = Array.isArray(args) ? args : args.split(" ");
      if (command === "node" && !existsSync3(argList[0])) {
        throw new Error(`File not found [${argList[0]}]`);
      }
      if (packageManagers.has(command) && !ensurePackageManagerInstalled(command, { operation: `${name}: ${command} ${Array.isArray(args) ? args.join(" ") : args}`.trim() })) {
        checkResult(name, 1, "error", exitOnFail);
        totalStatus += 1;
        continue;
      }
      const status = spawnSync2(command, Array.isArray(args) ? args : args.split(" "), {
        ...config,
        encoding: "utf8",
        env: { FORCE_COLOR: "3", ...process.env },
        shell: true,
        stdio: "inherit"
      }).status ?? 0;
      checkResult(name, status, "error", exitOnFail);
      totalStatus += status ?? 0;
    }
    return totalStatus;
  }, !!exitOnFail);
};

// src/actions/lintNext.ts
import path2 from "path";
import chalk5 from "chalk";
import { ESLint } from "eslint";
var dumpMessages = (lintResults) => {
  const colors = ["white", "yellow", "red"];
  const severity = ["none", "warning", "error"];
  for (const lintResult of lintResults) {
    if (lintResult.messages.length > 0) {
      console.log(chalk5.gray(`
${lintResult.filePath}`));
      for (const message of lintResult.messages) {
        console.log(
          chalk5.gray(`	${message.line}:${message.column}`),
          chalk5[colors[message.severity]](`	${severity[message.severity]}`),
          chalk5.white(`	${message.message}`),
          chalk5.gray(`	${message.ruleId}`)
        );
      }
    }
  }
};
async function lintOnePackage({
  cache,
  cwd,
  fix: fix2,
  verbose
}) {
  const engine = new ESLint({
    cache,
    cacheLocation: path2.join(cwd, ".eslintcache"),
    cacheStrategy: "content",
    cwd,
    fix: fix2,
    warnIgnored: false
  });
  const lintResults = await engine.lintFiles(".");
  dumpMessages(lintResults);
  if (fix2) {
    await ESLint.outputFixes(lintResults);
  }
  const errors = lintResults.reduce((sum, r) => sum + r.errorCount, 0);
  const warnings = lintResults.reduce((sum, r) => sum + r.warningCount, 0);
  const files = lintResults.length;
  if (verbose) {
    const filesColor = files < 100 ? "green" : files < 1e3 ? "yellow" : "red";
    console.log(chalk5.white(`  ${chalk5[filesColor](files)} files linted`));
  }
  return {
    errors,
    files,
    warnings
  };
}
async function lintNext({
  cache = false,
  fix: fix2 = false,
  jobs,
  pkg,
  verbose = false
}) {
  const rootDir = INIT_CWD();
  const pm = getPackageManager();
  const allWorkspaces = pm.listWorkspaces();
  const workspaces = pkg ? allWorkspaces.filter((ws) => ws.name === pkg) : allWorkspaces;
  if (workspaces.length === 0) {
    console.log(chalk5.red(pkg ? `Package "${pkg}" not found` : "No workspaces found"));
    return 1;
  }
  const concurrency = jobs;
  const label = fix2 ? "Fix" : "Lint";
  installOutputCapture();
  const results = Array.from(
    { length: workspaces.length },
    () => ({
      errors: 0,
      files: 0,
      output: [],
      pkg: "",
      timeMs: 0,
      warnings: 0
    })
  );
  await runWithConcurrency(
    workspaces.map((ws, i) => ({ i, ws })),
    concurrency,
    async ({ i, ws }) => {
      const output = [];
      await outputStorage.run(output, async () => {
        const pkgStart = Date.now();
        const absCwd = path2.resolve(rootDir, ws.location);
        console.log(chalk5.green(`${label} [${ws.name}]`));
        try {
          const {
            errors,
            files,
            warnings
          } = await lintOnePackage({
            cache,
            cwd: absCwd,
            fix: fix2,
            verbose
          });
          const timeMs = Date.now() - pkgStart;
          results[i] = {
            errors,
            files,
            output,
            pkg: ws.name,
            timeMs,
            warnings
          };
        } catch (ex) {
          output.push(chalk5.red(`${label} failed for ${ws.name}: ${ex.message}
`));
          results[i] = {
            errors: 1,
            files: 0,
            output,
            pkg: ws.name,
            timeMs: Date.now() - pkgStart,
            warnings: 0
          };
        }
      });
    }
  );
  let totalErrors = 0;
  let totalWarnings = 0;
  let totalFiles = 0;
  for (const result of results) {
    for (const line of result.output) {
      process.stdout.write(line);
    }
    totalErrors += result.errors;
    totalWarnings += result.warnings;
    totalFiles += result.files;
  }
  const errColor = totalErrors > 0 ? "red" : "green";
  const warnColor = totalWarnings > 0 ? "yellow" : "green";
  console.log(
    chalk5[errColor](`${totalErrors} errors`) + chalk5.gray(", ") + chalk5[warnColor](`${totalWarnings} warnings`) + chalk5.gray(` across ${totalFiles} files in ${workspaces.length} packages`)
  );
  return totalErrors;
}

// src/actions/lint.ts
var lintPackage = ({
  pkg,
  fix: fix2,
  verbose
}) => {
  const pm = getPackageManager();
  return runSteps(`${fix2 ? "Fix" : "Lint"} [${pkg}]`, [
    pm.runInWorkspace(pkg, fix2 ? "package-fix" : verbose ? "package-lint-verbose" : "package-lint")
  ]);
};
var lint = ({
  cache,
  fix: fix2,
  jobs,
  next,
  pkg,
  verbose
}) => {
  if (next) {
    return lintNext({
      cache,
      fix: fix2,
      jobs,
      pkg,
      verbose
    });
  }
  return pkg === void 0 ? lintAllPackages({ fix: fix2 }) : lintPackage({
    pkg,
    fix: fix2,
    verbose
  });
};
var lintAllPackages = ({ fix: fix2 = false } = {}) => {
  const fixOptions = fix2 ? ["--fix"] : [];
  return runSteps(`${fix2 ? "Fix" : "Lint"} [All-Packages]`, [
    ["eslint", ["--cache", "--cache-location", ".eslintcache", "--cache-strategy", "content", ...fixOptions]]
  ]);
};

// src/actions/fix.ts
var fix = (params) => {
  return lint({ ...params, fix: true });
};

// src/xy/param.ts
var packagePositionalParam = (yargs) => {
  return yargs.positional("package", { describe: "Specific package to target", type: "string" });
};

// src/xy/lint/fixCommand.ts
var fixCommand = {
  builder: (yargs) => {
    return packagePositionalParam(yargs).option("cache", {
      alias: "c",
      default: false,
      description: "Use caching for performance",
      type: "boolean"
    }).option("next", {
      alias: "n",
      default: false,
      description: "Fix per-package (lower memory, parallel)",
      type: "boolean"
    });
  },
  command: "fix [package]",
  deprecated: 'Use "xy lint --fix" instead',
  describe: "Fix - Run Eslint w/fix",
  handler: async (argv) => {
    console.warn(chalk6.yellow('Deprecated: use "xy lint --fix" instead of "xy fix"'));
    if (argv.verbose) console.log("Fix");
    process.exitCode = await fix({
      cache: argv.cache,
      jobs: argv.jobs,
      next: argv.next,
      pkg: argv.package,
      verbose: !!argv.verbose
    });
  }
};
export {
  fixCommand
};
//# sourceMappingURL=fixCommand.mjs.map