@efraindrummer/ghostdeps 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,162 @@
1
+ export function detectAiConfig(options = {}) {
2
+ const env = process.env;
3
+ const geminiKey = options.apiKey || env.GEMINI_API_KEY || env.GOOGLE_API_KEY;
4
+ const anthropicKey = options.apiKey || env.ANTHROPIC_API_KEY;
5
+ const openaiKey = options.apiKey || env.OPENAI_API_KEY;
6
+ if (options.provider === 'gemini') {
7
+ if (!geminiKey)
8
+ return null;
9
+ return { provider: 'gemini', apiKey: geminiKey, model: options.model || 'gemini-1.5-flash' };
10
+ }
11
+ if (options.provider === 'anthropic') {
12
+ if (!anthropicKey)
13
+ return null;
14
+ return { provider: 'anthropic', apiKey: anthropicKey, model: options.model || 'claude-3-5-haiku-20241022' };
15
+ }
16
+ if (options.provider === 'openai') {
17
+ if (!openaiKey)
18
+ return null;
19
+ return { provider: 'openai', apiKey: openaiKey, model: options.model || 'gpt-4o-mini' };
20
+ }
21
+ // Auto-detección por variables de entorno disponibles
22
+ if (geminiKey) {
23
+ return { provider: 'gemini', apiKey: geminiKey, model: options.model || 'gemini-1.5-flash' };
24
+ }
25
+ if (anthropicKey) {
26
+ return { provider: 'anthropic', apiKey: anthropicKey, model: options.model || 'claude-3-5-haiku-20241022' };
27
+ }
28
+ if (openaiKey) {
29
+ return { provider: 'openai', apiKey: openaiKey, model: options.model || 'gpt-4o-mini' };
30
+ }
31
+ return null;
32
+ }
33
+ export function buildAiPrompt(reports, summary) {
34
+ const problematic = reports.filter((r) => r.status === 'evaluated' && r.result && r.result.score < 70);
35
+ const payload = problematic.map((r) => ({
36
+ name: r.name,
37
+ version: r.spec,
38
+ kind: r.kind,
39
+ via: r.via,
40
+ score: r.result?.score,
41
+ category: r.result?.category,
42
+ mainAlert: r.result?.mainAlert?.message,
43
+ penalties: r.result?.penalties.map((p) => p.message),
44
+ daysSinceLastCommit: r.signals?.daysSinceLastCommit,
45
+ activeMaintainers: r.signals?.activeMaintainers,
46
+ archived: r.signals?.archived,
47
+ deprecated: r.signals?.deprecated,
48
+ }));
49
+ return `Actúa como un Ingeniero Principal de Ciberseguridad y Supply Chain Security experto en el ecosistema Node.js / JavaScript.
50
+
51
+ Se ha ejecutado la herramienta GhostDeps sobre un proyecto y se han detectado ${problematic.length} dependencias en riesgo (de un total de ${summary.total}):
52
+ - Críticas/Fantasma: ${summary.critical}
53
+ - Precaución: ${summary.caution}
54
+
55
+ A continuación tienes el detalle de las dependencias problemáticas:
56
+ \`\`\`json
57
+ ${JSON.stringify(payload, null, 2)}
58
+ \`\`\`
59
+
60
+ Por favor, proporciona una respuesta en Markdown clara, profesional y concisa (en español):
61
+ 1. **Diagnóstico Ejecutivo de Ciberseguridad**: Resumen rápido del nivel de exposición del proyecto.
62
+ 2. **Alternativas y Reemplazos Recomendados**: Para cada dependencia crítica o con bajo score, sugiere un reemplazo moderno, activo y seguro del ecosistema npm (o APIs nativas de Node.js como \`fetch\`, \`crypto\`, etc., si aplica).
63
+ 3. **Plan de Remediación Priorizado**: Qué acciones inmediatas debe tomar el equipo (ej. overrides en package.json para transitivas, vendorización, o actualización de paquetes directos).
64
+
65
+ Mantén la respuesta práctica y orientada a código.`;
66
+ }
67
+ export async function queryGemini(apiKey, model, prompt, timeoutMs = 25000) {
68
+ const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(apiKey)}`;
69
+ const res = await fetch(url, {
70
+ method: 'POST',
71
+ headers: { 'content-type': 'application/json' },
72
+ body: JSON.stringify({
73
+ contents: [{ parts: [{ text: prompt }] }],
74
+ generationConfig: { temperature: 0.2, maxOutputTokens: 2000 },
75
+ }),
76
+ signal: AbortSignal.timeout(timeoutMs),
77
+ });
78
+ if (!res.ok) {
79
+ const errorText = await res.text().catch(() => '');
80
+ throw new Error(`Error en API de Gemini (HTTP ${res.status}): ${errorText.slice(0, 200)}`);
81
+ }
82
+ const json = (await res.json());
83
+ const text = json.candidates?.[0]?.content?.parts?.[0]?.text;
84
+ if (!text)
85
+ throw new Error('Respuesta vacía o inesperada de la API de Gemini.');
86
+ return text;
87
+ }
88
+ export async function queryAnthropic(apiKey, model, prompt, timeoutMs = 25000) {
89
+ const url = 'https://api.anthropic.com/v1/messages';
90
+ const res = await fetch(url, {
91
+ method: 'POST',
92
+ headers: {
93
+ 'content-type': 'application/json',
94
+ 'x-api-key': apiKey,
95
+ 'anthropic-version': '2023-06-01',
96
+ },
97
+ body: JSON.stringify({
98
+ model,
99
+ max_tokens: 2000,
100
+ temperature: 0.2,
101
+ messages: [{ role: 'user', content: prompt }],
102
+ }),
103
+ signal: AbortSignal.timeout(timeoutMs),
104
+ });
105
+ if (!res.ok) {
106
+ const errorText = await res.text().catch(() => '');
107
+ throw new Error(`Error en API de Anthropic (HTTP ${res.status}): ${errorText.slice(0, 200)}`);
108
+ }
109
+ const json = (await res.json());
110
+ const text = json.content?.find((c) => c.type === 'text')?.text;
111
+ if (!text)
112
+ throw new Error('Respuesta vacía o inesperada de la API de Anthropic.');
113
+ return text;
114
+ }
115
+ export async function queryOpenAI(apiKey, model, prompt, timeoutMs = 25000) {
116
+ const url = 'https://api.openai.com/v1/chat/completions';
117
+ const res = await fetch(url, {
118
+ method: 'POST',
119
+ headers: {
120
+ 'content-type': 'application/json',
121
+ authorization: `Bearer ${apiKey}`,
122
+ },
123
+ body: JSON.stringify({
124
+ model,
125
+ temperature: 0.2,
126
+ max_tokens: 2000,
127
+ messages: [{ role: 'user', content: prompt }],
128
+ }),
129
+ signal: AbortSignal.timeout(timeoutMs),
130
+ });
131
+ if (!res.ok) {
132
+ const errorText = await res.text().catch(() => '');
133
+ throw new Error(`Error en API de OpenAI (HTTP ${res.status}): ${errorText.slice(0, 200)}`);
134
+ }
135
+ const json = (await res.json());
136
+ const text = json.choices?.[0]?.message?.content;
137
+ if (!text)
138
+ throw new Error('Respuesta vacía o inesperada de la API de OpenAI.');
139
+ return text;
140
+ }
141
+ export async function analyzeWithAi(reports, summary, options = {}) {
142
+ const config = detectAiConfig(options);
143
+ if (!config)
144
+ return null;
145
+ const prompt = buildAiPrompt(reports, summary);
146
+ const timeoutMs = options.timeoutMs ?? 30000;
147
+ let analysis;
148
+ if (config.provider === 'gemini') {
149
+ analysis = await queryGemini(config.apiKey, config.model, prompt, timeoutMs);
150
+ }
151
+ else if (config.provider === 'anthropic') {
152
+ analysis = await queryAnthropic(config.apiKey, config.model, prompt, timeoutMs);
153
+ }
154
+ else {
155
+ analysis = await queryOpenAI(config.apiKey, config.model, prompt, timeoutMs);
156
+ }
157
+ return {
158
+ provider: config.provider,
159
+ model: config.model,
160
+ analysis,
161
+ };
162
+ }
@@ -0,0 +1,87 @@
1
+ import { NotFoundError, errorMessage } from './errors.js';
2
+ import { computeScore, DEFAULT_WEIGHTS, THRESHOLDS } from './scoring/scoring.js';
3
+ import { buildSignals } from './scoring/signals.js';
4
+ import { mapWithConcurrency } from './utils.js';
5
+ const HOST_LABEL = { gitlab: 'GitLab', bitbucket: 'Bitbucket' };
6
+ function baseReport(dep) {
7
+ return {
8
+ name: dep.name,
9
+ registryName: dep.registryName,
10
+ spec: dep.spec,
11
+ kind: dep.kind,
12
+ depth: dep.depth,
13
+ via: dep.via,
14
+ status: 'evaluated',
15
+ reason: null,
16
+ npm: null,
17
+ github: null,
18
+ signals: null,
19
+ result: null,
20
+ };
21
+ }
22
+ /** Analiza un paquete. Nunca lanza: cualquier fallo se refleja en `status`/`reason`. */
23
+ export async function analyzePackage(dep, deps) {
24
+ const report = baseReport(dep);
25
+ const notEvaluable = (reason) => ({ ...report, status: 'not-evaluable', reason });
26
+ const failed = (err) => ({ ...report, status: 'error', reason: errorMessage(err) });
27
+ if (dep.unsupportedReason)
28
+ return notEvaluable(dep.unsupportedReason);
29
+ try {
30
+ report.npm = await deps.npm.getPackageInfo(dep.registryName);
31
+ }
32
+ catch (err) {
33
+ if (err instanceof NotFoundError)
34
+ return notEvaluable('No existe en el registry público de npm (¿privado?)');
35
+ return failed(err);
36
+ }
37
+ const repo = report.npm.repository;
38
+ if (!repo)
39
+ return notEvaluable('Sin campo "repository" en npm');
40
+ if (repo.host !== 'github') {
41
+ const host = HOST_LABEL[repo.host] ?? repo.hostname;
42
+ return notEvaluable(`Repo en ${host}: solo GitHub está soportado en el MVP`);
43
+ }
44
+ try {
45
+ report.github = await deps.github.getRepoHealth(repo.owner, repo.repo, repo.directory);
46
+ }
47
+ catch (err) {
48
+ if (err instanceof NotFoundError)
49
+ return notEvaluable(`Repo ${repo.owner}/${repo.repo} no encontrado o privado`);
50
+ // RateLimitError, TimeoutError, HttpError...: el paquete queda como error y el análisis sigue.
51
+ return failed(err);
52
+ }
53
+ report.signals = buildSignals(report.npm, report.github, deps.now);
54
+ report.result = computeScore(report.signals, deps.weights ?? DEFAULT_WEIGHTS, deps.thresholds ?? THRESHOLDS);
55
+ return report;
56
+ }
57
+ export async function analyzeAll(dependencies, deps, concurrency, onProgress) {
58
+ let done = 0;
59
+ return mapWithConcurrency(dependencies, concurrency, async (dep) => {
60
+ const r = await analyzePackage(dep, deps);
61
+ onProgress?.(++done, dependencies.length, dep.name);
62
+ return r;
63
+ });
64
+ }
65
+ const STATUS_ORDER = { evaluated: 0, 'not-evaluable': 1, error: 2 };
66
+ /** Peor score primero; después "No evaluable" y por último errores. */
67
+ export function sortReports(reports) {
68
+ return [...reports].sort((a, b) => {
69
+ const s = STATUS_ORDER[a.status] - STATUS_ORDER[b.status];
70
+ if (s !== 0)
71
+ return s;
72
+ const diff = (a.result?.score ?? 0) - (b.result?.score ?? 0);
73
+ return diff !== 0 ? diff : a.name.localeCompare(b.name);
74
+ });
75
+ }
76
+ export function summarize(reports) {
77
+ const summary = { total: reports.length, healthy: 0, caution: 0, critical: 0, notEvaluable: 0, errors: 0 };
78
+ for (const r of reports) {
79
+ if (r.status === 'error')
80
+ summary.errors++;
81
+ else if (r.status === 'not-evaluable')
82
+ summary.notEvaluable++;
83
+ else if (r.result)
84
+ summary[r.result.category]++;
85
+ }
86
+ return summary;
87
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,289 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ import { writeFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { stripVTControlCharacters } from 'node:util';
6
+ import chalk from 'chalk';
7
+ import { Command, CommanderError, InvalidArgumentError, Option } from 'commander';
8
+ import { analyzeWithAi, detectAiConfig } from './ai/advisor.js';
9
+ import { analyzeAll, sortReports, summarize } from './analyzer.js';
10
+ import { DiskCache, defaultCacheDir } from './clients/cache.js';
11
+ import { GitHubClient } from './clients/github.js';
12
+ import { RateLimitGate } from './clients/http.js';
13
+ import { NpmClient } from './clients/npm.js';
14
+ import { createIgnoreMatcher, loadConfig } from './config.js';
15
+ import { GhostDepsError, errorMessage } from './errors.js';
16
+ import { startMcpServer } from './mcp/server.js';
17
+ import { readLockfile, resolveTransitive } from './parser/lockfile.js';
18
+ import { readManifest } from './parser/manifest.js';
19
+ import { renderMarkdown } from './render/markdown.js';
20
+ import { renderSarif } from './render/sarif.js';
21
+ import { renderExplain, renderSummary, renderTable } from './render/table.js';
22
+ /** Códigos de salida documentados. */
23
+ export const EXIT = { OK: 0, FAIL_UNDER: 1, FATAL: 2 };
24
+ function readVersion() {
25
+ try {
26
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
27
+ return pkg.version ?? '0.0.0';
28
+ }
29
+ catch {
30
+ return '0.0.0';
31
+ }
32
+ }
33
+ function positiveInt(name, max = Number.MAX_SAFE_INTEGER) {
34
+ return (value) => {
35
+ const n = Number(value);
36
+ if (!Number.isInteger(n) || n < 1 || n > max) {
37
+ throw new InvalidArgumentError(`${name} debe ser un entero entre 1 y ${max}.`);
38
+ }
39
+ return n;
40
+ };
41
+ }
42
+ function scoreArg(value) {
43
+ const n = Number(value);
44
+ if (!Number.isFinite(n) || n < 0 || n > 100)
45
+ throw new InvalidArgumentError('Debe ser un número entre 0 y 100.');
46
+ return n;
47
+ }
48
+ /** `--ignore a,b --ignore "@types/*"` => ["a", "b", "@types/*"] */
49
+ function collectList(value, previous = []) {
50
+ return [...previous, ...value.split(',').map((s) => s.trim()).filter(Boolean)];
51
+ }
52
+ const log = (msg) => process.stderr.write(`${msg}\n`);
53
+ async function run(opts, command, version) {
54
+ if (opts.mcp) {
55
+ startMcpServer(version);
56
+ return new Promise(() => { }); // Escuchar indefinidamente sobre stdio
57
+ }
58
+ const fromCli = (key) => command.getOptionValueSource(key) === 'cli';
59
+ const format = opts.json ? 'json' : opts.format;
60
+ const quiet = format !== 'table'; // en json/markdown, stderr solo para avisos importantes
61
+ // --- Configuración efectiva: CLI > archivo > defaults ---
62
+ const config = await loadConfig(opts.path, opts.config);
63
+ const dev = fromCli('dev') ? opts.dev : (config.dev ?? opts.dev);
64
+ const transitive = fromCli('transitive') ? opts.transitive : (config.transitive ?? opts.transitive);
65
+ const depth = opts.depth ?? config.depth;
66
+ const concurrency = fromCli('concurrency') ? opts.concurrency : (config.concurrency ?? opts.concurrency);
67
+ const failUnder = opts.failUnder ?? config.failUnder;
68
+ const isIgnored = createIgnoreMatcher([...config.ignore, ...opts.ignore]);
69
+ const token = process.env.GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || undefined;
70
+ if (!token) {
71
+ log(chalk.yellow('⚠ GITHUB_TOKEN no configurado: la API de GitHub permite solo 60 peticiones/hora sin autenticar\n' +
72
+ ' (~15 paquetes). Crea un token sin permisos en https://github.com/settings/tokens y exporta GITHUB_TOKEN.'));
73
+ }
74
+ if (config.source && !quiet)
75
+ log(chalk.gray(`Configuración: ${config.source}`));
76
+ // --- Dependencias a analizar ---
77
+ const manifest = await readManifest(opts.path, { includeDev: dev });
78
+ let all = manifest.dependencies;
79
+ if (transitive) {
80
+ const { file, lock } = await readLockfile(opts.path);
81
+ const trans = resolveTransitive(lock, manifest.dependencies, { maxDepth: depth ?? Number.POSITIVE_INFINITY });
82
+ all = [...manifest.dependencies, ...trans];
83
+ if (!quiet)
84
+ log(chalk.gray(`Transitivas: ${trans.length} desde ${path.basename(file)}${depth ? ` (profundidad ≤ ${depth})` : ''}`));
85
+ }
86
+ const ignored = all.filter((d) => isIgnored(d.name) || isIgnored(d.registryName)).map((d) => d.name);
87
+ const toAnalyze = all.filter((d) => !ignored.includes(d.name));
88
+ if (ignored.length > 0 && !quiet)
89
+ log(chalk.gray(`Ignorados: ${ignored.join(', ')}`));
90
+ if (toAnalyze.length > 15 && !token) {
91
+ log(chalk.yellow(`⚠ ${toAnalyze.length} paquetes a analizar sin token: es muy probable agotar el rate limit.`));
92
+ }
93
+ else if (toAnalyze.length > 300) {
94
+ log(chalk.yellow(`⚠ ${toAnalyze.length} paquetes: ~${toAnalyze.length * 3} peticiones a GitHub. Considera --depth o "ignore".`));
95
+ }
96
+ const userAgent = `ghostdeps/${version} (+https://github.com/ghostdeps/ghostdeps)`;
97
+ const cache = new DiskCache(defaultCacheDir(), opts.cacheTtl * 3_600_000, opts.cache);
98
+ const gate = new RateLimitGate();
99
+ const retries = 3;
100
+ const now = new Date();
101
+ const npm = new NpmClient({ cache, timeoutMs: opts.timeout, retries, userAgent });
102
+ const github = new GitHubClient({
103
+ cache,
104
+ token,
105
+ timeoutMs: opts.timeout,
106
+ retries,
107
+ userAgent,
108
+ gate,
109
+ maxRateLimitWaitMs: opts.maxWait * 1000,
110
+ onRateLimitWait: (ms, resetAt) => log(chalk.yellow(`\n⏳ Rate limit de GitHub alcanzado; esperando ${Math.ceil(ms / 1000)} s (reset ${resetAt.toLocaleTimeString()})…`)),
111
+ now: () => now,
112
+ });
113
+ const interactive = !quiet && process.stderr.isTTY;
114
+ const reports = await analyzeAll(toAnalyze, { npm, github, now, weights: config.weights, thresholds: config.thresholds }, concurrency, (done, total, name) => {
115
+ if (interactive)
116
+ process.stderr.write(`\r\x1b[2K${chalk.gray(`Analizando ${done}/${total}: ${name}`)}`);
117
+ });
118
+ if (interactive)
119
+ process.stderr.write('\r\x1b[2K');
120
+ const sorted = sortReports(reports);
121
+ const summary = summarize(sorted);
122
+ const failing = failUnder === undefined
123
+ ? []
124
+ : sorted.filter((r) => r.status === 'evaluated' && r.result && r.result.score < failUnder).map((r) => r.name);
125
+ // --- Asesor de Ciberseguridad IA ---
126
+ let aiResult = null;
127
+ if (opts.ai) {
128
+ const hasRisks = sorted.some((r) => r.status === 'evaluated' && r.result && r.result.score < 70);
129
+ const aiConfig = detectAiConfig({ provider: opts.aiProvider, model: opts.aiModel });
130
+ if (!aiConfig) {
131
+ log(chalk.yellow('\n⚠ Modo --ai activado pero no se detectó ninguna clave de API.\n' +
132
+ ' Exporta GEMINI_API_KEY, ANTHROPIC_API_KEY u OPENAI_API_KEY en tu entorno.'));
133
+ }
134
+ else if (!hasRisks) {
135
+ if (!quiet)
136
+ log(chalk.green('\n🤖 IA: Todas las dependencias están saludables (score ≥ 70). No se requieren reemplazos.'));
137
+ }
138
+ else {
139
+ if (!quiet)
140
+ log(chalk.cyan(`\n🤖 Consultando a ${aiConfig.provider} (${aiConfig.model}) para análisis de mitigación y reemplazos...`));
141
+ try {
142
+ aiResult = await analyzeWithAi(sorted, summary, { provider: opts.aiProvider, model: opts.aiModel });
143
+ }
144
+ catch (err) {
145
+ log(chalk.red(`\n✖ Error consultando a la IA: ${err.message}`));
146
+ }
147
+ }
148
+ }
149
+ // --- Salida ---
150
+ let rendered;
151
+ if (format === 'json') {
152
+ rendered = JSON.stringify({
153
+ tool: 'ghostdeps',
154
+ version,
155
+ generatedAt: now.toISOString(),
156
+ manifest: manifest.manifestPath,
157
+ config: config.source,
158
+ options: { dev, transitive, depth: depth ?? null, failUnder: failUnder ?? null, authenticated: Boolean(token), ai: opts.ai },
159
+ thresholds: config.thresholds,
160
+ summary,
161
+ ignored,
162
+ failUnder: failUnder === undefined ? null : { threshold: failUnder, failing },
163
+ aiAnalysis: aiResult,
164
+ packages: sorted,
165
+ }, null, 2);
166
+ }
167
+ else if (format === 'markdown') {
168
+ rendered = renderMarkdown(sorted, summary, now, {
169
+ version,
170
+ projectName: manifest.projectName,
171
+ thresholds: config.thresholds,
172
+ failUnder,
173
+ failing,
174
+ ignored,
175
+ });
176
+ if (aiResult) {
177
+ rendered += `\n\n### 🤖 Recomendaciones de Ciberseguridad (${aiResult.provider} / ${aiResult.model})\n\n${aiResult.analysis}\n`;
178
+ }
179
+ }
180
+ else if (format === 'sarif') {
181
+ rendered = renderSarif(sorted, {
182
+ version,
183
+ manifestPath: manifest.manifestPath,
184
+ thresholds: config.thresholds,
185
+ });
186
+ }
187
+ else {
188
+ const title = manifest.projectName ? ` · ${manifest.projectName}` : '';
189
+ const parts = [
190
+ chalk.bold(`\n👻 GhostDeps v${version}${title}`),
191
+ renderTable(sorted, now),
192
+ renderSummary(summary, config.thresholds),
193
+ ...(opts.explain ? [renderExplain(sorted)] : []),
194
+ ];
195
+ if (aiResult) {
196
+ parts.push(chalk.bold.cyan(`\n🤖 Recomendaciones de Ciberseguridad (${aiResult.provider} / ${aiResult.model}):`));
197
+ parts.push(aiResult.analysis);
198
+ }
199
+ rendered = parts.join('\n');
200
+ }
201
+ if (opts.output) {
202
+ const file = path.resolve(opts.output);
203
+ await writeFile(file, `${stripVTControlCharacters(rendered)}\n`, 'utf8');
204
+ log(chalk.green(`✔ Informe escrito en ${file}`));
205
+ }
206
+ else {
207
+ process.stdout.write(`${rendered}\n`);
208
+ }
209
+ if (gate.resetAt && gate.resetAt.getTime() > Date.now() && summary.errors > 0) {
210
+ log(chalk.red(`\n✖ Se agotó el rate limit de GitHub (reset ${gate.resetAt.toLocaleTimeString()}). ` +
211
+ 'Los paquetes restantes quedaron como error; reintenta luego (los resultados ya obtenidos están en caché) ' +
212
+ (token ? 'o aumenta --max-wait.' : 'o configura GITHUB_TOKEN.')));
213
+ }
214
+ if (failUnder !== undefined) {
215
+ if (failing.length > 0) {
216
+ log(chalk.red(`\n✖ ${failing.length} paquete(s) por debajo de --fail-under ${failUnder}: ${failing.join(', ')}`));
217
+ return EXIT.FAIL_UNDER;
218
+ }
219
+ if (!quiet)
220
+ log(chalk.green(`\n✔ Ningún paquete evaluado por debajo de ${failUnder}.`));
221
+ }
222
+ return EXIT.OK;
223
+ }
224
+ async function main() {
225
+ const version = readVersion();
226
+ const program = new Command();
227
+ program
228
+ .name('ghostdeps')
229
+ .description('Detecta dependencias fantasma: abandonadas, con bus factor bajo o con señales de secuestro.')
230
+ .version(version, '-v, --version')
231
+ .option('-p, --path <dir>', 'directorio que contiene el package.json', process.cwd())
232
+ .option('--config <file>', 'archivo de configuración (por defecto .ghostdepsrc.json o "ghostdeps" en package.json)')
233
+ .option('-d, --dev', 'incluir también devDependencies', false)
234
+ .option('-t, --transitive', 'incluir dependencias transitivas (requiere package-lock.json)', false)
235
+ .option('--depth <n>', 'profundidad máxima con --transitive (1 = solo directas)', positiveInt('--depth', 100))
236
+ .option('-i, --ignore <paquetes>', 'paquetes a omitir, separados por coma; admite * (ej. "@types/*")', collectList, [])
237
+ .addOption(new Option('-f, --format <formato>', 'formato de salida').choices(['table', 'json', 'markdown', 'sarif']).default('table'))
238
+ .option('--json', 'atajo de --format json', false)
239
+ .option('-o, --output <file>', 'escribir el informe en un archivo en lugar de stdout')
240
+ .option('--fail-under <score>', 'exit code 1 si algún paquete evaluado queda por debajo del score', scoreArg)
241
+ .option('-c, --concurrency <n>', 'paquetes analizados en paralelo', positiveInt('--concurrency', 32), 4)
242
+ .option('--no-cache', 'ignorar y no escribir la caché en disco')
243
+ .option('--cache-ttl <hours>', 'TTL de la caché en horas', positiveInt('--cache-ttl'), 24)
244
+ .option('--timeout <ms>', 'timeout por request en milisegundos', positiveInt('--timeout'), 15_000)
245
+ .option('--max-wait <seconds>', 'espera máxima ante rate limit antes de abortar', positiveInt('--max-wait'), 60)
246
+ .option('--explain', 'mostrar el desglose de penalizaciones de cada paquete', false)
247
+ .option('--ai', 'analizar dependencias con IA para sugerir reemplazos y plan de mitigación', false)
248
+ .addOption(new Option('--ai-provider <provider>', 'proveedor de IA a utilizar').choices(['gemini', 'anthropic', 'openai']))
249
+ .option('--ai-model <model>', 'modelo específico de IA a consultar')
250
+ .option('--mcp', 'iniciar servidor MCP (Model Context Protocol) sobre stdio para agentes de IA', false)
251
+ .addHelpText('after', [
252
+ '',
253
+ 'Ejemplos:',
254
+ ' ghostdeps --dev --explain',
255
+ ' ghostdeps --transitive --depth 3 --ignore "@types/*"',
256
+ ' ghostdeps --ai',
257
+ ' ghostdeps --mcp',
258
+ ' ghostdeps --format markdown -o ghostdeps.md',
259
+ ' ghostdeps --fail-under 40',
260
+ '',
261
+ 'Variables de entorno:',
262
+ ' GITHUB_TOKEN / GH_TOKEN token de GitHub (recomendado; 5000 req/h)',
263
+ ' GEMINI_API_KEY clave para modo --ai con Google Gemini',
264
+ ' ANTHROPIC_API_KEY clave para modo --ai con Anthropic Claude',
265
+ ' OPENAI_API_KEY clave para modo --ai con OpenAI ChatGPT',
266
+ ' GHOSTDEPS_CACHE_DIR directorio de caché personalizado',
267
+ '',
268
+ 'Códigos de salida: 0 OK · 1 --fail-under incumplido · 2 error fatal',
269
+ ].join('\n'))
270
+ .action(async (opts, command) => {
271
+ process.exitCode = await run(opts, command, version);
272
+ });
273
+ // Evita que Commander haga process.exit(1) en errores de uso (colisionaría con --fail-under).
274
+ program.exitOverride();
275
+ try {
276
+ await program.parseAsync(process.argv);
277
+ }
278
+ catch (err) {
279
+ if (err instanceof CommanderError) {
280
+ // Commander ya imprimió el mensaje (o la ayuda/versión).
281
+ process.exitCode = err.exitCode === 0 ? EXIT.OK : EXIT.FATAL;
282
+ return;
283
+ }
284
+ const msg = err instanceof GhostDepsError ? err.message : `Error inesperado: ${errorMessage(err)}`;
285
+ log(chalk.red(`✖ ${msg}`));
286
+ process.exitCode = EXIT.FATAL;
287
+ }
288
+ }
289
+ void main();
@@ -0,0 +1,65 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ /** Incrementar cuando cambie la forma de los datos cacheados. */
6
+ const CACHE_SCHEMA = 'v1';
7
+ export function defaultCacheDir() {
8
+ const env = process.env;
9
+ if (env.GHOSTDEPS_CACHE_DIR)
10
+ return env.GHOSTDEPS_CACHE_DIR;
11
+ if (env.XDG_CACHE_HOME)
12
+ return path.join(env.XDG_CACHE_HOME, 'ghostdeps');
13
+ if (process.platform === 'win32' && env.LOCALAPPDATA) {
14
+ return path.join(env.LOCALAPPDATA, 'ghostdeps', 'cache');
15
+ }
16
+ return path.join(os.homedir(), '.cache', 'ghostdeps');
17
+ }
18
+ /**
19
+ * Caché clave/valor en disco con TTL. Guarda datos ya extraídos (no las respuestas crudas)
20
+ * para mantener los archivos pequeños. Cualquier fallo de lectura/escritura se ignora:
21
+ * la caché nunca debe romper un análisis.
22
+ */
23
+ export class DiskCache {
24
+ dir;
25
+ ttlMs;
26
+ enabled;
27
+ constructor(dir, ttlMs, enabled = true) {
28
+ this.dir = dir;
29
+ this.ttlMs = ttlMs;
30
+ this.enabled = enabled;
31
+ }
32
+ fileFor(key) {
33
+ const hash = createHash('sha256').update(`${CACHE_SCHEMA}:${key}`).digest('hex');
34
+ return path.join(this.dir, `${hash}.json`);
35
+ }
36
+ async get(key) {
37
+ if (!this.enabled)
38
+ return undefined;
39
+ try {
40
+ const raw = await readFile(this.fileFor(key), 'utf8');
41
+ const entry = JSON.parse(raw);
42
+ if (typeof entry.storedAt !== 'number' || Date.now() - entry.storedAt > this.ttlMs)
43
+ return undefined;
44
+ return entry.value;
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ }
50
+ async set(key, value) {
51
+ if (!this.enabled)
52
+ return;
53
+ try {
54
+ await mkdir(this.dir, { recursive: true });
55
+ const file = this.fileFor(key);
56
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
57
+ const entry = { storedAt: Date.now(), value };
58
+ await writeFile(tmp, JSON.stringify(entry), 'utf8');
59
+ await rename(tmp, file); // escritura atómica
60
+ }
61
+ catch {
62
+ // Ignorado a propósito.
63
+ }
64
+ }
65
+ }