index.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict';
  2. var url = require('url');
  3. var got = require('got');
  4. var registryUrl = require('registry-url');
  5. var registryAuthToken = require('registry-auth-token');
  6. var semver = require('semver');
  7. module.exports = function (name, version) {
  8. var scope = name.split('/')[0];
  9. var regUrl = registryUrl(scope);
  10. var pkgUrl = url.resolve(regUrl, encodeURIComponent(name).replace(/^%40/, '@'));
  11. var authInfo = registryAuthToken(regUrl);
  12. var headers = {};
  13. if (authInfo) {
  14. headers.authorization = authInfo.type + ' ' + authInfo.token;
  15. }
  16. return got(pkgUrl, {
  17. json: true,
  18. headers: headers
  19. })
  20. .then(function (res) {
  21. var data = res.body;
  22. if (version === 'latest') {
  23. data = data.versions[data['dist-tags'].latest];
  24. } else if (version) {
  25. if (!data.versions[version]) {
  26. var versions = Object.keys(data.versions);
  27. version = semver.maxSatisfying(versions, version);
  28. if (!version) {
  29. throw new Error('Version doesn\'t exist');
  30. }
  31. }
  32. data = data.versions[version];
  33. if (!data) {
  34. throw new Error('Version doesn\'t exist');
  35. }
  36. }
  37. return data;
  38. })
  39. .catch(function (err) {
  40. if (err.statusCode === 404) {
  41. throw new Error('Package `' + name + '` doesn\'t exist');
  42. }
  43. throw err;
  44. });
  45. };