@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,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 {};
package/dist/utils.js ADDED
@@ -0,0 +1,44 @@
1
+ const MS_PER_DAY = 86_400_000;
2
+ export function sleep(ms) {
3
+ return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
4
+ }
5
+ /** Días completos transcurridos entre una fecha ISO y `now`. null si no hay fecha válida. */
6
+ export function daysSince(iso, now) {
7
+ if (!iso)
8
+ return null;
9
+ const t = Date.parse(iso);
10
+ if (Number.isNaN(t))
11
+ return null;
12
+ return Math.max(0, Math.floor((now.getTime() - t) / MS_PER_DAY));
13
+ }
14
+ export function daysBetween(fromIso, toIso) {
15
+ if (!fromIso || !toIso)
16
+ return null;
17
+ const a = Date.parse(fromIso);
18
+ const b = Date.parse(toIso);
19
+ if (Number.isNaN(a) || Number.isNaN(b))
20
+ return null;
21
+ return Math.max(0, Math.floor((b - a) / MS_PER_DAY));
22
+ }
23
+ export function isoDaysAgo(days, now) {
24
+ return new Date(now.getTime() - days * MS_PER_DAY).toISOString();
25
+ }
26
+ /**
27
+ * Ejecuta `fn` sobre `items` con un máximo de `limit` promesas simultáneas,
28
+ * preservando el orden de los resultados. `fn` debería capturar sus propios errores.
29
+ */
30
+ export async function mapWithConcurrency(items, limit, fn) {
31
+ const results = new Array(items.length);
32
+ let next = 0;
33
+ const workerCount = Math.max(1, Math.min(limit, items.length));
34
+ const workers = Array.from({ length: workerCount }, async () => {
35
+ while (true) {
36
+ const index = next++;
37
+ if (index >= items.length)
38
+ return;
39
+ results[index] = await fn(items[index], index);
40
+ }
41
+ });
42
+ await Promise.all(workers);
43
+ return results;
44
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@efraindrummer/ghostdeps",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Detecta dependencias fantasma (abandonadas, bus factor bajo o con señales de secuestro) evaluando la salud social y de mantenimiento del repositorio origen.",
5
+ "keywords": [
6
+ "supply-chain",
7
+ "security",
8
+ "dependencies",
9
+ "npm",
10
+ "bus-factor",
11
+ "abandoned",
12
+ "cli"
13
+ ],
14
+ "license": "MIT",
15
+ "type": "module",
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "bin": {
20
+ "ghostdeps": "dist/cli.js"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "schema",
25
+ "README.md",
26
+ "CHANGELOG.md",
27
+ "LICENSE"
28
+ ],
29
+ "engines": {
30
+ "node": ">=20"
31
+ },
32
+ "scripts": {
33
+ "build": "tsc -p tsconfig.build.json",
34
+ "dev": "tsx src/cli.ts",
35
+ "start": "node dist/cli.js",
36
+ "test": "vitest run",
37
+ "test:watch": "vitest",
38
+ "typecheck": "tsc -p tsconfig.json --noEmit",
39
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
40
+ },
41
+ "dependencies": {
42
+ "chalk": "^5.3.0",
43
+ "cli-table3": "^0.6.5",
44
+ "commander": "^12.1.0"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^20.14.0",
48
+ "tsx": "^4.19.0",
49
+ "typescript": "^5.6.0",
50
+ "vitest": "^2.1.0"
51
+ }
52
+ }
@@ -0,0 +1,67 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$id": "https://unpkg.com/ghostdeps/schema/ghostdepsrc.schema.json",
4
+ "title": "GhostDeps configuration",
5
+ "description": "Configuración de GhostDeps (.ghostdepsrc.json o clave \"ghostdeps\" en package.json).",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "definitions": {
9
+ "points": { "type": "number", "minimum": 0, "maximum": 100 },
10
+ "tier": {
11
+ "type": "object",
12
+ "additionalProperties": false,
13
+ "required": ["threshold", "points"],
14
+ "properties": {
15
+ "threshold": { "type": "number", "minimum": 0, "maximum": 100000 },
16
+ "points": { "$ref": "#/definitions/points" }
17
+ }
18
+ },
19
+ "tiers": { "type": "array", "items": { "$ref": "#/definitions/tier" } }
20
+ },
21
+ "properties": {
22
+ "$schema": { "type": "string" },
23
+ "ignore": {
24
+ "description": "Paquetes a omitir. Admite comodín * (ej. \"@types/*\").",
25
+ "type": "array",
26
+ "items": { "type": "string", "minLength": 1 }
27
+ },
28
+ "failUnder": { "description": "Exit code 1 si algún paquete evaluado queda por debajo.", "type": "number", "minimum": 0, "maximum": 100 },
29
+ "dev": { "description": "Incluir devDependencies.", "type": "boolean" },
30
+ "transitive": { "description": "Incluir dependencias transitivas (package-lock.json).", "type": "boolean" },
31
+ "depth": { "description": "Profundidad máxima con transitive (1 = solo directas).", "type": "integer", "minimum": 1, "maximum": 100 },
32
+ "concurrency": { "description": "Paquetes analizados en paralelo.", "type": "integer", "minimum": 1, "maximum": 32 },
33
+ "thresholds": {
34
+ "type": "object",
35
+ "additionalProperties": false,
36
+ "properties": {
37
+ "healthy": { "description": "Score mínimo para verde (default 70).", "type": "number", "minimum": 0, "maximum": 100 },
38
+ "caution": { "description": "Score mínimo para amarillo (default 40).", "type": "number", "minimum": 0, "maximum": 100 }
39
+ }
40
+ },
41
+ "weights": {
42
+ "type": "object",
43
+ "additionalProperties": false,
44
+ "properties": {
45
+ "archived": { "$ref": "#/definitions/points", "description": "Default 40." },
46
+ "deprecated": { "$ref": "#/definitions/points", "description": "Default 40." },
47
+ "abandonment": { "$ref": "#/definitions/tiers", "description": "Días sin commits (umbral estricto). Default: >730:45, >365:25, >180:10." },
48
+ "stalePublish": { "$ref": "#/definitions/tier", "description": "Días sin publicar en npm. Default: >730:5." },
49
+ "busFactor": {
50
+ "type": "object",
51
+ "additionalProperties": false,
52
+ "properties": {
53
+ "zero": { "$ref": "#/definitions/points", "description": "Default 20." },
54
+ "one": { "$ref": "#/definitions/points", "description": "Default 15." },
55
+ "two": { "$ref": "#/definitions/points", "description": "Default 5." }
56
+ }
57
+ },
58
+ "unansweredIssues": { "$ref": "#/definitions/tiers", "description": "Issues sin respuesta (umbral inclusivo). Default: >=25:15, >=10:10, >=3:5." },
59
+ "repoRedirect": { "$ref": "#/definitions/points", "description": "Default 10." },
60
+ "maintainersChanged": { "$ref": "#/definitions/points", "description": "Default 15." },
61
+ "newPublisher": { "$ref": "#/definitions/points", "description": "Default 15." },
62
+ "hijackPattern": { "$ref": "#/definitions/points", "description": "Default 15." },
63
+ "dormantRevivalDays": { "type": "number", "minimum": 0, "maximum": 100000, "description": "Default 365." }
64
+ }
65
+ }
66
+ }
67
+ }