dependency-detective 0.2.0 → 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.
package/README.md CHANGED
@@ -1,173 +1,225 @@
1
- # dependency-detective 🕵️‍♂️
2
-
3
- A powerful Node.js tool that analyzes your project's dependencies, identifies unused packages, forecasts potential security risks, and suggests better alternatives based on community engagement and update frequency.
4
-
5
-
6
- ## 🔍 Overview
7
-
8
- **dependency-detective** addresses a common pain point that virtually every Node.js developer faces - dependency management gets messy as projects grow, and it's hard to know which packages are actually being used, which ones pose security risks, and which ones could be replaced with better alternatives.
9
-
10
- ## ✨ Features
11
-
12
- - **Unused Dependencies Detection**: Identifies truly unused packages that can be safely removed
13
- - **Security Vulnerabilities Check**: Highlights packages with known security issues
14
- - **Alternative Package Suggestions**: Recommends better alternatives based on community adoption, performance metrics, and update frequency
15
- - **Detailed Reporting**: Get comprehensive information about your dependency health in an easy-to-read format
16
-
17
- ## 📋 Installation
18
-
19
- ```bash
20
- # Install globally
21
- npm install -g dependency-detective
22
-
23
- # Or use with npx
24
- npx dependency-detective
25
- ```
26
-
27
- ## ⚙️ Configuration
28
-
29
- ### Snyk API Token (optional)
30
-
31
- Vulnerability checking requires a free Snyk account. Without a token the tool still reports unused dependencies and alternative suggestions — the vulnerability section is skipped with a clear message.
32
-
33
- 1. Sign up at [https://snyk.io](https://snyk.io) and copy your API token from Account Settings.
34
- 2. Create a `.env` file in your project root (or export in your shell profile):
35
-
36
- ```
37
- SNYK_API_TOKEN=your-token-here
38
- ```
39
-
40
- The tool loads `.env` automatically via dotenv.
41
-
42
- ## 🚀 Usage
43
-
44
- ```bash
45
- # Run in your project directory
46
- dependency-detective
47
-
48
- # Or specify a different project directory
49
- dependency-detective --directory /path/to/your/project
50
-
51
- # Show more detailed information
52
- dependency-detective --verbose
53
-
54
- # Skip alternative package suggestions
55
- dependency-detective --no-suggestions
56
- ```
57
-
58
- ## 📊 Example Output
59
-
60
- ```
61
- 📦 DEPENDENCY DETECTIVE REPORT
62
-
63
- 🗑️ Unused Dependencies:
64
- jquery v3.6.0
65
- moment v2.29.4
66
-
67
- Removing these could save approximately ~10MB of disk space
68
-
69
- 🔒 Security Vulnerabilities:
70
- lodash (1 issues)
71
-
72
- 💡 Recommended Alternatives:
73
- moment → date-fns
74
- jquery → No dependency needed
75
- express → fastify
76
-
77
- 📋 Next Steps:
78
- 1. Run with --verbose flag for more detailed information
79
- 2. Consider removing unused dependencies with: npm uninstall [package-names]
80
- 3. Address security vulnerabilities by updating affected packages
81
- 4. Evaluate suggested alternatives for potential improvements
82
- ```
83
-
84
- ## 🔧 Options
85
-
86
- | Option | Description |
87
- |--------|-------------|
88
- | `-d, --directory <path>` | Project directory to analyze (default: current directory) |
89
- | `-v, --verbose` | Show detailed output including reasons and statistics |
90
- | `--no-suggestions` | Skip suggesting alternative packages |
91
- | `--ignore <packages>` | Comma-separated list of package names to exclude from all checks |
92
- | `--help` | Display help information |
93
- | `--version` | Display version number |
94
-
95
- Use `--ignore` for packages that are intentionally hard to detect — build tools, PostCSS plugins, ESLint configs, and similar packages that are referenced in config files rather than imported in source code.
96
-
97
- ## 🧩 How It Works
98
-
99
- 1. **AST-Based Source Scanning**: The tool parses your JS/TS/JSX/TSX files using `@babel/parser` to accurately detect `import`, `require`, `export ... from`, and dynamic `import()` statements — no regex guessing
100
- 2. **Config File Scanning**: It also checks common config files (`tailwind.config.js`, `.eslintrc`, `postcss.config.js`, `vite.config.js`, `tsconfig.json`, and more) for packages referenced outside of source code
101
- 3. **Dependency Analysis**: It cross-references all found references with your `package.json`
102
- 4. **Security Checking**: It queries the Snyk API for known vulnerabilities (requires `SNYK_API_TOKEN`)
103
- 5. **Alternative Analysis**: It evaluates potential alternative packages based on multiple metrics
104
- 6. **Report Generation**: It presents findings in a clear, actionable format
105
-
106
- ## 🛠️ For Developers
107
-
108
- ### Project Structure
109
-
110
- ```
111
- dependency-detective/
112
- ├── index.js # CLI entry point
113
- ├── package.json
114
- └── src/
115
- ├── analyzer.js # Main analysis logic and result display
116
- ├── unused-detector.js # Orchestrates unused dependency detection
117
- ├── ast-parser.js # AST-based import extraction (@babel/parser)
118
- ├── config-scanner.js # Scans config files for package references
119
- ├── security-checker.js # Checks for vulnerabilities via Snyk API
120
- └── alternative-suggester.js # Suggests better alternatives
121
- ```
122
-
123
- ### Local Development
124
-
125
- ```bash
126
- # Clone the repository
127
- git clone https://github.com/yourusername/dependency-detective.git
128
- cd dependency-detective
129
-
130
- # Install dependencies
131
- npm install
132
-
133
- # Link for local testing
134
- npm link
135
-
136
- # Run tests
137
- npm test
138
- ```
139
-
140
- ## ⚠️ Limitations
141
-
142
- - Dynamically computed imports (`require(variable)`) cannot be statically detected — use `--ignore` to exempt these packages
143
- - Security vulnerability detection requires a Snyk API token and relies on Snyk's database, which may not cover every package
144
- - Alternative suggestions are based on general community metrics and might not be ideal for every specific use case
145
-
146
- ## 📝 Roadmap
147
-
148
- - [x] Improve detection accuracy with AST parsing
149
- - [x] Scan config files for build-tool package references
150
- - [ ] Add support for monorepos and workspaces
151
- - [ ] Visual reporting with charts and graphs
152
- - [ ] Interactive mode for bulk actions on dependencies
153
- - [ ] Customizable rules and thresholds
154
- - [ ] GitHub Actions integration
155
-
156
- ## 📄 License
157
-
158
- MIT
159
-
160
- ## 👥 Contributing
161
-
162
- Contributions are welcome! Please feel free to submit a Pull Request.
163
-
164
- 1. Fork the repository
165
- 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
166
- 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
167
- 4. Push to the branch (`git push origin feature/amazing-feature`)
168
- 5. Open a Pull Request
169
-
170
- ## 🙏 Acknowledgements
171
-
172
- - Thanks to all the open-source package maintainers
1
+ # dependency-detective 🕵️‍♂️
2
+
3
+ A Node.js tool that analyzes your project's dependencies: it identifies unused packages, checks for known security vulnerabilities (via the free OSV.dev database — no token required), and flags packages whose latest version has been officially deprecated.
4
+
5
+
6
+ ## 🔍 Overview
7
+
8
+ **dependency-detective** addresses a common pain point that virtually every Node.js developer faces - dependency management gets messy as projects grow, and it's hard to know which packages are actually being used, which ones pose security risks, and which ones could be replaced with better alternatives.
9
+
10
+ ## ✨ Features
11
+
12
+ - **Unused Dependencies Detection**: Identifies truly unused packages that can be safely removed
13
+ - **Security Vulnerabilities Check**: Highlights packages with known security issues, using the free OSV.dev database
14
+ - **Deprecated Package Detection**: Flags dependencies whose latest version has been officially deprecated by its maintainer
15
+ - **Detailed Reporting**: Get comprehensive information about your dependency health in an easy-to-read format
16
+
17
+ ## 📋 Installation
18
+
19
+ ```bash
20
+ # Install globally
21
+ npm install -g dependency-detective
22
+
23
+ # Or use with npx
24
+ npx dependency-detective
25
+ ```
26
+
27
+ ## ⚙️ Configuration
28
+
29
+ No configuration or API tokens are required. Vulnerability data comes from the free
30
+ [OSV.dev](https://osv.dev) database and works out of the box.
31
+
32
+ > Note: vulnerability checks read the **installed** version of each package from
33
+ > `node_modules`. Run `npm install` first for full coverage — uninstalled packages are
34
+ > reported as "not checked".
35
+
36
+ ## 🚀 Usage
37
+
38
+ ```bash
39
+ # Run in your project directory
40
+ dependency-detective
41
+
42
+ # Or specify a different project directory
43
+ dependency-detective --directory /path/to/your/project
44
+
45
+ # Show more detailed information
46
+ dependency-detective --verbose
47
+
48
+ # Skip the deprecated-package check
49
+ dependency-detective --no-suggestions
50
+
51
+ # Print the report as JSON
52
+ dependency-detective --json
53
+ ```
54
+
55
+ ## 📊 Example Output
56
+
57
+ ```
58
+ 📦 DEPENDENCY DETECTIVE REPORT
59
+
60
+ 🗑️ Unused Dependencies:
61
+ jquery v3.6.0
62
+ moment v2.29.4
63
+
64
+ Removing these could free about 3.2MB on disk
65
+
66
+ 🔒 Security Vulnerabilities:
67
+ lodash (1 issues)
68
+
69
+ ⚠️ Deprecated Packages:
70
+ request
71
+
72
+ 📋 Next Steps:
73
+ 1. Run with --verbose flag for more detailed information
74
+ 2. Consider removing unused dependencies with: npm uninstall [package-names]
75
+ 3. Address security vulnerabilities by updating affected packages
76
+ 4. Replace deprecated packages with maintained alternatives
77
+ ```
78
+
79
+ ## 🔧 Options
80
+
81
+ | Option | Description |
82
+ |--------|-------------|
83
+ | `-d, --directory <path>` | Project directory to analyze (default: current directory) |
84
+ | `-v, --verbose` | Show detailed output including reasons and statistics |
85
+ | `--no-suggestions` | Skip the deprecated-package check |
86
+ | `--ignore <packages>` | Comma-separated list of package names to exclude from all checks |
87
+ | `--json` | Print the report as JSON instead of the formatted report |
88
+ | `--help` | Display help information |
89
+ | `--version` | Display version number |
90
+
91
+ Use `--ignore` for packages that are intentionally hard to detect — build tools, PostCSS plugins, ESLint configs, and similar packages that are referenced in config files rather than imported in source code.
92
+
93
+ ## 🤖 Using in CI
94
+
95
+ The exit code tells your pipeline whether anything needs attention:
96
+
97
+ | Exit code | Meaning |
98
+ |-----------|---------|
99
+ | `0` | No unused dependencies or known vulnerabilities |
100
+ | `1` | Unused dependencies or known vulnerabilities found |
101
+ | `2` | The analysis could not run (for example, no `package.json`) |
102
+
103
+ Deprecated packages are reported but don't fail the run. If the vulnerability lookup itself fails (network error), `securityCheckFailed` is `true` in the JSON and the run doesn't fail on that alone.
104
+
105
+ ```bash
106
+ # Fail the build on unused or vulnerable dependencies
107
+ npx dependency-detective
108
+
109
+ # Save a machine-readable report
110
+ npx dependency-detective --json > dependency-report.json
111
+ ```
112
+
113
+ With `--json`, only JSON is written to stdout:
114
+
115
+ ```json
116
+ {
117
+ "directory": "/path/to/project",
118
+ "unused": [{ "name": "moment", "version": "^2.29.4" }],
119
+ "estimatedSavingsBytes": 4404019,
120
+ "vulnerabilities": [
121
+ {
122
+ "name": "lodash",
123
+ "issues": [
124
+ {
125
+ "id": "GHSA-35jh-r3h4-6jhm",
126
+ "severity": "HIGH",
127
+ "title": "Command Injection in lodash",
128
+ "fixedIn": "4.17.21",
129
+ "url": "https://osv.dev/vulnerability/GHSA-35jh-r3h4-6jhm"
130
+ }
131
+ ]
132
+ }
133
+ ],
134
+ "notChecked": [],
135
+ "securityCheckFailed": false,
136
+ "deprecated": [{ "name": "request", "message": "request has been deprecated", "lastUpdated": "2024-01-01T00:00:00.000Z" }],
137
+ "warnings": [],
138
+ "summary": { "unused": 1, "vulnerable": 1, "deprecated": 1 }
139
+ }
140
+ ```
141
+
142
+ `deprecated` is `null` when the check is skipped with `--no-suggestions`. If the analysis can't run, the output is `{ "error": "..." }` with exit code `2`.
143
+
144
+ ## 🧩 How It Works
145
+
146
+ 1. **AST-Based Source Scanning**: The tool parses your JS/TS/JSX/TSX files using `@babel/parser` to accurately detect `import`, `require`, `export ... from`, and dynamic `import()` statements — no regex guessing
147
+ 2. **Config File Scanning**: It also checks common config files (`tailwind.config.js`, `.eslintrc`, `postcss.config.js`, `vite.config.js`, `tsconfig.json`, and more) for packages referenced outside of source code. ESLint configs are understood in both flat (`eslint.config.*`) and legacy (`.eslintrc*`, including YAML and the `eslintConfig` field in `package.json`) form, including short names such as `react` for `eslint-plugin-react` and `airbnb` for `eslint-config-airbnb`
148
+ 3. **Script Scanning**: It checks your `package.json` scripts for each package's commands, read from its `bin` field — so `tsc` counts as using `typescript` and `run-p` as using `npm-run-all`
149
+ 4. **Dependency Analysis**: It cross-references all found references with your `package.json`
150
+ 5. **Security Checking**: It queries the free OSV.dev vulnerability database for the installed version of each package (no token required)
151
+ 6. **Deprecation Analysis**: It checks the npm registry for packages whose latest version is officially deprecated
152
+ 7. **Report Generation**: It presents findings in a clear, actionable format
153
+
154
+ ## 🛠️ For Developers
155
+
156
+ ### Project Structure
157
+
158
+ ```
159
+ dependency-detective/
160
+ ├── index.js # CLI entry point
161
+ ├── package.json
162
+ └── src/
163
+ ├── analyzer.js # Main analysis logic and result display
164
+ ├── unused-detector.js # Orchestrates unused dependency detection
165
+ ├── ast-parser.js # AST-based import extraction (@babel/parser)
166
+ ├── config-scanner.js # Scans config files for package references
167
+ ├── script-scanner.js # Matches npm script commands to packages via their bin field
168
+ ├── security-checker.js # Checks vulnerabilities via OSV.dev (no token)
169
+ ├── alternative-suggester.js # Flags officially-deprecated packages
170
+ └── util/
171
+ └── concurrency.js # Concurrency-capped async map helper
172
+ ```
173
+
174
+ ### Local Development
175
+
176
+ ```bash
177
+ # Clone the repository
178
+ git clone https://github.com/Marvinkwame/dependency-detective.git
179
+ cd dependency-detective
180
+
181
+ # Install dependencies
182
+ npm install
183
+
184
+ # Link for local testing
185
+ npm link
186
+
187
+ # Run tests
188
+ npm test
189
+ ```
190
+
191
+ ## ⚠️ Limitations
192
+
193
+ - Dynamically computed imports (`require(variable)`) cannot be statically detected — use `--ignore` to exempt these packages
194
+ - Vulnerability checks read the installed version from `node_modules`; uninstalled packages are skipped
195
+ - Vulnerability data comes from OSV.dev, whose coverage and severity ratings may differ from commercial databases
196
+ - Vue/Svelte/Astro single-file components are not yet scanned for imports
197
+
198
+ ## 📝 Roadmap
199
+
200
+ - [x] Improve detection accuracy with AST parsing
201
+ - [x] Scan config files for build-tool package references
202
+ - [x] Token-free vulnerability checks via OSV.dev
203
+ - [ ] `--fix` / interactive removal of unused dependencies
204
+ - [ ] Add support for monorepos and workspaces
205
+ - [x] `--json` output and CI mode with exit codes
206
+ - [ ] Maintenance/abandonment signals for dependencies
207
+
208
+ ## 📄 License
209
+
210
+ MIT
211
+
212
+ ## 👥 Contributing
213
+
214
+ Contributions are welcome! Please feel free to submit a Pull Request.
215
+
216
+ 1. Fork the repository
217
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
218
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
219
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
220
+ 5. Open a Pull Request
221
+
222
+ ## 🙏 Acknowledgements
223
+
224
+ - Thanks to all the open-source package maintainers
173
225
  - Inspired by similar tools like depcheck and npm-check
package/index.js CHANGED
@@ -1,26 +1,31 @@
1
- #!/usr/bin/env node
2
-
3
- import { createRequire } from 'module';
4
- import { program } from 'commander';
5
- import { analyzeProject } from "./src/analyzer.js"
6
- import 'dotenv/config';
7
-
8
- const require = createRequire(import.meta.url);
9
- const { version } = require('./package.json');
10
-
11
-
12
- program
13
- .version(version)
14
- .description('Analyzes your project dependencies to identify unused packages, security risks, and suggest alternatives')
15
- .option('-d, --directory <path>', 'project directory to analyze', process.cwd())
16
- .option('-v, --verbose', 'show detailed output')
17
- .option('--no-suggestions', 'skip suggesting alternative packages')
18
- .option('--ignore <packages>', 'comma-separated package names to exclude from analysis', '')
19
- .action(async (options) => {
20
- const ignoreList = options.ignore
21
- ? options.ignore.split(',').map(p => p.trim()).filter(Boolean)
22
- : [];
23
- await analyzeProject({ ...options, ignore: ignoreList });
24
- });
25
-
26
- program.parse(process.argv);
1
+ #!/usr/bin/env node
2
+
3
+ import { createRequire } from 'module';
4
+ import { program } from 'commander';
5
+ import { analyzeProject } from "./src/analyzer.js"
6
+
7
+ const require = createRequire(import.meta.url);
8
+ const { version } = require('./package.json');
9
+
10
+
11
+ program
12
+ .version(version)
13
+ .description('Analyzes your project dependencies to identify unused packages, security risks, and suggest alternatives')
14
+ .option('-d, --directory <path>', 'project directory to analyze', process.cwd())
15
+ .option('-v, --verbose', 'show detailed output')
16
+ .option('--no-suggestions', 'skip suggesting alternative packages')
17
+ .option('--ignore <packages>', 'comma-separated package names to exclude from analysis', '')
18
+ .option('--json', 'print the report as JSON (for CI and scripts)')
19
+ .addHelpText('after', `
20
+ Exit codes:
21
+ 0 no unused dependencies or known vulnerabilities
22
+ 1 unused dependencies or known vulnerabilities found
23
+ 2 the analysis could not run (e.g. no package.json)`)
24
+ .action(async (options) => {
25
+ const ignoreList = options.ignore
26
+ ? options.ignore.split(',').map(p => p.trim()).filter(Boolean)
27
+ : [];
28
+ process.exitCode = await analyzeProject({ ...options, ignore: ignoreList });
29
+ });
30
+
31
+ await program.parseAsync(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dependency-detective",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Analyzes your project's dependencies, identifies unused ones, forecasts potential security risks, and suggests better alternatives",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -9,7 +9,7 @@
9
9
  },
10
10
  "scripts": {
11
11
  "start": "node index.js",
12
- "test": "echo \"Error: no test specified\" && exit 1"
12
+ "test": "node --test"
13
13
  },
14
14
  "keywords": [
15
15
  "dependencies",
@@ -22,11 +22,10 @@
22
22
  "license": "MIT",
23
23
  "dependencies": {
24
24
  "@babel/parser": "^7.29.3",
25
- "axios": "^1.8.1",
25
+ "axios": "^1.21.1",
26
26
  "chalk": "^5.4.1",
27
27
  "commander": "^13.1.0",
28
- "dotenv": "^16.4.7",
29
- "glob": "^11.0.1",
28
+ "glob": "^14.0.6",
30
29
  "ora": "^8.2.0"
31
30
  },
32
31
  "repository": {
@@ -1,64 +1,32 @@
1
- import axios from "axios";
1
+ import axios from 'axios';
2
+ import { mapWithConcurrency } from './util/concurrency.js';
2
3
 
4
+ const CONCURRENCY = 8;
3
5
 
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;
6
+ export function extractDeprecation(registryDoc) {
7
+ const latest = registryDoc?.['dist-tags']?.latest;
8
+ if (!latest) return null;
9
+ const deprecated = registryDoc.versions?.[latest]?.deprecated;
10
+ if (!deprecated) return null;
11
+ return {
12
+ deprecated: typeof deprecated === 'string' ? deprecated : 'This package is deprecated',
13
+ lastUpdated: registryDoc.time?.modified ?? null,
14
+ };
19
15
  }
20
16
 
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
- }
17
+ export async function suggestAlternatives(dependencies) {
18
+ const deps = Object.keys(dependencies);
19
+ const alternatives = {};
36
20
 
37
- // Fetch alternatives from npms.io
21
+ await mapWithConcurrency(deps, CONCURRENCY, async (dep) => {
38
22
  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}`);
23
+ const res = await axios.get(`https://registry.npmjs.org/${dep}`);
24
+ const info = extractDeprecation(res.data);
25
+ if (info) alternatives[dep] = { name: dep, ...info };
26
+ } catch {
27
+ // per-dep registry failure — omit silently
53
28
  }
29
+ });
54
30
 
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
- }
31
+ return alternatives;
32
+ }