Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { detectContexts, resolvePrimaryContext } from "./detector/index.js";
import { PolyDispatcher } from "./dispatcher/index.js";
import { DockerGenerator } from "./docker/index.js";
import { PolyDoctor } from "./doctor/index.js";
import { engineRegistry } from "./engines/registry.js";
import {
PolyMcpServer,
generateMcpConfig,
Expand Down Expand Up @@ -89,7 +90,7 @@ COMMANDS:
mcp [install] Start stdio MCP server or 1-click install for Claude Desktop, Cursor, Windsurf
init [--ide] Initialize workspace or generate AI agent guidelines (.cursorrules, CLAUDE.md)
completion <shell> Generate native shell tab auto-completion (bash, zsh, fish, powershell)
which <ecosystem> Show active CLI binary for an ecosystem (npm, pypi, cargo, go)
which <ecosystem> Show active CLI binary for an ecosystem (npm, jsr, pypi, conda, cargo, go)

OPTIONS:
-D, --dev Install as a development dependency
Expand Down Expand Up @@ -1064,13 +1065,18 @@ async function main(): Promise<void> {

case "which": {
const ecosystem = positionalArgs[0]?.toLowerCase() as Ecosystem;
if (!ecosystem || !["npm", "pypi", "cargo", "go"].includes(ecosystem)) {
logError("Please specify a valid ecosystem: 'npm', 'pypi', 'cargo', or 'go'");
const resolved = ecosystem ? engineRegistry.resolveEcosystem(ecosystem) : undefined;
if (!resolved) {
const supported = engineRegistry
.listEcosystems()
.map((e) => `'${e}'`)
.join(", ");
logError(`Please specify a valid ecosystem: ${supported}`);
process.exit(1);
}

const dispatcher = new PolyDispatcher();
const info = dispatcher.which(ecosystem, cwd);
const info = dispatcher.which(resolved, cwd);
if (isJson) {
console.log(JSON.stringify({ ecosystem, ...info }, null, 2));
} else {
Expand Down
10 changes: 7 additions & 3 deletions src/completion/generator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import fs from "node:fs";
import path from "node:path";
import { engineRegistry } from "../engines/registry.js";
import { loadWorkspaceConfig, resolveWorkspaceMembers } from "../workspace/config.js";
import type { CommandDefinition, SupportedShell } from "./types.js";

Expand Down Expand Up @@ -185,7 +186,7 @@ export function resolveDynamicCompletions(type: string, cwd: string = process.cw

case "which":
case "ecosystems":
return ["npm", "pypi", "cargo", "go"];
return engineRegistry.listEcosystems();

case "shells":
return ["bash", "zsh", "fish", "powershell"];
Expand Down Expand Up @@ -303,7 +304,7 @@ ${zshEntries}
_values 'shell' bash zsh fish powershell
;;
which)
_values 'ecosystem' npm pypi cargo go
_values 'ecosystem' ${engineRegistry.listEcosystems().join(" ")}
;;
run)
local -a tasks
Expand Down Expand Up @@ -386,7 +387,10 @@ ${psEntries}
ForEach-Object { [System.Management.Automation.CompletionResult]::new(\$_, \$_, "ParameterValue", "\$_ shell completion") }
}
"which" {
@("npm", "pypi", "cargo", "go") |
@(${engineRegistry
.listEcosystems()
.map((e) => `"${e}"`)
.join(", ")}) |
Where-Object { \$_ -like "\$wordToComplete*" } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new(\$_, \$_, "ParameterValue", "Ecosystem package manager") }
}
Expand Down
4 changes: 2 additions & 2 deletions src/compliance/auditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ export class CrossStackAuditor {
if (lock) {
for (const member of lock.members) {
for (const depStr of member.directDependencies) {
// format: "npm:axios@^1.7.0" or "pypi:fastapi@>=0.110.0"
const match = depStr.match(/^([a-z]+):(.*)$/);
// format: "npm:axios@^1.7.0", "jsr:@std/path@^1.0.0", "conda:numpy@1.26.4"
const match = depStr.match(/^([a-z0-9_-]+):(.*)$/);
if (match) {
const ecosystem = match[1] as Ecosystem;
const rest = match[2];
Expand Down
2 changes: 1 addition & 1 deletion src/compliance/licenses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class LicenseAuditor {
if (lock) {
for (const member of lock.members) {
for (const depStr of member.directDependencies) {
const match = depStr.match(/^([a-z]+):(.*)$/);
const match = depStr.match(/^([a-z0-9_-]+):(.*)$/);
if (match) {
const ecosystem = match[1] as Ecosystem;
const rest = match[2];
Expand Down
28 changes: 13 additions & 15 deletions src/compliance/osv.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { engineRegistry } from "../engines/registry.js";
import type { Ecosystem } from "../types.js";
import type { AuditFinding, VulnerabilitySeverity } from "./types.js";

Expand Down Expand Up @@ -57,14 +58,20 @@ export class OsvClient {
async queryPackages(
packages: Array<{ name: string; ecosystem: Ecosystem; version: string; memberPath: string }>,
): Promise<AuditFinding[]> {
if (packages.length === 0) {
const queryable = packages
.map((pkg) => ({ pkg, osvEcosystem: this.mapEcosystemToOsv(pkg.ecosystem) }))
.filter((entry): entry is { pkg: (typeof packages)[number]; osvEcosystem: string } =>
Boolean(entry.osvEcosystem),
);

if (queryable.length === 0) {
return [];
}

const queries: OsvQueryItem[] = packages.map((pkg) => ({
const queries: OsvQueryItem[] = queryable.map(({ pkg, osvEcosystem }) => ({
package: {
name: pkg.name,
ecosystem: this.mapEcosystemToOsv(pkg.ecosystem),
ecosystem: osvEcosystem,
},
version: pkg.version.replace(/^[~^>=<]/, "").trim(),
}));
Expand All @@ -89,7 +96,7 @@ export class OsvClient {

data.results?.forEach((result, idx) => {
if (!result.vulns || result.vulns.length === 0) return;
const targetPkg = packages[idx];
const targetPkg = queryable[idx].pkg;

for (const vuln of result.vulns) {
const severity = this.normalizeSeverity(vuln);
Expand Down Expand Up @@ -133,17 +140,8 @@ export class OsvClient {
}
}

private mapEcosystemToOsv(ecosystem: Ecosystem): string {
switch (ecosystem) {
case "npm":
return "npm";
case "pypi":
return "PyPI";
case "cargo":
return "crates.io";
case "go":
return "Go";
}
private mapEcosystemToOsv(ecosystem: Ecosystem): string | undefined {
return engineRegistry.getOsvEcosystem(ecosystem);
}

private normalizeSeverity(vuln: {
Expand Down
5 changes: 3 additions & 2 deletions src/compliance/sbom.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import crypto from "node:crypto";
import fs from "node:fs";
import { engineRegistry } from "../engines/registry.js";
import { readCompositeLockfile } from "../workspace/lockfile.js";
import { LicenseAuditor } from "./licenses.js";
import type { SbomOptions } from "./types.js";
Expand Down Expand Up @@ -39,7 +40,7 @@ export class SbomGenerator {
const serialUuid = crypto.randomUUID();

const components = packages.map((pkg) => {
const purlEcosystem = pkg.ecosystem === "go" ? "golang" : pkg.ecosystem;
const purlEcosystem = engineRegistry.getSbomPurlType(pkg.ecosystem);
return {
type: "library",
name: pkg.packageName,
Expand Down Expand Up @@ -88,7 +89,7 @@ export class SbomGenerator {
): string {
const spdxPackages = packages.map((pkg, idx) => {
const safeId = pkg.packageName.replace(/[^a-zA-Z0-9]/g, "-");
const purlEcosystem = pkg.ecosystem === "go" ? "golang" : pkg.ecosystem;
const purlEcosystem = engineRegistry.getSbomPurlType(pkg.ecosystem);
return {
name: pkg.packageName,
SPDXID: `SPDXRef-Package-${safeId}-${idx}`,
Expand Down
2 changes: 1 addition & 1 deletion src/detector/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { detectContexts, resolvePrimaryContext } from "./tree-walker.js";
export { detectContexts, matchesManifestGlob, resolvePrimaryContext } from "./tree-walker.js";
118 changes: 69 additions & 49 deletions src/detector/tree-walker.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,55 @@
import fs from "node:fs";
import path from "node:path";
import { engineRegistry } from "../engines/registry.js";
import type { Ecosystem, ManifestContext } from "../types.js";

interface EcosystemRule {
ecosystem: Ecosystem;
manifests: string[];
lockfiles: string[];
/**
* Matches a single filename against an exact pattern or simple wildcard glob (e.g. *.csproj, *.rockspec, *.cabal).
*/
export function matchesManifestGlob(filename: string, pattern: string): boolean {
if (!pattern.includes("*") && !pattern.includes("?")) {
return filename === pattern;
}
const escaped = pattern
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
.replace(/\*/g, ".*")
.replace(/\?/g, ".");
return new RegExp(`^${escaped}$`, "i").test(filename);
}

const ECOSYSTEM_RULES: EcosystemRule[] = [
{
ecosystem: "npm",
manifests: ["package.json"],
lockfiles: ["pnpm-lock.yaml", "bun.lockb", "bun.lock", "yarn.lock", "package-lock.json"],
},
{
ecosystem: "pypi",
manifests: ["pyproject.toml", "requirements.txt", "Pipfile", "setup.py"],
lockfiles: ["uv.lock", "poetry.lock", "Pipfile.lock"],
},
{
ecosystem: "cargo",
manifests: ["Cargo.toml"],
lockfiles: ["Cargo.lock"],
},
{
ecosystem: "go",
manifests: ["go.mod"],
lockfiles: ["go.sum"],
},
];
function findMatchingManifest(
dir: string,
patterns: readonly string[],
cachedEntries?: string[],
): { matched?: string; entries?: string[] } {
let entries = cachedEntries;

for (const pattern of patterns) {
if (!pattern.includes("*") && !pattern.includes("?")) {
if (fs.existsSync(path.join(dir, pattern))) {
return { matched: pattern, entries };
}
} else {
if (!entries) {
try {
entries = fs.readdirSync(dir).sort();
} catch {
entries = [];
}
}
const hit = entries.find((entry) => matchesManifestGlob(entry, pattern));
if (hit) {
return { matched: hit, entries };
}
}
}

return { matched: undefined, entries };
}

/**
* Traverses upwards from the start directory up to the git root or system root,
* collecting all project manifests and computing proximity scores.
* collecting all project manifests via EngineRegistry and computing proximity scores.
*/
export function detectContexts(startDir: string): ManifestContext[] {
let current = path.resolve(startDir);
Expand All @@ -42,34 +58,38 @@ export function detectContexts(startDir: string): ManifestContext[] {
const visitedEcosystems = new Set<Ecosystem>();

while (true) {
for (const rule of ECOSYSTEM_RULES) {
if (visitedEcosystems.has(rule.ecosystem)) {
let dirEntriesCache: string[] | undefined;

for (const adapter of engineRegistry.getAdapters()) {
if (visitedEcosystems.has(adapter.ecosystem)) {
continue;
}

for (const manifest of rule.manifests) {
const manifestPath = path.join(current, manifest);
if (fs.existsSync(manifestPath)) {
let foundLockfile: string | undefined;
for (const lockfile of rule.lockfiles) {
const lockPath = path.join(current, lockfile);
if (fs.existsSync(lockPath)) {
foundLockfile = lockfile;
break;
}
const { matched: matchedManifest, entries } = findMatchingManifest(
current,
adapter.manifests,
dirEntriesCache,
);
dirEntriesCache = entries;

if (matchedManifest) {
let foundLockfile: string | undefined;
for (const lockfile of adapter.lockfiles) {
if (fs.existsSync(path.join(current, lockfile))) {
foundLockfile = lockfile;
break;
}
}

contexts.push({
directory: current,
ecosystem: rule.ecosystem,
manifestFile: manifest,
lockfile: foundLockfile,
distance,
});
contexts.push({
directory: current,
ecosystem: adapter.ecosystem,
manifestFile: matchedManifest,
lockfile: foundLockfile,
distance,
});

visitedEcosystems.add(rule.ecosystem);
break;
}
visitedEcosystems.add(adapter.ecosystem);
}
}

Expand Down
36 changes: 10 additions & 26 deletions src/dispatcher/executor.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
import { detectContexts, resolvePrimaryContext } from "../detector/tree-walker.js";
import {
type BaseEngine,
GoEngine,
NodeEngine,
PythonEngine,
RustEngine,
} from "../engines/index.js";
import { type BaseEngine, engineRegistry } from "../engines/index.js";
import { parsePackageSpec } from "../purl/parser.js";
import { RegistryRouter } from "../registry/index.js";
import { evaluateSandboxGate, injectSandboxFlags } from "../sandbox/index.js";
Expand Down Expand Up @@ -299,13 +293,7 @@ export class PolyDispatcher {
*/
which(ecosystem: Ecosystem, cwd?: string): { engine: string; effectiveCli: string } {
const engine = this.getEngineForEcosystem(ecosystem, cwd ?? process.cwd());
let effectiveCli = engine.name;
if (engine instanceof NodeEngine) {
effectiveCli = engine.getEffectiveCli();
} else if (engine instanceof PythonEngine) {
effectiveCli = engine.getEffectiveCli();
}
return { engine: engine.name, effectiveCli };
return { engine: engine.name, effectiveCli: engine.getEffectiveCli() };
}

private async resolveEcosystemForPackage(
Expand All @@ -328,24 +316,20 @@ export class PolyDispatcher {

throw new Error(
`Could not determine ecosystem for '${packageName}'.\n` +
`No manifest (package.json, pyproject.toml, Cargo.toml, go.mod) was found in '${cwd}' or its parents.\n` +
`Remediation: Pass an explicit ecosystem prefix, e.g. 'npm:${packageName}' or 'pypi:${packageName}'.`,
`No manifest (package.json, deno.json, pyproject.toml, environment.yml, Cargo.toml, go.mod) was found in '${cwd}' or its parents.\n` +
`Remediation: Pass an explicit ecosystem prefix, e.g. 'npm:${packageName}', 'jsr:@scope/pkg', 'pypi:${packageName}', or 'conda:${packageName}'.`,
);
}

private getEngineForEcosystem(ecosystem: Ecosystem, cwd: string): BaseEngine {
const contexts = detectContexts(cwd);
const ctx = contexts.find((c) => c.ecosystem === ecosystem);

switch (ecosystem) {
case "npm":
return new NodeEngine(ctx?.lockfile);
case "pypi":
return new PythonEngine(ctx?.lockfile);
case "cargo":
return new RustEngine();
case "go":
return new GoEngine();
}
return engineRegistry.createEngine(ecosystem, {
cwd,
ecosystem,
manifest: ctx?.manifestFile,
lockfile: ctx?.lockfile,
});
}
}
Loading
Loading