// src/lib/updo/runUpdo.ts
import chalk7 from "chalk";

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

// src/lib/runSteps.ts
import { spawnSync as spawnSync2 } from "child_process";
import { existsSync } from "fs";
import chalk4 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/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/lib/packageName.ts
import { readFileSync } 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(readFileSync(pkgPath, "utf8"));
    return pkg.name;
  } catch {
    return void 0;
  }
}

// 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/runSteps.ts
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" && !existsSync(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",
        // Merge per-step env on top so callers can supply overrides
        // (e.g. NODE_OPTIONS=--max-old-space-size=...); process.env still
        // seeds the common case so FORCE_COLOR etc. survive.
        env: {
          FORCE_COLOR: "3",
          ...process.env,
          ...config?.env
        },
        shell: true,
        stdio: "inherit"
      }).status ?? 0;
      checkResult(name, status, "error", exitOnFail);
      totalStatus += status ?? 0;
    }
    return totalStatus;
  }, !!exitOnFail);
};

// src/lib/updo/applyUpdates.ts
import { readFileSync as readFileSync2, writeFileSync } from "fs";
import PATH from "path";
import chalk5 from "chalk";
function applyUpdates(cwd, workspaces, updates) {
  const updateMap = new Map(updates.map((u) => [u.name, u]));
  let modified = 0;
  for (const ws of workspaces) {
    const pkgPath = PATH.resolve(cwd, ws.location, "package.json");
    let content;
    try {
      content = readFileSync2(pkgPath, "utf8");
    } catch {
      continue;
    }
    const pkg = JSON.parse(content);
    let changed = false;
    for (const depField of ["dependencies", "devDependencies", "peerDependencies"]) {
      const deps = pkg[depField];
      if (!deps) continue;
      for (const [name] of Object.entries(deps)) {
        const update = updateMap.get(name);
        if (!update) continue;
        const newRange = update.targetRange;
        if (deps[name] !== newRange) {
          deps[name] = newRange;
          changed = true;
        }
      }
    }
    if (changed) {
      writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}
`);
      modified++;
      console.log(chalk5.gray(`  Updated ${ws.name}`));
    }
  }
  return modified;
}

// src/lib/updo/collectWorkspaceDeps.ts
import { readFileSync as readFileSync3 } from "fs";
import PATH2 from "path";
var DEP_FIELDS = ["dependencies", "devDependencies", "peerDependencies"];
function collectWorkspaceDeps(cwd, workspaces, workspaceNames) {
  const declaredDeps = [];
  for (const ws of workspaces) {
    const pkgPath = PATH2.resolve(cwd, ws.location, "package.json");
    let pkg;
    try {
      pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
    } catch {
      continue;
    }
    for (const depField of DEP_FIELDS) {
      const deps = pkg[depField];
      if (!deps) continue;
      for (const [name, range] of Object.entries(deps)) {
        if (workspaceNames.has(name)) continue;
        if (range.startsWith("workspace:")) continue;
        declaredDeps.push({
          depType: depField,
          name,
          range,
          workspaceLocation: ws.location,
          workspaceName: ws.name
        });
      }
    }
  }
  return declaredDeps;
}

// src/lib/concurrency.ts
import { AsyncLocalStorage } from "async_hooks";
var outputStorage = new AsyncLocalStorage();
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/updo/fetchRegistryInfo.ts
var REGISTRY_BASE = "https://registry.npmjs.org";
async function fetchRegistryInfo(packageName2) {
  try {
    const url = `${REGISTRY_BASE}/${encodeURIComponent(packageName2)}`;
    const res = await fetch(url, { headers: { Accept: "application/vnd.npm.install-v1+json" } });
    if (!res.ok) {
      return { distTags: {}, versions: [] };
    }
    const data = await res.json();
    return {
      distTags: data["dist-tags"] ?? {},
      versions: Object.keys(data.versions ?? {})
    };
  } catch {
    return { distTags: {}, versions: [] };
  }
}
async function fetchAllRegistryInfo(packageNames, concurrency = 16) {
  const results = /* @__PURE__ */ new Map();
  let completed = 0;
  const total = packageNames.length;
  await runWithConcurrency(packageNames, concurrency, async (name) => {
    results.set(name, await fetchRegistryInfo(name));
    completed++;
    if (completed % 25 === 0 || completed === total) {
      process.stderr.write(`\r  Fetched ${completed}/${total} packages...`);
    }
  });
  if (total > 0) {
    process.stderr.write("\n");
  }
  return results;
}

// src/lib/updo/interactiveSelect.ts
import {
  createPrompt,
  ExitPromptError,
  isDownKey,
  isEnterKey,
  isSpaceKey,
  isUpKey,
  useKeypress,
  useRef,
  useState
} from "@inquirer/core";
import chalk6 from "chalk";
import semver from "semver";
function compareVersion(value) {
  if (!value || value === "mixed") return void 0;
  return semver.minVersion(value)?.version;
}
function diffColor(from, to, fallback) {
  const fromV = compareVersion(from);
  const toV = compareVersion(to);
  if (!fromV || !toV) return fallback;
  const diff = semver.diff(fromV, toV);
  if (diff === "major" || diff === "premajor") return chalk6.red;
  if (diff === "minor" || diff === "preminor") return chalk6.yellow;
  return chalk6.green;
}
function versionColor(version, current, mixedBaseline) {
  if (!version) return chalk6.gray;
  if (current === "mixed") {
    if (!mixedBaseline || version === mixedBaseline) return chalk6.green;
    return diffColor(mixedBaseline, version, chalk6.green);
  }
  if (!current || version === current) return chalk6.gray;
  return diffColor(current, version, chalk6.gray);
}
function pad(raw, colored, width) {
  return colored + " ".repeat(Math.max(0, width - raw.length));
}
function dot(selected) {
  return selected ? chalk6.green("\u25CF") : chalk6.dim("\u25CB");
}
function renderHeader(w) {
  const header = [
    "  ",
    chalk6.bold("Package".padEnd(w.name)),
    chalk6.bold("Current".padEnd(w.current)),
    chalk6.bold("  Wanted".padEnd(w.wanted + 2)),
    chalk6.bold("  Latest".padEnd(w.latest + 2)),
    chalk6.bold("  Next/RC".padEnd(w.next + 2))
  ].join("  ");
  const totalWidth = w.name + w.current + w.wanted + w.latest + w.next + 24;
  return `${header}
${chalk6.gray("\u2500".repeat(totalWidth))}`;
}
function renderRow(dep, selection, active, w) {
  const pointer = active ? chalk6.cyan("\u276F") : " ";
  const rawName = dep.name;
  const name = active ? chalk6.white(rawName) : chalk6.gray(rawName);
  const rawCurrent = dep.current ?? "-";
  const current = chalk6.gray(rawCurrent);
  const rawWanted = dep.wanted ?? "-";
  const wantedColorFn = dep.wanted ? versionColor(dep.wanted, dep.current) : chalk6.gray;
  const wantedDot = dep.wanted ? dot(selection === 0) : " ";
  const wanted = `${wantedDot} ${pad(rawWanted, wantedColorFn(rawWanted), w.wanted)}`;
  const rawLatest = dep.latest ?? "-";
  const latestColorFn = dep.latest ? versionColor(dep.latest, dep.current, dep.wanted) : chalk6.gray;
  const latestDot = dep.latest ? dot(selection === 1) : " ";
  const latest = `${latestDot} ${pad(rawLatest, latestColorFn(rawLatest), w.latest)}`;
  const rawNext = dep.next ?? "-";
  const nextColorFn = dep.next ? versionColor(dep.next, dep.current, dep.wanted) : chalk6.gray;
  const nextDot = dep.next ? dot(selection === 2) : " ";
  const next = `${nextDot} ${pad(rawNext, nextColorFn(rawNext), w.next)}`;
  return `${pointer} ${pad(rawName, name, w.name)}  ${pad(rawCurrent, current, w.current)}  ${wanted}  ${latest}  ${next}`;
}
function getAvailableSelections(dep) {
  const available = [-1];
  if (dep.wanted) available.push(0);
  if (dep.latest && dep.latest !== dep.wanted) available.push(1);
  if (dep.next) available.push(2);
  return available;
}
function getTargetVersion(dep, selection) {
  if (selection === 0) return dep.wanted;
  if (selection === 1) return dep.latest;
  if (selection === 2) return dep.next;
  return void 0;
}
function computeWidths(rows) {
  let name = 7;
  let current = 7;
  let wanted = 6;
  let latest = 6;
  let next = 7;
  for (const dep of rows) {
    name = Math.max(name, dep.name.length);
    current = Math.max(current, (dep.current ?? "-").length);
    wanted = Math.max(wanted, (dep.wanted ?? "-").length);
    latest = Math.max(latest, (dep.latest ?? "-").length);
    next = Math.max(next, (dep.next ?? "-").length);
  }
  return {
    current,
    latest,
    name,
    next,
    wanted
  };
}
function renderPage(rows, cursor, selections, w, pageSize) {
  const total = rows.length;
  let start = 0;
  if (total > pageSize) {
    start = Math.max(0, Math.min(cursor - Math.floor(pageSize / 2), total - pageSize));
  }
  const end = Math.min(start + pageSize, total);
  const lines = [];
  for (let i = start; i < end; i++) {
    lines.push(renderRow(rows[i], selections[i], i === cursor, w));
  }
  if (total > pageSize) {
    if (start > 0) lines.unshift(chalk6.dim("  \u2191 more"));
    if (end < total) lines.push(chalk6.dim("  \u2193 more"));
  }
  return lines.join("\n");
}
var updoPrompt = createPrompt((config, done) => {
  const { rows } = config;
  const [cursor, setCursor] = useState(0);
  const [tick, setTick] = useState(0);
  const availableSelectionsRef = useRef(rows.map((r) => getAvailableSelections(r)));
  const selectionsRef = useRef(rows.map(() => -1));
  const widthsRef = useRef(computeWidths(rows));
  useKeypress((key) => {
    if (key.name === "escape" || key.ctrl && key.name === "c") {
      done([]);
      return;
    }
    if (isEnterKey(key)) {
      const results = [];
      for (const [i, dep] of rows.entries()) {
        const version = getTargetVersion(dep, selectionsRef.current[i]);
        if (version) {
          results.push({
            name: dep.name,
            targetRange: version,
            workspaces: dep.workspaces
          });
        }
      }
      done(results);
      return;
    }
    if (isUpKey(key)) {
      setCursor(Math.max(0, cursor - 1));
    } else if (isDownKey(key)) {
      setCursor(Math.min(rows.length - 1, cursor + 1));
    } else if (isSpaceKey(key)) {
      const available = availableSelectionsRef.current[cursor];
      const currentSel = selectionsRef.current[cursor];
      const currentIdx = available.indexOf(currentSel);
      const nextIdx = (currentIdx + 1) % available.length;
      selectionsRef.current[cursor] = available[nextIdx];
      setTick(tick + 1);
    }
  });
  const w = widthsRef.current;
  const header = renderHeader(w);
  const page = renderPage(rows, cursor, selectionsRef.current, w, 20);
  const selectedCount = selectionsRef.current.filter((s) => s >= 0).length;
  const status = chalk6.gray(`  ${selectedCount} selected  \u2191/\u2193 navigate  space cycle version  enter confirm`);
  return `${header}
${page}
${status}`;
});
async function interactiveSelect(deps) {
  const updatable = deps.filter((d) => d.updateAvailable);
  if (updatable.length === 0) {
    console.log(chalk6.green("\nAll packages are up to date!"));
    return [];
  }
  if (!process.stdout.isTTY) {
    console.log(chalk6.yellow("Non-interactive environment detected, skipping selection."));
    return [];
  }
  try {
    return await updoPrompt({ rows: updatable });
  } catch (error) {
    if (error instanceof ExitPromptError) {
      return [];
    }
    throw error;
  }
}

// src/lib/updo/resolveVersions.ts
import semver2 from "semver";
function computeWanted(info, range) {
  return semver2.maxSatisfying(info.versions, range) ?? void 0;
}
function isUnboundedAbove(range) {
  try {
    const parsed = new semver2.Range(range);
    return parsed.set.some((comparators) => !comparators.some((c) => c.operator === "<" || c.operator === "<="));
  } catch {
    return false;
  }
}
function computePrerelease(info, latest) {
  if (!info) return void 0;
  let best;
  for (const tag of ["next", "rc", "beta"]) {
    const v = info.distTags[tag];
    if (!v) continue;
    if (!best || semver2.gt(v, best)) best = v;
  }
  if (!best) return void 0;
  if (latest && !semver2.gt(best, latest)) return void 0;
  return best;
}
function normalizeRange(prefix, version) {
  return version ? `${prefix}${version}` : void 0;
}
function maxVersion(versions) {
  let best;
  for (const version of versions) {
    if (!version) continue;
    if (!best || semver2.gt(version, best)) {
      best = version;
    }
  }
  return best;
}
function wouldChange(targetRange, declaredRanges) {
  return !!targetRange && declaredRanges.some((range) => range !== targetRange);
}
function resolveVersions(deps, registry) {
  const resolved = [];
  const grouped = /* @__PURE__ */ new Map();
  for (const dep of deps) {
    const existing = grouped.get(dep.name);
    if (existing) {
      existing.push(dep);
    } else {
      grouped.set(dep.name, [dep]);
    }
  }
  for (const [name, group] of grouped) {
    const info = registry.get(name);
    const preferredRangePrefix = group.some((dep) => dep.range.startsWith("^")) ? "^" : "~";
    const declaredRanges = [...new Set(group.map((dep) => dep.range))];
    const workspaces = [...new Set(group.map((dep) => dep.workspaceName))];
    const current = declaredRanges.length === 1 ? declaredRanges[0] : "mixed";
    const boundedRanges = declaredRanges.filter((range) => !isUnboundedAbove(range));
    const rangesForWanted = boundedRanges.length > 0 ? boundedRanges : declaredRanges;
    const wanted = normalizeRange(
      preferredRangePrefix,
      info ? maxVersion(rangesForWanted.map((range) => computeWanted(info, range))) : void 0
    );
    const latest = normalizeRange(preferredRangePrefix, info?.distTags.latest);
    const next = normalizeRange(preferredRangePrefix, computePrerelease(info, info?.distTags.latest));
    const updateAvailable = wouldChange(wanted, declaredRanges) || wouldChange(latest, declaredRanges) || wouldChange(next, declaredRanges);
    resolved.push({
      current,
      declaredRanges,
      latest,
      name,
      next,
      preferredRangePrefix,
      updateAvailable,
      wanted: wanted && wanted !== current ? wanted : void 0,
      workspaces
    });
  }
  return resolved.toSorted((a, b) => {
    if (a.updateAvailable !== b.updateAvailable) return a.updateAvailable ? -1 : 1;
    return a.name.localeCompare(b.name);
  });
}

// src/lib/updo/runUpdo.ts
async function runUpdo(pm, _options = {}) {
  const cwd = INIT_CWD();
  const workspaces = pm.listWorkspaces();
  const workspaceNames = new Set(workspaces.map((ws) => ws.name));
  const uniqueDependencyNames = /* @__PURE__ */ new Set();
  console.log(chalk7.gray("Scanning workspace dependencies..."));
  const declaredDeps = collectWorkspaceDeps(cwd, workspaces, workspaceNames);
  for (const dep of declaredDeps) {
    uniqueDependencyNames.add(dep.name);
  }
  console.log(chalk7.gray(`  Found ${uniqueDependencyNames.size} unique dependencies across ${workspaces.length} workspaces`));
  console.log(chalk7.gray("Fetching registry info..."));
  const registryInfo = await fetchAllRegistryInfo([...uniqueDependencyNames]);
  const resolved = resolveVersions(declaredDeps, registryInfo);
  const updates = await interactiveSelect(resolved);
  if (updates.length === 0) {
    console.log(chalk7.gray("No updates selected."));
    return 0;
  }
  console.log(chalk7.gray(`
Applying ${updates.length} updates...`));
  const modified = applyUpdates(cwd, workspaces, updates);
  console.log(chalk7.gray(`  Modified ${modified} package.json files`));
  console.log(chalk7.gray("Installing updated dependencies..."));
  return runSteps("Updo", [
    pm.install(),
    pm.dedupe()
  ], true);
}
export {
  runUpdo
};
//# sourceMappingURL=runUpdo.mjs.map