// 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 "node: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/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 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",
    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",
    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 "node:fs";
import PATH from "node: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 readWorkspacePatternsFromPackageJson(cwd = process.cwd()) {
  const pkg = readRootPackageJson(cwd);
  if (!pkg?.workspaces) return [];
  if (Array.isArray(pkg.workspaces)) return [...pkg.workspaces];
  return pkg.workspaces.packages ? [...pkg.workspaces.packages] : [];
}
function readPnpmWorkspacePatterns(cwd = process.cwd()) {
  const wsPath = PATH.resolve(cwd, "pnpm-workspace.yaml");
  if (!existsSync(wsPath)) return [];
  const content = readFileSync(wsPath, "utf8");
  const patterns = [];
  let inPackages = false;
  for (const line of content.split("\n")) {
    if (/^packages\s*:/.test(line.trim())) {
      inPackages = true;
      continue;
    }
    if (inPackages) {
      const match = /^\s+-\s+['"]?([^'"]+)['"]?\s*$/.exec(line);
      if (match) {
        patterns.push(match[1]);
      } else if (line.trim() !== "" && !/^\s/.test(line)) {
        break;
      }
    }
  }
  return patterns;
}
function readWorkspacePatterns(cwd = process.cwd()) {
  const fromPackageJson = readWorkspacePatternsFromPackageJson(cwd);
  return fromPackageJson.length > 0 ? fromPackageJson : readPnpmWorkspacePatterns(cwd);
}
function listDeclaredWorkspaces(cwd = process.cwd()) {
  const patterns = readWorkspacePatterns(cwd);
  const seen = /* @__PURE__ */ new Set();
  const workspaces = [];
  for (const pattern of patterns) {
    const matches = globSync(PATH.posix.join(pattern.replaceAll(PATH.sep, "/"), "package.json"), {
      absolute: true,
      cwd,
      ignore: ["**/node_modules/**", "**/dist/**", "**/build/**"]
    });
    for (const match of matches) {
      const pkg = readJsonFile(match);
      if (!pkg?.name) continue;
      const location = PATH.relative(cwd, PATH.dirname(match)) || ".";
      if (seen.has(location)) continue;
      seen.add(location);
      workspaces.push({ location, name: pkg.name });
    }
  }
  return workspaces.toSorted((a, b) => a.location.localeCompare(b.location));
}
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/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 "node:fs";
import path from "node: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/pnpmConfig/readMinReleaseAge.ts
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
import os from "node:os";
import PATH2 from "node:path";
import * as yaml from "yaml";
function emptySource() {
  return {
    excludeSet: void 0,
    ignoreMissingTime: void 0,
    minutes: void 0,
    strict: void 0
  };
}
function coerceNumber(value) {
  if (typeof value === "number" && Number.isFinite(value)) return value;
  if (typeof value === "string" && value.trim() !== "") {
    const n = Number(value);
    return Number.isFinite(n) ? n : void 0;
  }
  return void 0;
}
function coerceBoolean(value) {
  if (typeof value === "boolean") return value;
  if (typeof value === "string") {
    const lower = value.trim().toLowerCase();
    if (lower === "true") return true;
    if (lower === "false") return false;
  }
  return void 0;
}
function coerceStringArray(value) {
  if (Array.isArray(value)) {
    return value.filter((v) => typeof v === "string" && v.length > 0);
  }
  if (typeof value === "string") {
    return value.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
  }
  return void 0;
}
function readWorkspaceYaml(filePath) {
  const out = emptySource();
  if (!existsSync3(filePath)) return out;
  let parsed;
  try {
    parsed = yaml.parse(readFileSync3(filePath, "utf8"));
  } catch {
    return out;
  }
  if (parsed === null || typeof parsed !== "object") return out;
  const obj = parsed;
  out.minutes = coerceNumber(obj.minimumReleaseAge);
  out.excludeSet = coerceStringArray(obj.minimumReleaseAgeExclude);
  out.ignoreMissingTime = coerceBoolean(obj.minimumReleaseAgeIgnoreMissingTime);
  out.strict = coerceBoolean(obj.minimumReleaseAgeStrict);
  return out;
}
function applyNpmrcKey(out, key, value) {
  switch (key) {
    case "minimum-release-age":
    case "minimumreleaseage": {
      const n = coerceNumber(value);
      if (n !== void 0) out.minutes = n;
      return;
    }
    case "minimum-release-age-exclude":
    case "minimumreleaseageexclude": {
      const arr = coerceStringArray(value);
      if (arr !== void 0) out.excludeSet = arr;
      return;
    }
    case "minimum-release-age-ignore-missing-time":
    case "minimumreleaseageignoremissingtime": {
      const b = coerceBoolean(value);
      if (b !== void 0) out.ignoreMissingTime = b;
      return;
    }
    case "minimum-release-age-strict":
    case "minimumreleaseagestrict": {
      const b = coerceBoolean(value);
      if (b !== void 0) out.strict = b;
    }
  }
}
function readNpmrc(filePath) {
  const out = emptySource();
  if (!existsSync3(filePath)) return out;
  let text;
  try {
    text = readFileSync3(filePath, "utf8");
  } catch {
    return out;
  }
  for (const rawLine of text.split("\n")) {
    const line = rawLine.trim();
    if (!line || line.startsWith("#") || line.startsWith(";")) continue;
    const eq = line.indexOf("=");
    if (eq === -1) continue;
    const key = line.slice(0, eq).trim().toLowerCase();
    const value = line.slice(eq + 1).trim().replaceAll(/^["']|["']$/g, "");
    applyNpmrcKey(out, key, value);
  }
  return out;
}
function merge(primary, fallback) {
  return {
    minutes: primary.minutes ?? fallback.minutes,
    excludeSet: primary.excludeSet ?? fallback.excludeSet,
    ignoreMissingTime: primary.ignoreMissingTime ?? fallback.ignoreMissingTime,
    strict: primary.strict ?? fallback.strict
  };
}
function readMinReleaseAgeConfig(cwd) {
  const workspace = readWorkspaceYaml(PATH2.resolve(cwd, "pnpm-workspace.yaml"));
  const projectNpmrc = readNpmrc(PATH2.resolve(cwd, ".npmrc"));
  const userNpmrc = readNpmrc(PATH2.resolve(os.homedir(), ".npmrc"));
  const merged = merge(merge(workspace, projectNpmrc), userNpmrc);
  return {
    minutes: merged.minutes,
    exclude: merged.excludeSet ?? [],
    ignoreMissingTime: merged.ignoreMissingTime ?? true,
    strict: merged.strict ?? true
  };
}

// src/lib/reporting/xyReporter.ts
var jsonMode = false;
function isJsonMode() {
  return jsonMode;
}

// src/lib/runSteps.ts
import { existsSync as existsSync4 } from "node: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" && !existsSync4(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 = spawnSync(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
        },
        stdio: isJsonMode() ? ["inherit", 2, 2] : "inherit"
      }).status ?? 0;
      checkResult(name, status, "error", exitOnFail);
      totalStatus += status ?? 0;
    }
    return totalStatus;
  }, !!exitOnFail);
};

// src/lib/updo/applyUpdates.ts
import { readFileSync as readFileSync4, writeFileSync } from "node:fs";
import PATH3 from "node:path";
import chalk5 from "chalk";
import semver from "semver";
function isSimpleRange(range) {
  const trimmed = range.trim();
  if (trimmed.startsWith("^") || trimmed.startsWith("~")) return true;
  return semver.valid(trimmed) !== null;
}
function applyToBag(bag, updateMap) {
  if (!bag) return false;
  let changed = false;
  for (const name of Object.keys(bag)) {
    const update = updateMap.get(name);
    if (!update) continue;
    if (bag[name] !== update.targetRange) {
      bag[name] = update.targetRange;
      changed = true;
    }
  }
  return changed;
}
function applyToPeerBag(pkg, updateMap) {
  const peer = pkg.peerDependencies;
  if (!peer) return false;
  let changed = false;
  for (const name of Object.keys(peer)) {
    const update = updateMap.get(name);
    if (!update) continue;
    if (pkg.dependencies?.[name] !== void 0) continue;
    if (pkg.devDependencies?.[name] !== void 0) continue;
    if (!isSimpleRange(peer[name])) continue;
    if (peer[name] !== update.targetRange) {
      peer[name] = update.targetRange;
      changed = true;
    }
  }
  return changed;
}
function applyToWorkspace(pkgPath, updateMap) {
  let content;
  try {
    content = readFileSync4(pkgPath, "utf8");
  } catch {
    return false;
  }
  const pkg = JSON.parse(content);
  const depsChanged = applyToBag(pkg.dependencies, updateMap);
  const devDepsChanged = applyToBag(pkg.devDependencies, updateMap);
  const peerChanged = applyToPeerBag(pkg, updateMap);
  const changed = depsChanged || devDepsChanged || peerChanged;
  if (changed) {
    writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}
`);
  }
  return changed;
}
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 = PATH3.resolve(cwd, ws.location, "package.json");
    if (applyToWorkspace(pkgPath, updateMap)) {
      modified++;
      console.log(chalk5.gray(`  Updated ${ws.name}`));
    }
  }
  return modified;
}

// src/lib/updo/collectWorkspaceDeps.ts
import { readFileSync as readFileSync5 } from "node:fs";
import PATH4 from "node:path";
var DEP_FIELDS = ["dependencies", "devDependencies", "peerDependencies"];
function collectWorkspaceDeps(cwd, workspaces, workspaceNames) {
  const declaredDeps = [];
  for (const ws of workspaces) {
    const pkgPath = PATH4.resolve(cwd, ws.location, "package.json");
    let pkg;
    try {
      pkg = JSON.parse(readFileSync5(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/updo/fetchRegistryInfo.ts
import fs2 from "node:fs";
import os2 from "node:os";
import path2 from "node:path";
var REGISTRY_BASE = "https://registry.npmjs.org";
function parseNpmrc(filePath, into) {
  let text;
  try {
    text = fs2.readFileSync(filePath, "utf8");
  } catch {
    return;
  }
  for (const rawLine of text.split("\n")) {
    const line = rawLine.trim();
    if (!line || line.startsWith("#") || line.startsWith(";")) continue;
    const tokenMatch = /^\/\/([^:]+?):_authToken=(.+)$/.exec(line);
    if (tokenMatch) {
      const hostPath = tokenMatch[1];
      const token = tokenMatch[2].trim().replaceAll(/^["']|["']$/g, "");
      const host = hostPath.split("/")[0];
      into.tokens.set(`https://${host}`, token);
      continue;
    }
    const scopeMatch = /^(@[^:]+):registry=(.+)$/.exec(line);
    if (scopeMatch) {
      into.scopeRegistries.set(scopeMatch[1], scopeMatch[2].trim().replace(/\/$/, ""));
    }
  }
}
var cachedConfig;
function loadNpmrcConfig() {
  if (cachedConfig) return cachedConfig;
  const config = { scopeRegistries: /* @__PURE__ */ new Map(), tokens: /* @__PURE__ */ new Map() };
  parseNpmrc(path2.join(INIT_CWD(), ".npmrc"), config);
  parseNpmrc(path2.join(os2.homedir(), ".npmrc"), config);
  cachedConfig = config;
  return config;
}
function resolveRegistry(packageName2, config) {
  if (packageName2.startsWith("@")) {
    const scope = packageName2.split("/")[0];
    const scoped = config.scopeRegistries.get(scope);
    if (scoped) return scoped;
  }
  return REGISTRY_BASE;
}
async function fetchRegistryInfo(packageName2, options = {}) {
  try {
    const config = loadNpmrcConfig();
    const registry = resolveRegistry(packageName2, config);
    const url = `${registry}/${packageName2}`;
    const headers = {};
    if (!options.wantTimes) {
      headers.Accept = "application/vnd.npm.install-v1+json";
    }
    const token = config.tokens.get(registry);
    if (token) headers.Authorization = `Bearer ${token}`;
    const res = await fetch(url, { headers });
    if (!res.ok) {
      return { distTags: {}, versions: [] };
    }
    const data = await res.json();
    const versionKeys = Object.keys(data.versions ?? {});
    const result = {
      distTags: data["dist-tags"] ?? {},
      versions: versionKeys
    };
    if (options.wantTimes && data.time) {
      const publishTimes = {};
      for (const v of versionKeys) {
        const t = data.time[v];
        if (typeof t === "string") publishTimes[v] = t;
      }
      result.publishTimes = publishTimes;
    }
    return result;
  } catch {
    return { distTags: {}, versions: [] };
  }
}
async function fetchAllRegistryInfo(packageNames, options = {}) {
  const results = /* @__PURE__ */ new Map();
  const concurrency = options.concurrency ?? 16;
  let completed = 0;
  const total = packageNames.length;
  await runWithConcurrency(packageNames, concurrency, async (name) => {
    results.set(name, await fetchRegistryInfo(name, { wantTimes: options.wantTimes }));
    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";
var ORANGE = chalk6.hex("#ff8800");
var COLOR = {
  gray: chalk6.gray,
  green: chalk6.green,
  orange: ORANGE,
  red: chalk6.red,
  yellow: chalk6.yellow
};
function classifyCell(prefix, column, hasValue) {
  if (!hasValue) return "gray";
  if (column === "next") return "orange";
  if (column === "downgrade") return "red";
  if (prefix === "^") {
    if (column === "patch" || column === "minor") return "green";
    return "yellow";
  }
  if (prefix === "~") {
    if (column === "patch") return "green";
    if (column === "minor") return "yellow";
    return "red";
  }
  if (column === "patch") return "yellow";
  return "red";
}
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 valueOf(dep, column) {
  if (column === "patch") return dep.patch;
  if (column === "minor") return dep.minor;
  if (column === "major") return dep.major;
  if (column === "downgrade") return dep.downgrade;
  return dep.next;
}
function selectionFor(column) {
  if (column === "patch") return 0;
  if (column === "minor") return 1;
  if (column === "major") return 2;
  if (column === "next") return 3;
  return 4;
}
function renderCell(dep, column, selection, width) {
  const value = valueOf(dep, column);
  const raw = value ?? "-";
  const cls = classifyCell(dep.preferredRangePrefix, column, Boolean(value));
  const colored = COLOR[cls](raw);
  const sel = value ? dot(selection === selectionFor(column)) : " ";
  return `${sel} ${pad(raw, colored, width)}`;
}
function renderHeader(w, includeNext, includeDowngrade) {
  const parts = [
    "  ",
    chalk6.bold("Package".padEnd(w.name)),
    chalk6.bold("Current".padEnd(w.current)),
    chalk6.bold("  Patch".padEnd(w.patch + 2)),
    chalk6.bold("  Minor".padEnd(w.minor + 2)),
    chalk6.bold("  Major".padEnd(w.major + 2))
  ];
  if (includeNext) parts.push(chalk6.bold("  Next".padEnd(w.next + 2)));
  if (includeDowngrade) parts.push(chalk6.bold("  Down".padEnd(w.downgrade + 2)));
  const header = parts.join("  ");
  const totalWidth = w.name + w.current + w.patch + w.minor + w.major + (includeNext ? w.next + 2 : 0) + (includeDowngrade ? w.downgrade + 2 : 0) + 24;
  return `${header}
${chalk6.gray("\u2500".repeat(totalWidth))}`;
}
function renderRow(dep, selection, active, w, includeNext, includeDowngrade) {
  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 patch = renderCell(dep, "patch", selection, w.patch);
  const minor = renderCell(dep, "minor", selection, w.minor);
  const major = renderCell(dep, "major", selection, w.major);
  const next = includeNext ? `  ${renderCell(dep, "next", selection, w.next)}` : "";
  const downgrade = includeDowngrade ? `  ${renderCell(dep, "downgrade", selection, w.downgrade)}` : "";
  return `${pointer} ${pad(rawName, name, w.name)}  ${pad(rawCurrent, current, w.current)}  ${patch}  ${minor}  ${major}${next}${downgrade}`;
}
function getAvailableSelections(dep) {
  const available = [-1];
  if (dep.patch) available.push(0);
  if (dep.minor) available.push(1);
  if (dep.major) available.push(2);
  if (dep.next) available.push(3);
  if (dep.downgrade) available.push(4);
  return available;
}
var RISK_RANK = {
  green: 0,
  yellow: 1,
  red: 2
};
var CLASS_RANK = {
  green: 0,
  yellow: 1,
  red: 2
};
function defaultSelection(dep, options = {}) {
  const candidates = [
    {
      column: "patch",
      selection: 0,
      value: dep.patch
    },
    {
      column: "minor",
      selection: 1,
      value: dep.minor
    },
    {
      column: "major",
      selection: 2,
      value: dep.major
    }
  ];
  const maxRisk = RISK_RANK[options.risk ?? "green"];
  const eligible = candidates.filter((c) => c.value !== void 0).map((c) => {
    const cls = classifyCell(dep.preferredRangePrefix, c.column, true);
    return { ...c, cls: cls === "orange" || cls === "gray" ? "green" : cls };
  }).filter((c) => CLASS_RANK[c.cls] <= maxRisk);
  if (eligible.length === 0) {
    if (dep.downgrade && maxRisk >= CLASS_RANK.red) return 4;
    return -1;
  }
  if (options.latest) {
    return eligible.toSorted((a, b) => b.selection - a.selection)[0].selection;
  }
  const sorted = eligible.toSorted((a, b) => {
    if (a.cls !== b.cls) return CLASS_RANK[a.cls] - CLASS_RANK[b.cls];
    return a.selection - b.selection;
  });
  return sorted[0].selection;
}
function getTargetVersion(dep, selection) {
  if (selection === 0) return dep.patch;
  if (selection === 1) return dep.minor;
  if (selection === 2) return dep.major;
  if (selection === 3) return dep.next;
  if (selection === 4) return dep.downgrade;
  return void 0;
}
function computeWidths(rows) {
  let name = 7;
  let current = 7;
  let patch = 5;
  let minor = 5;
  let major = 5;
  let next = 4;
  let downgrade = 4;
  for (const dep of rows) {
    name = Math.max(name, dep.name.length);
    current = Math.max(current, dep.current.length);
    patch = Math.max(patch, (dep.patch ?? "-").length);
    minor = Math.max(minor, (dep.minor ?? "-").length);
    major = Math.max(major, (dep.major ?? "-").length);
    next = Math.max(next, (dep.next ?? "-").length);
    downgrade = Math.max(downgrade, (dep.downgrade ?? "-").length);
  }
  return {
    current,
    downgrade,
    major,
    minor,
    name,
    next,
    patch
  };
}
function renderPage(rows, cursor, selections, w, pageSize, includeNext, includeDowngrade) {
  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, includeNext, includeDowngrade));
  }
  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,
    includeNext,
    latest,
    risk
  } = config;
  const [cursor, setCursor] = useState(0);
  const [tick, setTick] = useState(0);
  const availableSelectionsRef = useRef(rows.map((r) => getAvailableSelections(r)));
  const selectionsRef = useRef(rows.map((r) => defaultSelection(r, { latest, risk })));
  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 includeDowngrade = rows.some((r) => r.downgrade !== void 0);
  const header = renderHeader(w, includeNext, includeDowngrade);
  const page = renderPage(rows, cursor, selectionsRef.current, w, 20, includeNext, includeDowngrade);
  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, options = {}) {
  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({
      includeNext: options.includeNext ?? false,
      latest: options.latest ?? false,
      risk: options.risk ?? "green",
      rows: updatable
    });
  } catch (error) {
    if (error instanceof ExitPromptError) {
      return [];
    }
    throw error;
  }
}

// src/lib/updo/resolveVersions.ts
import picomatch from "picomatch";
import semver2 from "semver";
function parseExclude(pattern) {
  const sep = pattern.indexOf("@", 1);
  if (sep > 0 && sep < pattern.length - 1) {
    const name = pattern.slice(0, sep);
    const version = pattern.slice(sep + 1);
    return { matcher: picomatch(name), version };
  }
  return { matcher: picomatch(pattern), version: void 0 };
}
function isExcluded(name, version, rules) {
  for (const rule of rules) {
    if (!rule.matcher(name)) continue;
    if (rule.version === void 0) return true;
    if (rule.version === version) return true;
    try {
      if (semver2.satisfies(version, rule.version)) return true;
    } catch {
    }
  }
  return false;
}
function buildExcludeRules(patterns) {
  return patterns.map(parseExclude);
}
function isVersionAllowed(name, version, info, filter, rules) {
  if (isExcluded(name, version, rules)) return true;
  const published = info.publishTimes?.[version];
  if (!published) return filter.ignoreMissingTime;
  const publishedMs = Date.parse(published);
  if (Number.isNaN(publishedMs)) return filter.ignoreMissingTime;
  return filter.now - publishedMs >= filter.minutes * 6e4;
}
function filterRegistryInfo(name, info, filter, rules) {
  const allowedVersions = info.versions.filter((v) => isVersionAllowed(name, v, info, filter, rules));
  const allowedSet = new Set(allowedVersions);
  const allowedDistTags = {};
  for (const [tag, version] of Object.entries(info.distTags)) {
    if (allowedSet.has(version)) allowedDistTags[tag] = version;
  }
  return {
    distTags: allowedDistTags,
    publishTimes: info.publishTimes,
    versions: allowedVersions
  };
}
function declaredRangeSatisfiable(declaredRanges, allowedStable) {
  for (const v of allowedStable) {
    for (const range of declaredRanges) {
      try {
        if (semver2.satisfies(v, range)) return true;
      } catch {
      }
    }
  }
  return false;
}
function pickDowngrade(allowedStable, anchor) {
  const below = allowedStable.filter((v) => semver2.lt(v, anchor));
  return highest(below);
}
function pickPrefix(declaredRanges) {
  if (declaredRanges.some((r) => r.startsWith("^"))) return "^";
  if (declaredRanges.some((r) => r.startsWith("~"))) return "~";
  return "";
}
function lowestAnchor(declaredRanges) {
  let lowest;
  for (const range of declaredRanges) {
    try {
      const min = semver2.minVersion(range);
      if (!min) continue;
      if (!lowest || semver2.lt(min, lowest)) lowest = min;
    } catch {
    }
  }
  return lowest;
}
function highest(versions) {
  if (versions.length === 0) return void 0;
  return versions.toSorted(semver2.rcompare)[0];
}
function isStable(version) {
  return semver2.prerelease(version) === null;
}
function format(prefix, version) {
  if (!version) return void 0;
  return `${prefix}${version}`;
}
function pickBuckets(stableVersions, anchor) {
  const above = stableVersions.filter((v) => semver2.gt(v, anchor));
  const sameMajor = above.filter((v) => semver2.major(v) === anchor.major);
  const samePatch = sameMajor.filter((v) => semver2.minor(v) === anchor.minor);
  const minorAbove = sameMajor.filter((v) => semver2.minor(v) > anchor.minor);
  const majorAbove = above.filter((v) => semver2.major(v) > anchor.major);
  return {
    major: highest(majorAbove),
    minor: highest(minorAbove),
    patch: highest(samePatch)
  };
}
function pickPrerelease(distTags, anchor) {
  let best;
  for (const tag of ["next", "rc", "beta", "alpha"]) {
    const v = distTags[tag];
    if (!v) continue;
    if (semver2.prerelease(v) === null) continue;
    if (!semver2.gt(v, anchor)) continue;
    if (!best || semver2.gt(v, best)) best = v;
  }
  return best;
}
function differentFromCurrent(value, current) {
  if (!value) return void 0;
  return value === current ? void 0 : value;
}
function resolveOne(name, group, info, options, excludeRules) {
  const nonPeer = group.filter((d) => d.depType !== "peerDependencies");
  const sourceForRange = nonPeer.length > 0 ? nonPeer : group;
  const declaredRanges = [...new Set(sourceForRange.map((d) => d.range))];
  const workspaces = [...new Set(group.map((d) => d.workspaceName))];
  const current = declaredRanges.length === 1 ? declaredRanges[0] : "mixed";
  const preferredRangePrefix = pickPrefix(declaredRanges);
  const anchor = lowestAnchor(declaredRanges);
  if (!info || !anchor) {
    return {
      current,
      declaredRanges,
      downgrade: void 0,
      major: void 0,
      minor: void 0,
      name,
      next: void 0,
      patch: void 0,
      preferredRangePrefix,
      updateAvailable: false,
      workspaces
    };
  }
  const effectiveInfo = options.minReleaseAge ? filterRegistryInfo(name, info, options.minReleaseAge, excludeRules) : info;
  const stable = effectiveInfo.versions.filter((v) => semver2.valid(v) !== null && isStable(v));
  const downgrade = options.minReleaseAge && !declaredRangeSatisfiable(declaredRanges, stable) ? format(preferredRangePrefix, pickDowngrade(stable, anchor)) : void 0;
  const buckets = pickBuckets(stable, anchor);
  const patchRaw = format(preferredRangePrefix, buckets.patch);
  const minorRaw = format(preferredRangePrefix, buckets.minor);
  const majorRaw = format(preferredRangePrefix, buckets.major);
  const nextRaw = options.includeNext ? format(preferredRangePrefix, pickPrerelease(effectiveInfo.distTags, anchor)) : void 0;
  let patch = differentFromCurrent(patchRaw, current);
  const minor = differentFromCurrent(minorRaw, current);
  const major = differentFromCurrent(majorRaw, current);
  const next = differentFromCurrent(nextRaw, current);
  if (!patch && declaredRanges.length > 1) {
    const allSameAnchor = declaredRanges.every((range) => {
      const v = semver2.minVersion(range);
      return v !== null && v.version === anchor.version;
    });
    if (allSameAnchor) {
      const normalized = `${preferredRangePrefix}${anchor.version}`;
      if (declaredRanges.some((r) => r !== normalized)) {
        patch = normalized;
      }
    }
  }
  const updateAvailable = Boolean(patch ?? minor ?? major ?? next ?? downgrade);
  return {
    current,
    declaredRanges,
    downgrade,
    major,
    minor,
    name,
    next,
    patch,
    preferredRangePrefix,
    updateAvailable,
    workspaces
  };
}
function resolveVersions(deps, registry, options = {}) {
  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]);
  }
  const excludeRules = options.minReleaseAge ? buildExcludeRules(options.minReleaseAge.exclude) : [];
  const resolved = [];
  for (const [name, group] of grouped) {
    resolved.push(resolveOne(name, group, registry.get(name), options, excludeRules));
  }
  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
import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
import PATH5 from "node:path";
import chalk7 from "chalk";
function listWorkspacesFromFs(cwd) {
  const workspaces = listDeclaredWorkspaces(cwd);
  const rootPath = PATH5.resolve(cwd, "package.json");
  if (existsSync5(rootPath)) {
    try {
      const root = JSON.parse(readFileSync6(rootPath, "utf8"));
      if (root.name && !workspaces.some((ws) => ws.location === ".")) {
        workspaces.unshift({ location: ".", name: root.name });
      }
    } catch {
    }
  }
  return workspaces;
}
function resolveMinReleaseAgeFilter(pm, cwd) {
  if (pm.name !== "pnpm") return void 0;
  const cfg = readMinReleaseAgeConfig(cwd);
  if (cfg.minutes === void 0 || cfg.minutes <= 0) return void 0;
  console.log(chalk7.gray(`  Filtering versions by minimumReleaseAge=${cfg.minutes}m (pnpm); ${cfg.exclude.length} exclude(s)`));
  return {
    exclude: cfg.exclude,
    ignoreMissingTime: cfg.ignoreMissingTime,
    minutes: cfg.minutes,
    now: Date.now()
  };
}
async function runUpdo(pm, options = {}) {
  const cwd = INIT_CWD();
  const workspaces = listWorkspacesFromFs(cwd);
  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`));
  const minReleaseAge = resolveMinReleaseAgeFilter(pm, cwd);
  console.log(chalk7.gray("Fetching registry info..."));
  const registryInfo = await fetchAllRegistryInfo([...uniqueDependencyNames], { wantTimes: minReleaseAge !== void 0 });
  const includeNext = options.next ?? false;
  const latest = options.latest ?? false;
  const risk = options.risk ?? "green";
  const resolved = resolveVersions(declaredDeps, registryInfo, { includeNext, minReleaseAge });
  const downgradeCount = resolved.filter((r) => r.downgrade !== void 0).length;
  if (downgradeCount > 0) {
    console.log(chalk7.yellow(`  ${downgradeCount} package(s) have a current range that pnpm will reject \u2014 see the red "Down" column for downgrade suggestions.`));
  }
  const updates = await interactiveSelect(resolved, {
    includeNext,
    latest,
    risk
  });
  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);
}

// src/actions/updo.ts
var updo = async ({
  latest = false,
  next = false,
  risk = "green"
} = {}) => {
  const pm = getPackageManager();
  return await runUpdo(pm, {
    latest,
    next,
    risk
  });
};
export {
  updo
};
//# sourceMappingURL=updo.mjs.map
