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/src/analyzer.js CHANGED
@@ -1,120 +1,221 @@
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
- const spinner = ora('Analyzing your project dependencies...').start();
11
- const ignoreSet = new Set(options.ignore || []);
12
-
13
- try {
14
- const packageJsonPath = path.join(options.directory, 'package.json');
15
-
16
- if (!fs.existsSync(packageJsonPath)) {
17
- spinner.fail('No package.json found in the specified directory');
18
- return;
19
- }
20
-
21
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
22
- const dependencies = {
23
- ...(packageJson.dependencies || {}),
24
- ...(packageJson.devDependencies || {}),
25
- };
26
-
27
- const filteredDependencies = Object.fromEntries(
28
- Object.entries(dependencies).filter(([depName]) => !ignoreSet.has(depName))
29
- );
30
-
31
- spinner.text = 'Scanning for unused dependencies...';
32
- const unusedDeps = await findUnusedDependencies(options.directory, filteredDependencies);
33
-
34
- spinner.text = 'Checking for security vulnerabilities...';
35
- const vulnerabilities = await checkVulnerabilities(filteredDependencies);
36
-
37
- let alternatives = {};
38
- if (options.suggestions !== false) {
39
- spinner.text = 'Finding better alternatives...';
40
- alternatives = await suggestAlternatives(filteredDependencies);
41
- }
42
-
43
- spinner.succeed('Analysis complete!');
44
-
45
- displayResults(unusedDeps, vulnerabilities, alternatives, options.verbose);
46
- } catch (error) {
47
- spinner.fail('Analysis failed');
48
- console.error(chalk.red('Error:'), error.message);
49
- }
50
- }
51
-
52
- function getSavingsEstimate(unusedDeps) {
53
-
54
- // Average size of an npm package in MB
55
- const AVERAGE_PACKAGE_SIZE_MB = 5;
56
-
57
- // Calculate the total estimated savings
58
- const totalSavingsMB = unusedDeps.length * AVERAGE_PACKAGE_SIZE_MB;
59
-
60
- // Return the formatted estimate
61
- return `~${totalSavingsMB}MB`;
62
- }
63
-
64
- // Define displayResults function
65
- function displayResults(unusedDeps, vulnerabilities, alternatives, verbose) {
66
- console.log('\n' + chalk.bold('📦 DEPENDENCY DETECTIVE REPORT') + '\n');
67
-
68
- // Display unused dependencies
69
- console.log(chalk.bold('🗑️ Unused Dependencies:'));
70
- if (unusedDeps.length === 0) {
71
- console.log(chalk.green(' No unused dependencies found. Great job!'));
72
- } else {
73
- unusedDeps.forEach(dep => {
74
- console.log(` ${chalk.yellow(dep.name)} ${chalk.dim(`v${dep.version}`)}`);
75
- if (verbose && dep.reason) {
76
- console.log(` ${chalk.dim(dep.reason)}`);
77
- }
78
- });
79
- console.log(chalk.dim(`\n Removing these could save approximately ${getSavingsEstimate(unusedDeps)} of disk space`));
80
- }
81
-
82
- // Display vulnerabilities
83
- console.log('\n' + chalk.bold('🔒 Security Vulnerabilities:'));
84
- if (vulnerabilities === null) {
85
- console.log(chalk.yellow(' ⚠ Skipped — SNYK_API_TOKEN not set.'));
86
- console.log(chalk.dim(' To enable: add SNYK_API_TOKEN=<your-token> to a .env file.'));
87
- console.log(chalk.dim(' Get a free token at https://snyk.io'));
88
- } else if (Object.keys(vulnerabilities).length === 0) {
89
- console.log(chalk.green(' No security vulnerabilities detected. You\'re secure!'));
90
- } else {
91
- Object.entries(vulnerabilities).forEach(([depName, issues]) => {
92
- console.log(` ${chalk.red(depName)} ${chalk.dim(`(${issues.length} issues)`)}`);
93
- if (verbose) {
94
- issues.forEach(issue => {
95
- console.log(` - ${issue.severity.toUpperCase()}: ${issue.title}`);
96
- console.log(` ${chalk.dim(issue.description)}`);
97
- });
98
- }
99
- });
100
- }
101
-
102
- // Display alternative suggestions
103
- if (Object.keys(alternatives).length > 0) {
104
- console.log('\n' + chalk.bold('💡 Recommended Alternatives:'));
105
- Object.entries(alternatives).forEach(([depName, suggestion]) => {
106
- console.log(` ${chalk.blue(depName)} → ${chalk.green(suggestion.name)}`);
107
- if (verbose) {
108
- console.log(` ${chalk.dim(suggestion.reason)}`);
109
- console.log(` ${chalk.dim(`Weekly downloads: ${suggestion.downloads.toLocaleString()}`)}`);
110
- console.log(` ${chalk.dim(`Last updated: ${suggestion.lastUpdated}`)}`);
111
- }
112
- });
113
- }
114
-
115
- console.log('\n' + chalk.bold('📋 Next Steps:'));
116
- console.log(' 1. Run with --verbose flag for more detailed information');
117
- console.log(' 2. Consider removing unused dependencies with: npm uninstall [package-names]');
118
- console.log(' 3. Address security vulnerabilities by updating affected packages');
119
- console.log(' 4. Evaluate suggested alternatives for potential improvements\n');
120
- }
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 const EXIT_OK = 0;
10
+ export const EXIT_ISSUES = 1;
11
+ export const EXIT_ERROR = 2;
12
+
13
+ class AnalysisError extends Error {}
14
+
15
+ /**
16
+ * Runs every check and returns a plain report object. Prints nothing.
17
+ * `onProgress` receives a short status message before each step.
18
+ */
19
+ export async function runAnalysis(options = {}, onProgress = () => {}) {
20
+ const directory = path.resolve(options.directory ?? process.cwd());
21
+ const ignoreSet = new Set(options.ignore || []);
22
+
23
+ const packageJsonPath = path.join(directory, 'package.json');
24
+ if (!fs.existsSync(packageJsonPath)) {
25
+ throw new AnalysisError(`No package.json found in ${directory}`);
26
+ }
27
+
28
+ let packageJson;
29
+ try {
30
+ packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
31
+ } catch (err) {
32
+ throw new AnalysisError(`Could not read ${packageJsonPath}: ${err.message}`);
33
+ }
34
+
35
+ const dependencies = Object.fromEntries(
36
+ Object.entries({
37
+ ...(packageJson.dependencies || {}),
38
+ ...(packageJson.devDependencies || {}),
39
+ }).filter(([depName]) => !ignoreSet.has(depName))
40
+ );
41
+
42
+ onProgress('Scanning for unused dependencies...');
43
+ const { unusedDeps, warnings } = await findUnusedDependencies(directory, dependencies, packageJson);
44
+
45
+ onProgress('Checking for security vulnerabilities...');
46
+ const security = await checkVulnerabilities(dependencies, directory);
47
+
48
+ let deprecated = null;
49
+ if (options.suggestions !== false) {
50
+ onProgress('Checking for deprecated packages...');
51
+ const found = await suggestAlternatives(dependencies);
52
+ deprecated = Object.values(found).map((info) => ({
53
+ name: info.name,
54
+ message: info.deprecated,
55
+ lastUpdated: info.lastUpdated,
56
+ }));
57
+ }
58
+
59
+ const unused = unusedDeps.map(({ name, version }) => ({ name, version }));
60
+ const vulnerabilities = Object.entries(security.vulnerabilities).map(([name, issues]) => ({
61
+ name,
62
+ issues,
63
+ }));
64
+
65
+ return {
66
+ directory,
67
+ unused,
68
+ estimatedSavingsBytes: getSavingsBytes(unused, directory),
69
+ vulnerabilities,
70
+ notChecked: security.skipped,
71
+ securityCheckFailed: security.failed,
72
+ deprecated,
73
+ warnings,
74
+ summary: {
75
+ unused: unused.length,
76
+ vulnerable: vulnerabilities.length,
77
+ deprecated: deprecated?.length ?? 0,
78
+ },
79
+ };
80
+ }
81
+
82
+ /** 1 when there are unused dependencies or known vulnerabilities, else 0. */
83
+ export function exitCodeFor(report) {
84
+ return report.unused.length > 0 || report.vulnerabilities.length > 0 ? EXIT_ISSUES : EXIT_OK;
85
+ }
86
+
87
+ /** CLI entry: prints the report (human-readable or JSON) and returns an exit code. */
88
+ export async function analyzeProject(options = {}) {
89
+ if (options.json) {
90
+ try {
91
+ const report = await runAnalysis(options);
92
+ console.log(JSON.stringify(report, null, 2));
93
+ return exitCodeFor(report);
94
+ } catch (error) {
95
+ console.log(JSON.stringify({ error: error.message }, null, 2));
96
+ return EXIT_ERROR;
97
+ }
98
+ }
99
+
100
+ const spinner = ora('Analyzing your project dependencies...').start();
101
+ try {
102
+ const report = await runAnalysis(options, (text) => {
103
+ spinner.text = text;
104
+ });
105
+ spinner.succeed('Analysis complete!');
106
+ displayResults(report, options.verbose);
107
+ return exitCodeFor(report);
108
+ } catch (error) {
109
+ if (error instanceof AnalysisError) {
110
+ spinner.fail(error.message);
111
+ } else {
112
+ spinner.fail('Analysis failed');
113
+ console.error(chalk.red('Error:'), error.message);
114
+ }
115
+ return EXIT_ERROR;
116
+ }
117
+ }
118
+
119
+ function dirSize(dir) {
120
+ let total = 0;
121
+ let entries;
122
+ try {
123
+ entries = fs.readdirSync(dir, { withFileTypes: true });
124
+ } catch {
125
+ return 0;
126
+ }
127
+ for (const entry of entries) {
128
+ const full = path.join(dir, entry.name);
129
+ if (entry.isDirectory()) {
130
+ total += dirSize(full);
131
+ } else {
132
+ try {
133
+ total += fs.statSync(full).size;
134
+ } catch {
135
+ // unreadable entry — skip
136
+ }
137
+ }
138
+ }
139
+ return total;
140
+ }
141
+
142
+ function getSavingsBytes(unused, directory) {
143
+ const nodeModules = path.join(directory, 'node_modules');
144
+ if (unused.length === 0 || !fs.existsSync(nodeModules)) return null;
145
+ let bytes = 0;
146
+ for (const dep of unused) {
147
+ bytes += dirSize(path.join(nodeModules, dep.name));
148
+ }
149
+ return bytes;
150
+ }
151
+
152
+ function displayResults(report, verbose) {
153
+ console.log('\n' + chalk.bold('📦 DEPENDENCY DETECTIVE REPORT') + '\n');
154
+
155
+ // Unused dependencies
156
+ console.log(chalk.bold('🗑️ Unused Dependencies:'));
157
+ if (report.unused.length === 0) {
158
+ console.log(chalk.green(' No unused dependencies found. Great job!'));
159
+ } else {
160
+ for (const dep of report.unused) {
161
+ console.log(` ${chalk.yellow(dep.name)} ${chalk.dim(`v${dep.version}`)}`);
162
+ if (verbose) {
163
+ console.log(` ${chalk.dim('Not imported in any source, config file or script')}`);
164
+ }
165
+ }
166
+ if (report.estimatedSavingsBytes !== null) {
167
+ const mb = (report.estimatedSavingsBytes / (1024 * 1024)).toFixed(1);
168
+ console.log(chalk.dim(`\n Removing these could free about ${mb}MB on disk`));
169
+ }
170
+ }
171
+
172
+ // Security vulnerabilities
173
+ console.log('\n' + chalk.bold('🔒 Security Vulnerabilities:'));
174
+ if (report.securityCheckFailed) {
175
+ console.log(chalk.yellow(' ⚠ Security check failed (network error). Try again later.'));
176
+ } else if (report.vulnerabilities.length === 0) {
177
+ console.log(chalk.green(' No known vulnerabilities detected.'));
178
+ } else {
179
+ for (const { name, issues } of report.vulnerabilities) {
180
+ console.log(` ${chalk.red(name)} ${chalk.dim(`(${issues.length} issues)`)}`);
181
+ if (verbose) {
182
+ for (const issue of issues) {
183
+ console.log(` - ${String(issue.severity).toUpperCase()}: ${issue.title}`);
184
+ const meta = [issue.fixedIn && `fixed in ${issue.fixedIn}`, issue.url].filter(Boolean);
185
+ if (meta.length > 0) console.log(` ${chalk.dim(meta.join(' · '))}`);
186
+ }
187
+ }
188
+ }
189
+ }
190
+ if (report.notChecked.length > 0) {
191
+ console.log(
192
+ chalk.dim(
193
+ ` ${report.notChecked.length} package(s) not checked (not installed) — run \`npm install\` for full coverage.`
194
+ )
195
+ );
196
+ }
197
+
198
+ // Deprecated packages
199
+ if (report.deprecated?.length > 0) {
200
+ console.log('\n' + chalk.bold('⚠️ Deprecated Packages:'));
201
+ for (const info of report.deprecated) {
202
+ console.log(` ${chalk.yellow(info.name)}`);
203
+ if (verbose) {
204
+ console.log(` ${chalk.dim(info.message)}`);
205
+ if (info.lastUpdated) console.log(` ${chalk.dim(`Last updated: ${info.lastUpdated}`)}`);
206
+ }
207
+ }
208
+ }
209
+
210
+ if (report.warnings.length > 0) {
211
+ console.log('\n' + chalk.dim('Warnings:'));
212
+ for (const w of report.warnings) console.log(chalk.dim(` - ${w}`));
213
+ }
214
+
215
+ // Next steps
216
+ console.log('\n' + chalk.bold('📋 Next Steps:'));
217
+ console.log(' 1. Run with --verbose flag for more detailed information');
218
+ console.log(' 2. Consider removing unused dependencies with: npm uninstall [package-names]');
219
+ console.log(' 3. Address security vulnerabilities by updating affected packages');
220
+ console.log(' 4. Replace deprecated packages with maintained alternatives\n');
221
+ }
package/src/ast-parser.js CHANGED
@@ -1,79 +1,85 @@
1
- import fs from 'fs';
2
- import { parse } from '@babel/parser';
3
-
4
- const BABEL_PLUGINS = ['jsx', 'typescript', 'dynamicImport', 'importMeta'];
5
-
6
- function extractPackageName(source) {
7
- if (source.startsWith('.')) return source;
8
- if (source.startsWith('@')) {
9
- return source.split('/').slice(0, 2).join('/');
10
- }
11
- return source.split('/')[0];
12
- }
13
-
14
- function walk(node, visitor) {
15
- if (!node || typeof node !== 'object' || Array.isArray(node)) return;
16
- if (!node.type) return;
17
- if (visitor[node.type]) visitor[node.type](node);
18
- for (const key of Object.keys(node)) {
19
- const child = node[key];
20
- if (Array.isArray(child)) {
21
- for (const item of child) {
22
- if (item && typeof item === 'object' && item.type) walk(item, visitor);
23
- }
24
- } else if (child && typeof child === 'object' && child.type) {
25
- walk(child, visitor);
26
- }
27
- }
28
- }
29
-
30
- export async function parseFileImports(filePath) {
31
- const referenced = new Set();
32
-
33
- let content;
34
- try {
35
- content = await fs.promises.readFile(filePath, 'utf8');
36
- } catch {
37
- return referenced;
38
- }
39
-
40
- let ast;
41
- try {
42
- ast = parse(content, {
43
- sourceType: 'unambiguous',
44
- plugins: BABEL_PLUGINS,
45
- errorRecovery: true,
46
- });
47
- } catch (err) {
48
- console.warn(`Warning: could not parse ${filePath}: ${err.message}`);
49
- return referenced;
50
- }
51
-
52
- walk(ast, {
53
- ImportDeclaration(node) {
54
- if (node.source?.value) referenced.add(extractPackageName(node.source.value));
55
- },
56
- ExportNamedDeclaration(node) {
57
- if (node.source?.value) referenced.add(extractPackageName(node.source.value));
58
- },
59
- ExportAllDeclaration(node) {
60
- if (node.source?.value) referenced.add(extractPackageName(node.source.value));
61
- },
62
- CallExpression(node) {
63
- if (
64
- node.callee?.type === 'Identifier' &&
65
- node.callee.name === 'require' &&
66
- node.arguments?.[0]?.type === 'StringLiteral'
67
- ) {
68
- referenced.add(extractPackageName(node.arguments[0].value));
69
- }
70
- },
71
- ImportExpression(node) {
72
- if (node.source?.type === 'StringLiteral') {
73
- referenced.add(extractPackageName(node.source.value));
74
- }
75
- },
76
- });
77
-
78
- return referenced;
79
- }
1
+ import fs from 'fs';
2
+ import { parse } from '@babel/parser';
3
+
4
+ const BABEL_PLUGINS = ['jsx', 'typescript', 'dynamicImport', 'importMeta'];
5
+
6
+ export function extractPackageName(source) {
7
+ if (source.startsWith('.')) return source;
8
+ if (source.startsWith('@')) {
9
+ return source.split('/').slice(0, 2).join('/');
10
+ }
11
+ return source.split('/')[0];
12
+ }
13
+
14
+ function walk(node, visitor) {
15
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return;
16
+ if (!node.type) return;
17
+ if (visitor[node.type]) visitor[node.type](node);
18
+ for (const key of Object.keys(node)) {
19
+ const child = node[key];
20
+ if (Array.isArray(child)) {
21
+ for (const item of child) {
22
+ if (item && typeof item === 'object' && item.type) walk(item, visitor);
23
+ }
24
+ } else if (child && typeof child === 'object' && child.type) {
25
+ walk(child, visitor);
26
+ }
27
+ }
28
+ }
29
+
30
+ export async function parseFileImports(filePath) {
31
+ const referenced = new Set();
32
+ const warnings = [];
33
+
34
+ let content;
35
+ try {
36
+ content = await fs.promises.readFile(filePath, 'utf8');
37
+ } catch {
38
+ return { referenced, warnings };
39
+ }
40
+
41
+ let ast;
42
+ try {
43
+ ast = parse(content, {
44
+ sourceType: 'unambiguous',
45
+ plugins: BABEL_PLUGINS,
46
+ errorRecovery: true,
47
+ });
48
+ } catch (err) {
49
+ warnings.push(`Could not parse ${filePath}: ${err.message}`);
50
+ return { referenced, warnings };
51
+ }
52
+
53
+ walk(ast, {
54
+ ImportDeclaration(node) {
55
+ if (node.source?.value) referenced.add(extractPackageName(node.source.value));
56
+ },
57
+ ExportNamedDeclaration(node) {
58
+ if (node.source?.value) referenced.add(extractPackageName(node.source.value));
59
+ },
60
+ ExportAllDeclaration(node) {
61
+ if (node.source?.value) referenced.add(extractPackageName(node.source.value));
62
+ },
63
+ CallExpression(node) {
64
+ // require('pkg') — CommonJS
65
+ const isRequire =
66
+ node.callee?.type === 'Identifier' && node.callee.name === 'require';
67
+ // import('pkg') — @babel/parser emits a CallExpression with an Import callee
68
+ const isDynamicImport = node.callee?.type === 'Import';
69
+ if (
70
+ (isRequire || isDynamicImport) &&
71
+ node.arguments?.[0]?.type === 'StringLiteral'
72
+ ) {
73
+ referenced.add(extractPackageName(node.arguments[0].value));
74
+ }
75
+ },
76
+ // ESTree-shaped dynamic import (only if a future estree plugin is enabled)
77
+ ImportExpression(node) {
78
+ if (node.source?.type === 'StringLiteral') {
79
+ referenced.add(extractPackageName(node.source.value));
80
+ }
81
+ },
82
+ });
83
+
84
+ return { referenced, warnings };
85
+ }