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.
@@ -1,65 +1,128 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
-
4
- const CONFIG_FILES = [
5
- 'tailwind.config.js',
6
- 'tailwind.config.ts',
7
- 'postcss.config.js',
8
- 'postcss.config.cjs',
9
- 'babel.config.js',
10
- 'babel.config.json',
11
- 'jest.config.js',
12
- 'jest.config.ts',
13
- 'vite.config.js',
14
- 'vite.config.ts',
15
- 'webpack.config.js',
16
- 'webpack.config.cjs',
17
- 'prettier.config.js',
18
- '.eslintrc',
19
- '.eslintrc.js',
20
- '.eslintrc.cjs',
21
- '.eslintrc.json',
22
- '.babelrc',
23
- '.babelrc.json',
24
- 'vitest.config.js',
25
- 'vitest.config.ts',
26
- 'tsconfig.json',
27
- '.stylelintrc',
28
- '.stylelintrc.json',
29
- 'svelte.config.js',
30
- 'astro.config.mjs',
31
- ];
32
-
33
- function escapeRegex(str) {
34
- return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
35
- }
36
-
37
- function isReferenced(content, depName) {
38
- const pattern = new RegExp(`['"\`]${escapeRegex(depName)}['"\`/]`);
39
- return pattern.test(content);
40
- }
41
-
42
- export async function scanConfigFiles(directory, dependencyNames) {
43
- if (!Array.isArray(dependencyNames) && !dependencyNames?.[Symbol.iterator]) {
44
- return new Set();
45
- }
46
-
47
- const referenced = new Set();
48
-
49
- await Promise.all(
50
- CONFIG_FILES.map(async (configFile) => {
51
- try {
52
- const content = await fs.promises.readFile(
53
- path.join(directory, configFile), 'utf8'
54
- );
55
- for (const depName of dependencyNames) {
56
- if (isReferenced(content, depName)) referenced.add(depName);
57
- }
58
- } catch {
59
- // file missing or unreadable — skip
60
- }
61
- })
62
- );
63
-
64
- return referenced;
65
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ const CONFIG_FILES = [
5
+ 'tailwind.config.js',
6
+ 'tailwind.config.ts',
7
+ 'postcss.config.js',
8
+ 'postcss.config.cjs',
9
+ 'babel.config.js',
10
+ 'babel.config.json',
11
+ 'jest.config.js',
12
+ 'jest.config.ts',
13
+ 'vite.config.js',
14
+ 'vite.config.ts',
15
+ 'webpack.config.js',
16
+ 'webpack.config.cjs',
17
+ 'prettier.config.js',
18
+ // ESLint flat config (default since ESLint 9)
19
+ 'eslint.config.js',
20
+ 'eslint.config.mjs',
21
+ 'eslint.config.cjs',
22
+ 'eslint.config.ts',
23
+ 'eslint.config.mts',
24
+ 'eslint.config.cts',
25
+ // ESLint legacy config
26
+ '.eslintrc',
27
+ '.eslintrc.js',
28
+ '.eslintrc.cjs',
29
+ '.eslintrc.json',
30
+ '.eslintrc.yaml',
31
+ '.eslintrc.yml',
32
+ '.babelrc',
33
+ '.babelrc.json',
34
+ 'vitest.config.js',
35
+ 'vitest.config.ts',
36
+ 'tsconfig.json',
37
+ '.stylelintrc',
38
+ '.stylelintrc.json',
39
+ 'svelte.config.js',
40
+ 'astro.config.mjs',
41
+ ];
42
+
43
+ function escapeRegex(str) {
44
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
45
+ }
46
+
47
+ export function isReferenced(content, depName) {
48
+ const pattern = new RegExp(`['"\`]${escapeRegex(depName)}['"\`/]`);
49
+ return pattern.test(content);
50
+ }
51
+
52
+ // Legacy ESLint configs can name plugins and shareable configs by short name
53
+ // ("react" for eslint-plugin-react), and YAML configs leave names unquoted.
54
+ const ESLINT_LEGACY_FILES = new Set([
55
+ '.eslintrc',
56
+ '.eslintrc.js',
57
+ '.eslintrc.cjs',
58
+ '.eslintrc.json',
59
+ '.eslintrc.yaml',
60
+ '.eslintrc.yml',
61
+ ]);
62
+
63
+ /**
64
+ * The short names ESLint accepts for a plugin or shareable-config package:
65
+ * eslint-plugin-react → react
66
+ * eslint-config-airbnb → airbnb
67
+ * @typescript-eslint/eslint-plugin → @typescript-eslint
68
+ * @scope/eslint-plugin-foo → @scope/foo
69
+ */
70
+ export function eslintShortNames(depName) {
71
+ const unscoped = depName.match(/^eslint-(?:plugin|config)-(.+)$/);
72
+ if (unscoped) return [unscoped[1]];
73
+
74
+ const scoped = depName.match(/^(@[^/]+)\/eslint-(?:plugin|config)(?:-(.+))?$/);
75
+ if (scoped) return [scoped[2] ? `${scoped[1]}/${scoped[2]}` : scoped[1]];
76
+
77
+ return [];
78
+ }
79
+
80
+ /**
81
+ * Whether a legacy ESLint config refers to depName, by full or short name,
82
+ * quoted or not. Matches `react`, `plugin:react/recommended` and rule keys
83
+ * like `react/jsx-key`, but not `react-hooks`.
84
+ */
85
+ export function isEslintReference(content, depName) {
86
+ const names = [depName, ...eslintShortNames(depName)];
87
+ if (names.length === 1) return false;
88
+ return names.some((name) =>
89
+ new RegExp(`(?:^|[\\s'"\`\\[,:])${escapeRegex(name)}(?:$|[\\s'"\`\\],/])`, 'm').test(content)
90
+ );
91
+ }
92
+
93
+ export async function scanConfigFiles(directory, dependencyNames, packageJson = {}) {
94
+ if (!Array.isArray(dependencyNames) && !dependencyNames?.[Symbol.iterator]) {
95
+ return new Set();
96
+ }
97
+
98
+ const referenced = new Set();
99
+
100
+ const check = (content, eslintLegacy) => {
101
+ for (const depName of dependencyNames) {
102
+ if (
103
+ isReferenced(content, depName) ||
104
+ (eslintLegacy && isEslintReference(content, depName))
105
+ ) {
106
+ referenced.add(depName);
107
+ }
108
+ }
109
+ };
110
+
111
+ await Promise.all(
112
+ CONFIG_FILES.map(async (configFile) => {
113
+ let content;
114
+ try {
115
+ content = await fs.promises.readFile(path.join(directory, configFile), 'utf8');
116
+ } catch {
117
+ return; // file missing or unreadable — skip
118
+ }
119
+ check(content, ESLINT_LEGACY_FILES.has(configFile));
120
+ })
121
+ );
122
+
123
+ if (packageJson?.eslintConfig) {
124
+ check(JSON.stringify(packageJson.eslintConfig), true);
125
+ }
126
+
127
+ return referenced;
128
+ }
@@ -0,0 +1,77 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ // Used when a package isn't installed, so its `bin` field can't be read.
5
+ // Only packages whose command differs from their package name are listed.
6
+ const KNOWN_COMMANDS = {
7
+ typescript: ['tsc', 'tsserver'],
8
+ 'npm-run-all': ['npm-run-all', 'run-s', 'run-p'],
9
+ 'npm-run-all2': ['npm-run-all', 'run-s', 'run-p'],
10
+ '@angular/cli': ['ng'],
11
+ '@nestjs/cli': ['nest'],
12
+ '@biomejs/biome': ['biome'],
13
+ '@playwright/test': ['playwright'],
14
+ '@changesets/cli': ['changeset'],
15
+ '@11ty/eleventy': ['eleventy'],
16
+ '@sveltejs/kit': ['svelte-kit'],
17
+ '@tauri-apps/cli': ['tauri'],
18
+ '@vue/cli-service': ['vue-cli-service'],
19
+ '@storybook/cli': ['storybook', 'sb'],
20
+ '@graphql-codegen/cli': ['graphql-codegen', 'gql-gen'],
21
+ 'ts-node': ['ts-node', 'ts-node-esm'],
22
+ 'webpack-cli': ['webpack-cli', 'webpack'],
23
+ 'http-server': ['http-server', 'hs'],
24
+ };
25
+
26
+ function escapeRegex(str) {
27
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
28
+ }
29
+
30
+ /**
31
+ * The command names a dependency can be invoked by in npm scripts: its own
32
+ * name plus every key of its `bin` field (read from node_modules). A string
33
+ * `bin` installs a command named after the package, minus any scope.
34
+ */
35
+ export function commandNames(directory, depName) {
36
+ const names = new Set([depName]);
37
+
38
+ let bin;
39
+ try {
40
+ const pkgPath = path.join(directory, 'node_modules', depName, 'package.json');
41
+ bin = JSON.parse(fs.readFileSync(pkgPath, 'utf8')).bin;
42
+ } catch {
43
+ for (const cmd of KNOWN_COMMANDS[depName] ?? []) names.add(cmd);
44
+ return [...names];
45
+ }
46
+
47
+ if (typeof bin === 'string') {
48
+ names.add(depName.startsWith('@') ? depName.split('/')[1] : depName);
49
+ } else if (bin && typeof bin === 'object') {
50
+ for (const cmd of Object.keys(bin)) names.add(cmd);
51
+ }
52
+ return [...names];
53
+ }
54
+
55
+ /**
56
+ * Whether any script invokes `command` as a whole word: at the start, after
57
+ * whitespace, a quote, `&&`/`||`/`;`/`(`, or a path such as node_modules/.bin/.
58
+ */
59
+ export function scriptsUse(scripts, command) {
60
+ const pattern = new RegExp(
61
+ `(?:^|[\\s'"/(;&|])${escapeRegex(command)}(?:$|[\\s'"/);&|])`
62
+ );
63
+ return scripts.some((script) => pattern.test(script));
64
+ }
65
+
66
+ export function findScriptReferences(directory, dependencyNames, scriptsObject = {}) {
67
+ const scripts = Object.values(scriptsObject);
68
+ const referenced = new Set();
69
+ if (scripts.length === 0) return referenced;
70
+
71
+ for (const dep of dependencyNames) {
72
+ if (commandNames(directory, dep).some((cmd) => scriptsUse(scripts, cmd))) {
73
+ referenced.add(dep);
74
+ }
75
+ }
76
+ return referenced;
77
+ }
@@ -1,58 +1,69 @@
1
- import axios from "axios";
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import axios from 'axios';
4
+ import { mapWithConcurrency } from './util/concurrency.js';
2
5
 
3
- export async function checkVulnerabilities(dependencies) {
4
- if (!process.env.SNYK_API_TOKEN) {
5
- return null;
6
- }
7
-
8
- const vulnerabilities = {};
6
+ const OSV_ENDPOINT = 'https://api.osv.dev/v1/query';
7
+ const CONCURRENCY = 8;
9
8
 
10
- for (const [depName, version] of Object.entries(dependencies)) {
11
- try {
12
- const issues = await checkPackageVulnerabilities(depName, version);
13
- if (issues.length > 0) {
14
- vulnerabilities[depName] = issues;
9
+ function fixedVersions(vuln, packageName) {
10
+ const fixed = new Set();
11
+ for (const affected of vuln.affected ?? []) {
12
+ if (affected.package?.name !== packageName) continue;
13
+ for (const range of affected.ranges ?? []) {
14
+ for (const event of range.events ?? []) {
15
+ if (event.fixed) fixed.add(event.fixed);
15
16
  }
16
- } catch (error) {
17
- console.error(
18
- `Failed to check vulnerabilities for ${depName}: ${error.message}`
19
- );
20
17
  }
21
18
  }
19
+ return fixed.size > 0 ? [...fixed].join(', ') : null;
20
+ }
22
21
 
23
- return vulnerabilities;
22
+ export function mapOsvVulns(vulns = [], packageName) {
23
+ return vulns.map((v) => ({
24
+ id: v.id ?? null,
25
+ severity: v.database_specific?.severity ?? 'UNKNOWN',
26
+ title: v.summary ?? v.id ?? 'Unknown vulnerability',
27
+ fixedIn: fixedVersions(v, packageName),
28
+ url: v.id ? `https://osv.dev/vulnerability/${v.id}` : null,
29
+ }));
24
30
  }
25
31
 
26
- async function checkPackageVulnerabilities(packageName, version) {
32
+ export function resolveInstalledVersion(directory, dep) {
27
33
  try {
28
- const response = await axios.get(
29
- `https://snyk.io/api/v1/test/npm/${packageName}/${version}`,
30
- {
31
- headers: {
32
- Authorization: `token ${process.env.SNYK_API_TOKEN}`,
33
- },
34
- }
35
- );
34
+ const pkgPath = path.join(directory, 'node_modules', dep, 'package.json');
35
+ return JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version || null;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
36
40
 
37
- const vulnerabilities = response.data.issues.vulnerabilities;
41
+ export async function checkVulnerabilities(dependencies, directory) {
42
+ const deps = Object.keys(dependencies);
43
+ const vulnerabilities = {};
44
+ const skipped = [];
45
+ let attempted = 0;
46
+ let errored = 0;
38
47
 
39
- return vulnerabilities.map((vuln) => ({
40
- severity: vuln.severity,
41
- title: vuln.title,
42
- description: vuln.description,
43
- }));
44
- } catch (error) {
45
- if (error.response && error.response.status === 401) {
46
- console.error(
47
- `Failed to authenticate with Snyk API. Please check your SNYK_API_TOKEN.`
48
- );
49
- } else if (error.response && error.response.status === 404) {
50
- console.error(`Package ${packageName} not found in Snyk database.`);
51
- } else {
52
- console.error(
53
- `Failed to fetch vulnerabilities for ${packageName}: ${error.message}`
54
- );
48
+ await mapWithConcurrency(deps, CONCURRENCY, async (dep) => {
49
+ const version = resolveInstalledVersion(directory, dep);
50
+ if (!version) {
51
+ skipped.push(dep);
52
+ return;
55
53
  }
56
- return [];
57
- }
54
+ attempted++;
55
+ try {
56
+ const res = await axios.post(OSV_ENDPOINT, {
57
+ version,
58
+ package: { name: dep, ecosystem: 'npm' },
59
+ });
60
+ const issues = mapOsvVulns(res.data?.vulns, dep);
61
+ if (issues.length > 0) vulnerabilities[dep] = issues;
62
+ } catch {
63
+ errored++;
64
+ }
65
+ });
66
+
67
+ const failed = attempted > 0 && errored === attempted;
68
+ return { vulnerabilities, skipped, failed };
58
69
  }
@@ -1,49 +1,69 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { glob } from 'glob';
4
- import { parseFileImports } from './ast-parser.js';
5
- import { scanConfigFiles } from './config-scanner.js';
6
-
7
- export async function findUnusedDependencies(directory, dependencies) {
8
- const allDeps = Object.keys(dependencies);
9
-
10
- const files = await glob('**/*.{js,jsx,ts,tsx}', {
11
- cwd: directory,
12
- ignore: ['**/node_modules/**', '**/dist/**', '**/build/**'],
13
- });
14
-
15
- const fileSets = await Promise.all(
16
- files.map(file => parseFileImports(path.join(directory, file)))
17
- );
18
-
19
- const allDepsSet = new Set(allDeps);
20
- const referenced = new Set();
21
- for (const set of fileSets) {
22
- for (const pkg of set) {
23
- if (allDepsSet.has(pkg)) referenced.add(pkg);
24
- }
25
- }
26
-
27
- const configReferenced = await scanConfigFiles(directory, allDeps);
28
- for (const pkg of configReferenced) referenced.add(pkg);
29
-
30
- const packageJson = JSON.parse(fs.readFileSync(path.join(directory, 'package.json'), 'utf8'));
31
- const scripts = Object.values(packageJson.scripts || {});
32
- for (const dep of allDeps) {
33
- const pattern = new RegExp(`(?:^|\\s|['"./])${dep.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:$|\\s|['"./])`);
34
- if (scripts.some(script => pattern.test(script))) referenced.add(dep);
35
- }
36
-
37
- const unusedDeps = [];
38
- for (const dep of allDeps) {
39
- if (!referenced.has(dep)) {
40
- unusedDeps.push({
41
- name: dep,
42
- version: dependencies[dep],
43
- reason: 'Not imported in any source or config file',
44
- });
45
- }
46
- }
47
-
48
- return unusedDeps;
49
- }
1
+ import path from 'path';
2
+ import { glob } from 'glob';
3
+ import { parseFileImports } from './ast-parser.js';
4
+ import { scanConfigFiles } from './config-scanner.js';
5
+ import { findScriptReferences } from './script-scanner.js';
6
+
7
+ export function resolveTypesUsage(referenced, deps) {
8
+ const used = new Set();
9
+ for (const dep of deps) {
10
+ if (!dep.startsWith('@types/')) continue;
11
+ if (dep === '@types/node') {
12
+ used.add(dep);
13
+ continue;
14
+ }
15
+ const base = dep.slice('@types/'.length);
16
+ // @types encodes scoped packages as `scope__name` → `@scope/name`
17
+ const baseName = base.includes('__') ? '@' + base.replace('__', '/') : base;
18
+ if (referenced.has(baseName)) used.add(dep);
19
+ }
20
+ return used;
21
+ }
22
+
23
+ export async function findUnusedDependencies(directory, dependencies, packageJson) {
24
+ const allDeps = Object.keys(dependencies);
25
+ const warnings = [];
26
+
27
+ const files = await glob('**/*.{js,jsx,ts,tsx,mjs,cjs}', {
28
+ cwd: directory,
29
+ ignore: ['**/node_modules/**', '**/dist/**', '**/build/**'],
30
+ });
31
+
32
+ const parsed = await Promise.all(
33
+ files.map((file) => parseFileImports(path.join(directory, file)))
34
+ );
35
+
36
+ const allDepsSet = new Set(allDeps);
37
+ const referenced = new Set();
38
+ const allReferenced = new Set();
39
+ for (const { referenced: fileRefs, warnings: fileWarnings } of parsed) {
40
+ for (const pkg of fileRefs) {
41
+ allReferenced.add(pkg);
42
+ if (allDepsSet.has(pkg)) referenced.add(pkg);
43
+ }
44
+ warnings.push(...fileWarnings);
45
+ }
46
+
47
+ const configReferenced = await scanConfigFiles(directory, allDeps, packageJson);
48
+ for (const pkg of configReferenced) referenced.add(pkg);
49
+
50
+ const scriptReferenced = findScriptReferences(directory, allDeps, packageJson.scripts);
51
+ for (const pkg of scriptReferenced) referenced.add(pkg);
52
+
53
+ // @types/* resolution: use the full referenced set (all imports, not only deps)
54
+ const typesUsed = resolveTypesUsage(allReferenced, allDeps);
55
+ for (const dep of typesUsed) referenced.add(dep);
56
+
57
+ const unusedDeps = [];
58
+ for (const dep of allDeps) {
59
+ if (!referenced.has(dep)) {
60
+ unusedDeps.push({
61
+ name: dep,
62
+ version: dependencies[dep],
63
+ reason: 'Not imported in any source or config file',
64
+ });
65
+ }
66
+ }
67
+
68
+ return { unusedDeps, warnings };
69
+ }
@@ -0,0 +1,15 @@
1
+ export async function mapWithConcurrency(items, limit, fn) {
2
+ const results = new Array(items.length);
3
+ let index = 0;
4
+
5
+ async function worker() {
6
+ while (index < items.length) {
7
+ const current = index++;
8
+ results[current] = await fn(items[current], current);
9
+ }
10
+ }
11
+
12
+ const workerCount = Math.min(limit, items.length);
13
+ await Promise.all(Array.from({ length: workerCount }, () => worker()));
14
+ return results;
15
+ }
@@ -0,0 +1,28 @@
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
+ });
@@ -0,0 +1,97 @@
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
+ });