@efraindrummer/ghostdeps 0.2.0 → 0.4.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.
- package/CHANGELOG.md +17 -0
- package/README.md +143 -5
- package/dist/ai/advisor.js +162 -0
- package/dist/cli.js +244 -13
- package/dist/clients/npm.js +34 -0
- package/dist/diff/inspect.js +223 -0
- package/dist/fix/remediator.js +124 -0
- package/dist/mcp/server.js +194 -0
- package/dist/parser/lockfile.js +165 -4
- package/dist/render/html.js +562 -0
- package/dist/render/sarif.js +6 -0
- package/dist/scoring/scoring.js +10 -0
- package/dist/scoring/signals.js +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Motor de remediación automática (ghostdeps fix).
|
|
3
|
+
* Genera e inyecta overrides/resolutions en package.json para aislar
|
|
4
|
+
* o actualizar dependencias transitivas vulnerables o fantasmas.
|
|
5
|
+
*/
|
|
6
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
/**
|
|
9
|
+
* Detecta el gestor de paquetes predominante en base al lockfile del proyecto.
|
|
10
|
+
*/
|
|
11
|
+
export async function detectPackageManager(dir) {
|
|
12
|
+
const check = async (filename) => {
|
|
13
|
+
try {
|
|
14
|
+
await readFile(path.resolve(dir, filename));
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
if (await check('pnpm-lock.yaml'))
|
|
22
|
+
return 'pnpm';
|
|
23
|
+
if (await check('yarn.lock'))
|
|
24
|
+
return 'yarn';
|
|
25
|
+
return 'npm';
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Propone soluciones a partir de los reportes de análisis.
|
|
29
|
+
*/
|
|
30
|
+
export function generateProposals(reports, customOverrides = {}) {
|
|
31
|
+
const proposals = [];
|
|
32
|
+
// Overrides explícitos proporcionados por el usuario
|
|
33
|
+
for (const [pkgName, targetVersion] of Object.entries(customOverrides)) {
|
|
34
|
+
proposals.push({
|
|
35
|
+
packageName: pkgName,
|
|
36
|
+
currentSpec: 'custom',
|
|
37
|
+
targetVersion,
|
|
38
|
+
reason: 'Override manual indicado por el usuario',
|
|
39
|
+
severity: 'critical',
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
for (const r of reports) {
|
|
43
|
+
if (customOverrides[r.name])
|
|
44
|
+
continue;
|
|
45
|
+
// Paquetes críticos o con scripts sospechosos
|
|
46
|
+
if (r.result?.category === 'critical' || r.signals?.installScripts?.suspicious) {
|
|
47
|
+
if (r.npm?.latestVersion && r.npm.latestVersion !== r.spec) {
|
|
48
|
+
const reason = r.signals?.installScripts?.suspicious
|
|
49
|
+
? 'Posible versión comprometida por scripts de instalación'
|
|
50
|
+
: r.result?.mainAlert?.message ?? 'Dependencia identificada como crítica';
|
|
51
|
+
proposals.push({
|
|
52
|
+
packageName: r.name,
|
|
53
|
+
currentSpec: r.spec,
|
|
54
|
+
targetVersion: r.npm.latestVersion,
|
|
55
|
+
reason,
|
|
56
|
+
severity: 'critical',
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return proposals;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Genera el plan de modificación de package.json según el gestor (npm overrides, yarn resolutions, pnpm.overrides).
|
|
65
|
+
*/
|
|
66
|
+
export async function createFixPlan(packageJsonPath, proposals, pm) {
|
|
67
|
+
const raw = await readFile(packageJsonPath, 'utf8');
|
|
68
|
+
const pkgJson = JSON.parse(raw);
|
|
69
|
+
let changesMade = false;
|
|
70
|
+
if (proposals.length > 0) {
|
|
71
|
+
if (pm === 'npm') {
|
|
72
|
+
pkgJson.overrides = pkgJson.overrides ?? {};
|
|
73
|
+
for (const p of proposals) {
|
|
74
|
+
if (pkgJson.overrides[p.packageName] !== p.targetVersion) {
|
|
75
|
+
pkgJson.overrides[p.packageName] = p.targetVersion;
|
|
76
|
+
changesMade = true;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
else if (pm === 'yarn') {
|
|
81
|
+
pkgJson.resolutions = pkgJson.resolutions ?? {};
|
|
82
|
+
for (const p of proposals) {
|
|
83
|
+
if (pkgJson.resolutions[p.packageName] !== p.targetVersion) {
|
|
84
|
+
pkgJson.resolutions[p.packageName] = p.targetVersion;
|
|
85
|
+
changesMade = true;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
else if (pm === 'pnpm') {
|
|
90
|
+
pkgJson.pnpm = pkgJson.pnpm ?? {};
|
|
91
|
+
pkgJson.pnpm.overrides = pkgJson.pnpm.overrides ?? {};
|
|
92
|
+
for (const p of proposals) {
|
|
93
|
+
if (pkgJson.pnpm.overrides[p.packageName] !== p.targetVersion) {
|
|
94
|
+
pkgJson.pnpm.overrides[p.packageName] = p.targetVersion;
|
|
95
|
+
changesMade = true;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const updatedContent = JSON.stringify(pkgJson, null, 2) + '\n';
|
|
101
|
+
return {
|
|
102
|
+
packageManager: pm,
|
|
103
|
+
packageJsonPath,
|
|
104
|
+
proposals,
|
|
105
|
+
originalContent: raw,
|
|
106
|
+
updatedContent,
|
|
107
|
+
changesMade,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Aplica el plan a disco. Si backup=true genera package.json.bak.
|
|
112
|
+
*/
|
|
113
|
+
export async function applyFixPlan(plan, options = {}) {
|
|
114
|
+
if (options.dryRun || !plan.changesMade) {
|
|
115
|
+
return { written: false };
|
|
116
|
+
}
|
|
117
|
+
let backupPath;
|
|
118
|
+
if (options.backup) {
|
|
119
|
+
backupPath = `${plan.packageJsonPath}.bak`;
|
|
120
|
+
await writeFile(backupPath, plan.originalContent, 'utf8');
|
|
121
|
+
}
|
|
122
|
+
await writeFile(plan.packageJsonPath, plan.updatedContent, 'utf8');
|
|
123
|
+
return { written: true, backupPath };
|
|
124
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Servidor MCP (Model Context Protocol) para GhostDeps.
|
|
3
|
+
* Permite que agentes de IA como Claude Desktop, Cursor, Gemini CLI o ChatGPT
|
|
4
|
+
* llamen a GhostDeps como una herramienta (tool) a través de stdio (JSON-RPC 2.0).
|
|
5
|
+
*/
|
|
6
|
+
import readline from 'node:readline';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { analyzeAll, sortReports, summarize } from '../analyzer.js';
|
|
9
|
+
import { DiskCache, defaultCacheDir } from '../clients/cache.js';
|
|
10
|
+
import { GitHubClient } from '../clients/github.js';
|
|
11
|
+
import { RateLimitGate } from '../clients/http.js';
|
|
12
|
+
import { NpmClient } from '../clients/npm.js';
|
|
13
|
+
import { createIgnoreMatcher, loadConfig } from '../config.js';
|
|
14
|
+
import { readLockfile, resolveTransitive } from '../parser/lockfile.js';
|
|
15
|
+
import { readManifest } from '../parser/manifest.js';
|
|
16
|
+
import { renderMarkdown } from '../render/markdown.js';
|
|
17
|
+
export function createAuditToolDefinition() {
|
|
18
|
+
return {
|
|
19
|
+
name: 'ghostdeps_audit',
|
|
20
|
+
description: 'Audita la salud social, de mantenimiento y ciberseguridad de las dependencias de un proyecto Node.js / JavaScript. ' +
|
|
21
|
+
'Detecta paquetes abandonados, bus factor crítico (0 o 1 mantenedor), repositorios archivados y posibles señales de secuestro (hijacking).',
|
|
22
|
+
inputSchema: {
|
|
23
|
+
type: 'object',
|
|
24
|
+
properties: {
|
|
25
|
+
path: {
|
|
26
|
+
type: 'string',
|
|
27
|
+
description: 'Ruta al directorio que contiene el package.json (por defecto el directorio actual).',
|
|
28
|
+
},
|
|
29
|
+
dev: {
|
|
30
|
+
type: 'boolean',
|
|
31
|
+
description: 'Incluir también devDependencies en el análisis.',
|
|
32
|
+
},
|
|
33
|
+
transitive: {
|
|
34
|
+
type: 'boolean',
|
|
35
|
+
description: 'Incluir dependencias transitivas leyendo package-lock.json o yarn.lock.',
|
|
36
|
+
},
|
|
37
|
+
depth: {
|
|
38
|
+
type: 'integer',
|
|
39
|
+
description: 'Profundidad máxima para dependencias transitivas (1 = solo directas).',
|
|
40
|
+
},
|
|
41
|
+
failUnder: {
|
|
42
|
+
type: 'number',
|
|
43
|
+
description: 'Umbral mínimo de Health Score (0 a 100).',
|
|
44
|
+
},
|
|
45
|
+
ignore: {
|
|
46
|
+
type: 'array',
|
|
47
|
+
items: { type: 'string' },
|
|
48
|
+
description: 'Lista de nombres o patrones comodín a ignorar (ej: ["@types/*"]).',
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
export async function executeMcpAudit(args = {}, version) {
|
|
55
|
+
const targetDir = typeof args.path === 'string' && args.path ? path.resolve(args.path) : process.cwd();
|
|
56
|
+
const includeDev = Boolean(args.dev);
|
|
57
|
+
const includeTransitive = Boolean(args.transitive);
|
|
58
|
+
const depth = typeof args.depth === 'number' ? args.depth : undefined;
|
|
59
|
+
const failUnder = typeof args.failUnder === 'number' ? args.failUnder : undefined;
|
|
60
|
+
const ignoreList = Array.isArray(args.ignore) ? args.ignore.filter((i) => typeof i === 'string') : [];
|
|
61
|
+
const config = await loadConfig(targetDir);
|
|
62
|
+
const isIgnored = createIgnoreMatcher([...config.ignore, ...ignoreList]);
|
|
63
|
+
const manifest = await readManifest(targetDir, { includeDev: includeDev || (config.dev ?? false) });
|
|
64
|
+
let all = manifest.dependencies;
|
|
65
|
+
if (includeTransitive || config.transitive) {
|
|
66
|
+
try {
|
|
67
|
+
const { lock } = await readLockfile(targetDir);
|
|
68
|
+
const trans = resolveTransitive(lock, manifest.dependencies, {
|
|
69
|
+
maxDepth: depth ?? config.depth ?? Number.POSITIVE_INFINITY,
|
|
70
|
+
});
|
|
71
|
+
all = [...manifest.dependencies, ...trans];
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
process.stderr.write(`[GhostDeps MCP] Advertencia al leer lockfile: ${err.message}\n`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const ignored = all.filter((d) => isIgnored(d.name) || isIgnored(d.registryName)).map((d) => d.name);
|
|
78
|
+
const toAnalyze = all.filter((d) => !ignored.includes(d.name));
|
|
79
|
+
const token = process.env.GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || undefined;
|
|
80
|
+
const userAgent = `ghostdeps/${version} (+https://github.com/ghostdeps/ghostdeps)`;
|
|
81
|
+
const cache = new DiskCache(defaultCacheDir(), 24 * 3_600_000, true);
|
|
82
|
+
const gate = new RateLimitGate();
|
|
83
|
+
const now = new Date();
|
|
84
|
+
const npm = new NpmClient({ cache, timeoutMs: 15_000, retries: 3, userAgent });
|
|
85
|
+
const github = new GitHubClient({
|
|
86
|
+
cache,
|
|
87
|
+
token,
|
|
88
|
+
timeoutMs: 15_000,
|
|
89
|
+
retries: 3,
|
|
90
|
+
userAgent,
|
|
91
|
+
gate,
|
|
92
|
+
maxRateLimitWaitMs: 30_000,
|
|
93
|
+
now: () => now,
|
|
94
|
+
});
|
|
95
|
+
const reports = await analyzeAll(toAnalyze, { npm, github, now, weights: config.weights, thresholds: config.thresholds }, config.concurrency ?? 4);
|
|
96
|
+
const sorted = sortReports(reports);
|
|
97
|
+
const summary = summarize(sorted);
|
|
98
|
+
const failing = failUnder === undefined
|
|
99
|
+
? []
|
|
100
|
+
: sorted.filter((r) => r.status === 'evaluated' && r.result && r.result.score < failUnder).map((r) => r.name);
|
|
101
|
+
return renderMarkdown(sorted, summary, now, {
|
|
102
|
+
version,
|
|
103
|
+
projectName: manifest.projectName,
|
|
104
|
+
thresholds: config.thresholds,
|
|
105
|
+
failUnder,
|
|
106
|
+
failing,
|
|
107
|
+
ignored,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
export function startMcpServer(version) {
|
|
111
|
+
const rl = readline.createInterface({
|
|
112
|
+
input: process.stdin,
|
|
113
|
+
output: process.stdout,
|
|
114
|
+
terminal: false,
|
|
115
|
+
});
|
|
116
|
+
const sendResponse = (id, result) => {
|
|
117
|
+
if (id === undefined)
|
|
118
|
+
return;
|
|
119
|
+
const msg = JSON.stringify({ jsonrpc: '2.0', id, result });
|
|
120
|
+
process.stdout.write(`${msg}\n`);
|
|
121
|
+
};
|
|
122
|
+
const sendError = (id, code, message) => {
|
|
123
|
+
if (id === undefined)
|
|
124
|
+
return;
|
|
125
|
+
const msg = JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } });
|
|
126
|
+
process.stdout.write(`${msg}\n`);
|
|
127
|
+
};
|
|
128
|
+
process.stderr.write(`[GhostDeps MCP Server] Iniciado sobre stdio (v${version})\n`);
|
|
129
|
+
rl.on('line', async (line) => {
|
|
130
|
+
const trimmed = line.trim();
|
|
131
|
+
if (!trimmed)
|
|
132
|
+
return;
|
|
133
|
+
let req;
|
|
134
|
+
try {
|
|
135
|
+
req = JSON.parse(trimmed);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
sendError(undefined, -32700, 'Parse error: invalid JSON');
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const { id, method, params } = req;
|
|
142
|
+
try {
|
|
143
|
+
if (method === 'initialize') {
|
|
144
|
+
sendResponse(id, {
|
|
145
|
+
protocolVersion: '2024-11-05',
|
|
146
|
+
capabilities: { tools: {} },
|
|
147
|
+
serverInfo: {
|
|
148
|
+
name: '@efraindrummer/ghostdeps',
|
|
149
|
+
version,
|
|
150
|
+
},
|
|
151
|
+
});
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (method === 'notifications/initialized') {
|
|
155
|
+
// Notificación del cliente, no requiere respuesta
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (method === 'ping') {
|
|
159
|
+
sendResponse(id, {});
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
if (method === 'tools/list') {
|
|
163
|
+
sendResponse(id, {
|
|
164
|
+
tools: [createAuditToolDefinition()],
|
|
165
|
+
});
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (method === 'tools/call') {
|
|
169
|
+
const toolName = params?.name;
|
|
170
|
+
if (toolName !== 'ghostdeps_audit') {
|
|
171
|
+
sendError(id, -32601, `Herramienta desconocida: ${toolName}`);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
const args = params?.arguments ?? {};
|
|
175
|
+
const markdown = await executeMcpAudit(args, version);
|
|
176
|
+
sendResponse(id, {
|
|
177
|
+
content: [
|
|
178
|
+
{
|
|
179
|
+
type: 'text',
|
|
180
|
+
text: markdown,
|
|
181
|
+
},
|
|
182
|
+
],
|
|
183
|
+
isError: false,
|
|
184
|
+
});
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
// Método no implementado
|
|
188
|
+
sendError(id, -32601, `Método no soportado: ${method}`);
|
|
189
|
+
}
|
|
190
|
+
catch (err) {
|
|
191
|
+
sendError(id, -32603, `Error interno ejecutando ${method}: ${err.message}`);
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
}
|
package/dist/parser/lockfile.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
import { readFile } from 'node:fs/promises';
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import { ManifestError } from '../errors.js';
|
|
12
|
-
export const LOCKFILE_NAMES = ['npm-shrinkwrap.json', 'package-lock.json', 'yarn.lock'];
|
|
12
|
+
export const LOCKFILE_NAMES = ['npm-shrinkwrap.json', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];
|
|
13
13
|
function unquote(s) {
|
|
14
14
|
const t = s.trim();
|
|
15
15
|
if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) {
|
|
@@ -98,6 +98,89 @@ export function parseYarnLock(content) {
|
|
|
98
98
|
flush();
|
|
99
99
|
return { type: 'yarn', entries };
|
|
100
100
|
}
|
|
101
|
+
/**
|
|
102
|
+
* Parser ligero y seguro para pnpm-lock.yaml (v5/v6/v9).
|
|
103
|
+
*/
|
|
104
|
+
export function parsePnpmLock(content) {
|
|
105
|
+
const packages = new Map();
|
|
106
|
+
const lines = content.split(/\r?\n/);
|
|
107
|
+
let inPackages = false;
|
|
108
|
+
let currentKey = null;
|
|
109
|
+
let currentPkg = null;
|
|
110
|
+
let subSection = 'none';
|
|
111
|
+
const flush = () => {
|
|
112
|
+
if (currentKey && currentPkg && currentPkg.name && currentPkg.version) {
|
|
113
|
+
packages.set(currentKey, {
|
|
114
|
+
name: currentPkg.name,
|
|
115
|
+
version: currentPkg.version,
|
|
116
|
+
dependencies: currentPkg.dependencies ?? {},
|
|
117
|
+
optionalDependencies: currentPkg.optionalDependencies ?? {},
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
currentKey = null;
|
|
121
|
+
currentPkg = null;
|
|
122
|
+
subSection = 'none';
|
|
123
|
+
};
|
|
124
|
+
for (let i = 0; i < lines.length; i++) {
|
|
125
|
+
const rawLine = lines[i] ?? '';
|
|
126
|
+
const trimmed = rawLine.trim();
|
|
127
|
+
if (!trimmed || trimmed.startsWith('#'))
|
|
128
|
+
continue;
|
|
129
|
+
if (rawLine.startsWith('packages:')) {
|
|
130
|
+
inPackages = true;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (!inPackages)
|
|
134
|
+
continue;
|
|
135
|
+
if (!rawLine.startsWith(' ') && trimmed.endsWith(':')) {
|
|
136
|
+
flush();
|
|
137
|
+
inPackages = false;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (rawLine.startsWith(' ') && !rawLine.startsWith(' ') && trimmed.endsWith(':')) {
|
|
141
|
+
flush();
|
|
142
|
+
let key = trimmed.slice(0, -1).trim();
|
|
143
|
+
key = unquote(key).replace(/^\//, '').replace(/\(.*$/, '');
|
|
144
|
+
const lastAt = key.lastIndexOf('@');
|
|
145
|
+
if (lastAt > 0) {
|
|
146
|
+
const name = key.slice(0, lastAt);
|
|
147
|
+
const version = key.slice(lastAt + 1);
|
|
148
|
+
currentKey = `${name}@${version}`;
|
|
149
|
+
currentPkg = { name, version, dependencies: {}, optionalDependencies: {} };
|
|
150
|
+
}
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (!currentPkg)
|
|
154
|
+
continue;
|
|
155
|
+
if (rawLine.startsWith(' ') && !rawLine.startsWith(' ')) {
|
|
156
|
+
if (trimmed === 'dependencies:') {
|
|
157
|
+
subSection = 'dependencies';
|
|
158
|
+
}
|
|
159
|
+
else if (trimmed === 'optionalDependencies:') {
|
|
160
|
+
subSection = 'optionalDependencies';
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
subSection = 'none';
|
|
164
|
+
}
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
if (rawLine.startsWith(' ') && (subSection === 'dependencies' || subSection === 'optionalDependencies')) {
|
|
168
|
+
const colonIdx = trimmed.indexOf(':');
|
|
169
|
+
if (colonIdx > 0) {
|
|
170
|
+
const depName = unquote(trimmed.slice(0, colonIdx));
|
|
171
|
+
const depVersion = unquote(trimmed.slice(colonIdx + 1));
|
|
172
|
+
if (subSection === 'dependencies') {
|
|
173
|
+
currentPkg.dependencies[depName] = depVersion;
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
currentPkg.optionalDependencies[depName] = depVersion;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
flush();
|
|
182
|
+
return { type: 'pnpm', packages };
|
|
183
|
+
}
|
|
101
184
|
export async function readLockfile(dir) {
|
|
102
185
|
for (const name of LOCKFILE_NAMES) {
|
|
103
186
|
const file = path.resolve(dir, name);
|
|
@@ -119,6 +202,15 @@ export async function readLockfile(dir) {
|
|
|
119
202
|
throw new ManifestError(`Error al procesar ${file}: ${cause.message}`, { cause });
|
|
120
203
|
}
|
|
121
204
|
}
|
|
205
|
+
if (name === 'pnpm-lock.yaml') {
|
|
206
|
+
try {
|
|
207
|
+
const lock = parsePnpmLock(content);
|
|
208
|
+
return { file, lock };
|
|
209
|
+
}
|
|
210
|
+
catch (cause) {
|
|
211
|
+
throw new ManifestError(`Error al procesar ${file}: ${cause.message}`, { cause });
|
|
212
|
+
}
|
|
213
|
+
}
|
|
122
214
|
try {
|
|
123
215
|
const parsed = JSON.parse(content);
|
|
124
216
|
const lock = {
|
|
@@ -132,8 +224,8 @@ export async function readLockfile(dir) {
|
|
|
132
224
|
throw new ManifestError(`${file} no es un JSON válido.`, { cause });
|
|
133
225
|
}
|
|
134
226
|
}
|
|
135
|
-
throw new ManifestError(`--transitive requiere package-lock.json
|
|
136
|
-
'Ejecuta "npm install" o "
|
|
227
|
+
throw new ManifestError(`--transitive requiere package-lock.json, yarn.lock o pnpm-lock.yaml en ${path.resolve(dir)}. ` +
|
|
228
|
+
'Ejecuta "npm install", "yarn install" o "pnpm install".');
|
|
137
229
|
}
|
|
138
230
|
/**
|
|
139
231
|
* Resolución estilo Node para npm: busca `<from>/node_modules/<name>` y sube por los ancestros.
|
|
@@ -279,13 +371,82 @@ function resolveYarnTransitive(lock, direct, options) {
|
|
|
279
371
|
}
|
|
280
372
|
return result;
|
|
281
373
|
}
|
|
374
|
+
function resolvePnpmTransitive(lock, direct, options) {
|
|
375
|
+
const packages = lock.packages;
|
|
376
|
+
const directNames = new Set(direct.map((d) => d.name));
|
|
377
|
+
const seenNames = new Set(directNames);
|
|
378
|
+
const visited = new Set();
|
|
379
|
+
const result = [];
|
|
380
|
+
const findEntry = (name, spec) => {
|
|
381
|
+
if (spec) {
|
|
382
|
+
const cleanSpec = spec.replace(/\(.*$/, '');
|
|
383
|
+
const exactKey = `${name}@${cleanSpec}`;
|
|
384
|
+
if (packages.has(exactKey))
|
|
385
|
+
return packages.get(exactKey);
|
|
386
|
+
if (packages.has(spec))
|
|
387
|
+
return packages.get(spec);
|
|
388
|
+
}
|
|
389
|
+
const prefix = `${name}@`;
|
|
390
|
+
for (const [k, v] of packages) {
|
|
391
|
+
if (k.startsWith(prefix))
|
|
392
|
+
return v;
|
|
393
|
+
}
|
|
394
|
+
return undefined;
|
|
395
|
+
};
|
|
396
|
+
const queue = [];
|
|
397
|
+
for (const d of direct) {
|
|
398
|
+
if (d.unsupportedReason)
|
|
399
|
+
continue;
|
|
400
|
+
const pkg = findEntry(d.name, d.spec);
|
|
401
|
+
if (!pkg)
|
|
402
|
+
continue;
|
|
403
|
+
const visitKey = `${d.name}@${pkg.version}`;
|
|
404
|
+
if (visited.has(visitKey))
|
|
405
|
+
continue;
|
|
406
|
+
visited.add(visitKey);
|
|
407
|
+
queue.push({ name: d.name, pkg, depth: 1, via: [d.name] });
|
|
408
|
+
}
|
|
409
|
+
while (queue.length > 0) {
|
|
410
|
+
const node = queue.shift();
|
|
411
|
+
if (node.depth >= options.maxDepth)
|
|
412
|
+
continue;
|
|
413
|
+
const children = { ...node.pkg.dependencies, ...node.pkg.optionalDependencies };
|
|
414
|
+
for (const [childName, childSpec] of Object.entries(children).sort(([a], [b]) => a.localeCompare(b))) {
|
|
415
|
+
const childPkg = findEntry(childName, childSpec);
|
|
416
|
+
if (!childPkg)
|
|
417
|
+
continue;
|
|
418
|
+
const visitKey = `${childName}@${childPkg.version}`;
|
|
419
|
+
if (visited.has(visitKey))
|
|
420
|
+
continue;
|
|
421
|
+
visited.add(visitKey);
|
|
422
|
+
const depth = node.depth + 1;
|
|
423
|
+
if (!seenNames.has(childName)) {
|
|
424
|
+
seenNames.add(childName);
|
|
425
|
+
const spec = {
|
|
426
|
+
name: childName,
|
|
427
|
+
registryName: childPkg.name,
|
|
428
|
+
spec: childPkg.version,
|
|
429
|
+
kind: 'transitive',
|
|
430
|
+
depth,
|
|
431
|
+
via: node.via,
|
|
432
|
+
};
|
|
433
|
+
result.push(spec);
|
|
434
|
+
}
|
|
435
|
+
queue.push({ name: childName, pkg: childPkg, depth, via: [...node.via, childName] });
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
return result;
|
|
439
|
+
}
|
|
282
440
|
/**
|
|
283
441
|
* Devuelve SOLO las dependencias transitivas (profundidad >= 2), deduplicadas por nombre,
|
|
284
|
-
* alcanzables desde las directas indicadas en un lockfile de npm o
|
|
442
|
+
* alcanzables desde las directas indicadas en un lockfile de npm, Yarn o pnpm.
|
|
285
443
|
*/
|
|
286
444
|
export function resolveTransitive(lock, direct, options) {
|
|
287
445
|
if (lock.type === 'yarn') {
|
|
288
446
|
return resolveYarnTransitive(lock, direct, options);
|
|
289
447
|
}
|
|
448
|
+
if (lock.type === 'pnpm') {
|
|
449
|
+
return resolvePnpmTransitive(lock, direct, options);
|
|
450
|
+
}
|
|
290
451
|
return resolveNpmTransitive(lock, direct, options);
|
|
291
452
|
}
|