// 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 detectPackageManagerFromPackageJson(cwd = process.cwd()) {
  const packageManager = readRootPackageJson(cwd)?.packageManager;
  if (!(packageManager != null && packageManager.length > 0)) return void 0;
  return packageManager.split("@", 1)[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 != null && packageManager.length > 0 && 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/reporting/runWithEnvelope.ts
import { performance as performance2 } from "node:perf_hooks";

// src/lib/reporting/xyReporter.ts
import { performance } from "node:perf_hooks";
var reporterState = {
  currentCommand: "unknown",
  isEnvelopeEmitted: false,
  isJsonModeEnabled: false,
  isStrictModeEnabled: false,
  originalStdoutWrite: void 0,
  startTime: 0
};
function isJsonMode() {
  return reporterState.isJsonModeEnabled;
}
function setCurrentCommand(name) {
  reporterState.currentCommand = name;
  reporterState.startTime = performance.now();
  reporterState.isEnvelopeEmitted = false;
}
function emitJson(envelope) {
  if (reporterState.isEnvelopeEmitted) return;
  reporterState.isEnvelopeEmitted = true;
  const json = JSON.stringify(envelope) + "\n";
  if (reporterState.originalStdoutWrite) {
    reporterState.originalStdoutWrite(json);
  } else {
    process.stdout.write(json);
  }
}

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

// src/actions/license.ts
import chalk from "chalk";
import { init } from "license-checker-rseidelsohn";
var license = async (pkg) => {
  const workspaces = getPackageManager().listWorkspaces();
  const workspaceList = workspaces.filter(({ name }) => {
    return pkg === void 0 || name === pkg;
  });
  const exclude = /* @__PURE__ */ new Set([
    "MIT",
    "MIT*",
    "ISC",
    "Apache-2.0",
    "BSD",
    "BSD*",
    "BSD-2-Clause",
    "BSD-3-Clause",
    "CC-BY-4.0",
    "Unlicense",
    "CC-BY-3.0",
    "CC0-1.0",
    "LGPL-3.0-only",
    "LGPL-3.0",
    "LGPL-3.0-or-later",
    "Python-2.0"
  ]);
  console.log(chalk.green("License Checker"));
  const results = await Promise.all(
    workspaceList.map(({ location, name }) => {
      return new Promise((resolve) => {
        init({ production: true, start: location }, (error, packages) => {
          if (error) {
            console.error(chalk.red(`License Checker [${name}] Error`));
            console.error(chalk.gray(error));
            console.log("\n");
            resolve(1);
          } else {
            console.log(chalk.green(`License Checker [${name}]`));
            let count = 0;
            for (const [name2, info] of Object.entries(packages)) {
              const licenses = Array.isArray(info.licenses) ? info.licenses : [info.licenses];
              for (const license2 of licenses) {
                if (license2 != null && license2.length > 0) {
                  const processedLicense = license2.startsWith("(") && license2.at(-1) === ")" ? license2.slice(1, -2) : license2;
                  const orLicenses = processedLicense.split(" OR ");
                  let isOrLicenseFound = false;
                  for (const orLicense of orLicenses) {
                    if (exclude.has(orLicense)) {
                      isOrLicenseFound = true;
                    }
                  }
                  if (!isOrLicenseFound) {
                    count++;
                    console.warn(chalk.yellow(`${name2}: Package License not allowed [${license2}]`));
                  }
                }
              }
            }
            console.log("\n");
            resolve(count);
          }
        });
      });
    })
  );
  return results.reduce((prev, value) => prev || value, 0);
};

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

// src/xy/common/licenseCommand.ts
var licenseCommand = {
  builder: (yargs) => {
    return packagePositionalParam(yargs);
  },
  command: "license [package]",
  describe: "License - Check licenses of dependencies",
  handler: async (argv) => {
    if (Boolean(argv.verbose)) console.log(`License: ${argv.package ?? "all"}`);
    await withEnvelope("license", () => license());
  }
};
export {
  licenseCommand
};
//# sourceMappingURL=licenseCommand.mjs.map
