// src/actions/deplint/findFiles.ts
import fs from "fs";
import path from "path";

// src/actions/deplint/findFilesByGlob.ts
import { globSync } from "glob";
function findFilesByGlob(cwd, pattern, ignore) {
  return globSync(pattern, {
    cwd,
    absolute: true,
    ignore,
    nodir: true
  });
}

// src/actions/deplint/findFiles.ts
var codeExtensions = "*.{ts,tsx,mts,cts,js,mjs,cjs}";
var codeExtensionRe = /\.(?:ts|tsx|mts|cts|js|mjs|cjs)$/i;
function readPackageJson(location) {
  try {
    return JSON.parse(fs.readFileSync(`${location}/package.json`, "utf8"));
  } catch {
    return void 0;
  }
}
function getWorkspaceIgnores(pkg) {
  const ws = pkg?.workspaces;
  if (Array.isArray(ws)) return ws;
  if (ws && Array.isArray(ws.packages)) return ws.packages;
  return [];
}
function getBinFiles(location, pkg) {
  const bin = pkg?.bin;
  if (!bin) return [];
  const entries = typeof bin === "string" ? [bin] : Object.values(bin);
  const results = [];
  for (const entry of entries) {
    if (typeof entry !== "string") continue;
    const abs = path.resolve(location, entry);
    if (!codeExtensionRe.test(abs)) continue;
    if (!fs.existsSync(abs)) continue;
    results.push(abs);
  }
  return results;
}
function uniqueFiles(...lists) {
  const seen = /* @__PURE__ */ new Set();
  const result = [];
  for (const list of lists) {
    for (const file of list) {
      if (seen.has(file)) continue;
      seen.add(file);
      result.push(file);
    }
  }
  return result;
}
function findFiles(location) {
  const pkg = readPackageJson(location);
  const workspaceIgnores = getWorkspaceIgnores(pkg).map((w) => `${w}/**`);
  const ignore = ["**/node_modules/**", "dist/**", ...workspaceIgnores];
  const allFiles = findFilesByGlob(location, `./**/${codeExtensions}`, ignore);
  const distGlobFiles = [
    ...findFilesByGlob(location, "./dist/**/*.d.ts"),
    ...findFilesByGlob(location, `./dist/**/${codeExtensions}`)
  ];
  const binFiles = getBinFiles(location, pkg);
  const distFiles = uniqueFiles(distGlobFiles, binFiles);
  return { allFiles, distFiles };
}

// src/actions/deplint/getDependenciesFromPackageJson.ts
import fs2 from "fs";
import path2 from "path";
function getDependenciesFromPackageJson(packageJsonPath) {
  const packageJsonFullPath = path2.resolve(packageJsonPath);
  const rawContent = fs2.readFileSync(packageJsonFullPath, "utf8");
  const packageJson = JSON.parse(rawContent);
  const depsRecord = packageJson.dependencies ?? {};
  const devDepsRecord = packageJson.devDependencies ?? {};
  const peerDepsRecord = packageJson.peerDependencies ?? {};
  const dependencies = Object.keys(depsRecord);
  const devDependencies = Object.keys(devDepsRecord);
  const peerDependencies = Object.keys(peerDepsRecord);
  const dependencyVersions = depsRecord;
  const devDependencyVersions = devDepsRecord;
  const peerDependencyVersions = peerDepsRecord;
  return {
    dependencies,
    dependencyVersions,
    devDependencies,
    devDependencyVersions,
    peerDependencies,
    peerDependencyVersions
  };
}

// src/actions/deplint/getExtendsFromTsconfigs.ts
import fs3 from "fs";
import { globSync as globSync2 } from "glob";

// src/actions/deplint/getBasePackageName.ts
function getBasePackageName(importName) {
  const importNameScrubbed = importName.replaceAll('"', "").trim();
  if (importNameScrubbed.startsWith("@")) {
    const parts = importNameScrubbed.split("/");
    return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : importNameScrubbed;
  }
  return importNameScrubbed.split("/")[0];
}

// src/actions/deplint/getExtendsFromTsconfigs.ts
var isExternalReference = (ref) => !ref.startsWith(".") && !ref.startsWith("/");
function parseExtendsField(value) {
  if (typeof value === "string") return [value];
  if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
  return [];
}
function parseTsconfig(file) {
  const content = fs3.readFileSync(file, "utf8");
  const cleaned = content.replaceAll(/\/\/.*/g, "").replaceAll(/,\s*([}\]])/g, "$1");
  return JSON.parse(cleaned);
}
function getExtendsFromTsconfigs(location) {
  const tsconfigFiles = globSync2("./tsconfig*.json", { cwd: location, absolute: true });
  const packages = /* @__PURE__ */ new Set();
  for (const file of tsconfigFiles) {
    try {
      const parsed = parseTsconfig(file);
      const refs = parseExtendsField(parsed.extends);
      for (const ref of refs) {
        if (isExternalReference(ref)) {
          packages.add(getBasePackageName(ref));
        }
      }
    } catch {
    }
  }
  return [...packages];
}

// src/actions/deplint/getExternalImportsFromFiles.ts
import fs5 from "fs";
import chalk from "chalk";

// src/actions/deplint/getImportsFromFile.ts
import fs4 from "fs";
import path3 from "path";
import ts from "typescript";
function isTypeOnlyImportClause(clause) {
  if (clause === void 0) {
    return false;
  }
  if ("phaseModifier" in clause) {
    const mod = clause.phaseModifier;
    const kind = typeof mod === "number" ? mod : mod?.kind;
    return kind === ts.SyntaxKind.TypeKeyword;
  }
  return clause.isTypeOnly ?? false;
}
function getImportsFromFile(filePath, importPaths, typeImportPaths) {
  const sourceCode = fs4.readFileSync(filePath, "utf8");
  const isMjsFile = filePath.endsWith(".mjs");
  const sourceFile = ts.createSourceFile(
    path3.basename(filePath),
    sourceCode,
    ts.ScriptTarget.Latest,
    true,
    isMjsFile ? ts.ScriptKind.JS : void 0
  );
  const imports = [];
  const typeImports = [];
  const isDeclarationFile2 = filePath.endsWith(".d.ts");
  function visit(node) {
    if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
      const moduleSpecifier = node.moduleSpecifier?.getFullText();
      const isTypeImport = ts.isImportDeclaration(node) ? isTypeOnlyImportClause(node.importClause) : false;
      if (typeof moduleSpecifier === "string") {
        const trimmed = moduleSpecifier.replaceAll("'", "").replaceAll('"', "").trim();
        if (isTypeImport || isDeclarationFile2) {
          typeImports.push(trimmed);
        } else {
          imports.push(trimmed);
        }
      }
    } else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
      const [arg] = node.arguments;
      if (ts.isStringLiteral(arg)) {
        imports.push(arg.text);
      }
    } else if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "require" && node.arguments.length > 0 && ts.isStringLiteral(node.arguments[0])) {
      imports.push(node.arguments[0].text);
    }
    ts.forEachChild(node, visit);
  }
  visit(sourceFile);
  for (const ref of sourceFile.typeReferenceDirectives) {
    typeImports.push(ref.fileName);
  }
  const importsStartsWithExcludes = [".", "#", "node:"];
  const isValidImport = (imp) => !importsStartsWithExcludes.some((exc) => imp.startsWith(exc)) && !imp.includes("*") && !imp.includes("!");
  const cleanedImports = imports.filter(isValidImport).map(getBasePackageName);
  const cleanedTypeImports = typeImports.filter(isValidImport).map(getBasePackageName);
  for (const imp of cleanedImports) {
    importPaths[imp] = importPaths[imp] ?? [];
    importPaths[imp].push(filePath);
  }
  for (const imp of cleanedTypeImports) {
    typeImportPaths[imp] = typeImportPaths[imp] ?? [];
    typeImportPaths[imp].push(filePath);
  }
  return [cleanedImports, cleanedTypeImports];
}

// src/actions/deplint/getExternalImportsFromFiles.ts
var internalImportPrefixes = [".", "#", "node:"];
var removeInternalImports = (imports) => {
  return imports.filter((imp) => !internalImportPrefixes.some((prefix) => imp.startsWith(prefix)));
};
var isDeclarationFile = (file) => file.endsWith(".d.ts") || file.endsWith(".d.cts") || file.endsWith(".d.mts");
var toolingConfigFilePattern = /(?:^|[\\/])xy\.config\.[cm]?[jt]sx?$/;
var isToolingConfigFile = (file) => toolingConfigFilePattern.test(file);
function excludeToolingConfigImports(paths) {
  const filtered = {};
  for (const [imp, files] of Object.entries(paths)) {
    const kept = files.filter((file) => !isToolingConfigFile(file));
    if (kept.length > 0) filtered[imp] = kept;
  }
  return filtered;
}
function warnMissingDist(name, location, allFiles) {
  if (allFiles.length > 0 && fs5.existsSync(`${location}/src`)) {
    const prefix = name ? `[${chalk.blue(name)}] ` : "";
    console.warn(`${prefix}${chalk.yellow("deplint: dist/ not found \u2014 using source imports (compile first for best accuracy)")}`);
  }
}
function shipsTsconfig(location) {
  try {
    const raw = fs5.readFileSync(`${location}/package.json`, "utf8");
    const pkg = JSON.parse(raw);
    const files = pkg.files;
    return files?.some((f) => f === "tsconfig.json" || f.includes("tsconfig")) ?? false;
  } catch {
    return false;
  }
}
function getExternalImportsFromFiles({
  allFiles,
  distFiles,
  location,
  name,
  tsconfigExtends = [],
  tsconfigTypes = []
}) {
  const srcImportPaths = {};
  const srcTypeImportPaths = {};
  for (const path7 of allFiles) getImportsFromFile(path7, srcImportPaths, srcTypeImportPaths);
  const allImportPaths = { ...srcImportPaths };
  for (const [key, paths] of Object.entries(srcTypeImportPaths)) {
    allImportPaths[key] = [...allImportPaths[key] ?? [], ...paths];
  }
  const distImportPaths = {};
  const distTypeImportPaths = {};
  const hasDist = distFiles.length > 0;
  if (hasDist) {
    const distTypeFiles = distFiles.filter(isDeclarationFile);
    const distCodeFiles = distFiles.filter((file) => !isDeclarationFile(file));
    for (const path7 of distCodeFiles) getImportsFromFile(path7, distImportPaths, distImportPaths);
    for (const path7 of distTypeFiles) getImportsFromFile(path7, distTypeImportPaths, distTypeImportPaths);
  } else {
    warnMissingDist(name, location, allFiles);
  }
  const effectiveDistImportPaths = hasDist ? distImportPaths : excludeToolingConfigImports(srcImportPaths);
  const effectiveDistTypeImportPaths = hasDist ? distTypeImportPaths : excludeToolingConfigImports(srcTypeImportPaths);
  const allImports = Object.keys(allImportPaths);
  const distImports = Object.keys(effectiveDistImportPaths);
  const externalAllImports = removeInternalImports(allImports);
  const externalDistImports = removeInternalImports(distImports);
  const externalDistTypeImports = removeInternalImports(Object.keys(effectiveDistTypeImportPaths));
  const isDistTsconfig = shipsTsconfig(location);
  for (const ext of tsconfigExtends) {
    if (!externalAllImports.includes(ext)) externalAllImports.push(ext);
    if (isDistTsconfig && !externalDistImports.includes(ext)) externalDistImports.push(ext);
  }
  for (const typ of tsconfigTypes) {
    if (!externalAllImports.includes(typ)) externalAllImports.push(typ);
  }
  return {
    allImportPaths,
    allImports,
    distImportPaths: effectiveDistImportPaths,
    distImports,
    externalAllImports,
    externalDistImports,
    externalDistTypeImports,
    tsconfigExtends: [...tsconfigExtends]
  };
}

// src/actions/deplint/checkPackage/getMismatchedPeerDevVersions.ts
import chalk3 from "chalk";
import semver2 from "semver";

// src/actions/deplint/packageJsonEditor.ts
import fs7 from "fs";
import chalk2 from "chalk";
import semver from "semver";
import sortPackageJson from "sort-package-json";

// src/actions/deplint/getRequiredPeerDependencies.ts
import fs6 from "fs";
import path4 from "path";
function findDepPackageJson(location, dep) {
  let dir = location;
  while (true) {
    const candidate = path4.join(dir, "node_modules", dep, "package.json");
    if (fs6.existsSync(candidate)) return candidate;
    const parent = path4.dirname(dir);
    if (parent === dir) return void 0;
    dir = parent;
  }
}
function getRequiredPeerDependencies(location, allDeps) {
  const required = /* @__PURE__ */ new Set();
  for (const dep of allDeps) {
    const depPkgPath = findDepPackageJson(location, dep);
    if (!depPkgPath) continue;
    try {
      const raw = fs6.readFileSync(depPkgPath, "utf8");
      const pkg = JSON.parse(raw);
      const peerDeps = pkg.peerDependencies;
      const meta = pkg.peerDependenciesMeta;
      if (peerDeps) {
        for (const peer of Object.keys(peerDeps)) {
          if (meta?.[peer]?.optional) continue;
          required.add(peer);
        }
      }
    } catch {
    }
  }
  return required;
}

// src/actions/deplint/packageJsonEditor.ts
function readPackageJson2(location) {
  return JSON.parse(fs7.readFileSync(`${location}/package.json`, "utf8"));
}
function writePackageJson(location, pkg) {
  const sorted = sortPackageJson(JSON.stringify(pkg, null, 2));
  fs7.writeFileSync(`${location}/package.json`, `${sorted}
`);
}
function moveDep(pkg, dep, from, to) {
  const fromSection = pkg[from];
  if (!fromSection?.[dep]) return;
  const version = fromSection[dep];
  delete fromSection[dep];
  if (Object.keys(fromSection).length === 0) {
    delete pkg[from];
  }
  const toSection = pkg[to] ?? {};
  toSection[dep] = version;
  pkg[to] = toSection;
  if (from === "peerDependencies" && to !== "peerDependencies") {
    removePeerMeta(pkg, dep);
  }
}
function removeDep(pkg, dep, section) {
  const sectionObj = pkg[section];
  if (!sectionObj?.[dep]) return;
  delete sectionObj[dep];
  if (Object.keys(sectionObj).length === 0) {
    delete pkg[section];
  }
  if (section === "peerDependencies") {
    removePeerMeta(pkg, dep);
  }
}
function addDep(pkg, dep, version, section) {
  const sectionObj = pkg[section] ?? {};
  sectionObj[dep] = version;
  pkg[section] = sectionObj;
}
function removePeerMeta(pkg, dep) {
  const meta = pkg.peerDependenciesMeta;
  if (!meta?.[dep]) return;
  delete meta[dep];
  if (Object.keys(meta).length === 0) {
    delete pkg.peerDependenciesMeta;
  }
}
function formatPeerRange(version, boundType = "major") {
  const parsed = semver.parse(version);
  if (!parsed) return `~${version}`;
  if (boundType === "minor") return `>=${parsed.version} <${parsed.major}.${parsed.minor + 1}`;
  return `>=${parsed.version} <${parsed.major + 1}`;
}
function inferPeerBoundType(devRange) {
  return devRange?.startsWith("~") ? "minor" : "major";
}
function readInstalledVersion(location, dep) {
  const depPkgPath = findDepPackageJson(location, dep);
  if (!depPkgPath) return void 0;
  try {
    const depPkg = JSON.parse(fs7.readFileSync(depPkgPath, "utf8"));
    return depPkg.version;
  } catch {
    return void 0;
  }
}
function resolvePeerLowerBound(location, dep, devRange) {
  if (devRange && devRange !== "*" && !devRange.startsWith("workspace:") && !devRange.startsWith("catalog:") && !devRange.startsWith("npm:")) {
    try {
      const min = semver.minVersion(devRange);
      if (min) return min.version;
    } catch {
    }
  }
  return readInstalledVersion(location, dep);
}
function resolveDepVersion(location, dep) {
  const version = readInstalledVersion(location, dep);
  return version ? `~${version}` : "*";
}
function resolvePeerDepVersion(location, dep, devRange) {
  const lower = resolvePeerLowerBound(location, dep, devRange);
  return lower ? formatPeerRange(lower, inferPeerBoundType(devRange)) : "*";
}
function logFix(workspace, action, dep, detail) {
  const detailStr = detail ? ` (${detail})` : "";
  console.log(`[${chalk2.blue(workspace.name)}] Fixed: ${action} ${chalk2.green(dep)}${detailStr}`);
}

// src/actions/deplint/checkPackage/getMismatchedPeerDevVersions.ts
function findMismatchedPeerDevVersions({
  peerDependencies,
  peerDependencyVersions,
  devDependencyVersions
}, exclude) {
  const mismatches = [];
  for (const dep of peerDependencies) {
    if (exclude?.has(dep)) continue;
    const peerVersion = peerDependencyVersions[dep];
    const devVersion = devDependencyVersions[dep];
    const hasWorkspaceProtocol = devVersion?.startsWith("workspace:") || peerVersion?.startsWith("workspace:");
    if (devVersion && peerVersion !== devVersion && !hasWorkspaceProtocol && !semver2.subset(devVersion, peerVersion)) {
      mismatches.push({
        dep,
        devVersion,
        peerVersion
      });
    }
  }
  return mismatches;
}
function getMismatchedPeerDevVersions({ name, location }, packageParams, exclude) {
  const mismatches = findMismatchedPeerDevVersions(packageParams, exclude);
  for (const {
    dep,
    peerVersion,
    devVersion
  } of mismatches) {
    console.log(
      `[${chalk3.blue(name)}] Peer/dev version mismatch ${chalk3.red(dep)} \u2014 peer: ${chalk3.yellow(peerVersion)}, dev: ${chalk3.cyan(devVersion)}`
    );
  }
  if (mismatches.length > 0) {
    console.log(`  ${chalk3.yellow(`${location}/package.json`)}
`);
  }
  return mismatches.length;
}
function fixMismatchedPeerDevVersions(workspace, packageParams, exclude) {
  const mismatches = findMismatchedPeerDevVersions(packageParams, exclude);
  if (mismatches.length === 0) return 0;
  const pkg = readPackageJson2(workspace.location);
  for (const { dep, devVersion } of mismatches) {
    if (pkg.peerDependencies?.[dep]) {
      pkg.peerDependencies[dep] = devVersion;
      console.log(
        `[${chalk3.blue(workspace.name)}] Fixed: synced peerDependency ${chalk3.green(dep)} to devDependency version ${chalk3.cyan(devVersion)}`
      );
    }
  }
  writePackageJson(workspace.location, pkg);
  return mismatches.length;
}

// src/actions/deplint/checkPackage/getUnlistedDependencies.ts
import { builtinModules } from "module";
import chalk4 from "chalk";

// src/actions/deplint/isTerminalPackage.ts
import fs8 from "fs";
var EXPORT_META_KEYS = /* @__PURE__ */ new Set([".", "./package.json", "./README.md"]);
function exportsLookCliOnly(exports) {
  if (exports === void 0) return true;
  if (typeof exports === "string") return true;
  return Object.keys(exports).every((k) => EXPORT_META_KEYS.has(k));
}
function isTerminalPackage(location) {
  try {
    const pkg = JSON.parse(
      fs8.readFileSync(`${location}/package.json`, "utf8")
    );
    if (pkg.private === true) return true;
    if (pkg.xy?.commands?.deplint?.terminal === true) return true;
    const hasBin = pkg.bin !== void 0;
    const hasNoLegacyEntries = !pkg.main && !pkg.module;
    if (hasBin && hasNoLegacyEntries && exportsLookCliOnly(pkg.exports)) {
      return true;
    }
    return false;
  } catch {
    return false;
  }
}

// src/actions/deplint/tsScriptsAliases.ts
var VARIANT_MAP = {
  "@xylabs/ts-scripts-yarn3": "@xylabs/ts-scripts-pnpm",
  "@xylabs/ts-scripts-pnpm": "@xylabs/ts-scripts-yarn3",
  "@xylabs/ts-scripts-react-yarn3": "@xylabs/ts-scripts-react-pnpm",
  "@xylabs/ts-scripts-react-pnpm": "@xylabs/ts-scripts-react-yarn3"
};
function isSatisfiedByTsScriptsVariant(imp, allDeps) {
  const variant = VARIANT_MAP[imp];
  return variant !== void 0 && allDeps.includes(variant);
}
function isUsedViaTsScriptsVariant(dep, imports) {
  const variant = VARIANT_MAP[dep];
  return variant !== void 0 && imports.includes(variant);
}

// src/actions/deplint/checkPackage/getUnlistedDependencies.ts
function isRuntimeImportListed(imp, name, dependencies, peerDependencies) {
  return dependencies.includes(imp) || imp === name || peerDependencies.includes(imp) || builtinModules.includes(imp);
}
function isDistTypeImportListed(imp, name, dependencies, devDependencies, peerDependencies) {
  return dependencies.includes(imp) || imp === name || dependencies.includes(`@types/${imp}`) || devDependencies.includes(`@types/${imp}`) || peerDependencies.includes(imp) || peerDependencies.includes(`@types/${imp}`) || builtinModules.includes(imp);
}
function logMissing(name, imp, importPaths) {
  console.log(`[${chalk4.blue(name)}] Missing dependency in package.json: ${chalk4.red(imp)}`);
  if (importPaths[imp]) {
    console.log(`  ${importPaths[imp].join("\n ")}`);
  }
}
function shouldBePeerDependency(imp, _location, _currentPeers, _distImports, workspaceNames) {
  if (workspaceNames?.has(imp)) return false;
  if (imp.startsWith("@types/")) return false;
  return true;
}
function findUnlistedDependencies(name, dependencies, devDependencies, peerDependencies, externalDistImports, externalDistTypeImports) {
  const allDeps = [...dependencies, ...devDependencies, ...peerDependencies];
  const results = [];
  for (const imp of externalDistImports) {
    if (!isRuntimeImportListed(imp, name, dependencies, peerDependencies) && !isSatisfiedByTsScriptsVariant(imp, allDeps)) {
      results.push({ imp, section: "dependencies" });
    }
  }
  for (const imp of externalDistTypeImports) {
    if (!isDistTypeImportListed(imp, name, dependencies, devDependencies, peerDependencies) && !isSatisfiedByTsScriptsVariant(imp, allDeps)) {
      results.push({ imp, section: "dependencies" });
    }
  }
  return results;
}
function getUnlistedDependencies({ name, location }, {
  dependencies,
  devDependencies,
  peerDependencies
}, {
  externalDistImports,
  externalDistTypeImports,
  distImportPaths
}) {
  const unlisted = findUnlistedDependencies(name, dependencies, devDependencies, peerDependencies, externalDistImports, externalDistTypeImports);
  for (const { imp } of unlisted) {
    logMissing(name, imp, distImportPaths);
  }
  if (unlisted.length > 0) {
    console.log(`  ${chalk4.yellow(`${location}/package.json`)}
`);
  }
  return unlisted.length;
}
function fixUnlistedDependencies(workspace, {
  dependencies,
  devDependencies,
  peerDependencies
}, { externalDistImports, externalDistTypeImports }, workspaceNames, isTerminal) {
  const unlisted = findUnlistedDependencies(workspace.name, dependencies, devDependencies, peerDependencies, externalDistImports, externalDistTypeImports);
  if (unlisted.length === 0) return 0;
  const pkg = readPackageJson2(workspace.location);
  const isTerminalResolved = isTerminal ?? isTerminalPackage(workspace.location);
  const devVersions = pkg.devDependencies ?? {};
  for (const { imp, section } of unlisted) {
    const isPeer = !isTerminalResolved && section === "dependencies" && shouldBePeerDependency(imp, workspace.location, peerDependencies, externalDistImports, workspaceNames);
    if (isPeer) {
      const devVersion = resolveDepVersion(workspace.location, imp);
      const peerVersion = resolvePeerDepVersion(workspace.location, imp, devVersions[imp] ?? devVersion);
      addDep(pkg, imp, peerVersion, "peerDependencies");
      logFix(workspace, "added to peerDependencies", imp, peerVersion);
      addDep(pkg, imp, devVersion, "devDependencies");
      logFix(workspace, "added to devDependencies", imp, devVersion);
    } else {
      const version = resolveDepVersion(workspace.location, imp);
      addDep(pkg, imp, version, section);
      logFix(workspace, `added to ${section}`, imp, version);
    }
  }
  writePackageJson(workspace.location, pkg);
  return unlisted.length;
}

// src/actions/deplint/checkPackage/getUnlistedDevDependencies.ts
import { builtinModules as builtinModules2 } from "module";
import chalk5 from "chalk";
function findUnlistedDevDeps(name, dependencies, devDependencies, peerDependencies, externalAllImports, distImports, externalDistTypeImports) {
  const results = [];
  for (const imp of externalAllImports) {
    if (!distImports.includes(imp) && !externalDistTypeImports.includes(imp) && imp !== name && !dependencies.includes(imp) && !dependencies.includes(`@types/${imp}`) && !peerDependencies.includes(imp) && !peerDependencies.includes(`@types/${imp}`) && !devDependencies.includes(imp) && !devDependencies.includes(`@types/${imp}`) && !builtinModules2.includes(imp) && !isSatisfiedByTsScriptsVariant(imp, [...dependencies, ...devDependencies, ...peerDependencies])) {
      results.push(imp);
    }
  }
  return results;
}
function getUnlistedDevDependencies({ name, location }, {
  devDependencies,
  dependencies,
  peerDependencies
}, {
  allImportPaths,
  externalAllImports,
  distImports,
  externalDistTypeImports
}) {
  const unlisted = findUnlistedDevDeps(name, dependencies, devDependencies, peerDependencies, externalAllImports, distImports, externalDistTypeImports);
  for (const imp of unlisted) {
    console.log(`[${chalk5.blue(name)}] Missing devDependency in package.json: ${chalk5.red(imp)}`);
    if (allImportPaths[imp]) {
      console.log(`  ${allImportPaths[imp].join("\n ")}`);
    }
  }
  if (unlisted.length > 0) {
    console.log(`  ${chalk5.yellow(`${location}/package.json`)}
`);
  }
  return unlisted.length;
}
function fixUnlistedDevDependencies(workspace, {
  devDependencies,
  dependencies,
  peerDependencies
}, {
  externalAllImports,
  distImports,
  externalDistTypeImports
}) {
  const unlisted = findUnlistedDevDeps(workspace.name, dependencies, devDependencies, peerDependencies, externalAllImports, distImports, externalDistTypeImports);
  if (unlisted.length === 0) return 0;
  const pkg = readPackageJson2(workspace.location);
  for (const imp of unlisted) {
    const version = resolveDepVersion(workspace.location, imp);
    addDep(pkg, imp, version, "devDependencies");
    logFix(workspace, "added to devDependencies", imp, version);
  }
  writePackageJson(workspace.location, pkg);
  return unlisted.length;
}

// src/actions/deplint/checkPackage/getUnnecessaryPeerDependencies.ts
import chalk7 from "chalk";

// src/actions/deplint/checkPackage/getUnsatisfiedPeerDependencies.ts
import fs9 from "fs";
import chalk6 from "chalk";
import semver3 from "semver";
import sortPackageJson2 from "sort-package-json";
function readDepPackageJson(location, dep) {
  const depPkgPath = findDepPackageJson(location, dep);
  if (!depPkgPath) return void 0;
  try {
    return JSON.parse(fs9.readFileSync(depPkgPath, "utf8"));
  } catch {
    return void 0;
  }
}
function readPeerDeps(location, dep) {
  const pkg = readDepPackageJson(location, dep);
  if (!pkg) return [];
  const peers = pkg.peerDependencies;
  return Object.keys(peers ?? {});
}
function readPeerVersionRange(location, dep, peer) {
  const pkg = readDepPackageJson(location, dep);
  if (!pkg) return void 0;
  const peers = pkg.peerDependencies;
  return peers?.[peer];
}
function readInstalledVersion2(location, dep) {
  const pkg = readDepPackageJson(location, dep);
  if (!pkg) return void 0;
  return pkg.version;
}
function isPeerOptionalInAll(location, peer, sources) {
  for (const source of sources) {
    const pkg = readDepPackageJson(location, source.requiredBy);
    if (!pkg) continue;
    const meta = pkg.peerDependenciesMeta?.[peer];
    if (!meta?.optional) return false;
  }
  return true;
}
var MAX_TRANSITIVE_DEPTH = 2;
function collectPeerSources(location, dependencies, devDependencies, peerDependencies = []) {
  const peerSources = /* @__PURE__ */ new Map();
  const visited = /* @__PURE__ */ new Set();
  function addPeerSource(peer, source) {
    const sources = peerSources.get(peer) ?? [];
    sources.push(source);
    peerSources.set(peer, sources);
  }
  function collectFromDeps(deps, isRuntime, chain) {
    for (const dep of deps) {
      const visitKey = `${dep}:${chain.join(">")}`;
      if (visited.has(visitKey)) continue;
      visited.add(visitKey);
      for (const peer of readPeerDeps(location, dep)) {
        addPeerSource(peer, {
          chain: chain.length > 0 ? [...chain, dep] : void 0,
          isRuntimeDep: isRuntime,
          requiredBy: dep
        });
      }
      if (chain.length < MAX_TRANSITIVE_DEPTH) {
        const depPkg = readDepPackageJson(location, dep);
        if (depPkg) {
          const transitiveDeps = Object.keys(depPkg.dependencies ?? {});
          collectFromDeps(transitiveDeps, isRuntime, [...chain, dep]);
        }
      }
    }
  }
  const runtimeRoots = [.../* @__PURE__ */ new Set([...dependencies, ...peerDependencies])];
  collectFromDeps(runtimeRoots, true, []);
  const devOnly = devDependencies.filter((d) => !runtimeRoots.includes(d));
  collectFromDeps(devOnly, false, []);
  return peerSources;
}
function formatChain(sources) {
  const chainsWithDepth = sources.filter((s) => s.chain && s.chain.length > 0);
  if (chainsWithDepth.length === 0) return "";
  const first = chainsWithDepth[0];
  return ` (via ${chalk6.dim(first.chain.join(" \u2192 "))})`;
}
function getRequiredTransitivePeers(location, { dependencies, devDependencies, peerDependencies }) {
  const peerSources = collectPeerSources(location, dependencies, devDependencies, peerDependencies);
  return new Set(peerSources.keys());
}
function logUnsatisfiedPeer(name, unsatisfied) {
  const {
    peer,
    sources,
    reason,
    hasRuntimeSource,
    installedVersion,
    versionRange
  } = unsatisfied;
  const chainInfo = formatChain(sources);
  if (reason === "version-mismatch") {
    const requiredByList = sources.map((s) => s.requiredBy);
    console.log(
      `[${chalk6.blue(name)}] Peer dependency version mismatch ${chalk6.red(peer)} \u2014 installed ${chalk6.yellow(installedVersion ?? "unknown")} does not satisfy ${chalk6.cyan(versionRange)} (required by ${chalk6.cyan(requiredByList.join(", "))})` + chainInfo
    );
  } else if (reason === "under-exposed") {
    const requiredByList = sources.filter((s) => s.isRuntimeDep).map((s) => s.requiredBy);
    console.log(
      `[${chalk6.blue(name)}] Under-exposed peer dependency ${chalk6.red(peer)} (required by ${chalk6.cyan(requiredByList.join(", "))})` + chainInfo + " \u2014 present in devDependencies but must also be in dependencies or peerDependencies for consumers"
    );
  } else if (hasRuntimeSource) {
    const requiredByList = sources.filter((s) => s.isRuntimeDep).map((s) => s.requiredBy);
    console.log(
      `[${chalk6.blue(name)}] Unsatisfied peer dependency ${chalk6.red(peer)} (required by ${chalk6.cyan(requiredByList.join(", "))})` + chainInfo + " \u2014 must be in dependencies or peerDependencies"
    );
  } else {
    const requiredByList = sources.map((s) => s.requiredBy);
    console.log(
      `[${chalk6.blue(name)}] Unsatisfied peer dependency ${chalk6.red(peer)} (required by devDependency ${chalk6.cyan(requiredByList.join(", "))})` + chainInfo + " \u2014 must be in dependencies, devDependencies, or peerDependencies"
    );
  }
}
function resolveVersionRange(location, sources, peer) {
  for (const source of sources) {
    const range = readPeerVersionRange(location, source.requiredBy, peer);
    if (range) return range;
  }
  return "*";
}
function checkVersionSatisfaction(location, peer, requestedRange) {
  const installedVersion = readInstalledVersion2(location, peer);
  if (!installedVersion) return { satisfied: true };
  if (requestedRange === "*") return { installedVersion, satisfied: true };
  if (requestedRange.startsWith("workspace:")) return { installedVersion, satisfied: true };
  try {
    const satisfied = semver3.satisfies(installedVersion, requestedRange, { includePrerelease: true });
    return { installedVersion, satisfied };
  } catch {
    return { installedVersion, satisfied: true };
  }
}
function findDeclaredPeerVersionMismatches(name, location, peerDependencies, peerDependencyVersions, exclude) {
  const results = [];
  for (const peer of peerDependencies) {
    if (exclude?.has(peer) || peer === name) continue;
    const declaredRange = peerDependencyVersions[peer];
    if (!declaredRange || declaredRange === "*") continue;
    const { installedVersion, satisfied } = checkVersionSatisfaction(location, peer, declaredRange);
    if (!satisfied) {
      results.push({
        hasRuntimeSource: true,
        installedVersion,
        peer,
        reason: "version-mismatch",
        sources: [{ isRuntimeDep: true, requiredBy: name }],
        versionRange: declaredRange
      });
    }
  }
  return results;
}
function findUnsatisfiedPeers({ name, location }, {
  dependencies,
  devDependencies,
  peerDependencies,
  peerDependencyVersions
}, exclude, isTerminal, forcePeerOptional) {
  const peerSources = collectPeerSources(location, dependencies, devDependencies, peerDependencies);
  const depsSet = new Set(dependencies);
  const devDepsSet = new Set(devDependencies);
  const peerDepsSet = new Set(peerDependencies);
  const isTerminalResolved = isTerminal ?? isTerminalPackage(location);
  const unsatisfied = [];
  for (const [peer, sources] of peerSources) {
    if (exclude?.has(peer) || peer === name) continue;
    if (!forcePeerOptional?.has(peer) && isPeerOptionalInAll(location, peer, sources)) continue;
    const hasRuntimeSource = sources.some((s) => s.isRuntimeDep);
    const isPresent = depsSet.has(peer) || devDepsSet.has(peer);
    if (!isPresent) {
      const versionRange2 = resolveVersionRange(location, sources, peer);
      unsatisfied.push({
        hasRuntimeSource,
        peer,
        reason: "missing",
        sources,
        versionRange: versionRange2
      });
      continue;
    }
    const hasDirectRuntimeSource = sources.some((s) => s.isRuntimeDep && !s.chain);
    if (hasDirectRuntimeSource && !isTerminalResolved && !depsSet.has(peer) && !peerDepsSet.has(peer)) {
      const versionRange2 = resolveVersionRange(location, sources, peer);
      unsatisfied.push({
        hasRuntimeSource,
        peer,
        reason: "under-exposed",
        sources,
        versionRange: versionRange2
      });
      continue;
    }
    const versionRange = resolveVersionRange(location, sources, peer);
    const { installedVersion, satisfied } = checkVersionSatisfaction(location, peer, versionRange);
    if (!satisfied) {
      const mismatchedSources = findMismatchedSources(location, sources, peer, installedVersion);
      unsatisfied.push({
        hasRuntimeSource,
        installedVersion,
        mismatchedSources,
        peer,
        reason: "version-mismatch",
        sources,
        versionRange
      });
    }
  }
  return [
    ...unsatisfied,
    ...findDeclaredPeerVersionMismatches(name, location, peerDependencies, peerDependencyVersions, exclude)
  ];
}
function findMismatchedSources(location, sources, peer, installedVersion) {
  if (!installedVersion) return [];
  return sources.filter((source) => {
    const range = readPeerVersionRange(location, source.requiredBy, peer);
    if (!range || range === "*" || range.startsWith("workspace:")) return false;
    try {
      return !semver3.satisfies(installedVersion, range, { includePrerelease: true });
    } catch {
      return false;
    }
  });
}
function getUnsatisfiedPeerDependencies(workspace, packageParams, exclude) {
  const unsatisfied = findUnsatisfiedPeers(workspace, packageParams, exclude);
  for (const entry of unsatisfied) {
    logUnsatisfiedPeer(workspace.name, entry);
  }
  if (unsatisfied.length > 0) {
    console.log(`  ${chalk6.yellow(`${workspace.location}/package.json`)}
`);
  }
  return {
    count: unsatisfied.length,
    unsatisfiedPeers: new Set(unsatisfied.map((u) => u.peer))
  };
}
function fixVersionMismatch(workspaceName, entry, pkg) {
  const {
    installedVersion,
    peer,
    versionRange
  } = entry;
  if (!installedVersion) {
    logUnsatisfiedPeer(workspaceName, entry);
    console.log(
      `  ${chalk6.dim("(version mismatch \u2014 could not resolve installed version)")}`
    );
    return false;
  }
  const match = /^(\d+)\.(\d+)/.exec(installedVersion);
  if (!match) {
    logUnsatisfiedPeer(workspaceName, entry);
    console.log(
      `  ${chalk6.dim("(version mismatch \u2014 could not resolve installed version)")}`
    );
    return false;
  }
  const expectedVersion = versionRange.startsWith("^") ? `^${match[1]}` : `~${match[1]}.${match[2]}`;
  if (pkg.peerDependencies?.[peer] && !pkg.peerDependencies[peer].startsWith("workspace:")) {
    pkg.peerDependencies[peer] = expectedVersion;
  }
  if (pkg.devDependencies?.[peer] && !pkg.devDependencies[peer].startsWith("workspace:")) {
    pkg.devDependencies[peer] = expectedVersion;
  }
  console.log(
    `[${chalk6.blue(workspaceName)}] Fixed: updated ${chalk6.green(peer)} version to ${chalk6.cyan(expectedVersion)} (was ${chalk6.yellow(versionRange)})`
  );
  return true;
}
function fixUnsatisfiedPeerDependencies(workspace, packageParams, exclude, isTerminal) {
  const isTerminalResolved = isTerminal ?? isTerminalPackage(workspace.location);
  const unsatisfied = findUnsatisfiedPeers(workspace, packageParams, exclude, isTerminalResolved);
  if (unsatisfied.length === 0) return { addedPeers: /* @__PURE__ */ new Set(), count: 0 };
  const packageJsonPath = `${workspace.location}/package.json`;
  const pkg = JSON.parse(fs9.readFileSync(packageJsonPath, "utf8"));
  const addedPeers = /* @__PURE__ */ new Set();
  let fixedCount = 0;
  for (const entry of unsatisfied) {
    const {
      hasRuntimeSource,
      peer,
      reason,
      sources,
      versionRange
    } = entry;
    if (reason === "version-mismatch") {
      if (fixVersionMismatch(workspace.name, entry, pkg)) fixedCount++;
      continue;
    }
    const sections = reason === "under-exposed" ? ["peerDependencies"] : resolvePeerTargetSections(hasRuntimeSource, isTerminalResolved);
    for (const section of sections) {
      pkg[section] = pkg[section] ?? {};
      pkg[section][peer] = versionRange;
    }
    addedPeers.add(peer);
    const requiredByList = sources.map((s) => s.requiredBy).join(", ");
    console.log(
      `[${chalk6.blue(workspace.name)}] Fixed: added ${chalk6.green(peer)}@${versionRange} to ${chalk6.cyan(sections.join(" + "))} (required by ${requiredByList})`
    );
    fixedCount++;
  }
  if (fixedCount > 0) {
    const sorted = sortPackageJson2(JSON.stringify(pkg, null, 2));
    fs9.writeFileSync(packageJsonPath, `${sorted}
`);
  }
  return { addedPeers, count: unsatisfied.length };
}
function resolvePeerTargetSections(hasRuntimeSource, isTerminal) {
  if (!hasRuntimeSource) return ["devDependencies"];
  if (isTerminal) return ["dependencies"];
  return ["peerDependencies", "devDependencies"];
}

// src/actions/deplint/checkPackage/getUnnecessaryPeerDependencies.ts
function isPeerImportedInDist(dep, externalDistImports, externalDistTypeImports) {
  const baseName = dep.replace(/^@types\//, "");
  return externalDistImports.includes(dep) || externalDistImports.includes(baseName) || externalDistTypeImports.includes(dep) || externalDistTypeImports.includes(baseName);
}
function findUnrequestedPeerDeps(location, packageParams, { externalDistImports, externalDistTypeImports }, isTerminal, exclude) {
  const requiredPeers = isTerminal ? null : getRequiredTransitivePeers(location, packageParams);
  const unrequested = [];
  for (const dep of packageParams.peerDependencies) {
    if (exclude?.has(dep)) continue;
    if (packageParams.dependencies.includes(dep)) continue;
    if (!isPeerImportedInDist(dep, externalDistImports, externalDistTypeImports)) continue;
    if (!requiredPeers?.has(dep)) {
      unrequested.push(dep);
    }
  }
  return unrequested;
}
function getUnrequestedPeerDependencies({ name, location }, packageParams, sourceParams, exclude, isTerminal) {
  const isTerminalResolved = isTerminal ?? isTerminalPackage(location);
  if (!isTerminalResolved) return 0;
  const unrequested = findUnrequestedPeerDeps(location, packageParams, sourceParams, true, exclude);
  for (const dep of unrequested) {
    console.log(
      `[${chalk7.blue(name)}] Unnecessary peerDependency ${chalk7.red(dep)} \u2014 imported in dist but no dependency requires it as a peer; should be a dependency`
    );
  }
  if (unrequested.length > 0) {
    console.log(`  ${chalk7.yellow(`${location}/package.json`)}
`);
  }
  return unrequested.length;
}
function fixUnrequestedPeerDependencies(workspace, packageParams, sourceParams, exclude, isTerminal) {
  const isTerminalResolved = isTerminal ?? isTerminalPackage(workspace.location);
  const unrequested = findUnrequestedPeerDeps(workspace.location, packageParams, sourceParams, isTerminalResolved, exclude);
  if (unrequested.length === 0) return 0;
  const tsconfigExtendsSet = new Set(sourceParams.tsconfigExtends);
  const fixable = isTerminalResolved ? unrequested : unrequested.filter((dep) => tsconfigExtendsSet.has(dep));
  if (fixable.length === 0) return 0;
  const pkg = readPackageJson2(workspace.location);
  for (const dep of fixable) {
    const version = packageParams.peerDependencyVersions[dep] ?? "*";
    removeDep(pkg, dep, "peerDependencies");
    pkg.dependencies = pkg.dependencies ?? {};
    pkg.dependencies[dep] = version;
    logFix(workspace, "moved from peerDependencies to dependencies", dep);
  }
  writePackageJson(workspace.location, pkg);
  return fixable.length;
}
function findRedundantPeerDeps({ peerDependencies, dependencies }, exclude) {
  const depsSet = new Set(dependencies);
  const redundant = [];
  for (const dep of peerDependencies) {
    if (exclude?.has(dep)) continue;
    if (depsSet.has(dep)) {
      redundant.push(dep);
    }
  }
  return redundant;
}
function getRedundantPeerDependencies({ name, location }, packageParams, exclude) {
  const redundant = findRedundantPeerDeps(packageParams, exclude);
  for (const dep of redundant) {
    console.log(
      `[${chalk7.blue(name)}] Redundant peerDependency ${chalk7.red(dep)} \u2014 already listed in dependencies`
    );
  }
  if (redundant.length > 0) {
    console.log(`  ${chalk7.yellow(`${location}/package.json`)}
`);
  }
  return redundant.length;
}
function fixRedundantPeerDependencies(workspace, packageParams, exclude) {
  const redundant = findRedundantPeerDeps(packageParams, exclude);
  if (redundant.length === 0) return 0;
  const pkg = readPackageJson2(workspace.location);
  for (const dep of redundant) {
    removeDep(pkg, dep, "peerDependencies");
    logFix(workspace, "removed redundant peerDependency (kept in dependencies)", dep);
  }
  writePackageJson(workspace.location, pkg);
  return redundant.length;
}

// src/actions/deplint/checkPackage/getUnusedDependencies.ts
import chalk8 from "chalk";
function isDepImported(dep, distImports, distTypeImports) {
  const baseName = dep.replace(/^@types\//, "");
  return distImports.includes(dep) || distImports.includes(baseName) || distTypeImports.includes(dep) || distTypeImports.includes(baseName);
}
function findUnusedDependencies(location, dependencies, devDependencies, externalDistImports, externalDistTypeImports, externalAllImports, exclude) {
  const runtimeRequiredPeers = getRequiredPeerDependencies(location, dependencies);
  const devRequiredPeers = getRequiredPeerDependencies(location, devDependencies);
  const results = [];
  for (const dep of dependencies) {
    if (exclude?.has(dep)) continue;
    if (runtimeRequiredPeers.has(dep)) continue;
    const isImported = isDepImported(dep, externalDistImports, externalDistTypeImports);
    if (isImported || isUsedViaTsScriptsVariant(dep, [...externalDistImports, ...externalDistTypeImports])) continue;
    if (devRequiredPeers.has(dep)) {
      results.push({
        dep,
        kind: "move-to-dev",
        reason: "only needed as peer of devDependencies"
      });
    } else if (externalAllImports.includes(dep)) {
      results.push({ dep, kind: "move-to-dev" });
    } else {
      results.push({ dep, kind: "remove" });
    }
  }
  return results;
}
function getUnusedDependencies({ name, location }, { dependencies, devDependencies }, {
  externalDistImports,
  externalDistTypeImports,
  externalAllImports
}, exclude) {
  const unused = findUnusedDependencies(location, dependencies, devDependencies, externalDistImports, externalDistTypeImports, externalAllImports, exclude);
  for (const {
    dep,
    kind,
    reason
  } of unused) {
    const reasonStr = reason ? ` (${reason})` : "";
    if (kind === "move-to-dev") {
      console.log(`[${chalk8.blue(name)}] dependency should be devDependency in package.json: ${chalk8.red(dep)}${reasonStr}`);
    } else {
      console.log(`[${chalk8.blue(name)}] Unused dependency in package.json: ${chalk8.red(dep)}`);
    }
  }
  if (unused.length > 0) {
    console.log(`  ${chalk8.yellow(`${location}/package.json`)}
`);
  }
  return unused.length;
}
function fixUnusedDependencies(workspace, { dependencies, devDependencies }, {
  externalDistImports,
  externalDistTypeImports,
  externalAllImports
}, exclude) {
  const unused = findUnusedDependencies(workspace.location, dependencies, devDependencies, externalDistImports, externalDistTypeImports, externalAllImports, exclude);
  if (unused.length === 0) return 0;
  const pkg = readPackageJson2(workspace.location);
  for (const { dep, kind } of unused) {
    if (kind === "move-to-dev") {
      moveDep(pkg, dep, "dependencies", "devDependencies");
      logFix(workspace, "moved to devDependencies", dep);
    } else {
      removeDep(pkg, dep, "dependencies");
      logFix(workspace, "removed from dependencies", dep);
    }
  }
  writePackageJson(workspace.location, pkg);
  return unused.length;
}

// src/actions/deplint/checkPackage/getUnusedDevDependencies.ts
import chalk9 from "chalk";

// src/actions/deplint/getCliReferencedPackagesFromFiles.ts
import fs11 from "fs";
import path6 from "path";
import ts2 from "typescript";

// src/actions/deplint/getScriptReferencedPackages.ts
import fs10 from "fs";
import path5 from "path";
function getBinNames(location, dep) {
  const depPkgPath = findDepPackageJson(location, dep);
  if (!depPkgPath) return [];
  try {
    const raw = fs10.readFileSync(depPkgPath, "utf8");
    const pkg = JSON.parse(raw);
    if (!pkg.bin) return [];
    if (typeof pkg.bin === "string") return [pkg.name?.split("/").pop() ?? dep];
    return Object.keys(pkg.bin);
  } catch {
    return [];
  }
}
function tokenizeScript(script) {
  return script.split(/[&|;$()"`\s]+/).map((t) => t.trim()).filter(Boolean);
}
function getScriptReferencedPackages(location, allDeps) {
  const pkgPath = path5.join(location, "package.json");
  let scripts;
  try {
    const raw = fs10.readFileSync(pkgPath, "utf8");
    const pkg = JSON.parse(raw);
    scripts = pkg.scripts ?? {};
  } catch {
    return /* @__PURE__ */ new Set();
  }
  const scriptText = Object.values(scripts).join(" ");
  const tokens = new Set(tokenizeScript(scriptText));
  const binToPackage = /* @__PURE__ */ new Map();
  for (const dep of allDeps) {
    const bins = getBinNames(location, dep);
    for (const bin of bins) {
      binToPackage.set(bin, dep);
    }
  }
  const referenced = /* @__PURE__ */ new Set();
  for (const token of tokens) {
    const baseName = getBasePackageName(token);
    if (allDeps.includes(baseName)) {
      referenced.add(baseName);
    }
    const pkg = binToPackage.get(token);
    if (pkg) {
      referenced.add(pkg);
    }
  }
  return referenced;
}

// src/actions/deplint/getCliReferencedPackagesFromFiles.ts
var shellCommandFunctions = /* @__PURE__ */ new Set(["execSync", "exec"]);
var directExecFunctions = /* @__PURE__ */ new Set(["spawn", "spawnSync", "execFile", "execFileSync"]);
var allExecFunctions = /* @__PURE__ */ new Set([...shellCommandFunctions, ...directExecFunctions]);
function getCommandTokensFromFile(filePath) {
  const tokens = /* @__PURE__ */ new Set();
  let sourceCode;
  try {
    sourceCode = fs11.readFileSync(filePath, "utf8");
  } catch {
    return tokens;
  }
  const isMjsFile = filePath.endsWith(".mjs");
  const sourceFile = ts2.createSourceFile(
    path6.basename(filePath),
    sourceCode,
    ts2.ScriptTarget.Latest,
    true,
    isMjsFile ? ts2.ScriptKind.JS : void 0
  );
  function visit(node) {
    if (ts2.isCallExpression(node) && node.arguments.length > 0) {
      const fnName = getFunctionName(node.expression);
      if (fnName && allExecFunctions.has(fnName)) {
        const firstArg = node.arguments[0];
        if (ts2.isStringLiteral(firstArg) || ts2.isNoSubstitutionTemplateLiteral(firstArg)) {
          const value = firstArg.text;
          if (shellCommandFunctions.has(fnName)) {
            for (const token of tokenizeScript(value)) {
              tokens.add(token);
            }
          } else {
            tokens.add(value);
          }
        } else if (ts2.isTemplateExpression(firstArg)) {
          const head = firstArg.head.text;
          if (head) {
            for (const token of tokenizeScript(head)) {
              tokens.add(token);
            }
          }
        }
      }
    }
    ts2.forEachChild(node, visit);
  }
  visit(sourceFile);
  return tokens;
}
function getFunctionName(expr) {
  if (ts2.isIdentifier(expr)) {
    return expr.text;
  }
  if (ts2.isPropertyAccessExpression(expr) && ts2.isIdentifier(expr.name)) {
    return expr.name.text;
  }
  return void 0;
}
function getCliReferencedPackagesFromFiles(allFiles, location, allDeps) {
  const allTokens = /* @__PURE__ */ new Set();
  for (const file of allFiles) {
    for (const token of getCommandTokensFromFile(file)) {
      allTokens.add(token);
    }
  }
  if (allTokens.size === 0) return /* @__PURE__ */ new Set();
  const binToPackage = /* @__PURE__ */ new Map();
  for (const dep of allDeps) {
    for (const bin of getBinNames(location, dep)) {
      binToPackage.set(bin, dep);
    }
  }
  const referenced = /* @__PURE__ */ new Set();
  for (const token of allTokens) {
    const baseName = getBasePackageName(token);
    if (allDeps.includes(baseName)) {
      referenced.add(baseName);
    }
    const pkg = binToPackage.get(token);
    if (pkg) {
      referenced.add(pkg);
    }
  }
  return referenced;
}

// src/actions/deplint/implicitDevDependencies.ts
import fs12 from "fs";
var hasFileWithExtension = (files, extensions) => files.some((f) => extensions.some((ext) => f.endsWith(ext)));
var tsExtensions = [".ts", ".tsx", ".mts", ".cts"];
var hasTypescriptFiles = ({ allFiles }) => hasFileWithExtension(allFiles, tsExtensions);
var decoratorPattern = /^\s*@[a-zA-Z]\w*/m;
var hasDecorators = ({ allFiles }) => allFiles.filter((f) => tsExtensions.some((ext) => f.endsWith(ext))).some((file) => {
  try {
    const content = fs12.readFileSync(file, "utf8");
    return decoratorPattern.test(content);
  } catch {
    return false;
  }
});
var hasDependencyRequiringTslib = ({ location, allDependencies }) => allDependencies.some((dep) => {
  const pkgPath = findDepPackageJson(location, dep);
  if (!pkgPath) return false;
  try {
    const pkg = JSON.parse(fs12.readFileSync(pkgPath, "utf8"));
    const peers = pkg.peerDependencies;
    return peers !== void 0 && "tslib" in peers;
  } catch {
    return false;
  }
});
var importPlugins = /* @__PURE__ */ new Set(["eslint-plugin-import-x", "eslint-plugin-import"]);
function hasImportPlugin({ location, allDependencies }) {
  if (allDependencies.some((d) => importPlugins.has(d))) return true;
  for (const dep of allDependencies) {
    const pkgPath = findDepPackageJson(location, dep);
    if (!pkgPath) continue;
    try {
      const pkg = JSON.parse(fs12.readFileSync(pkgPath, "utf8"));
      const transitiveDeps = [
        ...Object.keys(pkg.dependencies ?? {}),
        ...Object.keys(pkg.peerDependencies ?? {})
      ];
      if (transitiveDeps.some((d) => importPlugins.has(d))) return true;
    } catch {
    }
  }
  return false;
}
var hasVitest = ({ allDependencies }) => allDependencies.includes("vitest");
var rules = [
  {
    package: "typescript",
    isNeeded: hasTypescriptFiles
  },
  {
    package: "eslint-import-resolver-typescript",
    isNeeded: (context) => hasTypescriptFiles(context) && context.allDependencies.includes("eslint") && hasImportPlugin(context)
  },
  {
    package: "tslib",
    isNeeded: (context) => hasDecorators(context) || hasDependencyRequiringTslib(context)
  },
  {
    package: "@vitest/coverage-v8",
    isNeeded: hasVitest
  },
  {
    package: "@xylabs/toolchain",
    isNeeded: hasTypescriptFiles
  }
];
function getImplicitDevDependencies(context) {
  const implicit = /* @__PURE__ */ new Set();
  for (const rule of rules) {
    if (rule.isNeeded(context)) {
      implicit.add(rule.package);
    }
  }
  return implicit;
}

// src/actions/deplint/checkPackage/getUnusedDevDependencies.ts
var allExternalImports = ({
  externalAllImports,
  externalDistImports,
  externalDistTypeImports
}) => {
  return /* @__PURE__ */ new Set([
    ...externalAllImports,
    ...externalDistImports,
    ...externalDistTypeImports
  ]);
};
function isDevDepUsed(dep, allImports, implicitDeps, requiredPeers, scriptRefs, cliRefs) {
  if (implicitDeps.has(dep)) return true;
  if (requiredPeers.has(dep)) return true;
  if (scriptRefs.has(dep)) return true;
  if (cliRefs.has(dep)) return true;
  if (dep.startsWith("@types/")) {
    const baseName = dep.replace(/^@types\//, "");
    return allImports.has(baseName) || allImports.has(dep) || implicitDeps.has(baseName);
  }
  if (allImports.has(dep)) return true;
  return isUsedViaTsScriptsVariant(dep, [...allImports]);
}
function findUnusedDevDeps(location, dependencies, devDependencies, peerDependencies, sourceParams, fileContext, exclude) {
  const allImports = allExternalImports(sourceParams);
  const allDeps = [...dependencies, ...devDependencies, ...peerDependencies];
  const implicitDeps = getImplicitDevDependencies({
    ...fileContext,
    allDependencies: allDeps,
    location
  });
  const requiredPeers = getRequiredPeerDependencies(location, allDeps);
  const scriptRefs = getScriptReferencedPackages(location, allDeps);
  const cliRefs = getCliReferencedPackagesFromFiles(fileContext.allFiles, location, allDeps);
  const unused = [];
  for (const dep of devDependencies) {
    if (exclude?.has(dep)) continue;
    if (dependencies.includes(dep) || peerDependencies.includes(dep)) continue;
    if (!isDevDepUsed(dep, allImports, implicitDeps, requiredPeers, scriptRefs, cliRefs)) {
      unused.push(dep);
    }
  }
  return unused;
}
function getUnusedDevDependencies({ name, location }, {
  devDependencies,
  dependencies,
  peerDependencies
}, sourceParams, fileContext, exclude) {
  const unused = findUnusedDevDeps(location, dependencies, devDependencies, peerDependencies, sourceParams, fileContext, exclude);
  for (const dep of unused) {
    console.log(`[${chalk9.blue(name)}] Unused devDependency in package.json: ${chalk9.red(dep)}`);
  }
  if (unused.length > 0) {
    console.log(`  ${chalk9.yellow(`${location}/package.json`)}
`);
  }
  return unused.length;
}
function fixUnusedDevDependencies(workspace, {
  devDependencies,
  dependencies,
  peerDependencies
}, sourceParams, fileContext, exclude) {
  const unused = findUnusedDevDeps(workspace.location, dependencies, devDependencies, peerDependencies, sourceParams, fileContext, exclude);
  if (unused.length === 0) return 0;
  const pkg = readPackageJson2(workspace.location);
  for (const dep of unused) {
    removeDep(pkg, dep, "devDependencies");
    logFix(workspace, "removed from devDependencies", dep);
  }
  writePackageJson(workspace.location, pkg);
  return unused.length;
}

// src/actions/deplint/checkPackage/getUnusedPeerDependencies.ts
import chalk10 from "chalk";
function isPeerUsed(dep, externalDistImports, externalDistTypeImports) {
  const baseName = dep.replace(/^@types\//, "");
  return externalDistImports.includes(dep) || externalDistImports.includes(baseName) || externalDistTypeImports.includes(dep) || externalDistTypeImports.includes(baseName);
}
function findUnusedPeerDeps(peerDependencies, externalDistImports, externalDistTypeImports, exclude) {
  const unused = [];
  for (const dep of peerDependencies) {
    if (exclude?.has(dep)) continue;
    if (!isPeerUsed(dep, externalDistImports, externalDistTypeImports)) {
      unused.push(dep);
    }
  }
  return unused;
}
function getUnusedPeerDependencies({ name, location }, { peerDependencies, dependencies }, { externalDistImports, externalDistTypeImports }, exclude) {
  const unused = findUnusedPeerDeps(peerDependencies, externalDistImports, externalDistTypeImports, exclude);
  for (const dep of unused) {
    if (dependencies.includes(dep)) {
      console.log(`[${chalk10.blue(name)}] Unused peerDependency [already a dependency] in package.json: ${chalk10.red(dep)}`);
    } else {
      console.log(`[${chalk10.blue(name)}] Unused peerDependency in package.json: ${chalk10.red(dep)}`);
    }
  }
  if (unused.length > 0) {
    console.log(`  ${chalk10.yellow(`${location}/package.json`)}
`);
  }
  return unused.length;
}
function fixUnusedPeerDependencies(workspace, { peerDependencies }, { externalDistImports, externalDistTypeImports }, exclude) {
  const unused = findUnusedPeerDeps(peerDependencies, externalDistImports, externalDistTypeImports, exclude);
  if (unused.length === 0) return 0;
  const pkg = readPackageJson2(workspace.location);
  for (const dep of unused) {
    removeDep(pkg, dep, "peerDependencies");
    logFix(workspace, "removed from peerDependencies", dep);
  }
  writePackageJson(workspace.location, pkg);
  return unused.length;
}

// src/actions/deplint/checkPackage/getWorkspaceVersionProblems.ts
import chalk11 from "chalk";
import semver4 from "semver";
function checkSection(deps, versions, section, workspaceNames, problems) {
  for (const dep of deps) {
    if (!workspaceNames.has(dep)) continue;
    const version = versions[dep];
    if (version && !version.startsWith("workspace:")) {
      problems.push({
        dep,
        section,
        version
      });
    }
  }
}
function findWorkspaceVersionProblems(packageParams, workspaceNames) {
  const problems = [];
  checkSection(packageParams.dependencies, packageParams.dependencyVersions, "dependencies", workspaceNames, problems);
  checkSection(packageParams.devDependencies, packageParams.devDependencyVersions, "devDependencies", workspaceNames, problems);
  checkSection(packageParams.peerDependencies, packageParams.peerDependencyVersions, "peerDependencies", workspaceNames, problems);
  return problems;
}
function getWorkspaceVersionProblems({ name, location }, packageParams, workspaceNames) {
  const problems = findWorkspaceVersionProblems(packageParams, workspaceNames);
  for (const {
    dep,
    section,
    version
  } of problems) {
    console.log(
      `[${chalk11.blue(name)}] Workspace dependency ${chalk11.red(dep)} in ${chalk11.cyan(section)} should use workspace: protocol \u2014 found ${chalk11.yellow(version)}`
    );
  }
  if (problems.length > 0) {
    console.log(`  ${chalk11.yellow(`${location}/package.json`)}
`);
  }
  return problems.length;
}
function fixWorkspaceVersionProblems(workspace, packageParams, workspaceNames) {
  const problems = findWorkspaceVersionProblems(packageParams, workspaceNames);
  if (problems.length === 0) return 0;
  const pkg = readPackageJson2(workspace.location);
  for (const { dep, section } of problems) {
    addDep(pkg, dep, "workspace:~", section);
    logFix(workspace, `set workspace:~ for ${section}`, dep);
  }
  writePackageJson(workspace.location, pkg);
  return problems.length;
}

// src/actions/deplint/checkPackage/checkPackage.ts
function logVerbose(name, location, allFiles, distFiles, tsconfigExtends) {
  console.info(`Checking package: ${name} at ${location}`);
  console.info(`All files: ${allFiles.length}, Distribution files: ${distFiles.length}`);
  for (const file of allFiles) {
    console.info(`File: ${file}`);
  }
  for (const file of distFiles) {
    console.info(`Distribution file: ${file}`);
  }
  for (const ext of tsconfigExtends) {
    console.info(`Tsconfig extends: ${ext}`);
  }
}
function resolveCheckFlags(deps, devDeps, peerDeps) {
  const noneExplicit = !(deps || devDeps || peerDeps);
  return {
    checkDeps: deps || noneExplicit,
    checkDevDeps: devDeps || noneExplicit,
    checkPeerDeps: peerDeps || noneExplicit
  };
}
function checkPackage({
  name,
  location,
  deps = false,
  devDeps = false,
  exclude,
  fix = false,
  peerDeps = false,
  verbose = false,
  workspaceNames
}) {
  const { allFiles, distFiles } = findFiles(location);
  const tsconfigExtends = getExtendsFromTsconfigs(location);
  if (verbose) {
    logVerbose(name, location, allFiles, distFiles, tsconfigExtends);
  }
  const {
    checkDeps,
    checkDevDeps,
    checkPeerDeps
  } = resolveCheckFlags(deps, devDeps, peerDeps);
  const sourceParams = getExternalImportsFromFiles({
    allFiles,
    distFiles,
    location,
    name,
    tsconfigExtends
  });
  const packageJsonPath = `${location}/package.json`;
  const packageParams = getDependenciesFromPackageJson(packageJsonPath);
  const workspace = { name, location };
  const fileContext = { allFiles, distFiles };
  if (fix) {
    return fixPackage(workspace, packageParams, sourceParams, fileContext, checkDeps, checkDevDeps, checkPeerDeps, exclude, packageJsonPath, workspaceNames);
  }
  return checkPackageProblems(workspace, packageParams, sourceParams, fileContext, checkDeps, checkDevDeps, checkPeerDeps, exclude, workspaceNames);
}
function checkPackageProblems(workspace, packageParams, sourceParams, fileContext, checkDeps, checkDevDeps, checkPeerDeps, exclude, workspaceNames) {
  const allRequiredPeers = checkDeps || checkDevDeps ? getRequiredTransitivePeers(workspace.location, packageParams) : /* @__PURE__ */ new Set();
  const peerExclude = /* @__PURE__ */ new Set([...exclude ?? [], ...allRequiredPeers]);
  const { count: unsatisfiedPeerDependencies } = checkDeps || checkDevDeps ? getUnsatisfiedPeerDependencies(workspace, packageParams, exclude) : { count: 0 };
  const unlistedDependencies = checkDeps ? getUnlistedDependencies(workspace, packageParams, sourceParams) : 0;
  const unusedDependencies = checkDeps ? getUnusedDependencies(workspace, packageParams, sourceParams, peerExclude) : 0;
  const unlistedDevDependencies = checkDevDeps ? getUnlistedDevDependencies(workspace, packageParams, sourceParams) : 0;
  const unusedDevDependencies = checkDevDeps ? getUnusedDevDependencies(workspace, packageParams, sourceParams, fileContext, peerExclude) : 0;
  const unusedPeerDependencies = checkPeerDeps ? getUnusedPeerDependencies(workspace, packageParams, sourceParams, exclude) : 0;
  const unrequestedPeerDependencies = checkPeerDeps ? getUnrequestedPeerDependencies(workspace, packageParams, sourceParams, exclude) : 0;
  const redundantPeerDependencies = checkPeerDeps ? getRedundantPeerDependencies(workspace, packageParams, exclude) : 0;
  const mismatchedPeerDevVersions = checkPeerDeps ? getMismatchedPeerDevVersions(workspace, packageParams, exclude) : 0;
  const workspaceVersionProblems = workspaceNames ? getWorkspaceVersionProblems(workspace, packageParams, workspaceNames) : 0;
  return unlistedDependencies + unlistedDevDependencies + unusedDependencies + unusedDevDependencies + unusedPeerDependencies + unrequestedPeerDependencies + redundantPeerDependencies + unsatisfiedPeerDependencies + mismatchedPeerDevVersions + workspaceVersionProblems;
}
function fixPhase1AddMissing(ctx, packageParams) {
  let total = 0;
  total += ctx.checkDeps ? fixUnlistedDependencies(ctx.workspace, packageParams, ctx.sourceParams, ctx.workspaceNames) : 0;
  const afterDepsParams = total > 0 ? getDependenciesFromPackageJson(ctx.packageJsonPath) : packageParams;
  total += ctx.checkDevDeps ? fixUnlistedDevDependencies(ctx.workspace, afterDepsParams, ctx.sourceParams) : 0;
  const beforePeersParams = total > 0 ? getDependenciesFromPackageJson(ctx.packageJsonPath) : afterDepsParams;
  const peerResult = ctx.checkDeps || ctx.checkDevDeps ? fixUnsatisfiedPeerDependencies(ctx.workspace, beforePeersParams, ctx.exclude) : { addedPeers: /* @__PURE__ */ new Set(), count: 0 };
  total += peerResult.count;
  return { addedPeers: peerResult.addedPeers, total };
}
function fixPhase2RemoveUnused(ctx, addedPeers, prevTotal) {
  let total = 0;
  const updatedParams = getDependenciesFromPackageJson(ctx.packageJsonPath);
  const allRequiredPeers = ctx.checkDeps || ctx.checkDevDeps ? getRequiredTransitivePeers(ctx.workspace.location, updatedParams) : /* @__PURE__ */ new Set();
  const peerExclude = /* @__PURE__ */ new Set([...ctx.exclude ?? [], ...addedPeers, ...allRequiredPeers]);
  total += ctx.checkPeerDeps ? fixUnrequestedPeerDependencies(ctx.workspace, updatedParams, ctx.sourceParams, ctx.exclude) : 0;
  const afterMoveParams = ctx.checkPeerDeps && total + prevTotal > 0 ? getDependenciesFromPackageJson(ctx.packageJsonPath) : updatedParams;
  total += ctx.checkDeps ? fixUnusedDependencies(ctx.workspace, afterMoveParams, ctx.sourceParams, peerExclude) : 0;
  total += ctx.checkDevDeps ? fixUnusedDevDependencies(ctx.workspace, afterMoveParams, ctx.sourceParams, ctx.fileContext, peerExclude) : 0;
  total += ctx.checkPeerDeps ? fixUnusedPeerDependencies(ctx.workspace, afterMoveParams, ctx.sourceParams, ctx.exclude) : 0;
  total += ctx.checkPeerDeps ? fixRedundantPeerDependencies(ctx.workspace, afterMoveParams, ctx.exclude) : 0;
  return total;
}
function fixPhase3SyncVersions(ctx) {
  let total = 0;
  const finalParams = getDependenciesFromPackageJson(ctx.packageJsonPath);
  if (ctx.checkPeerDeps) {
    total += fixMismatchedPeerDevVersions(ctx.workspace, finalParams, ctx.exclude);
  }
  if (ctx.workspaceNames) {
    total += fixWorkspaceVersionProblems(ctx.workspace, finalParams, ctx.workspaceNames);
  }
  return total;
}
function fixPackage(workspace, packageParams, sourceParams, fileContext, checkDeps, checkDevDeps, checkPeerDeps, exclude, packageJsonPath, workspaceNames) {
  const ctx = {
    checkDeps,
    checkDevDeps,
    checkPeerDeps,
    exclude,
    fileContext,
    packageJsonPath,
    sourceParams,
    workspace,
    workspaceNames
  };
  const { addedPeers, total: phase1Total } = fixPhase1AddMissing(ctx, packageParams);
  const phase2Total = fixPhase2RemoveUnused(ctx, addedPeers, phase1Total);
  const phase3Total = fixPhase3SyncVersions(ctx);
  return phase1Total + phase2Total + phase3Total;
}
export {
  checkPackage
};
//# sourceMappingURL=checkPackage.mjs.map