summaryrefslogtreecommitdiff
path: root/deps/npm/node_modules/update-notifier/node_modules/latest-version/node_modules/package-json/index.js
blob: 1e97b7c860f9c756fc084d83538ce0e2c80284f9 (plain)
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
'use strict';
const url = require('url');
const got = require('got');
const registryUrl = require('registry-url');
const registryAuthToken = require('registry-auth-token');
const semver = require('semver');

module.exports = (name, version) => {
	const scope = name.split('/')[0];
	const regUrl = registryUrl(scope);
	const pkgUrl = url.resolve(regUrl, encodeURIComponent(name).replace(/^%40/, '@'));
	const authInfo = registryAuthToken(regUrl);
	const headers = {};

	if (authInfo) {
		headers.authorization = `${authInfo.type} ${authInfo.token}`;
	}

	return got(pkgUrl, {json: true, headers})
		.then(res => {
			let data = res.body;

			if (data['dist-tags'][version]) {
				data = data.versions[data['dist-tags'][version]];
			} else if (version) {
				if (!data.versions[version]) {
					const 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(err => {
			if (err.statusCode === 404) {
				throw new Error(`Package \`${name}\` doesn't exist`);
			}

			throw err;
		});
};