dependency-detective 0.4.0 → 0.4.1
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/package.json +12 -5
- package/.claude/worktrees/amazing-bartik-b7ca06/.claude/settings.local.json +0 -19
- package/.claude/worktrees/amazing-bartik-b7ca06/LICENSE +0 -21
- package/.claude/worktrees/amazing-bartik-b7ca06/README.md +0 -151
- package/.claude/worktrees/amazing-bartik-b7ca06/docs/superpowers/specs/2026-05-09-correctness-fixes-design.md +0 -118
- package/.claude/worktrees/amazing-bartik-b7ca06/index.js +0 -19
- package/.claude/worktrees/amazing-bartik-b7ca06/package-lock.json +0 -915
- package/.claude/worktrees/amazing-bartik-b7ca06/package.json +0 -36
- package/.claude/worktrees/amazing-bartik-b7ca06/src/alternative-suggester.js +0 -64
- package/.claude/worktrees/amazing-bartik-b7ca06/src/analyzer.js +0 -141
- package/.claude/worktrees/amazing-bartik-b7ca06/src/security-checker.js +0 -62
- package/.claude/worktrees/amazing-bartik-b7ca06/src/unused-detector.js +0 -71
- package/tests/alternative-suggester.test.js +0 -28
- package/tests/analyzer.test.js +0 -97
- package/tests/ast-parser.test.js +0 -32
- package/tests/concurrency.test.js +0 -24
- package/tests/config-scanner.test.js +0 -87
- package/tests/fixtures/sample-imports.js +0 -6
- package/tests/script-scanner.test.js +0 -61
- package/tests/security-checker.test.js +0 -55
- package/tests/unused-detector.test.js +0 -18
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "dependency-detective",
|
|
3
|
-
"version": "0.1.1",
|
|
4
|
-
"description": "Analyzes your project's dependencies, identifies unused ones, forecasts potential security risks, and suggests better alternatives",
|
|
5
|
-
"main": "index.js",
|
|
6
|
-
"type": "module",
|
|
7
|
-
"bin": {
|
|
8
|
-
"dependency-detective": "./index.js"
|
|
9
|
-
},
|
|
10
|
-
"scripts": {
|
|
11
|
-
"start": "node index.js",
|
|
12
|
-
"test": "echo \"Error: no test specified\" && exit 1"
|
|
13
|
-
},
|
|
14
|
-
"keywords": [
|
|
15
|
-
"dependencies",
|
|
16
|
-
"npm",
|
|
17
|
-
"node",
|
|
18
|
-
"security",
|
|
19
|
-
"optimization"
|
|
20
|
-
],
|
|
21
|
-
"author": "Marvin Ackerman",
|
|
22
|
-
"license": "MIT",
|
|
23
|
-
"dependencies": {
|
|
24
|
-
"axios": "^1.8.1",
|
|
25
|
-
"chalk": "^5.4.1",
|
|
26
|
-
"commander": "^13.1.0",
|
|
27
|
-
"dotenv": "^16.4.7",
|
|
28
|
-
"glob": "^11.0.1",
|
|
29
|
-
"ora": "^8.2.0"
|
|
30
|
-
},
|
|
31
|
-
"repository": {
|
|
32
|
-
"type": "git",
|
|
33
|
-
"url": "https://github.com/Marvinkwame/dependency-detective"
|
|
34
|
-
},
|
|
35
|
-
"homepage": "https://github.com/Marvinkwame/dependency-detective#"
|
|
36
|
-
}
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import axios from "axios";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
export async function suggestAlternatives(dependencies) {
|
|
5
|
-
const alternatives = {};
|
|
6
|
-
|
|
7
|
-
for (const [depName, version] of Object.entries(dependencies)) {
|
|
8
|
-
try {
|
|
9
|
-
const suggestion = await findBetterAlternative(depName, version);
|
|
10
|
-
if (suggestion) {
|
|
11
|
-
alternatives[depName] = suggestion;
|
|
12
|
-
}
|
|
13
|
-
} catch (error) {
|
|
14
|
-
console.error(`Failed to find alternatives for ${depName}: ${error.message}`);
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
return alternatives;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export async function findBetterAlternative(packageName, version) {
|
|
22
|
-
try {
|
|
23
|
-
// Fetch package data from npm registry
|
|
24
|
-
const npmResponse = await axios.get(`https://registry.npmjs.org/${packageName}`);
|
|
25
|
-
const packageData = npmResponse.data;
|
|
26
|
-
|
|
27
|
-
// Check if the package is deprecated
|
|
28
|
-
if (packageData.deprecated) {
|
|
29
|
-
return {
|
|
30
|
-
name: packageName,
|
|
31
|
-
reason: `This package is deprecated: ${packageData.deprecated}`,
|
|
32
|
-
downloads: packageData.downloads || 0,
|
|
33
|
-
lastUpdated: packageData.time.modified,
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
// Fetch alternatives from npms.io
|
|
38
|
-
try {
|
|
39
|
-
const alternativesResponse = await axios.get(`https://api.npms.io/v2/package/${packageName}`);
|
|
40
|
-
const alternativesData = alternativesResponse.data;
|
|
41
|
-
|
|
42
|
-
if (alternativesData.alternatives && alternativesData.alternatives.length > 0) {
|
|
43
|
-
const bestAlternative = alternativesData.alternatives[0];
|
|
44
|
-
return {
|
|
45
|
-
name: bestAlternative.package.name,
|
|
46
|
-
reason: `Recommended alternative: ${bestAlternative.package.description}`,
|
|
47
|
-
downloads: bestAlternative.package.downloads,
|
|
48
|
-
lastUpdated: bestAlternative.package.date,
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
} catch (error) {
|
|
52
|
-
console.error(`No alternatives found for ${packageName} in npms.io: ${error.message}`);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
return null;
|
|
56
|
-
} catch (error) {
|
|
57
|
-
if (error.response && error.response.status === 404) {
|
|
58
|
-
console.error(`Package ${packageName} not found in npm registry.`);
|
|
59
|
-
} else {
|
|
60
|
-
console.error(`Failed to fetch alternatives for ${packageName}: ${error.message}`);
|
|
61
|
-
}
|
|
62
|
-
return null;
|
|
63
|
-
}
|
|
64
|
-
}
|
|
@@ -1,141 +0,0 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import chalk from 'chalk';
|
|
4
|
-
import ora from 'ora';
|
|
5
|
-
import { findUnusedDependencies } from './unused-detector.js';
|
|
6
|
-
import { checkVulnerabilities } from './security-checker.js';
|
|
7
|
-
import { suggestAlternatives } from './alternative-suggester.js';
|
|
8
|
-
|
|
9
|
-
export async function analyzeProject(options) {
|
|
10
|
-
//default dependencies for react/nextjs project
|
|
11
|
-
const REQUIRED_DEPENDENCIES = new Set([
|
|
12
|
-
'react',
|
|
13
|
-
'react-dom',
|
|
14
|
-
'next',
|
|
15
|
-
'@types/node',
|
|
16
|
-
'@types/react',
|
|
17
|
-
'@types/react-dom',
|
|
18
|
-
'eslint',
|
|
19
|
-
'eslint-config-next',
|
|
20
|
-
'postcss',
|
|
21
|
-
'typescript',
|
|
22
|
-
]);
|
|
23
|
-
|
|
24
|
-
const spinner = ora('Analyzing your project dependencies...').start();
|
|
25
|
-
|
|
26
|
-
try {
|
|
27
|
-
// Get package.json from the target directory
|
|
28
|
-
const packageJsonPath = path.join(options.directory, 'package.json');
|
|
29
|
-
|
|
30
|
-
if (!fs.existsSync(packageJsonPath)) {
|
|
31
|
-
spinner.fail('No package.json found in the specified directory');
|
|
32
|
-
return;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
|
|
36
|
-
const dependencies = {
|
|
37
|
-
...(packageJson.dependencies || {}),
|
|
38
|
-
...(packageJson.devDependencies || {}),
|
|
39
|
-
};
|
|
40
|
-
|
|
41
|
-
// Filter out required dependencies
|
|
42
|
-
const filteredDependencies = Object.fromEntries(
|
|
43
|
-
Object.entries(dependencies).filter(
|
|
44
|
-
([depName]) => !REQUIRED_DEPENDENCIES.has(depName)
|
|
45
|
-
)
|
|
46
|
-
);
|
|
47
|
-
|
|
48
|
-
// Identifing unused dependencies
|
|
49
|
-
spinner.text = 'Scanning for unused dependencies...';
|
|
50
|
-
const unusedDeps = await findUnusedDependencies(options.directory, filteredDependencies);
|
|
51
|
-
|
|
52
|
-
// Checking for security vulnerabilities
|
|
53
|
-
spinner.text = 'Checking for security vulnerabilities...';
|
|
54
|
-
const vulnerabilities = await checkVulnerabilities(filteredDependencies);
|
|
55
|
-
|
|
56
|
-
// Suggesting alternatives (if enabled)
|
|
57
|
-
let alternatives = {};
|
|
58
|
-
if (options.suggestions !== false) {
|
|
59
|
-
spinner.text = 'Finding better alternatives...';
|
|
60
|
-
alternatives = await suggestAlternatives(filteredDependencies);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
spinner.succeed('Analysis complete!');
|
|
65
|
-
|
|
66
|
-
// Display results
|
|
67
|
-
displayResults(unusedDeps, vulnerabilities, alternatives, options.verbose);
|
|
68
|
-
} catch (error) {
|
|
69
|
-
spinner.fail('Analysis failed');
|
|
70
|
-
console.error(chalk.red('Error:'), error.message);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
function getSavingsEstimate(unusedDeps) {
|
|
78
|
-
|
|
79
|
-
// Average size of an npm package in MB
|
|
80
|
-
const AVERAGE_PACKAGE_SIZE_MB = 5;
|
|
81
|
-
|
|
82
|
-
// Calculate the total estimated savings
|
|
83
|
-
const totalSavingsMB = unusedDeps.length * AVERAGE_PACKAGE_SIZE_MB;
|
|
84
|
-
|
|
85
|
-
// Return the formatted estimate
|
|
86
|
-
return `~${totalSavingsMB}MB`;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// Define displayResults function
|
|
90
|
-
function displayResults(unusedDeps, vulnerabilities, alternatives, verbose) {
|
|
91
|
-
console.log('\n' + chalk.bold('📦 DEPENDENCY DETECTIVE REPORT') + '\n');
|
|
92
|
-
|
|
93
|
-
// Display unused dependencies
|
|
94
|
-
console.log(chalk.bold('🗑️ Unused Dependencies:'));
|
|
95
|
-
if (unusedDeps.length === 0) {
|
|
96
|
-
console.log(chalk.green(' No unused dependencies found. Great job!'));
|
|
97
|
-
} else {
|
|
98
|
-
unusedDeps.forEach(dep => {
|
|
99
|
-
console.log(` ${chalk.yellow(dep.name)} ${chalk.dim(`v${dep.version}`)}`);
|
|
100
|
-
if (verbose && dep.reason) {
|
|
101
|
-
console.log(` ${chalk.dim(dep.reason)}`);
|
|
102
|
-
}
|
|
103
|
-
});
|
|
104
|
-
console.log(chalk.dim(`\n Removing these could save approximately ${getSavingsEstimate(unusedDeps)} of disk space`));
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
// Display vulnerabilities
|
|
108
|
-
console.log('\n' + chalk.bold('🔒 Security Vulnerabilities:'));
|
|
109
|
-
if (Object.keys(vulnerabilities).length === 0) {
|
|
110
|
-
console.log(chalk.green(' No security vulnerabilities detected. You\'re secure!'));
|
|
111
|
-
} else {
|
|
112
|
-
Object.entries(vulnerabilities).forEach(([depName, issues]) => {
|
|
113
|
-
console.log(` ${chalk.red(depName)} ${chalk.dim(`(${issues.length} issues)`)}`);
|
|
114
|
-
if (verbose) {
|
|
115
|
-
issues.forEach(issue => {
|
|
116
|
-
console.log(` - ${issue.severity.toUpperCase()}: ${issue.title}`);
|
|
117
|
-
console.log(` ${chalk.dim(issue.description)}`);
|
|
118
|
-
});
|
|
119
|
-
}
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
// Display alternative suggestions
|
|
124
|
-
if (Object.keys(alternatives).length > 0) {
|
|
125
|
-
console.log('\n' + chalk.bold('💡 Recommended Alternatives:'));
|
|
126
|
-
Object.entries(alternatives).forEach(([depName, suggestion]) => {
|
|
127
|
-
console.log(` ${chalk.blue(depName)} → ${chalk.green(suggestion.name)}`);
|
|
128
|
-
if (verbose) {
|
|
129
|
-
console.log(` ${chalk.dim(suggestion.reason)}`);
|
|
130
|
-
console.log(` ${chalk.dim(`Weekly downloads: ${suggestion.downloads.toLocaleString()}`)}`);
|
|
131
|
-
console.log(` ${chalk.dim(`Last updated: ${suggestion.lastUpdated}`)}`);
|
|
132
|
-
}
|
|
133
|
-
});
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
console.log('\n' + chalk.bold('📋 Next Steps:'));
|
|
137
|
-
console.log(' 1. Run with --verbose flag for more detailed information');
|
|
138
|
-
console.log(' 2. Consider removing unused dependencies with: npm uninstall [package-names]');
|
|
139
|
-
console.log(' 3. Address security vulnerabilities by updating affected packages');
|
|
140
|
-
console.log(' 4. Evaluate suggested alternatives for potential improvements\n');
|
|
141
|
-
}
|
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
import https from "https";
|
|
2
|
-
import axios from "axios";
|
|
3
|
-
|
|
4
|
-
export async function checkVulnerabilities(dependencies) {
|
|
5
|
-
const vulnerabilities = {};
|
|
6
|
-
|
|
7
|
-
for (const [depName, version] of Object.entries(dependencies)) {
|
|
8
|
-
try {
|
|
9
|
-
const issues = await checkPackageVulnerabilities(depName, version);
|
|
10
|
-
if (issues.length > 0) {
|
|
11
|
-
vulnerabilities[depName] = issues;
|
|
12
|
-
}
|
|
13
|
-
} catch (error) {
|
|
14
|
-
console.error(
|
|
15
|
-
`Failed to check vulnerabilities for ${depName}: ${error.message}`
|
|
16
|
-
);
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
return vulnerabilities;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export async function checkPackageVulnerabilities(packageName, version) {
|
|
24
|
-
try {
|
|
25
|
-
const SNYK_API_TOKEN = "5867f5b0-1275-4bff-99b3-c307c545b6dd";
|
|
26
|
-
if (!SNYK_API_TOKEN) {
|
|
27
|
-
throw new Error(
|
|
28
|
-
"Snyk API token is missing. Please set the SNYK_API_TOKEN environment variable."
|
|
29
|
-
);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const response = await axios.get(
|
|
33
|
-
`https://snyk.io/api/v1/test/npm/${packageName}/${version}`,
|
|
34
|
-
{
|
|
35
|
-
headers: {
|
|
36
|
-
Authorization: `token ${SNYK_API_TOKEN}`,
|
|
37
|
-
},
|
|
38
|
-
}
|
|
39
|
-
);
|
|
40
|
-
|
|
41
|
-
const vulnerabilities = response.data.issues.vulnerabilities;
|
|
42
|
-
|
|
43
|
-
return vulnerabilities.map((vuln) => ({
|
|
44
|
-
severity: vuln.severity,
|
|
45
|
-
title: vuln.title,
|
|
46
|
-
description: vuln.description,
|
|
47
|
-
}));
|
|
48
|
-
} catch (error) {
|
|
49
|
-
if (error.response && error.response.status === 401) {
|
|
50
|
-
console.error(
|
|
51
|
-
`Failed to authenticate with Snyk API. Please check your SNYK_API_TOKEN.`
|
|
52
|
-
);
|
|
53
|
-
} else if (error.response && error.response.status === 404) {
|
|
54
|
-
console.error(`Package ${packageName} not found in Snyk database.`);
|
|
55
|
-
} else {
|
|
56
|
-
console.error(
|
|
57
|
-
`Failed to fetch vulnerabilities for ${packageName}: ${error.message}`
|
|
58
|
-
);
|
|
59
|
-
}
|
|
60
|
-
return [];
|
|
61
|
-
}
|
|
62
|
-
}
|
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
//const fs = require('fs');
|
|
2
|
-
//const path = require('path');
|
|
3
|
-
//const glob = require('glob');
|
|
4
|
-
|
|
5
|
-
import fs from "fs"
|
|
6
|
-
import path from "path"
|
|
7
|
-
import { glob } from "glob"
|
|
8
|
-
|
|
9
|
-
export async function findUnusedDependencies(directory, dependencies) {
|
|
10
|
-
const unusedDeps = [];
|
|
11
|
-
const allDeps = Object.keys(dependencies);
|
|
12
|
-
|
|
13
|
-
// Get all JavaScript/TypeScript files in the project
|
|
14
|
-
const files = glob.sync('**/*.{js,jsx,ts,tsx}', {
|
|
15
|
-
cwd: directory,
|
|
16
|
-
ignore: ['**/node_modules/**', '**/dist/**', '**/build/**'],
|
|
17
|
-
});
|
|
18
|
-
|
|
19
|
-
const fileContents = files.map(file =>
|
|
20
|
-
fs.readFileSync(path.join(directory, file), 'utf8')
|
|
21
|
-
);
|
|
22
|
-
|
|
23
|
-
allDeps.forEach(dep => {
|
|
24
|
-
const version = dependencies[dep];
|
|
25
|
-
let isUsed = false;
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
const importPatterns = [
|
|
29
|
-
new RegExp(`import.*from\\s+['"]${dep}['\"]`),
|
|
30
|
-
new RegExp(`import\\s+['"]${dep}['\"]`),
|
|
31
|
-
new RegExp(`require\\s*\\(\\s*['"]${dep}['\"]\\s*\\)`),
|
|
32
|
-
new RegExp(`import\\s*\\(\\s*['"]${dep}['\"]\\s*\\)`),
|
|
33
|
-
];
|
|
34
|
-
|
|
35
|
-
// Also check for submodule imports
|
|
36
|
-
const submodulePattern = new RegExp(`import.*from\\s+['"]${dep}/`);
|
|
37
|
-
const submoduleRequirePattern = new RegExp(`require\\s*\\(\\s*['"]${dep}/`);
|
|
38
|
-
|
|
39
|
-
// Check if the dependency is mentioned in any file
|
|
40
|
-
for (const content of fileContents) {
|
|
41
|
-
if (
|
|
42
|
-
importPatterns.some(pattern => pattern.test(content)) ||
|
|
43
|
-
submodulePattern.test(content) ||
|
|
44
|
-
submoduleRequirePattern.test(content)
|
|
45
|
-
) {
|
|
46
|
-
isUsed = true;
|
|
47
|
-
break;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// Check package.json for dependencies that might be used in scripts
|
|
52
|
-
const packageJson = JSON.parse(fs.readFileSync(path.join(directory, 'package.json'), 'utf8'));
|
|
53
|
-
const scripts = packageJson.scripts || {};
|
|
54
|
-
|
|
55
|
-
if (!isUsed) {
|
|
56
|
-
// Check if it's used in npm scripts
|
|
57
|
-
isUsed = Object.values(scripts).some(script => script.includes(dep));
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// If the dependency is still not found to be used, add it to the unused list
|
|
61
|
-
if (!isUsed) {
|
|
62
|
-
unusedDeps.push({
|
|
63
|
-
name: dep,
|
|
64
|
-
version,
|
|
65
|
-
reason: `Not imported or used in scripts`,
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
return unusedDeps;
|
|
71
|
-
}
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { test } from 'node:test';
|
|
2
|
-
import assert from 'node:assert/strict';
|
|
3
|
-
import { extractDeprecation } from '../src/alternative-suggester.js';
|
|
4
|
-
|
|
5
|
-
test('extractDeprecation returns message for deprecated latest version', () => {
|
|
6
|
-
const doc = {
|
|
7
|
-
'dist-tags': { latest: '2.88.2' },
|
|
8
|
-
versions: { '2.88.2': { deprecated: 'request has been deprecated' } },
|
|
9
|
-
time: { modified: '2020-01-01T00:00:00.000Z' },
|
|
10
|
-
};
|
|
11
|
-
assert.deepEqual(extractDeprecation(doc), {
|
|
12
|
-
deprecated: 'request has been deprecated',
|
|
13
|
-
lastUpdated: '2020-01-01T00:00:00.000Z',
|
|
14
|
-
});
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
test('extractDeprecation returns null for a healthy package', () => {
|
|
18
|
-
const doc = {
|
|
19
|
-
'dist-tags': { latest: '5.0.0' },
|
|
20
|
-
versions: { '5.0.0': {} },
|
|
21
|
-
time: { modified: '2024-01-01T00:00:00.000Z' },
|
|
22
|
-
};
|
|
23
|
-
assert.equal(extractDeprecation(doc), null);
|
|
24
|
-
});
|
|
25
|
-
|
|
26
|
-
test('extractDeprecation returns null when latest is missing', () => {
|
|
27
|
-
assert.equal(extractDeprecation({}), null);
|
|
28
|
-
});
|
package/tests/analyzer.test.js
DELETED
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
import { test } from 'node:test';
|
|
2
|
-
import assert from 'node:assert/strict';
|
|
3
|
-
import fs from 'node:fs';
|
|
4
|
-
import os from 'node:os';
|
|
5
|
-
import path from 'node:path';
|
|
6
|
-
import { spawnSync } from 'node:child_process';
|
|
7
|
-
import { fileURLToPath } from 'node:url';
|
|
8
|
-
import { runAnalysis, exitCodeFor } from '../src/analyzer.js';
|
|
9
|
-
|
|
10
|
-
const cli = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'index.js');
|
|
11
|
-
|
|
12
|
-
// Packages are never installed in these projects, so the security check skips
|
|
13
|
-
// them and, with suggestions off, no network calls are made.
|
|
14
|
-
function tempProject(packageJson, files = {}) {
|
|
15
|
-
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dd-analyzer-'));
|
|
16
|
-
if (packageJson) {
|
|
17
|
-
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(packageJson));
|
|
18
|
-
}
|
|
19
|
-
for (const [name, content] of Object.entries(files)) {
|
|
20
|
-
fs.writeFileSync(path.join(dir, name), content);
|
|
21
|
-
}
|
|
22
|
-
return dir;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
function runCli(args) {
|
|
26
|
-
const res = spawnSync(process.execPath, [cli, ...args], { encoding: 'utf8' });
|
|
27
|
-
return { code: res.status, stdout: res.stdout, stderr: res.stderr };
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
const emptyReport = {
|
|
31
|
-
unused: [],
|
|
32
|
-
vulnerabilities: [],
|
|
33
|
-
deprecated: [],
|
|
34
|
-
};
|
|
35
|
-
|
|
36
|
-
test('exitCodeFor is 0 for a clean report', () => {
|
|
37
|
-
assert.equal(exitCodeFor(emptyReport), 0);
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
test('exitCodeFor is 1 when there are unused deps or vulnerabilities', () => {
|
|
41
|
-
assert.equal(exitCodeFor({ ...emptyReport, unused: [{ name: 'x' }] }), 1);
|
|
42
|
-
assert.equal(exitCodeFor({ ...emptyReport, vulnerabilities: [{ name: 'x', issues: [{}] }] }), 1);
|
|
43
|
-
});
|
|
44
|
-
|
|
45
|
-
test('exitCodeFor ignores deprecated packages', () => {
|
|
46
|
-
assert.equal(exitCodeFor({ ...emptyReport, deprecated: [{ name: 'request' }] }), 0);
|
|
47
|
-
});
|
|
48
|
-
|
|
49
|
-
test('runAnalysis returns a plain report object', async () => {
|
|
50
|
-
const dir = tempProject(
|
|
51
|
-
{ dependencies: { express: '^4.0.0', lodash: '^4.0.0' } },
|
|
52
|
-
{ 'index.js': "import express from 'express';\n" }
|
|
53
|
-
);
|
|
54
|
-
const report = await runAnalysis({ directory: dir, suggestions: false });
|
|
55
|
-
assert.deepEqual(report.unused, [{ name: 'lodash', version: '^4.0.0' }]);
|
|
56
|
-
assert.deepEqual(report.vulnerabilities, []);
|
|
57
|
-
assert.deepEqual(report.notChecked.sort(), ['express', 'lodash']);
|
|
58
|
-
assert.equal(report.securityCheckFailed, false);
|
|
59
|
-
assert.equal(report.deprecated, null);
|
|
60
|
-
assert.deepEqual(report.summary, { unused: 1, vulnerable: 0, deprecated: 0 });
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
test('--json prints only JSON and exits 1 when unused deps are found', () => {
|
|
64
|
-
const dir = tempProject(
|
|
65
|
-
{ dependencies: { lodash: '^4.0.0' } },
|
|
66
|
-
{ 'index.js': 'console.log(1);\n' }
|
|
67
|
-
);
|
|
68
|
-
const { code, stdout } = runCli(['--json', '--no-suggestions', '-d', dir]);
|
|
69
|
-
assert.equal(code, 1);
|
|
70
|
-
const report = JSON.parse(stdout);
|
|
71
|
-
assert.deepEqual(report.unused, [{ name: 'lodash', version: '^4.0.0' }]);
|
|
72
|
-
});
|
|
73
|
-
|
|
74
|
-
test('--json exits 0 for a clean project', () => {
|
|
75
|
-
const dir = tempProject(
|
|
76
|
-
{ dependencies: { lodash: '^4.0.0' } },
|
|
77
|
-
{ 'index.js': "require('lodash');\n" }
|
|
78
|
-
);
|
|
79
|
-
const { code, stdout } = runCli(['--json', '--no-suggestions', '-d', dir]);
|
|
80
|
-
assert.equal(code, 0);
|
|
81
|
-
assert.deepEqual(JSON.parse(stdout).unused, []);
|
|
82
|
-
});
|
|
83
|
-
|
|
84
|
-
test('missing package.json exits 2, with a JSON error in --json mode', () => {
|
|
85
|
-
const dir = tempProject(null);
|
|
86
|
-
const json = runCli(['--json', '-d', dir]);
|
|
87
|
-
assert.equal(json.code, 2);
|
|
88
|
-
assert.match(JSON.parse(json.stdout).error, /package\.json/);
|
|
89
|
-
|
|
90
|
-
const human = runCli(['-d', dir]);
|
|
91
|
-
assert.equal(human.code, 2);
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
test('human-readable mode also exits 1 when unused deps are found', () => {
|
|
95
|
-
const dir = tempProject({ dependencies: { lodash: '^4.0.0' } }, { 'a.js': '1;\n' });
|
|
96
|
-
assert.equal(runCli(['--no-suggestions', '-d', dir]).code, 1);
|
|
97
|
-
});
|
package/tests/ast-parser.test.js
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import { test } from 'node:test';
|
|
2
|
-
import assert from 'node:assert/strict';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { fileURLToPath } from 'node:url';
|
|
5
|
-
import { extractPackageName, parseFileImports } from '../src/ast-parser.js';
|
|
6
|
-
|
|
7
|
-
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
8
|
-
|
|
9
|
-
test('extractPackageName handles bare, scoped, subpath, relative', () => {
|
|
10
|
-
assert.equal(extractPackageName('express'), 'express');
|
|
11
|
-
assert.equal(extractPackageName('lodash/get'), 'lodash');
|
|
12
|
-
assert.equal(extractPackageName('@babel/core'), '@babel/core');
|
|
13
|
-
assert.equal(extractPackageName('@babel/core/lib/x'), '@babel/core');
|
|
14
|
-
assert.equal(extractPackageName('./local'), './local');
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
test('parseFileImports captures import, require, dynamic import, export-from', async () => {
|
|
18
|
-
const { referenced, warnings } = await parseFileImports(
|
|
19
|
-
path.join(here, 'fixtures', 'sample-imports.js')
|
|
20
|
-
);
|
|
21
|
-
assert.ok(referenced.has('express'));
|
|
22
|
-
assert.ok(referenced.has('chalk'));
|
|
23
|
-
assert.ok(referenced.has('ora'));
|
|
24
|
-
assert.ok(referenced.has('lodash'));
|
|
25
|
-
assert.deepEqual(warnings, []);
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
test('parseFileImports returns empty result for missing file', async () => {
|
|
29
|
-
const { referenced, warnings } = await parseFileImports('/no/such/file.js');
|
|
30
|
-
assert.equal(referenced.size, 0);
|
|
31
|
-
assert.deepEqual(warnings, []);
|
|
32
|
-
});
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { test } from 'node:test';
|
|
2
|
-
import assert from 'node:assert/strict';
|
|
3
|
-
import { mapWithConcurrency } from '../src/util/concurrency.js';
|
|
4
|
-
|
|
5
|
-
test('maps all items preserving input order', async () => {
|
|
6
|
-
const out = await mapWithConcurrency([1, 2, 3, 4], 2, async (x) => x * 2);
|
|
7
|
-
assert.deepEqual(out, [2, 4, 6, 8]);
|
|
8
|
-
});
|
|
9
|
-
|
|
10
|
-
test('never runs more than `limit` concurrently', async () => {
|
|
11
|
-
let active = 0;
|
|
12
|
-
let max = 0;
|
|
13
|
-
await mapWithConcurrency([1, 2, 3, 4, 5, 6], 2, async () => {
|
|
14
|
-
active++;
|
|
15
|
-
max = Math.max(max, active);
|
|
16
|
-
await new Promise((r) => setTimeout(r, 10));
|
|
17
|
-
active--;
|
|
18
|
-
});
|
|
19
|
-
assert.ok(max <= 2, `observed max concurrency ${max} exceeded 2`);
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
test('empty input returns empty array', async () => {
|
|
23
|
-
assert.deepEqual(await mapWithConcurrency([], 4, async (x) => x), []);
|
|
24
|
-
});
|
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
import { test } from 'node:test';
|
|
2
|
-
import assert from 'node:assert/strict';
|
|
3
|
-
import fs from 'node:fs';
|
|
4
|
-
import os from 'node:os';
|
|
5
|
-
import path from 'node:path';
|
|
6
|
-
import { isReferenced, eslintShortNames, isEslintReference, scanConfigFiles } from '../src/config-scanner.js';
|
|
7
|
-
|
|
8
|
-
test('matches quoted references and subpaths', () => {
|
|
9
|
-
assert.ok(isReferenced(`import x from 'tailwindcss'`, 'tailwindcss'));
|
|
10
|
-
assert.ok(isReferenced(`require('tailwindcss/plugin')`, 'tailwindcss'));
|
|
11
|
-
assert.ok(isReferenced(`plugins: ["@tailwindcss/forms"]`, '@tailwindcss/forms'));
|
|
12
|
-
});
|
|
13
|
-
|
|
14
|
-
test('does not match unrelated substrings', () => {
|
|
15
|
-
assert.ok(!isReferenced(`// tailwindcss-typography notes`, 'tailwindcss'));
|
|
16
|
-
assert.ok(!isReferenced(`const tailwindcssHelper = 1`, 'tailwindcss'));
|
|
17
|
-
});
|
|
18
|
-
|
|
19
|
-
test('eslintShortNames maps plugin and config packages to their short names', () => {
|
|
20
|
-
assert.deepEqual(eslintShortNames('eslint-plugin-react'), ['react']);
|
|
21
|
-
assert.deepEqual(eslintShortNames('eslint-config-airbnb'), ['airbnb']);
|
|
22
|
-
assert.deepEqual(eslintShortNames('@typescript-eslint/eslint-plugin'), ['@typescript-eslint']);
|
|
23
|
-
assert.deepEqual(eslintShortNames('@scope/eslint-plugin-foo'), ['@scope/foo']);
|
|
24
|
-
assert.deepEqual(eslintShortNames('@vue/eslint-config-typescript'), ['@vue/typescript']);
|
|
25
|
-
assert.deepEqual(eslintShortNames('@scope/eslint-config'), ['@scope']);
|
|
26
|
-
assert.deepEqual(eslintShortNames('react'), []);
|
|
27
|
-
assert.deepEqual(eslintShortNames('eslint'), []);
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
test('isEslintReference matches short names in legacy JSON and YAML configs', () => {
|
|
31
|
-
assert.ok(isEslintReference(`{ "plugins": ["react"] }`, 'eslint-plugin-react'));
|
|
32
|
-
assert.ok(isEslintReference(`{ "extends": ["plugin:react/recommended"] }`, 'eslint-plugin-react'));
|
|
33
|
-
assert.ok(isEslintReference(`{ "rules": { "react/jsx-key": "error" } }`, 'eslint-plugin-react'));
|
|
34
|
-
assert.ok(isEslintReference(`extends:\n - airbnb\n`, 'eslint-config-airbnb'));
|
|
35
|
-
assert.ok(isEslintReference(`extends: airbnb/hooks`, 'eslint-config-airbnb'));
|
|
36
|
-
assert.ok(isEslintReference(`{ "extends": ["plugin:@typescript-eslint/recommended"] }`, '@typescript-eslint/eslint-plugin'));
|
|
37
|
-
assert.ok(isEslintReference(`{ "plugins": ["eslint-plugin-react"] }`, 'eslint-plugin-react'));
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
test('isEslintReference does not match other packages sharing a prefix', () => {
|
|
41
|
-
assert.ok(!isEslintReference(`{ "plugins": ["react-hooks"] }`, 'eslint-plugin-react'));
|
|
42
|
-
assert.ok(!isEslintReference(`{ "extends": ["airbnb-base"] }`, 'eslint-config-airbnb'));
|
|
43
|
-
});
|
|
44
|
-
|
|
45
|
-
function tempProject(files) {
|
|
46
|
-
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dd-eslint-'));
|
|
47
|
-
for (const [name, content] of Object.entries(files)) {
|
|
48
|
-
fs.writeFileSync(path.join(dir, name), content);
|
|
49
|
-
}
|
|
50
|
-
return dir;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
test('scanConfigFiles reads eslint.config.mjs flat config', async () => {
|
|
54
|
-
const dir = tempProject({
|
|
55
|
-
'eslint.config.mjs': `import js from '@eslint/js';\nimport react from 'eslint-plugin-react';\nexport default [js.configs.recommended, react.configs.flat.recommended];\n`,
|
|
56
|
-
});
|
|
57
|
-
const found = await scanConfigFiles(dir, ['@eslint/js', 'eslint-plugin-react', 'lodash']);
|
|
58
|
-
assert.deepEqual([...found].sort(), ['@eslint/js', 'eslint-plugin-react']);
|
|
59
|
-
});
|
|
60
|
-
|
|
61
|
-
test('scanConfigFiles resolves short names in .eslintrc.yml', async () => {
|
|
62
|
-
const dir = tempProject({
|
|
63
|
-
'.eslintrc.yml': `extends:\n - airbnb\n - plugin:react/recommended\nplugins:\n - "@typescript-eslint"\n`,
|
|
64
|
-
});
|
|
65
|
-
const found = await scanConfigFiles(dir, [
|
|
66
|
-
'eslint-config-airbnb',
|
|
67
|
-
'eslint-plugin-react',
|
|
68
|
-
'@typescript-eslint/eslint-plugin',
|
|
69
|
-
'eslint-plugin-vue',
|
|
70
|
-
]);
|
|
71
|
-
assert.deepEqual([...found].sort(), [
|
|
72
|
-
'@typescript-eslint/eslint-plugin',
|
|
73
|
-
'eslint-config-airbnb',
|
|
74
|
-
'eslint-plugin-react',
|
|
75
|
-
]);
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
test('scanConfigFiles reads the eslintConfig field of package.json', async () => {
|
|
79
|
-
const dir = tempProject({});
|
|
80
|
-
const packageJson = { eslintConfig: { extends: ['prettier'], plugins: ['import'] } };
|
|
81
|
-
const found = await scanConfigFiles(
|
|
82
|
-
dir,
|
|
83
|
-
['eslint-config-prettier', 'eslint-plugin-import', 'eslint-plugin-vue'],
|
|
84
|
-
packageJson
|
|
85
|
-
);
|
|
86
|
-
assert.deepEqual([...found].sort(), ['eslint-config-prettier', 'eslint-plugin-import']);
|
|
87
|
-
});
|