// src/pm/pnpmPackageManager.ts
import { readFileSync as readFileSync2 } from "node:fs";
import PATH2 from "node:path";

// src/pm/resolveWorkspace.ts
import chalk from "chalk";
function shortName(name) {
  const slash = name.lastIndexOf("/");
  return slash === -1 ? name : name.slice(slash + 1);
}
function resolveWorkspace(workspaces, query) {
  const exact = workspaces.find((ws) => ws.name === query);
  if (exact) return exact;
  const byLocation = workspaces.find((ws) => ws.location === query);
  if (byLocation) return byLocation;
  const byShort = workspaces.filter((ws) => shortName(ws.name) === query);
  if (byShort.length === 1) return byShort[0];
  if (byShort.length > 1) {
    console.error(chalk.red(`Ambiguous workspace "${query}"; matches: ${byShort.map((ws) => ws.name).join(", ")}`));
    return void 0;
  }
  return void 0;
}

// src/lib/packageManagerRuntime.ts
import fs from "node:fs";
import chalk2 from "chalk";

// src/lib/crossSpawn.ts
import crossSpawn from "cross-spawn";
function spawnSync(command, args, options) {
  return crossSpawn.sync(command, args, options);
}

// src/lib/packageManagerRuntime.ts
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"
};
var SUPPORTED_PLATFORMS = ["darwin", "linux", "win32"];
function currentPlatform() {
  return SUPPORTED_PLATFORMS.find((platform) => platform === process.platform) ?? "unknown";
}
function shouldAskYesNo(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 shouldInstallWithHomebrew(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 didEnsurePackageManagerInstalled(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 isConfirmed = shouldAskYesNo(chalk2.cyan(`Install ${displayName} with Homebrew now? [y/N] `));
  if (!isConfirmed) {
    console.error(chalk2.gray(`Skipping install. Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk2.cyan(`Installing ${displayName} via Homebrew...
`));
  if (!shouldInstallWithHomebrew(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;
}
function failureResult() {
  return {
    output: ["", ""],
    pid: 0,
    signal: null,
    status: 1,
    stderr: "",
    stdout: ""
  };
}
function spawnPackageManagerSync(pm, args, options) {
  if (!didEnsurePackageManagerInstalled(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(path) {
  if (!existsSync(path)) return void 0;
  try {
    return JSON.parse(readFileSync(path, "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 isInPackages = false;
  for (const line of content.split("\n")) {
    if (/^packages\s*:/.test(line.trim())) {
      isInPackages = true;
      continue;
    }
    if (isInPackages) {
      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 workspaceFromPackageJsonMatch(match, cwd, seen) {
  const pkg = readJsonFile(match);
  const name = pkg?.name;
  if (name === void 0 || name.length === 0) return void 0;
  const location = PATH.relative(cwd, PATH.dirname(match)) || ".";
  if (seen.has(location)) return void 0;
  seen.add(location);
  return { location, name };
}
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 workspace = workspaceFromPackageJsonMatch(match, cwd, seen);
      if (workspace) workspaces.push(workspace);
    }
  }
  return workspaces.toSorted((a, b) => a.location.localeCompare(b.location));
}

// src/pm/pnpmPackageManager.ts
function collectWorkspaceInstalledVersions(workspace, versions) {
  for (const depField of ["dependencies", "devDependencies", "optionalDependencies"]) {
    const deps = workspace[depField];
    if (deps === void 0) continue;
    for (const [name, info] of Object.entries(deps)) {
      if (info.version.length > 0 && !versions.has(name)) {
        versions.set(name, info.version);
      }
    }
  }
}
function isPublishableWorkspace(location) {
  try {
    const pkgPath = PATH2.resolve(location, "package.json");
    const pkg = JSON.parse(readFileSync2(pkgPath, "utf8"));
    return pkg.private !== true;
  } catch {
    return false;
  }
}
var PnpmPackageManager = class {
  command = "pnpm";
  lockfile = "pnpm-lock.yaml";
  name = "pnpm";
  dedupe() {
    return ["pnpm", ["dedupe"]];
  }
  findWorkspace(name) {
    return resolveWorkspace(this.listWorkspaces(), name);
  }
  foreachWorkspace(script, args = [], options) {
    const cwd = process.env.INIT_CWD ?? process.cwd();
    if (readWorkspacePatterns(cwd).length === 0) {
      return ["pnpm", ["exec", "run-or-exec", script, ...args]];
    }
    const filter = options.incremental ?? false ? ["--filter", "...[HEAD~1]"] : [];
    const rootFlag = options.includeWorkspaceRoot ?? false ? ["--include-workspace-root"] : [];
    return ["pnpm", ["-r", `--workspace-concurrency=${options.jobs}`, ...rootFlag, ...filter, "exec", "run-or-exec", script, ...args]];
  }
  install() {
    return ["pnpm", ["install"]];
  }
  listInstalledVersions() {
    const result = spawnPackageManagerSync("pnpm", ["list", "--recursive", "--json", "--depth=0"], {
      context: { operation: "Inspect installed pnpm package versions" },
      encoding: "utf8",
      maxBuffer: 64 * 1024 * 1024
    });
    const versions = /* @__PURE__ */ new Map();
    if (result.error) return versions;
    try {
      const parsed = JSON.parse(result.stdout);
      if (Array.isArray(parsed)) {
        for (const workspace of parsed) {
          collectWorkspaceInstalledVersions(workspace, versions);
        }
      }
    } catch {
    }
    return versions;
  }
  listWorkspaces() {
    const cwd = process.env.INIT_CWD ?? process.cwd();
    const result = spawnPackageManagerSync("pnpm", ["list", "--recursive", "--json", "--depth=0"], {
      context: { operation: "List pnpm workspaces" },
      encoding: "utf8",
      maxBuffer: 64 * 1024 * 1024
    });
    if (result.error) {
      throw result.error;
    }
    try {
      const parsed = JSON.parse(result.stdout);
      if (Array.isArray(parsed)) {
        return parsed.map((pkg) => {
          const rel = PATH2.relative(cwd, pkg.path);
          return {
            location: rel === "" ? "." : rel,
            name: pkg.name
          };
        });
      }
    } catch {
    }
    return listDeclaredWorkspaces(cwd);
  }
  outdated() {
    return ["pnpm", ["outdated", "-r"]];
  }
  publish(options = {}) {
    const reporterFlags = options.verbose ?? false ? ["--loglevel=debug"] : ["--reporter=append-only"];
    const env = { NODE_OPTIONS: "--max-old-space-size=8192" };
    const baseFlags = ["--no-git-checks", ...reporterFlags];
    const chunkSize = options.chunkSize ?? 0;
    if (chunkSize <= 0) {
      return [["pnpm", ["publish", "-r", ...baseFlags], { env }]];
    }
    const publishable = this.listWorkspaces().filter((ws) => isPublishableWorkspace(ws.location));
    if (publishable.length === 0) {
      return [["pnpm", ["publish", "-r", ...baseFlags], { env }]];
    }
    const chunks = [];
    for (let i = 0; i < publishable.length; i += chunkSize) {
      chunks.push(publishable.slice(i, i + chunkSize));
    }
    return chunks.map((chunk) => [
      "pnpm",
      [
        "publish",
        ...chunk.flatMap((ws) => ["--filter", ws.name]),
        ...baseFlags
      ],
      { env }
    ]);
  }
  runInWorkspace(pkg, script, args = []) {
    const resolved = this.findWorkspace(pkg)?.name ?? pkg;
    return this.runInWorkspaceByName(resolved, script, args);
  }
  runInWorkspaceByName(pkg, script, args = []) {
    const resolved = pkg;
    return ["pnpm", ["--filter", resolved, "exec", "run-or-exec", script, ...args]];
  }
  runXy(args) {
    return ["pnpm", ["xy", ...args]];
  }
  versionApply() {
    return ["pnpm", ["install", "--lockfile-only"]];
  }
  versionBump(type) {
    return [
      ["pnpm", ["version", type, "--recursive", "--no-git-tag-version"]]
    ];
  }
};
export {
  PnpmPackageManager
};
//# sourceMappingURL=pnpmPackageManager.mjs.map
