-
Notifications
You must be signed in to change notification settings - Fork 4
/
check-peer-deps.js
307 lines (268 loc) · 8.2 KB
/
check-peer-deps.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
const { exec: execCP } = require('child_process');
const { promisify } = require('util');
const { readFile: readFileFS } = require('fs');
const semver = require('semver');
const commandLineArgs = require('command-line-args');
const commandLineUsage = require('command-line-usage');
const exec = promisify(execCP);
const readFile = promisify(readFileFS);
const optionDefinitions = [
{
name: 'help',
description: 'Show this help',
type: Boolean,
alias: 'h',
},
{
name: 'debug',
description: 'Enable debug information',
type: Boolean,
alias: 'd',
defaultValue: false,
},
{
name: 'no-include-dev',
description: "Don't include development packages when checking whether a "
+ 'peerDependency has been satisfied',
defaultValue: false,
},
{
name: 'include-resolutions',
description: 'Check for resolutions section of package.json when checking whether a peerDependency has been satisfied',
defaultValue: false,
},
{
name: 'max-retries',
description: 'Specify how many retries are allowed for [underline]{npm} commands',
type: Number,
typeLabel: '[underline]{retries}',
defaultValue: 2,
},
{
name: 'directory',
description: 'The directory to check peerDependencies within. Defaults '
+ 'to the current directory.',
type: String,
typeLabel: '[underline]{directory}',
defaultValue: process.cwd(),
},
];
const usageSections = [
{
header: 'check-peer-deps',
content: 'Verifies that the peerDependency requirements of all top level '
+ 'dependencies are satisfied.',
},
{
header: 'Options',
optionList: optionDefinitions,
},
];
let options;
// Internal vars
const deps = new Map();
const npmVers = new Map();
const peerDeps = new Map();
const resolutions = new Map();
const log = (value) => {
if (options.debug) {
console.log(value);
}
};
const addDeps = (dependencies) => {
if (!dependencies) {
return;
}
Object.entries(dependencies).forEach((entry) => {
const [name, range] = entry;
deps.set(name, range);
});
};
const addResolutions = (res) => {
if (!res) {
return;
}
Object.entries(res).forEach((entry) => {
const [name, range] = entry;
resolutions.set(name, range);
});
};
const readPackageConfig = async (path) => {
let packageConfig = {};
try {
const contents = await readFile(path, { encoding: 'utf8' });
packageConfig = JSON.parse(contents);
} catch (e) {
console.error(e.message);
}
return packageConfig;
};
const npmView = async (name, keys) => {
const opts = ['view', '--json', name].concat(keys);
const command = ['npm'].concat(opts).join(' ');
log(`Running '${command}'`);
let remainingTries = options['max-retries'];
let output;
do {
try {
// eslint-disable-next-line no-await-in-loop
({ stdout: output } = await exec(command));
} catch (e) {
log(`'${command}' failed with error ${e}, retrying...`);
// Do nothing when it fails...
}
remainingTries -= 1;
} while (remainingTries > 0 && !output);
if (!output) {
console.error(`To many retries of '${command}' without success, exiting!`);
process.exit(1);
}
return JSON.parse(output);
};
const gatherNpmVer = async (range, name) => {
log(`Getting versions for ${name}@${range}...`);
const versions = await npmView(name, 'versions');
const ranges = {
versions,
minimum: semver.minSatisfying(versions, range),
maximum: semver.maxSatisfying(versions, range),
};
log(`${name}@${range}: '${ranges.minimum}' to '${ranges.maximum}'`);
npmVers.set(name, ranges);
};
const getNpmVersions = async () => {
// Gather the unique package names
const toCheck = new Set();
peerDeps.forEach((peerDependencies) => {
peerDependencies.forEach((range, name) => {
toCheck.add(name);
});
});
// Grab the versions from NPM
return Promise.all(Array.from(toCheck.values()).map(async (name) => {
if (deps.has(name) && !npmVers.has(name)) {
await gatherNpmVer(deps.get(name), name);
}
}));
};
const addPeerDeps = (name, peerDependencies) => {
if (!peerDeps.has(name)) {
peerDeps.set(name, new Map());
}
const currDeps = peerDeps.get(name);
Object.entries(peerDependencies).forEach((entry) => {
const [depName, depRange] = entry;
log(`${name} peerDependency: ${depName}@${depRange}`);
currDeps.set(depName, depRange);
});
};
// Get the peerDependencies
const getNpmPeerDep = async (range, name) => {
log(`Getting NPM peerDependencies for ${name}`);
const npmPeerDeps = await npmView(name, 'peerDependencies');
addPeerDeps(name, npmPeerDeps);
};
const getPeerDep = async (range, name) => {
log(`Getting peerDependencies for ${name}`);
// Hacktown, USA.
const packagePath = `${options.directory}/node_modules/${name}/package.json`;
const packageInfo = await readPackageConfig(packagePath);
if (!packageInfo.peerDependencies) {
return;
}
if (!npmVers.has(name)) {
await gatherNpmVer(range, name);
}
if (semver.lt(packageInfo.version, npmVers.get(name).maximum)) {
// The installed version isn't the highest allowed, check the latest from NPM
log(`${name}: Installed version lower than allowed version. Using NPM to determine peerDependencies.`);
await getNpmPeerDep(range, name);
} else {
log(`${name}: Using local package.json's to determine peerDependencies.`);
addPeerDeps(name, packageInfo.peerDependencies);
}
};
const getPeerDeps = async () => {
const promises = [];
deps.forEach((range, name) => {
promises.push(getPeerDep(range, name));
});
return Promise.all(promises);
};
// peerDependencies checks
const checkPeerDependencies = (peerDependencies, name) => {
peerDependencies.forEach((peerDepRange, peerDepName) => {
log(`Checking ${name}'s peerDependency of '${peerDepName}@${peerDepRange}'`);
let found = false;
if (deps.has(peerDepName)) {
// Verify that the minimum allowed version still satisfies the peerDep
const minAllowedVer = npmVers.get(peerDepName).minimum;
if (semver.satisfies(minAllowedVer, peerDepRange)) {
found = true;
}
}
if (resolutions.has(`${name}/${peerDepName}`)) {
const minAllowedVer = resolutions.get(`${name}/${peerDepName}`);
if (semver.satisfies(minAllowedVer, peerDepRange)) {
found = true;
}
}
if (!found) {
console.error(`A dependency satisfying ${name}'s peerDependency of '${peerDepName}@${peerDepRange}' was not found!`);
if (deps.has(peerDepName)) {
console.log(`Current: ${peerDepName}@${deps.get(peerDepName)}`);
const { versions } = npmVers.get(peerDepName);
const maxUsable = semver.maxSatisfying(versions, peerDepRange);
console.log(`Package dependencies can satisfy the peerDependency? ${maxUsable ? 'Yes' : 'No'}`);
}
}
});
};
const checkAllPeerDeps = () => {
peerDeps.forEach(checkPeerDependencies);
};
const findDependencies = async () => {
const packageConfig = await readPackageConfig(`${options.directory}/package.json`);
// Get the dependencies to process
addDeps(packageConfig.dependencies);
if (options['include-resolutions'] && packageConfig.resolutions) {
addResolutions(packageConfig.resolutions);
}
if (!options['no-include-dev'] && packageConfig.devDependencies) {
addDeps(packageConfig.devDependencies);
}
};
// Main function
async function checkPeerDeps() {
let shouldExit = false;
options = commandLineArgs(optionDefinitions);
if (options.help) {
console.log(commandLineUsage(usageSections));
shouldExit = true;
}
if (!shouldExit) {
await findDependencies();
if (deps.size < 1) {
console.error('No dependencies in the current package!');
shouldExit = true;
}
}
if (!shouldExit) {
log('Dependencies:');
deps.forEach((range, name) => { log(`${name}: ${range}`); });
log('');
log('Determining peerDependencies...');
await getPeerDeps();
log('Done.');
log('');
// Get the NPM versions required to check the peerDependencies
log('Determining peerDependency version ranges from NPM...');
await getNpmVersions();
log('Done.');
log('');
log('Checking versions...');
checkAllPeerDeps();
log('Done.');
}
}
module.exports = checkPeerDeps;