index.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const {format} = require('util')
  2. const semver = require('semver')
  3. const checkEngine = (target, npmVer, nodeVer, force = false) => {
  4. const nodev = force ? null : nodeVer
  5. const eng = target.engines
  6. const opt = { includePrerelease: true }
  7. if (!eng) {
  8. return
  9. }
  10. const nodeFail = nodev && eng.node && !semver.satisfies(nodev, eng.node, opt)
  11. const npmFail = npmVer && eng.npm && !semver.satisfies(npmVer, eng.npm, opt)
  12. if (nodeFail || npmFail) {
  13. throw Object.assign(new Error('Unsupported engine'), {
  14. pkgid: target._id,
  15. current: { node: nodeVer, npm: npmVer },
  16. required: eng,
  17. code: 'EBADENGINE'
  18. })
  19. }
  20. }
  21. const checkPlatform = (target, force = false) => {
  22. if (force) {
  23. return
  24. }
  25. const platform = process.platform
  26. const arch = process.arch
  27. const osOk = target.os ? checkList(platform, target.os) : true
  28. const cpuOk = target.cpu ? checkList(arch, target.cpu) : true
  29. if (!osOk || !cpuOk) {
  30. throw Object.assign(new Error('Unsupported platform'), {
  31. pkgid: target._id,
  32. current: {
  33. os: platform,
  34. cpu: arch
  35. },
  36. required: {
  37. os: target.os,
  38. cpu: target.cpu
  39. },
  40. code: 'EBADPLATFORM'
  41. })
  42. }
  43. }
  44. const checkList = (value, list) => {
  45. if (typeof list === 'string') {
  46. list = [list]
  47. }
  48. if (list.length === 1 && list[0] === 'any') {
  49. return true
  50. }
  51. // match none of the negated values, and at least one of the
  52. // non-negated values, if any are present.
  53. let negated = 0
  54. let match = false
  55. for (const entry of list) {
  56. const negate = entry.charAt(0) === '!'
  57. const test = negate ? entry.slice(1) : entry
  58. if (negate) {
  59. negated ++
  60. if (value === test) {
  61. return false
  62. }
  63. } else {
  64. match = match || value === test
  65. }
  66. }
  67. return match || negated === list.length
  68. }
  69. module.exports = {
  70. checkEngine,
  71. checkPlatform
  72. }