-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
index.js
58 lines (48 loc) · 1.29 KB
/
index.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
'use strict';
var got = require('got');
var registryUrl = require('registry-url');
var rc = require('rc');
var semver = require('semver');
module.exports = function (name, version) {
var scope = name.split('/')[0];
var url = registryUrl(scope) +
encodeURIComponent(name).replace(/^%40/, '@');
var npmrc = rc('npm');
var token = npmrc[scope + ':_authToken'] || npmrc['//registry.npmjs.org/:_authToken'];
var headers = {};
if (token) {
if (process.env.NPM_TOKEN) {
token = token.replace('${NPM_TOKEN}', process.env.NPM_TOKEN);
}
headers.authorization = 'Bearer ' + token;
}
return got(url, {
json: true,
headers: headers
})
.then(function (res) {
var data = res.body;
if (version === 'latest') {
data = data.versions[data['dist-tags'].latest];
} else if (version) {
if (!data.versions[version]) {
var versions = Object.keys(data.versions);
version = semver.maxSatisfying(versions, version);
if (!version) {
throw new Error('Version doesn\'t exist');
}
}
data = data.versions[version];
if (!data) {
throw new Error('Version doesn\'t exist');
}
}
return data;
})
.catch(function (err) {
if (err.statusCode === 404) {
throw new Error('Package `' + name + '` doesn\'t exist');
}
throw err;
});
};