@efraindrummer/ghostdeps 0.0.0-stage → 0.2.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 +23 -0
- package/LICENSE +21 -0
- package/README.md +602 -2
- package/dist/analyzer.js +87 -0
- package/dist/cli.js +241 -0
- package/dist/clients/cache.js +65 -0
- package/dist/clients/github.js +150 -0
- package/dist/clients/http.js +122 -0
- package/dist/clients/npm.js +115 -0
- package/dist/config.js +194 -0
- package/dist/errors.js +69 -0
- package/dist/parser/lockfile.js +291 -0
- package/dist/parser/manifest.js +94 -0
- package/dist/parser/repoUrl.js +103 -0
- package/dist/render/markdown.js +75 -0
- package/dist/render/sarif.js +139 -0
- package/dist/render/table.js +95 -0
- package/dist/scoring/scoring.js +113 -0
- package/dist/scoring/signals.js +19 -0
- package/dist/types.js +5 -0
- package/dist/utils.js +44 -0
- package/package.json +50 -4
- package/schema/ghostdepsrc.schema.json +67 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { normalizeRepository } from '../parser/repoUrl.js';
|
|
2
|
+
import { fetchJson } from './http.js';
|
|
3
|
+
const REGISTRY = 'https://registry.npmjs.org';
|
|
4
|
+
/** Nº de versiones previas a la última que se usan para comparar publicadores. */
|
|
5
|
+
const PUBLISHER_HISTORY = 5;
|
|
6
|
+
function personName(p) {
|
|
7
|
+
if (!p)
|
|
8
|
+
return null;
|
|
9
|
+
if (typeof p === 'string')
|
|
10
|
+
return p.replace(/\s*<.*$/, '').trim() || null;
|
|
11
|
+
return p.name ?? p.email ?? null;
|
|
12
|
+
}
|
|
13
|
+
function personList(value) {
|
|
14
|
+
if (value === undefined)
|
|
15
|
+
return null;
|
|
16
|
+
const arr = Array.isArray(value) ? value : [value];
|
|
17
|
+
return [...new Set(arr.map(personName).filter((n) => !!n))].sort();
|
|
18
|
+
}
|
|
19
|
+
function diffMaintainers(previous, current) {
|
|
20
|
+
const prev = new Set(previous);
|
|
21
|
+
const curr = new Set(current);
|
|
22
|
+
return {
|
|
23
|
+
added: current.filter((m) => !prev.has(m)),
|
|
24
|
+
removed: previous.filter((m) => !curr.has(m)),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export function registryUrl(name) {
|
|
28
|
+
const encoded = name.startsWith('@') ? `@${encodeURIComponent(name.slice(1))}` : encodeURIComponent(name);
|
|
29
|
+
return `${REGISTRY}/${encoded}`;
|
|
30
|
+
}
|
|
31
|
+
/** Extracción pura (testeable) de la información relevante del "packument" de npm. */
|
|
32
|
+
export function extractNpmInfo(name, doc) {
|
|
33
|
+
const versions = doc.versions ?? {};
|
|
34
|
+
const time = doc.time ?? {};
|
|
35
|
+
// Versiones ordenadas cronológicamente por fecha de publicación.
|
|
36
|
+
const chronological = Object.entries(time)
|
|
37
|
+
.filter(([v]) => v !== 'created' && v !== 'modified' && versions[v] !== undefined)
|
|
38
|
+
.sort(([, a], [, b]) => Date.parse(a) - Date.parse(b))
|
|
39
|
+
.map(([v]) => v);
|
|
40
|
+
const latestTag = doc['dist-tags']?.latest;
|
|
41
|
+
const latestVersion = latestTag && versions[latestTag] ? latestTag : (chronological[chronological.length - 1] ?? null);
|
|
42
|
+
const latestDoc = latestVersion ? versions[latestVersion] : undefined;
|
|
43
|
+
const latestPublishedAt = latestVersion ? (time[latestVersion] ?? null) : null;
|
|
44
|
+
// Versiones publicadas antes que la "latest" (excluye versiones posteriores, p. ej. backports).
|
|
45
|
+
const latestTime = latestPublishedAt ? Date.parse(latestPublishedAt) : Number.POSITIVE_INFINITY;
|
|
46
|
+
const previous = chronological.filter((v) => v !== latestVersion && Date.parse(time[v] ?? '') < latestTime);
|
|
47
|
+
const previousVersion = previous[previous.length - 1] ?? null;
|
|
48
|
+
const previousDoc = previousVersion ? versions[previousVersion] : undefined;
|
|
49
|
+
const latestPublisher = personName(latestDoc?._npmUser);
|
|
50
|
+
const previousPublishers = [
|
|
51
|
+
...new Set(previous
|
|
52
|
+
.slice(-PUBLISHER_HISTORY)
|
|
53
|
+
.map((v) => personName(versions[v]?._npmUser))
|
|
54
|
+
.filter((n) => !!n)),
|
|
55
|
+
];
|
|
56
|
+
const latestMaintainers = personList(latestDoc?.maintainers);
|
|
57
|
+
const previousMaintainers = personList(previousDoc?.maintainers);
|
|
58
|
+
const maintainersChange = latestMaintainers && previousMaintainers ? diffMaintainers(previousMaintainers, latestMaintainers) : null;
|
|
59
|
+
// Repo: preferimos el de la última versión; si falta, el del documento; si falta, homepage.
|
|
60
|
+
const repoField = latestDoc?.repository ?? doc.repository;
|
|
61
|
+
let repository = normalizeRepository(repoField);
|
|
62
|
+
if (!repository) {
|
|
63
|
+
const homepage = latestDoc?.homepage ?? doc.homepage;
|
|
64
|
+
const fromHomepage = homepage ? normalizeRepository(homepage) : null;
|
|
65
|
+
if (fromHomepage && fromHomepage.host === 'github')
|
|
66
|
+
repository = fromHomepage;
|
|
67
|
+
}
|
|
68
|
+
let rawRepositoryUrl = null;
|
|
69
|
+
if (typeof repoField === 'string')
|
|
70
|
+
rawRepositoryUrl = repoField;
|
|
71
|
+
else if (repoField && typeof repoField === 'object') {
|
|
72
|
+
const url = repoField.url;
|
|
73
|
+
if (typeof url === 'string')
|
|
74
|
+
rawRepositoryUrl = url;
|
|
75
|
+
}
|
|
76
|
+
const deprecatedRaw = latestDoc?.deprecated;
|
|
77
|
+
const deprecated = typeof deprecatedRaw === 'string' && deprecatedRaw.length > 0
|
|
78
|
+
? deprecatedRaw
|
|
79
|
+
: deprecatedRaw === true
|
|
80
|
+
? 'deprecated'
|
|
81
|
+
: null;
|
|
82
|
+
return {
|
|
83
|
+
name: doc.name ?? name,
|
|
84
|
+
latestVersion,
|
|
85
|
+
latestPublishedAt,
|
|
86
|
+
previousPublishedAt: previousVersion ? (time[previousVersion] ?? null) : null,
|
|
87
|
+
deprecated,
|
|
88
|
+
maintainers: personList(doc.maintainers) ?? [],
|
|
89
|
+
repository,
|
|
90
|
+
rawRepositoryUrl,
|
|
91
|
+
latestPublisher,
|
|
92
|
+
previousPublishers,
|
|
93
|
+
maintainersChange,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
export class NpmClient {
|
|
97
|
+
opts;
|
|
98
|
+
constructor(opts) {
|
|
99
|
+
this.opts = opts;
|
|
100
|
+
}
|
|
101
|
+
async getPackageInfo(name) {
|
|
102
|
+
const key = `npm:${name}`;
|
|
103
|
+
const cached = await this.opts.cache.get(key);
|
|
104
|
+
if (cached)
|
|
105
|
+
return cached;
|
|
106
|
+
const { data } = await fetchJson(registryUrl(name), {
|
|
107
|
+
timeoutMs: this.opts.timeoutMs,
|
|
108
|
+
retries: this.opts.retries,
|
|
109
|
+
headers: { accept: 'application/json', 'user-agent': this.opts.userAgent },
|
|
110
|
+
});
|
|
111
|
+
const info = extractNpmInfo(name, data);
|
|
112
|
+
await this.opts.cache.set(key, info);
|
|
113
|
+
return info;
|
|
114
|
+
}
|
|
115
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuración por proyecto. Se busca, en orden:
|
|
3
|
+
* 1. el archivo indicado con --config
|
|
4
|
+
* 2. .ghostdepsrc.json o .ghostdepsrc (JSON) en el directorio analizado
|
|
5
|
+
* 3. la clave "ghostdeps" del package.json
|
|
6
|
+
* Precedencia final: flags de CLI > archivo de configuración > valores por defecto.
|
|
7
|
+
*/
|
|
8
|
+
import { readFile } from 'node:fs/promises';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { ConfigError } from './errors.js';
|
|
11
|
+
import { DEFAULT_WEIGHTS, THRESHOLDS } from './scoring/scoring.js';
|
|
12
|
+
export const CONFIG_FILES = ['.ghostdepsrc.json', '.ghostdepsrc'];
|
|
13
|
+
const TOP_LEVEL_KEYS = ['$schema', 'ignore', 'failUnder', 'dev', 'transitive', 'depth', 'concurrency', 'weights', 'thresholds'];
|
|
14
|
+
const NUMERIC_WEIGHTS = [
|
|
15
|
+
'archived',
|
|
16
|
+
'deprecated',
|
|
17
|
+
'repoRedirect',
|
|
18
|
+
'maintainersChanged',
|
|
19
|
+
'newPublisher',
|
|
20
|
+
'hijackPattern',
|
|
21
|
+
'dormantRevivalDays',
|
|
22
|
+
];
|
|
23
|
+
const TIER_WEIGHTS = ['abandonment', 'unansweredIssues'];
|
|
24
|
+
const WEIGHT_KEYS = [...NUMERIC_WEIGHTS, ...TIER_WEIGHTS, 'stalePublish', 'busFactor'];
|
|
25
|
+
function isObj(v) {
|
|
26
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
27
|
+
}
|
|
28
|
+
function checkKeys(obj, allowed, where, source) {
|
|
29
|
+
const unknown = Object.keys(obj).filter((k) => !allowed.includes(k));
|
|
30
|
+
if (unknown.length > 0) {
|
|
31
|
+
throw new ConfigError(`${source}: clave(s) desconocida(s) en ${where}: ${unknown.join(', ')}. Permitidas: ${allowed.join(', ')}.`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function num(v, where, source, min, max, integer = false) {
|
|
35
|
+
if (typeof v !== 'number' || !Number.isFinite(v) || v < min || v > max || (integer && !Number.isInteger(v))) {
|
|
36
|
+
throw new ConfigError(`${source}: "${where}" debe ser un ${integer ? 'entero' : 'número'} entre ${min} y ${max}.`);
|
|
37
|
+
}
|
|
38
|
+
return v;
|
|
39
|
+
}
|
|
40
|
+
function bool(v, where, source) {
|
|
41
|
+
if (typeof v !== 'boolean')
|
|
42
|
+
throw new ConfigError(`${source}: "${where}" debe ser true o false.`);
|
|
43
|
+
return v;
|
|
44
|
+
}
|
|
45
|
+
function tier(v, where, source) {
|
|
46
|
+
if (!isObj(v))
|
|
47
|
+
throw new ConfigError(`${source}: "${where}" debe ser un objeto { "threshold", "points" }.`);
|
|
48
|
+
checkKeys(v, ['threshold', 'points'], where, source);
|
|
49
|
+
return {
|
|
50
|
+
threshold: num(v.threshold, `${where}.threshold`, source, 0, 100_000),
|
|
51
|
+
points: num(v.points, `${where}.points`, source, 0, 100),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function tiers(v, where, source) {
|
|
55
|
+
if (!Array.isArray(v))
|
|
56
|
+
throw new ConfigError(`${source}: "${where}" debe ser un array de tramos.`);
|
|
57
|
+
// El motor espera los tramos de mayor a menor umbral.
|
|
58
|
+
return v.map((t, i) => tier(t, `${where}[${i}]`, source)).sort((a, b) => b.threshold - a.threshold);
|
|
59
|
+
}
|
|
60
|
+
function parseWeights(v, source) {
|
|
61
|
+
const w = {
|
|
62
|
+
...DEFAULT_WEIGHTS,
|
|
63
|
+
busFactor: { ...DEFAULT_WEIGHTS.busFactor },
|
|
64
|
+
stalePublish: { ...DEFAULT_WEIGHTS.stalePublish },
|
|
65
|
+
};
|
|
66
|
+
if (v === undefined)
|
|
67
|
+
return w;
|
|
68
|
+
if (!isObj(v))
|
|
69
|
+
throw new ConfigError(`${source}: "weights" debe ser un objeto.`);
|
|
70
|
+
checkKeys(v, WEIGHT_KEYS, 'weights', source);
|
|
71
|
+
for (const key of NUMERIC_WEIGHTS) {
|
|
72
|
+
if (v[key] !== undefined) {
|
|
73
|
+
const max = key === 'dormantRevivalDays' ? 100_000 : 100;
|
|
74
|
+
w[key] = num(v[key], `weights.${key}`, source, 0, max);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
for (const key of TIER_WEIGHTS) {
|
|
78
|
+
if (v[key] !== undefined)
|
|
79
|
+
w[key] = tiers(v[key], `weights.${key}`, source);
|
|
80
|
+
}
|
|
81
|
+
if (v.stalePublish !== undefined)
|
|
82
|
+
w.stalePublish = tier(v.stalePublish, 'weights.stalePublish', source);
|
|
83
|
+
if (v.busFactor !== undefined) {
|
|
84
|
+
if (!isObj(v.busFactor))
|
|
85
|
+
throw new ConfigError(`${source}: "weights.busFactor" debe ser un objeto.`);
|
|
86
|
+
checkKeys(v.busFactor, ['zero', 'one', 'two'], 'weights.busFactor', source);
|
|
87
|
+
for (const k of ['zero', 'one', 'two']) {
|
|
88
|
+
if (v.busFactor[k] !== undefined)
|
|
89
|
+
w.busFactor[k] = num(v.busFactor[k], `weights.busFactor.${k}`, source, 0, 100);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return w;
|
|
93
|
+
}
|
|
94
|
+
function parseThresholds(v, source) {
|
|
95
|
+
const t = { ...THRESHOLDS };
|
|
96
|
+
if (v === undefined)
|
|
97
|
+
return t;
|
|
98
|
+
if (!isObj(v))
|
|
99
|
+
throw new ConfigError(`${source}: "thresholds" debe ser un objeto.`);
|
|
100
|
+
checkKeys(v, ['healthy', 'caution'], 'thresholds', source);
|
|
101
|
+
if (v.healthy !== undefined)
|
|
102
|
+
t.healthy = num(v.healthy, 'thresholds.healthy', source, 0, 100);
|
|
103
|
+
if (v.caution !== undefined)
|
|
104
|
+
t.caution = num(v.caution, 'thresholds.caution', source, 0, 100);
|
|
105
|
+
if (t.caution > t.healthy) {
|
|
106
|
+
throw new ConfigError(`${source}: "thresholds.caution" (${t.caution}) no puede ser mayor que "healthy" (${t.healthy}).`);
|
|
107
|
+
}
|
|
108
|
+
return t;
|
|
109
|
+
}
|
|
110
|
+
/** Valida y normaliza un objeto de configuración ya parseado. */
|
|
111
|
+
export function parseConfig(raw, source) {
|
|
112
|
+
if (!isObj(raw))
|
|
113
|
+
throw new ConfigError(`${source}: la configuración debe ser un objeto JSON.`);
|
|
114
|
+
checkKeys(raw, TOP_LEVEL_KEYS, 'la raíz', source);
|
|
115
|
+
let ignore = [];
|
|
116
|
+
if (raw.ignore !== undefined) {
|
|
117
|
+
if (!Array.isArray(raw.ignore) || raw.ignore.some((p) => typeof p !== 'string' || p.trim() === '')) {
|
|
118
|
+
throw new ConfigError(`${source}: "ignore" debe ser un array de nombres/patrones (ej. ["left-pad", "@types/*"]).`);
|
|
119
|
+
}
|
|
120
|
+
ignore = raw.ignore.map((p) => p.trim());
|
|
121
|
+
}
|
|
122
|
+
const config = {
|
|
123
|
+
source,
|
|
124
|
+
ignore,
|
|
125
|
+
weights: parseWeights(raw.weights, source),
|
|
126
|
+
thresholds: parseThresholds(raw.thresholds, source),
|
|
127
|
+
};
|
|
128
|
+
if (raw.failUnder !== undefined)
|
|
129
|
+
config.failUnder = num(raw.failUnder, 'failUnder', source, 0, 100);
|
|
130
|
+
if (raw.dev !== undefined)
|
|
131
|
+
config.dev = bool(raw.dev, 'dev', source);
|
|
132
|
+
if (raw.transitive !== undefined)
|
|
133
|
+
config.transitive = bool(raw.transitive, 'transitive', source);
|
|
134
|
+
if (raw.depth !== undefined)
|
|
135
|
+
config.depth = num(raw.depth, 'depth', source, 1, 100, true);
|
|
136
|
+
if (raw.concurrency !== undefined)
|
|
137
|
+
config.concurrency = num(raw.concurrency, 'concurrency', source, 1, 32, true);
|
|
138
|
+
return config;
|
|
139
|
+
}
|
|
140
|
+
export function defaultConfig() {
|
|
141
|
+
return { ...parseConfig({}, '(defaults)'), source: null };
|
|
142
|
+
}
|
|
143
|
+
async function readJson(file) {
|
|
144
|
+
let content;
|
|
145
|
+
try {
|
|
146
|
+
content = await readFile(file, 'utf8');
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
if (err.code === 'ENOENT')
|
|
150
|
+
return undefined;
|
|
151
|
+
throw new ConfigError(`No se pudo leer ${file}: ${err.message}`, { cause: err });
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
return JSON.parse(content);
|
|
155
|
+
}
|
|
156
|
+
catch (cause) {
|
|
157
|
+
throw new ConfigError(`${file} no es un JSON válido.`, { cause });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
export async function loadConfig(dir, explicitPath) {
|
|
161
|
+
if (explicitPath) {
|
|
162
|
+
const file = path.resolve(explicitPath);
|
|
163
|
+
const raw = await readJson(file);
|
|
164
|
+
if (raw === undefined)
|
|
165
|
+
throw new ConfigError(`No existe el archivo de configuración ${file}.`);
|
|
166
|
+
return parseConfig(raw, file);
|
|
167
|
+
}
|
|
168
|
+
for (const name of CONFIG_FILES) {
|
|
169
|
+
const file = path.resolve(dir, name);
|
|
170
|
+
const raw = await readJson(file);
|
|
171
|
+
if (raw !== undefined)
|
|
172
|
+
return parseConfig(raw, file);
|
|
173
|
+
}
|
|
174
|
+
const pkgFile = path.resolve(dir, 'package.json');
|
|
175
|
+
try {
|
|
176
|
+
const pkg = await readJson(pkgFile);
|
|
177
|
+
if (isObj(pkg) && pkg.ghostdeps !== undefined)
|
|
178
|
+
return parseConfig(pkg.ghostdeps, `${pkgFile} ("ghostdeps")`);
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
// Un package.json inválido lo reportará el lector de manifest con un mensaje más preciso.
|
|
182
|
+
}
|
|
183
|
+
return defaultConfig();
|
|
184
|
+
}
|
|
185
|
+
/** Convierte un patrón con `*` en RegExp anclada. */
|
|
186
|
+
function patternToRegExp(pattern) {
|
|
187
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
|
|
188
|
+
return new RegExp(`^${escaped}$`);
|
|
189
|
+
}
|
|
190
|
+
/** Devuelve un predicado que indica si un paquete está ignorado (por nombre o patrón con `*`). */
|
|
191
|
+
export function createIgnoreMatcher(patterns) {
|
|
192
|
+
const regexes = patterns.map(patternToRegExp);
|
|
193
|
+
return (name) => regexes.some((r) => r.test(name));
|
|
194
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Jerarquía de errores tipados. Cada error lleva un `code` estable (útil en --json/CI)
|
|
3
|
+
* y un mensaje legible para humanos.
|
|
4
|
+
*/
|
|
5
|
+
export class GhostDepsError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
constructor(code, message, options) {
|
|
8
|
+
super(message, options);
|
|
9
|
+
this.name = new.target.name;
|
|
10
|
+
this.code = code;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export class ManifestError extends GhostDepsError {
|
|
14
|
+
constructor(message, options) {
|
|
15
|
+
super('MANIFEST_ERROR', message, options);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export class ConfigError extends GhostDepsError {
|
|
19
|
+
constructor(message, options) {
|
|
20
|
+
super('CONFIG_ERROR', message, options);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export class NetworkError extends GhostDepsError {
|
|
24
|
+
url;
|
|
25
|
+
constructor(url, cause) {
|
|
26
|
+
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
27
|
+
super('NETWORK_ERROR', `Error de red al consultar ${url}: ${detail}`, { cause });
|
|
28
|
+
this.url = url;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export class TimeoutError extends GhostDepsError {
|
|
32
|
+
url;
|
|
33
|
+
timeoutMs;
|
|
34
|
+
constructor(url, timeoutMs) {
|
|
35
|
+
super('TIMEOUT', `Timeout (${timeoutMs} ms) al consultar ${url}`);
|
|
36
|
+
this.url = url;
|
|
37
|
+
this.timeoutMs = timeoutMs;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export class HttpError extends GhostDepsError {
|
|
41
|
+
url;
|
|
42
|
+
status;
|
|
43
|
+
constructor(url, status, body) {
|
|
44
|
+
const snippet = body ? `: ${body.slice(0, 200)}` : '';
|
|
45
|
+
super('HTTP_ERROR', `HTTP ${status} al consultar ${url}${snippet}`);
|
|
46
|
+
this.url = url;
|
|
47
|
+
this.status = status;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export class NotFoundError extends GhostDepsError {
|
|
51
|
+
url;
|
|
52
|
+
constructor(url) {
|
|
53
|
+
super('NOT_FOUND', `Recurso no encontrado (404): ${url}`);
|
|
54
|
+
this.url = url;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export class RateLimitError extends GhostDepsError {
|
|
58
|
+
resetAt;
|
|
59
|
+
constructor(resetAt, hint) {
|
|
60
|
+
const when = resetAt ? ` hasta las ${resetAt.toLocaleTimeString()}` : '';
|
|
61
|
+
super('RATE_LIMITED', `Rate limit de GitHub agotado${when}.${hint ? ' ' + hint : ''}`);
|
|
62
|
+
this.resetAt = resetAt;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
export function errorMessage(err) {
|
|
66
|
+
if (err instanceof Error)
|
|
67
|
+
return err.message;
|
|
68
|
+
return String(err);
|
|
69
|
+
}
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolución de dependencias transitivas a partir de lockfiles:
|
|
3
|
+
* - package-lock.json / npm-shrinkwrap.json (npm v2/v3, npm >= 7)
|
|
4
|
+
* - yarn.lock (Yarn v1 clásico)
|
|
5
|
+
*
|
|
6
|
+
* Recorre el grafo en anchura (BFS) para registrar el camino más corto
|
|
7
|
+
* desde el proyecto (`via`) y la profundidad de cada dependencia.
|
|
8
|
+
*/
|
|
9
|
+
import { readFile } from 'node:fs/promises';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { ManifestError } from '../errors.js';
|
|
12
|
+
export const LOCKFILE_NAMES = ['npm-shrinkwrap.json', 'package-lock.json', 'yarn.lock'];
|
|
13
|
+
function unquote(s) {
|
|
14
|
+
const t = s.trim();
|
|
15
|
+
if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) {
|
|
16
|
+
return t.slice(1, -1);
|
|
17
|
+
}
|
|
18
|
+
return t;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Parser ligero y seguro para yarn.lock (v1).
|
|
22
|
+
* Mapea especificaciones (`foo@^1.0.0`) a la versión resuelta y sus dependencias.
|
|
23
|
+
*/
|
|
24
|
+
export function parseYarnLock(content) {
|
|
25
|
+
const entries = new Map();
|
|
26
|
+
const lines = content.split(/\r?\n/);
|
|
27
|
+
let currentHeaders = [];
|
|
28
|
+
let currentPkg = null;
|
|
29
|
+
let section = 'none';
|
|
30
|
+
const flush = () => {
|
|
31
|
+
if (currentHeaders.length > 0 && currentPkg && currentPkg.name && currentPkg.version) {
|
|
32
|
+
const pkg = {
|
|
33
|
+
name: currentPkg.name,
|
|
34
|
+
version: currentPkg.version,
|
|
35
|
+
resolved: currentPkg.resolved,
|
|
36
|
+
dependencies: currentPkg.dependencies ?? {},
|
|
37
|
+
optionalDependencies: currentPkg.optionalDependencies ?? {},
|
|
38
|
+
};
|
|
39
|
+
for (const h of currentHeaders) {
|
|
40
|
+
entries.set(h, pkg);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
currentHeaders = [];
|
|
44
|
+
currentPkg = null;
|
|
45
|
+
section = 'none';
|
|
46
|
+
};
|
|
47
|
+
for (let i = 0; i < lines.length; i++) {
|
|
48
|
+
const rawLine = lines[i] ?? '';
|
|
49
|
+
const trimmed = rawLine.trim();
|
|
50
|
+
if (!trimmed || trimmed.startsWith('#'))
|
|
51
|
+
continue;
|
|
52
|
+
// Header de nivel superior (ej. "foo@^1.0.0", "foo@^1.2.0":)
|
|
53
|
+
if (!rawLine.startsWith(' ') && trimmed.endsWith(':')) {
|
|
54
|
+
flush();
|
|
55
|
+
const headerStr = trimmed.slice(0, -1);
|
|
56
|
+
const parts = headerStr.split(',').map((p) => unquote(p));
|
|
57
|
+
currentHeaders = parts;
|
|
58
|
+
const first = parts[0] ?? '';
|
|
59
|
+
const at = first.lastIndexOf('@');
|
|
60
|
+
const name = at > 0 ? first.slice(0, at) : first;
|
|
61
|
+
currentPkg = { name, dependencies: {}, optionalDependencies: {} };
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (!currentPkg)
|
|
65
|
+
continue;
|
|
66
|
+
// Propiedades directas (2 espacios de indentación)
|
|
67
|
+
if (rawLine.startsWith(' ') && !rawLine.startsWith(' ')) {
|
|
68
|
+
section = 'none';
|
|
69
|
+
if (trimmed.startsWith('version ')) {
|
|
70
|
+
currentPkg.version = unquote(trimmed.slice(8));
|
|
71
|
+
}
|
|
72
|
+
else if (trimmed.startsWith('resolved ')) {
|
|
73
|
+
currentPkg.resolved = unquote(trimmed.slice(9));
|
|
74
|
+
}
|
|
75
|
+
else if (trimmed === 'dependencies:') {
|
|
76
|
+
section = 'dependencies';
|
|
77
|
+
}
|
|
78
|
+
else if (trimmed === 'optionalDependencies:') {
|
|
79
|
+
section = 'optionalDependencies';
|
|
80
|
+
}
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
// Sub-claves de dependencias (4 espacios de indentación)
|
|
84
|
+
if (rawLine.startsWith(' ') && (section === 'dependencies' || section === 'optionalDependencies')) {
|
|
85
|
+
const parts = trimmed.split(/\s+/);
|
|
86
|
+
if (parts.length >= 2) {
|
|
87
|
+
const depName = unquote(parts[0] ?? '');
|
|
88
|
+
const depSpec = unquote(parts.slice(1).join(' '));
|
|
89
|
+
if (section === 'dependencies') {
|
|
90
|
+
currentPkg.dependencies[depName] = depSpec;
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
currentPkg.optionalDependencies[depName] = depSpec;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
flush();
|
|
99
|
+
return { type: 'yarn', entries };
|
|
100
|
+
}
|
|
101
|
+
export async function readLockfile(dir) {
|
|
102
|
+
for (const name of LOCKFILE_NAMES) {
|
|
103
|
+
const file = path.resolve(dir, name);
|
|
104
|
+
let content;
|
|
105
|
+
try {
|
|
106
|
+
content = await readFile(file, 'utf8');
|
|
107
|
+
}
|
|
108
|
+
catch (err) {
|
|
109
|
+
if (err.code === 'ENOENT')
|
|
110
|
+
continue;
|
|
111
|
+
throw new ManifestError(`No se pudo leer ${file}: ${err.message}`, { cause: err });
|
|
112
|
+
}
|
|
113
|
+
if (name === 'yarn.lock') {
|
|
114
|
+
try {
|
|
115
|
+
const lock = parseYarnLock(content);
|
|
116
|
+
return { file, lock };
|
|
117
|
+
}
|
|
118
|
+
catch (cause) {
|
|
119
|
+
throw new ManifestError(`Error al procesar ${file}: ${cause.message}`, { cause });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
const parsed = JSON.parse(content);
|
|
124
|
+
const lock = {
|
|
125
|
+
type: 'npm',
|
|
126
|
+
lockfileVersion: typeof parsed.lockfileVersion === 'number' ? parsed.lockfileVersion : undefined,
|
|
127
|
+
packages: typeof parsed.packages === 'object' && parsed.packages !== null ? parsed.packages : undefined,
|
|
128
|
+
};
|
|
129
|
+
return { file, lock };
|
|
130
|
+
}
|
|
131
|
+
catch (cause) {
|
|
132
|
+
throw new ManifestError(`${file} no es un JSON válido.`, { cause });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
throw new ManifestError(`--transitive requiere package-lock.json o yarn.lock en ${path.resolve(dir)}. ` +
|
|
136
|
+
'Ejecuta "npm install" o "yarn install".');
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Resolución estilo Node para npm: busca `<from>/node_modules/<name>` y sube por los ancestros.
|
|
140
|
+
*/
|
|
141
|
+
export function resolvePackageKey(packages, name, fromKey) {
|
|
142
|
+
let base = fromKey;
|
|
143
|
+
while (true) {
|
|
144
|
+
const candidate = base ? `${base}/node_modules/${name}` : `node_modules/${name}`;
|
|
145
|
+
if (packages[candidate])
|
|
146
|
+
return candidate;
|
|
147
|
+
if (!base)
|
|
148
|
+
return null;
|
|
149
|
+
const idx = base.lastIndexOf('/node_modules/');
|
|
150
|
+
base = idx >= 0 ? base.slice(0, idx) : '';
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function unsupportedReasonFromUrl(resolved) {
|
|
154
|
+
if (!resolved)
|
|
155
|
+
return undefined;
|
|
156
|
+
if (resolved.startsWith('file:'))
|
|
157
|
+
return 'Dependencia local (file:)';
|
|
158
|
+
if (/^git(\+|:|@)/.test(resolved))
|
|
159
|
+
return 'Dependencia instalada desde git';
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
function resolveNpmTransitive(lock, direct, options) {
|
|
163
|
+
if (!lock.packages) {
|
|
164
|
+
throw new ManifestError(`lockfileVersion ${lock.lockfileVersion ?? '?'} no soportado para --transitive: regenera el lockfile con npm >= 7.`);
|
|
165
|
+
}
|
|
166
|
+
const packages = lock.packages;
|
|
167
|
+
const directNames = new Set(direct.map((d) => d.name));
|
|
168
|
+
const seenNames = new Set(directNames);
|
|
169
|
+
const visitedKeys = new Set();
|
|
170
|
+
const result = [];
|
|
171
|
+
const queue = [];
|
|
172
|
+
for (const d of direct) {
|
|
173
|
+
if (d.unsupportedReason)
|
|
174
|
+
continue;
|
|
175
|
+
const key = resolvePackageKey(packages, d.name, '');
|
|
176
|
+
if (!key || visitedKeys.has(key))
|
|
177
|
+
continue;
|
|
178
|
+
visitedKeys.add(key);
|
|
179
|
+
queue.push({ key, depth: 1, via: [d.name] });
|
|
180
|
+
}
|
|
181
|
+
while (queue.length > 0) {
|
|
182
|
+
const node = queue.shift();
|
|
183
|
+
if (node.depth >= options.maxDepth)
|
|
184
|
+
continue;
|
|
185
|
+
const entry = packages[node.key];
|
|
186
|
+
if (!entry || entry.link)
|
|
187
|
+
continue;
|
|
188
|
+
const children = { ...entry.dependencies, ...entry.optionalDependencies };
|
|
189
|
+
for (const childName of Object.keys(children).sort()) {
|
|
190
|
+
const childKey = resolvePackageKey(packages, childName, node.key);
|
|
191
|
+
if (!childKey || visitedKeys.has(childKey))
|
|
192
|
+
continue;
|
|
193
|
+
visitedKeys.add(childKey);
|
|
194
|
+
const child = packages[childKey];
|
|
195
|
+
const depth = node.depth + 1;
|
|
196
|
+
if (!seenNames.has(childName) && !child.link) {
|
|
197
|
+
seenNames.add(childName);
|
|
198
|
+
const spec = {
|
|
199
|
+
name: childName,
|
|
200
|
+
registryName: child.name ?? childName,
|
|
201
|
+
spec: child.version ?? '?',
|
|
202
|
+
kind: 'transitive',
|
|
203
|
+
depth,
|
|
204
|
+
via: node.via,
|
|
205
|
+
};
|
|
206
|
+
const reason = unsupportedReasonFromUrl(child.resolved);
|
|
207
|
+
if (reason)
|
|
208
|
+
spec.unsupportedReason = reason;
|
|
209
|
+
result.push(spec);
|
|
210
|
+
}
|
|
211
|
+
queue.push({ key: childKey, depth, via: [...node.via, childName] });
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return result;
|
|
215
|
+
}
|
|
216
|
+
function resolveYarnTransitive(lock, direct, options) {
|
|
217
|
+
const entries = lock.entries;
|
|
218
|
+
const directNames = new Set(direct.map((d) => d.name));
|
|
219
|
+
const seenNames = new Set(directNames);
|
|
220
|
+
const visited = new Set();
|
|
221
|
+
const result = [];
|
|
222
|
+
const findEntry = (name, spec) => {
|
|
223
|
+
if (spec) {
|
|
224
|
+
const directKey = `${name}@${spec}`;
|
|
225
|
+
if (entries.has(directKey))
|
|
226
|
+
return entries.get(directKey);
|
|
227
|
+
}
|
|
228
|
+
const prefix = `${name}@`;
|
|
229
|
+
for (const [k, v] of entries) {
|
|
230
|
+
if (k.startsWith(prefix))
|
|
231
|
+
return v;
|
|
232
|
+
}
|
|
233
|
+
return undefined;
|
|
234
|
+
};
|
|
235
|
+
const queue = [];
|
|
236
|
+
for (const d of direct) {
|
|
237
|
+
if (d.unsupportedReason)
|
|
238
|
+
continue;
|
|
239
|
+
const pkg = findEntry(d.name, d.spec);
|
|
240
|
+
if (!pkg)
|
|
241
|
+
continue;
|
|
242
|
+
const visitKey = `${d.name}@${pkg.version}`;
|
|
243
|
+
if (visited.has(visitKey))
|
|
244
|
+
continue;
|
|
245
|
+
visited.add(visitKey);
|
|
246
|
+
queue.push({ name: d.name, pkg, depth: 1, via: [d.name] });
|
|
247
|
+
}
|
|
248
|
+
while (queue.length > 0) {
|
|
249
|
+
const node = queue.shift();
|
|
250
|
+
if (node.depth >= options.maxDepth)
|
|
251
|
+
continue;
|
|
252
|
+
const children = { ...node.pkg.dependencies, ...node.pkg.optionalDependencies };
|
|
253
|
+
for (const [childName, childSpec] of Object.entries(children).sort(([a], [b]) => a.localeCompare(b))) {
|
|
254
|
+
const childPkg = findEntry(childName, childSpec);
|
|
255
|
+
if (!childPkg)
|
|
256
|
+
continue;
|
|
257
|
+
const visitKey = `${childName}@${childPkg.version}`;
|
|
258
|
+
if (visited.has(visitKey))
|
|
259
|
+
continue;
|
|
260
|
+
visited.add(visitKey);
|
|
261
|
+
const depth = node.depth + 1;
|
|
262
|
+
if (!seenNames.has(childName)) {
|
|
263
|
+
seenNames.add(childName);
|
|
264
|
+
const spec = {
|
|
265
|
+
name: childName,
|
|
266
|
+
registryName: childPkg.name,
|
|
267
|
+
spec: childPkg.version,
|
|
268
|
+
kind: 'transitive',
|
|
269
|
+
depth,
|
|
270
|
+
via: node.via,
|
|
271
|
+
};
|
|
272
|
+
const reason = unsupportedReasonFromUrl(childPkg.resolved);
|
|
273
|
+
if (reason)
|
|
274
|
+
spec.unsupportedReason = reason;
|
|
275
|
+
result.push(spec);
|
|
276
|
+
}
|
|
277
|
+
queue.push({ name: childName, pkg: childPkg, depth, via: [...node.via, childName] });
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return result;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Devuelve SOLO las dependencias transitivas (profundidad >= 2), deduplicadas por nombre,
|
|
284
|
+
* alcanzables desde las directas indicadas en un lockfile de npm o Yarn.
|
|
285
|
+
*/
|
|
286
|
+
export function resolveTransitive(lock, direct, options) {
|
|
287
|
+
if (lock.type === 'yarn') {
|
|
288
|
+
return resolveYarnTransitive(lock, direct, options);
|
|
289
|
+
}
|
|
290
|
+
return resolveNpmTransitive(lock, direct, options);
|
|
291
|
+
}
|