dependency-detective 0.1.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/.claude/worktrees/amazing-bartik-b7ca06/.claude/settings.local.json +19 -0
  2. package/.claude/worktrees/amazing-bartik-b7ca06/LICENSE +21 -0
  3. package/.claude/worktrees/amazing-bartik-b7ca06/README.md +151 -0
  4. package/.claude/worktrees/amazing-bartik-b7ca06/docs/superpowers/specs/2026-05-09-correctness-fixes-design.md +118 -0
  5. package/.claude/worktrees/amazing-bartik-b7ca06/index.js +19 -0
  6. package/.claude/worktrees/amazing-bartik-b7ca06/package-lock.json +915 -0
  7. package/.claude/worktrees/amazing-bartik-b7ca06/package.json +36 -0
  8. package/.claude/worktrees/amazing-bartik-b7ca06/src/alternative-suggester.js +64 -0
  9. package/.claude/worktrees/amazing-bartik-b7ca06/src/analyzer.js +141 -0
  10. package/.claude/worktrees/amazing-bartik-b7ca06/src/security-checker.js +62 -0
  11. package/.claude/worktrees/amazing-bartik-b7ca06/src/unused-detector.js +71 -0
  12. package/README.md +224 -150
  13. package/index.js +31 -19
  14. package/package.json +5 -5
  15. package/src/alternative-suggester.js +24 -56
  16. package/src/analyzer.js +221 -141
  17. package/src/ast-parser.js +85 -0
  18. package/src/config-scanner.js +128 -0
  19. package/src/script-scanner.js +77 -0
  20. package/src/security-checker.js +56 -49
  21. package/src/unused-detector.js +50 -52
  22. package/src/util/concurrency.js +15 -0
  23. package/tests/alternative-suggester.test.js +28 -0
  24. package/tests/analyzer.test.js +97 -0
  25. package/tests/ast-parser.test.js +32 -0
  26. package/tests/concurrency.test.js +24 -0
  27. package/tests/config-scanner.test.js +87 -0
  28. package/tests/fixtures/sample-imports.js +6 -0
  29. package/tests/script-scanner.test.js +61 -0
  30. package/tests/security-checker.test.js +55 -0
  31. package/tests/unused-detector.test.js +18 -0
@@ -0,0 +1,36 @@
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
+ }
@@ -0,0 +1,64 @@
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
+ }
@@ -0,0 +1,141 @@
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
+ }
@@ -0,0 +1,62 @@
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
+ }
@@ -0,0 +1,71 @@
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
+ }