@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.
@@ -0,0 +1,94 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { ManifestError } from '../errors.js';
4
+ /** Especificadores que no apuntan al registry de npm y por tanto no se evalúan. */
5
+ const NON_REGISTRY_PREFIXES = [
6
+ ['file:', 'Dependencia local (file:)'],
7
+ ['link:', 'Dependencia local (link:)'],
8
+ ['portal:', 'Dependencia local (portal:)'],
9
+ ['workspace:', 'Paquete del workspace (workspace:)'],
10
+ ['git+', 'Dependencia instalada desde git'],
11
+ ['git:', 'Dependencia instalada desde git'],
12
+ ['git@', 'Dependencia instalada desde git'],
13
+ ['http:', 'Dependencia instalada desde una URL (tarball)'],
14
+ ['https:', 'Dependencia instalada desde una URL (tarball)'],
15
+ ['github:', 'Dependencia instalada directamente desde GitHub'],
16
+ ['gitlab:', 'Dependencia instalada directamente desde GitLab'],
17
+ ['bitbucket:', 'Dependencia instalada directamente desde Bitbucket'],
18
+ ];
19
+ export function classifySpec(name, spec, kind) {
20
+ const trimmed = spec.trim();
21
+ const base = { name, registryName: name, spec: trimmed, kind, depth: 1, via: [] };
22
+ // Alias: "foo": "npm:bar@^1.0.0" -> se evalúa "bar".
23
+ if (trimmed.startsWith('npm:')) {
24
+ const rest = trimmed.slice(4);
25
+ const at = rest.lastIndexOf('@');
26
+ return { ...base, registryName: at > 0 ? rest.slice(0, at) : rest };
27
+ }
28
+ for (const [prefix, reason] of NON_REGISTRY_PREFIXES) {
29
+ if (trimmed.startsWith(prefix))
30
+ return { ...base, unsupportedReason: reason };
31
+ }
32
+ // Shorthand de GitHub como especificador: "usuario/repo" o "usuario/repo#rama".
33
+ // Un rango semver o un dist-tag nunca contienen "/".
34
+ if (trimmed.includes('/')) {
35
+ return { ...base, unsupportedReason: 'Dependencia instalada directamente desde GitHub (shorthand)' };
36
+ }
37
+ return base;
38
+ }
39
+ function readDependencyBlock(manifest, kind, manifestPath) {
40
+ const block = manifest[kind];
41
+ if (block === undefined || block === null)
42
+ return [];
43
+ if (typeof block !== 'object' || Array.isArray(block)) {
44
+ throw new ManifestError(`El campo "${kind}" de ${manifestPath} debe ser un objeto.`);
45
+ }
46
+ return Object.entries(block).map(([name, spec]) => {
47
+ if (typeof spec !== 'string') {
48
+ throw new ManifestError(`La versión de "${name}" en "${kind}" debe ser un string.`);
49
+ }
50
+ return classifySpec(name, spec, kind);
51
+ });
52
+ }
53
+ export function parseManifestContent(content, manifestPath, options) {
54
+ let json;
55
+ try {
56
+ json = JSON.parse(content);
57
+ }
58
+ catch (cause) {
59
+ throw new ManifestError(`${manifestPath} no es un JSON válido.`, { cause });
60
+ }
61
+ if (typeof json !== 'object' || json === null || Array.isArray(json)) {
62
+ throw new ManifestError(`${manifestPath} debe contener un objeto JSON.`);
63
+ }
64
+ const manifest = json;
65
+ const deps = readDependencyBlock(manifest, 'dependencies', manifestPath);
66
+ if (options.includeDev) {
67
+ const seen = new Set(deps.map((d) => d.name));
68
+ for (const dev of readDependencyBlock(manifest, 'devDependencies', manifestPath)) {
69
+ // Si está en ambos bloques, prevalece `dependencies`.
70
+ if (!seen.has(dev.name))
71
+ deps.push(dev);
72
+ }
73
+ }
74
+ return {
75
+ manifestPath,
76
+ projectName: typeof manifest.name === 'string' ? manifest.name : null,
77
+ dependencies: deps,
78
+ };
79
+ }
80
+ export async function readManifest(dir, options) {
81
+ const manifestPath = path.resolve(dir, 'package.json');
82
+ let content;
83
+ try {
84
+ content = await readFile(manifestPath, 'utf8');
85
+ }
86
+ catch (cause) {
87
+ const code = cause.code;
88
+ if (code === 'ENOENT') {
89
+ throw new ManifestError(`No se encontró package.json en ${path.resolve(dir)}. Usa --path <dir>.`);
90
+ }
91
+ throw new ManifestError(`No se pudo leer ${manifestPath}: ${cause.message}`, { cause });
92
+ }
93
+ return parseManifestContent(content, manifestPath, options);
94
+ }
@@ -0,0 +1,103 @@
1
+ const SHORTHAND_PROVIDER = /^(github|gitlab|bitbucket):([^/\s]+)\/([^/\s#]+?)(?:\.git)?(?:#.*)?$/i;
2
+ /** "owner/repo" sin protocolo: el registry lo interpreta como GitHub. */
3
+ const BARE_SHORTHAND = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:#.*)?$/;
4
+ /** Sintaxis tipo scp: git@github.com:owner/repo.git */
5
+ const SCP_LIKE = /^(?:[\w.-]+@)?([\w.-]+\.[a-z]{2,}):(?!\/\/)\/?([^/]+)\/(.+)$/i;
6
+ const PROVIDER_HOSTNAMES = {
7
+ github: 'github.com',
8
+ gitlab: 'gitlab.com',
9
+ bitbucket: 'bitbucket.org',
10
+ };
11
+ function hostFromHostname(hostname) {
12
+ if (hostname === 'github.com')
13
+ return 'github';
14
+ if (hostname === 'gitlab.com')
15
+ return 'gitlab';
16
+ if (hostname === 'bitbucket.org')
17
+ return 'bitbucket';
18
+ return 'other';
19
+ }
20
+ function cleanDirectory(dir) {
21
+ if (!dir)
22
+ return undefined;
23
+ const cleaned = dir.trim().replace(/^\.?\/+/, '').replace(/\/+$/, '');
24
+ return cleaned.length > 0 ? cleaned : undefined;
25
+ }
26
+ function cleanRepoName(repo) {
27
+ return repo.replace(/\.git$/i, '').replace(/#.*$/, '');
28
+ }
29
+ function build(hostname, owner, repo, directory) {
30
+ const name = cleanRepoName(repo);
31
+ if (!owner || !name)
32
+ return null;
33
+ const host = hostFromHostname(hostname);
34
+ const ref = { host, hostname, owner, repo: name, url: `https://${hostname}/${owner}/${name}` };
35
+ const dir = cleanDirectory(directory);
36
+ if (dir)
37
+ ref.directory = dir;
38
+ return ref;
39
+ }
40
+ /**
41
+ * Normaliza el campo `repository` de npm (string u objeto {type,url,directory}) a un RepoRef.
42
+ * Soporta: git+https, git://, git+ssh://, ssh scp-like (git@host:o/r), https con /tree/<rama>/<dir>,
43
+ * shorthand `github:o/r`, `gitlab:o/r`, `bitbucket:o/r` y `o/r`.
44
+ */
45
+ export function normalizeRepository(input) {
46
+ let raw;
47
+ let directory;
48
+ if (typeof input === 'string') {
49
+ raw = input;
50
+ }
51
+ else if (input && typeof input === 'object') {
52
+ const obj = input;
53
+ if (typeof obj.url === 'string')
54
+ raw = obj.url;
55
+ if (typeof obj.directory === 'string')
56
+ directory = obj.directory;
57
+ }
58
+ if (!raw)
59
+ return null;
60
+ raw = raw.trim();
61
+ if (!raw)
62
+ return null;
63
+ const provider = SHORTHAND_PROVIDER.exec(raw);
64
+ if (provider) {
65
+ const [, kind, owner, repo] = provider;
66
+ const hostname = PROVIDER_HOSTNAMES[(kind ?? '').toLowerCase()];
67
+ return hostname && owner && repo ? build(hostname, owner, repo, directory) : null;
68
+ }
69
+ const bare = BARE_SHORTHAND.exec(raw);
70
+ if (bare && !raw.includes(':')) {
71
+ const [, owner, repo] = bare;
72
+ return owner && repo ? build('github.com', owner, repo, directory) : null;
73
+ }
74
+ const scp = SCP_LIKE.exec(raw);
75
+ if (scp) {
76
+ const [, hostname, owner, rest] = scp;
77
+ if (!hostname || !owner || !rest)
78
+ return null;
79
+ const repo = rest.split('/')[0] ?? '';
80
+ return build(hostname.toLowerCase().replace(/^www\./, ''), owner, repo, directory);
81
+ }
82
+ let urlString = raw.replace(/^git\+/, '');
83
+ urlString = urlString.replace(/^git:\/\//, 'https://').replace(/^ssh:\/\//, 'https://');
84
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(urlString))
85
+ urlString = `https://${urlString}`;
86
+ let url;
87
+ try {
88
+ url = new URL(urlString);
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ const hostname = url.hostname.toLowerCase().replace(/^www\./, '');
94
+ const segments = url.pathname.split('/').filter(Boolean);
95
+ const [owner, repo, kind, , ...dirParts] = segments;
96
+ if (!owner || !repo)
97
+ return null;
98
+ // https://github.com/o/r/tree/main/packages/x -> directory = packages/x
99
+ if (!directory && (kind === 'tree' || kind === 'blob') && dirParts.length > 0) {
100
+ directory = dirParts.join('/');
101
+ }
102
+ return build(hostname, owner, repo, directory);
103
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Salida Markdown (GitHub Flavored), pensada para comentarios de PR y para
3
+ * `$GITHUB_STEP_SUMMARY` en GitHub Actions. Sin colores ANSI.
4
+ */
5
+ import { CATEGORY_LABELS, THRESHOLDS } from '../scoring/scoring.js';
6
+ import { daysSince } from '../utils.js';
7
+ const ICON = { healthy: '🟢', caution: '🟡', critical: '🔴' };
8
+ /** Escapa caracteres que romperían una celda de tabla Markdown. */
9
+ export function escapeCell(text) {
10
+ return text.replace(/\\/g, '\\\\').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
11
+ }
12
+ function icon(r) {
13
+ if (r.status === 'error')
14
+ return '❌';
15
+ if (r.status === 'not-evaluable' || !r.result)
16
+ return '⚪';
17
+ return ICON[r.result.category];
18
+ }
19
+ function nameMd(r) {
20
+ const base = `\`${escapeCell(r.name)}\``;
21
+ if (r.kind === 'devDependencies')
22
+ return `${base} <sub>dev</sub>`;
23
+ if (r.kind === 'transitive')
24
+ return `${base}<br><sub>↳ ${escapeCell(r.via.join(' › '))}</sub>`;
25
+ return base;
26
+ }
27
+ function alertMd(r) {
28
+ if (r.status === 'error')
29
+ return `Error: ${escapeCell(r.reason ?? 'desconocido')}`;
30
+ if (r.status === 'not-evaluable')
31
+ return `_No evaluable: ${escapeCell(r.reason ?? '')}_`;
32
+ return r.result?.mainAlert ? escapeCell(r.result.mainAlert.message) : 'Sin alertas';
33
+ }
34
+ export function renderMarkdown(reports, summary, now, meta) {
35
+ const t = meta.thresholds ?? THRESHOLDS;
36
+ const lines = [];
37
+ const title = meta.projectName ? ` — \`${escapeCell(meta.projectName)}\`` : '';
38
+ lines.push(`## 👻 GhostDeps${title}`, '');
39
+ lines.push(`**${summary.total} dependencias:** 🔴 ${summary.critical} crítico/fantasma · 🟡 ${summary.caution} precaución · ` +
40
+ `🟢 ${summary.healthy} saludable · ⚪ ${summary.notEvaluable} no evaluable` +
41
+ (summary.errors > 0 ? ` · ❌ ${summary.errors} error(es)` : ''), '');
42
+ if (meta.failUnder !== undefined) {
43
+ const failing = meta.failing ?? [];
44
+ lines.push(failing.length > 0
45
+ ? `> [!CAUTION]\n> ${failing.length} paquete(s) por debajo de \`--fail-under ${meta.failUnder}\`: ${failing.map((n) => `\`${escapeCell(n)}\``).join(', ')}`
46
+ : `> [!TIP]\n> Ningún paquete evaluado por debajo de \`--fail-under ${meta.failUnder}\`.`, '');
47
+ }
48
+ lines.push('| | Paquete | Score | Días últ. commit | Mant. activos | Alerta principal |');
49
+ lines.push('|:-:|---|--:|--:|--:|---|');
50
+ for (const r of reports) {
51
+ const days = r.github ? daysSince(r.github.lastCommitAt, now) : null;
52
+ const score = r.result ? `**${r.result.score}**` : r.status === 'error' ? 'ERROR' : 'N/E';
53
+ const maint = r.github ? `${r.github.activeMaintainers}${r.github.activeMaintainersCapped ? '+' : ''}` : '—';
54
+ lines.push(`| ${icon(r)} | ${nameMd(r)} | ${score} | ${days ?? '—'} | ${maint} | ${alertMd(r)} |`);
55
+ }
56
+ const detailed = reports.filter((r) => r.result && r.result.penalties.length > 0);
57
+ if (detailed.length > 0) {
58
+ lines.push('', '<details>', '<summary>Desglose de penalizaciones</summary>', '');
59
+ for (const r of detailed) {
60
+ const res = r.result;
61
+ lines.push(`**\`${escapeCell(r.name)}\` → ${res.score}/100 (${CATEGORY_LABELS[res.category]})**`, '');
62
+ for (const p of res.penalties)
63
+ lines.push(`- \`-${p.points}\` ${escapeCell(p.message)}`);
64
+ lines.push('');
65
+ }
66
+ lines.push('</details>');
67
+ }
68
+ lines.push('');
69
+ if (meta.ignored && meta.ignored.length > 0) {
70
+ lines.push(`<sub>Ignorados: ${meta.ignored.map((n) => `\`${escapeCell(n)}\``).join(', ')}</sub><br>`);
71
+ }
72
+ lines.push(`<sub>Umbrales: 🟢 ≥ ${t.healthy} · 🟡 ${t.caution}–${t.healthy - 1} · 🔴 < ${t.caution} · ` +
73
+ `Generado por GhostDeps v${meta.version} el ${now.toISOString().slice(0, 10)}</sub>`);
74
+ return lines.join('\n');
75
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Generador de reportes en formato SARIF 2.1.0 (Static Analysis Results Interchange Format)
3
+ * Estándar de la industria para integración directa con GitHub Code Scanning,
4
+ * GitLab Security y visores SARIF en CI/CD y editores.
5
+ */
6
+ import path from 'node:path';
7
+ import { THRESHOLDS } from '../scoring/scoring.js';
8
+ export const SARIF_RULES = {
9
+ 'archived': {
10
+ id: 'GD001',
11
+ name: 'ArchivedRepository',
12
+ shortDescription: { text: 'Repositorio archivado en la forja de código' },
13
+ defaultConfiguration: { level: 'error' },
14
+ },
15
+ 'deprecated': {
16
+ id: 'GD002',
17
+ name: 'DeprecatedPackage',
18
+ shortDescription: { text: 'Paquete marcado como deprecated en el registry npm' },
19
+ defaultConfiguration: { level: 'error' },
20
+ },
21
+ 'abandoned': {
22
+ id: 'GD003',
23
+ name: 'AbandonedRepository',
24
+ shortDescription: { text: 'Repositorio sin actividad de commits durante periodos prolongados' },
25
+ defaultConfiguration: { level: 'error' },
26
+ },
27
+ 'bus-factor': {
28
+ id: 'GD004',
29
+ name: 'LowBusFactor',
30
+ shortDescription: { text: 'Riesgo de bus factor crítico (0 o 1 mantenedor activo en 12 meses)' },
31
+ defaultConfiguration: { level: 'warning' },
32
+ },
33
+ 'unanswered-issues': {
34
+ id: 'GD005',
35
+ name: 'UnansweredIssues',
36
+ shortDescription: { text: 'Gran cantidad de issues abiertos antiguos sin respuesta' },
37
+ defaultConfiguration: { level: 'note' },
38
+ },
39
+ 'repo-redirect': {
40
+ id: 'GD006',
41
+ name: 'RepoRedirectTransfer',
42
+ shortDescription: { text: 'El repositorio redirige a otro propietario (posible transferencia)' },
43
+ defaultConfiguration: { level: 'warning' },
44
+ },
45
+ 'maintainers-changed': {
46
+ id: 'GD007',
47
+ name: 'MaintainersSetChanged',
48
+ shortDescription: { text: 'Cambios no habituales en la lista de maintainers de npm' },
49
+ defaultConfiguration: { level: 'warning' },
50
+ },
51
+ 'new-publisher': {
52
+ id: 'GD008',
53
+ name: 'NewReleasePublisher',
54
+ shortDescription: { text: 'La última versión fue publicada por una cuenta nueva sin historial reciente' },
55
+ defaultConfiguration: { level: 'warning' },
56
+ },
57
+ 'hijack-pattern': {
58
+ id: 'GD009',
59
+ name: 'PotentialHijackingPattern',
60
+ shortDescription: { text: 'Patrón combinado de posible secuestro de paquete o compromiso de cuenta' },
61
+ defaultConfiguration: { level: 'error' },
62
+ },
63
+ 'stale-publish': {
64
+ id: 'GD010',
65
+ name: 'StaleNpmPublish',
66
+ shortDescription: { text: 'Tiempo excesivo transcurrido desde la última publicación en npm' },
67
+ defaultConfiguration: { level: 'note' },
68
+ },
69
+ };
70
+ export function renderSarif(reports, options) {
71
+ const t = options.thresholds ?? THRESHOLDS;
72
+ const manifestRel = path.basename(options.manifestPath) || 'package.json';
73
+ const rulesList = Object.values(SARIF_RULES);
74
+ const results = [];
75
+ for (const r of reports) {
76
+ if (r.status !== 'evaluated' || !r.result)
77
+ continue;
78
+ const res = r.result;
79
+ // Solo generar resultados si hay penalizaciones o score sub-óptimo
80
+ if (res.penalties.length === 0)
81
+ continue;
82
+ const level = res.score < t.caution ? 'error' : res.score < t.healthy ? 'warning' : 'note';
83
+ // Generar un resultado para la alerta principal
84
+ const mainPenalty = res.mainAlert ?? res.penalties[0];
85
+ const rule = mainPenalty ? SARIF_RULES[mainPenalty.id] : undefined;
86
+ const ruleId = rule?.id ?? 'GD000';
87
+ const viaText = r.via && r.via.length > 0 ? ` (via ${r.via.join(' › ')})` : '';
88
+ const details = res.penalties.map((p) => `- [${p.id}] ${p.message} (-${p.points} pts)`).join('\n');
89
+ results.push({
90
+ ruleId,
91
+ level,
92
+ message: {
93
+ text: `[Health Score ${res.score}/100] ${r.name}@${r.spec}${viaText}: ${mainPenalty?.message ?? 'Riesgo detectado'}`,
94
+ },
95
+ locations: [
96
+ {
97
+ physicalLocation: {
98
+ artifactLocation: {
99
+ uri: manifestRel,
100
+ uriBaseId: '%SRCROOT%',
101
+ },
102
+ region: {
103
+ startLine: 1,
104
+ },
105
+ },
106
+ },
107
+ ],
108
+ properties: {
109
+ packageName: r.name,
110
+ spec: r.spec,
111
+ kind: r.kind,
112
+ depth: r.depth,
113
+ via: r.via,
114
+ score: res.score,
115
+ category: res.category,
116
+ penalties: res.penalties,
117
+ details,
118
+ },
119
+ });
120
+ }
121
+ const sarifLog = {
122
+ $schema: 'https://json.schemastore.org/sarif-2.1.0.json',
123
+ version: '2.1.0',
124
+ runs: [
125
+ {
126
+ tool: {
127
+ driver: {
128
+ name: 'ghostdeps',
129
+ version: options.version,
130
+ informationUri: 'https://github.com/ghostdeps/ghostdeps',
131
+ rules: rulesList,
132
+ },
133
+ },
134
+ results,
135
+ },
136
+ ],
137
+ };
138
+ return JSON.stringify(sarifLog, null, 2);
139
+ }
@@ -0,0 +1,95 @@
1
+ import chalk from 'chalk';
2
+ import Table from 'cli-table3';
3
+ import { CATEGORY_LABELS, THRESHOLDS } from '../scoring/scoring.js';
4
+ import { daysSince } from '../utils.js';
5
+ const COLOR = {
6
+ healthy: chalk.green,
7
+ caution: chalk.yellow,
8
+ critical: chalk.red,
9
+ };
10
+ function truncate(text, max) {
11
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
12
+ }
13
+ function scoreCell(r) {
14
+ if (r.status === 'error')
15
+ return chalk.red.bold('ERROR');
16
+ if (r.status === 'not-evaluable' || !r.result)
17
+ return chalk.gray('N/E');
18
+ return COLOR[r.result.category].bold(String(r.result.score));
19
+ }
20
+ function maintainersCell(r) {
21
+ if (!r.github)
22
+ return chalk.gray('—');
23
+ const n = r.github.activeMaintainers;
24
+ const text = `${n}${r.github.activeMaintainersCapped ? '+' : ''}`;
25
+ return n <= 1 ? chalk.red(text) : n === 2 ? chalk.yellow(text) : text;
26
+ }
27
+ function alertCell(r, width) {
28
+ if (r.status === 'error')
29
+ return chalk.red(truncate(r.reason ?? 'Error desconocido', width));
30
+ if (r.status === 'not-evaluable') {
31
+ const extra = r.npm?.deprecated ? ' · deprecated' : '';
32
+ return chalk.gray(truncate(`No evaluable: ${r.reason ?? ''}${extra}`, width));
33
+ }
34
+ const alert = r.result?.mainAlert;
35
+ if (!alert)
36
+ return chalk.green('Sin alertas');
37
+ const color = r.result ? COLOR[r.result.category] : (s) => s;
38
+ return color(truncate(alert.message, width));
39
+ }
40
+ export function renderTable(reports, now) {
41
+ const alertWidth = Math.max(30, Math.min(70, (process.stdout.columns ?? 120) - 60));
42
+ const table = new Table({
43
+ head: ['Paquete', 'Score', 'Días últ. commit', 'Mant. activos', 'Alerta principal'].map((h) => chalk.bold(h)),
44
+ style: { head: [], border: ['gray'] },
45
+ wordWrap: false,
46
+ });
47
+ for (const r of reports) {
48
+ const days = r.github ? daysSince(r.github.lastCommitAt, now) : null;
49
+ table.push([
50
+ nameCell(r),
51
+ scoreCell(r),
52
+ days === null ? chalk.gray('—') : String(days),
53
+ maintainersCell(r),
54
+ alertCell(r, alertWidth),
55
+ ]);
56
+ }
57
+ return table.toString();
58
+ }
59
+ /** Nombre del paquete con marca de dev o la ruta por la que llega si es transitiva. */
60
+ export function nameCell(r) {
61
+ if (r.kind === 'devDependencies')
62
+ return `${r.name} ${chalk.gray('(dev)')}`;
63
+ if (r.kind === 'transitive') {
64
+ return `${r.name}\n${chalk.gray(truncate(`↳ ${r.via.join(' › ')}`, 40))}`;
65
+ }
66
+ return r.name;
67
+ }
68
+ /** Desglose explicable de penalizaciones (flag --explain). */
69
+ export function renderExplain(reports) {
70
+ const lines = [chalk.bold('\nDesglose de penalizaciones:')];
71
+ for (const r of reports) {
72
+ if (r.status !== 'evaluated' || !r.result)
73
+ continue;
74
+ const color = COLOR[r.result.category];
75
+ lines.push(`\n${color.bold(`${r.name} → ${r.result.score}/100 (${CATEGORY_LABELS[r.result.category]})`)}`);
76
+ if (r.github?.redirected)
77
+ lines.push(chalk.gray(` repo: ${r.github.requestedFullName} → ${r.github.fullName}`));
78
+ if (r.result.penalties.length === 0)
79
+ lines.push(chalk.green(' Sin penalizaciones'));
80
+ for (const p of r.result.penalties)
81
+ lines.push(` ${chalk.red(`-${p.points}`.padStart(4))} ${p.message}`);
82
+ }
83
+ return lines.join('\n');
84
+ }
85
+ export function renderSummary(s, t = THRESHOLDS) {
86
+ const parts = [
87
+ chalk.red(`● Crítico/Fantasma (<${t.caution}): ${s.critical}`),
88
+ chalk.yellow(`● Precaución (${t.caution}-${t.healthy - 1}): ${s.caution}`),
89
+ chalk.green(`● Saludable (≥${t.healthy}): ${s.healthy}`),
90
+ chalk.gray(`○ No evaluable: ${s.notEvaluable}`),
91
+ ];
92
+ if (s.errors > 0)
93
+ parts.push(chalk.red.bold(`✖ Errores: ${s.errors}`));
94
+ return `\n${chalk.bold(`Resumen (${s.total} dependencias):`)} ${parts.join(' ')}`;
95
+ }
@@ -0,0 +1,113 @@
1
+ export const DEFAULT_WEIGHTS = Object.freeze({
2
+ archived: 40,
3
+ deprecated: 40,
4
+ abandonment: [
5
+ { threshold: 730, points: 45 }, // > 24 meses
6
+ { threshold: 365, points: 25 }, // > 12 meses
7
+ { threshold: 180, points: 10 }, // > 6 meses
8
+ ],
9
+ stalePublish: { threshold: 730, points: 5 },
10
+ busFactor: { zero: 20, one: 15, two: 5 },
11
+ unansweredIssues: [
12
+ { threshold: 25, points: 15 },
13
+ { threshold: 10, points: 10 },
14
+ { threshold: 3, points: 5 },
15
+ ],
16
+ repoRedirect: 10,
17
+ maintainersChanged: 15,
18
+ newPublisher: 15,
19
+ hijackPattern: 15,
20
+ dormantRevivalDays: 365,
21
+ });
22
+ export const THRESHOLDS = Object.freeze({
23
+ healthy: 70,
24
+ caution: 40,
25
+ });
26
+ export const CATEGORY_LABELS = {
27
+ healthy: 'Saludable',
28
+ caution: 'Precaución',
29
+ critical: 'Crítico/Fantasma',
30
+ };
31
+ /** Prioridad para desempatar la alerta principal cuando dos penalizaciones pesan igual. */
32
+ const PRIORITY = [
33
+ 'hijack-pattern',
34
+ 'archived',
35
+ 'deprecated',
36
+ 'new-publisher',
37
+ 'maintainers-changed',
38
+ 'abandoned',
39
+ 'bus-factor',
40
+ 'repo-redirect',
41
+ 'unanswered-issues',
42
+ 'stale-publish',
43
+ ];
44
+ export function categorize(score, t = THRESHOLDS) {
45
+ if (score >= t.healthy)
46
+ return 'healthy';
47
+ if (score >= t.caution)
48
+ return 'caution';
49
+ return 'critical';
50
+ }
51
+ function months(days) {
52
+ return Math.floor(days / 30);
53
+ }
54
+ export function computeScore(s, w = DEFAULT_WEIGHTS, t = THRESHOLDS) {
55
+ const penalties = [];
56
+ const add = (id, points, message) => {
57
+ if (points > 0)
58
+ penalties.push({ id, points, message });
59
+ };
60
+ if (s.archived)
61
+ add('archived', w.archived, 'Repositorio archivado (solo lectura)');
62
+ if (s.deprecated)
63
+ add('deprecated', w.deprecated, 'Paquete marcado como deprecated en npm');
64
+ if (s.daysSinceLastCommit !== null) {
65
+ const days = s.daysSinceLastCommit;
66
+ const tier = w.abandonment.find((t) => days > t.threshold);
67
+ if (tier)
68
+ add('abandoned', tier.points, `Sin commits desde hace ${days} días (~${months(days)} meses)`);
69
+ }
70
+ if (s.daysSinceLastPublish !== null && s.daysSinceLastPublish > w.stalePublish.threshold) {
71
+ add('stale-publish', w.stalePublish.points, `Sin publicar en npm desde hace ${s.daysSinceLastPublish} días`);
72
+ }
73
+ if (s.activeMaintainers !== null) {
74
+ const n = s.activeMaintainers;
75
+ if (n <= 0)
76
+ add('bus-factor', w.busFactor.zero, 'Ningún mantenedor activo en 12 meses');
77
+ else if (n === 1)
78
+ add('bus-factor', w.busFactor.one, 'Bus factor = 1 (un solo mantenedor activo)');
79
+ else if (n === 2)
80
+ add('bus-factor', w.busFactor.two, 'Bus factor = 2');
81
+ }
82
+ if (s.unansweredIssues !== null) {
83
+ const n = s.unansweredIssues;
84
+ const tier = w.unansweredIssues.find((t) => n >= t.threshold);
85
+ if (tier)
86
+ add('unanswered-issues', tier.points, `${n} issues abiertos >30 días sin respuesta`);
87
+ }
88
+ // --- Señales de transferencia / hijacking (proxies) ---
89
+ if (s.repoRedirected)
90
+ add('repo-redirect', w.repoRedirect, 'El repo redirige a otro owner/nombre (posible transferencia)');
91
+ const maintainersChanged = s.maintainersAdded.length > 0;
92
+ if (maintainersChanged) {
93
+ add('maintainers-changed', w.maintainersChanged, `Nuevos maintainers en la última versión: ${s.maintainersAdded.join(', ')}`);
94
+ }
95
+ if (s.newPublisher)
96
+ add('new-publisher', w.newPublisher, 'La última versión la publicó un usuario nuevo');
97
+ const dormantRevival = s.publishGapDays !== null && s.publishGapDays > w.dormantRevivalDays;
98
+ if (s.newPublisher && (maintainersChanged || s.repoRedirected || dormantRevival)) {
99
+ const why = dormantRevival
100
+ ? `tras ${s.publishGapDays} días sin publicar`
101
+ : 'junto a otra señal de transferencia';
102
+ add('hijack-pattern', w.hijackPattern, `Patrón de posible secuestro: publicador nuevo ${why}`);
103
+ }
104
+ const total = penalties.reduce((acc, p) => acc + p.points, 0);
105
+ const score = Math.max(0, Math.min(100, 100 - total));
106
+ const sorted = [...penalties].sort((a, b) => b.points - a.points || PRIORITY.indexOf(a.id) - PRIORITY.indexOf(b.id));
107
+ return {
108
+ score,
109
+ category: categorize(score, t),
110
+ penalties: sorted,
111
+ mainAlert: sorted[0] ?? null,
112
+ };
113
+ }
@@ -0,0 +1,19 @@
1
+ import { daysBetween, daysSince } from '../utils.js';
2
+ /** Convierte datos crudos de npm + GitHub en señales normalizadas para el scoring. */
3
+ export function buildSignals(npm, gh, now) {
4
+ const newPublisher = npm.latestPublisher !== null &&
5
+ npm.previousPublishers.length > 0 &&
6
+ !npm.previousPublishers.includes(npm.latestPublisher);
7
+ return {
8
+ daysSinceLastCommit: daysSince(gh.lastCommitAt, now),
9
+ daysSinceLastPublish: daysSince(npm.latestPublishedAt, now),
10
+ publishGapDays: daysBetween(npm.previousPublishedAt, npm.latestPublishedAt),
11
+ archived: gh.archived,
12
+ deprecated: npm.deprecated !== null,
13
+ activeMaintainers: gh.activeMaintainers,
14
+ unansweredIssues: gh.unansweredIssues,
15
+ repoRedirected: gh.redirected,
16
+ maintainersAdded: npm.maintainersChange?.added ?? [],
17
+ newPublisher,
18
+ };
19
+ }
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Tipos de dominio compartidos. Todas las fechas se manejan como strings ISO-8601
3
+ * para que los objetos sean serializables tal cual (caché en disco y salida --json).
4
+ */
5
+ export {};