// src/actions/deplint/getScriptReferencedPackages.ts
import fs2 from "node:fs";
import path2 from "node:path";

// 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/getRequiredPeerDependencies.ts
import fs from "node:fs";
import path from "node:path";
function findDepPackageJson(location, dep) {
  let dir = location;
  while (true) {
    const candidate = path.join(dir, "node_modules", dep, "package.json");
    if (fs.existsSync(candidate)) return candidate;
    const parent = path.dirname(dir);
    if (parent === dir) return void 0;
    dir = parent;
  }
}

// src/actions/deplint/getScriptReferencedPackages.ts
function getBinNames(location, dep) {
  const depPkgPath = findDepPackageJson(location, dep);
  if (!depPkgPath) return [];
  try {
    const raw = fs2.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 = path2.join(location, "package.json");
  let scripts;
  try {
    const raw = fs2.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;
}
export {
  getBinNames,
  getScriptReferencedPackages,
  tokenizeScript
};
//# sourceMappingURL=getScriptReferencedPackages.mjs.map
