npa.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. 'use strict'
  2. module.exports = npa
  3. module.exports.resolve = resolve
  4. module.exports.Result = Result
  5. let url
  6. let HostedGit
  7. let semver
  8. let path
  9. let validatePackageName
  10. let osenv
  11. const isWindows = process.platform === 'win32' || global.FAKE_WINDOWS
  12. const hasSlashes = isWindows ? /\\|[/]/ : /[/]/
  13. const isURL = /^(?:git[+])?[a-z]+:/i
  14. const isFilename = /[.](?:tgz|tar.gz|tar)$/i
  15. function npa (arg, where) {
  16. let name
  17. let spec
  18. if (typeof arg === 'object') {
  19. if (arg instanceof Result && (!where || where === arg.where)) {
  20. return arg
  21. } else if (arg.name && arg.rawSpec) {
  22. return npa.resolve(arg.name, arg.rawSpec, where || arg.where)
  23. } else {
  24. return npa(arg.raw, where || arg.where)
  25. }
  26. }
  27. const nameEndsAt = arg[0] === '@' ? arg.slice(1).indexOf('@') + 1 : arg.indexOf('@')
  28. const namePart = nameEndsAt > 0 ? arg.slice(0, nameEndsAt) : arg
  29. if (isURL.test(arg)) {
  30. spec = arg
  31. } else if (namePart[0] !== '@' && (hasSlashes.test(namePart) || isFilename.test(namePart))) {
  32. spec = arg
  33. } else if (nameEndsAt > 0) {
  34. name = namePart
  35. spec = arg.slice(nameEndsAt + 1)
  36. } else {
  37. if (!validatePackageName) validatePackageName = require('validate-npm-package-name')
  38. const valid = validatePackageName(arg)
  39. if (valid.validForOldPackages) {
  40. name = arg
  41. } else {
  42. spec = arg
  43. }
  44. }
  45. return resolve(name, spec, where, arg)
  46. }
  47. const isFilespec = isWindows ? /^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/ : /^(?:[.]|~[/]|[/]|[a-zA-Z]:)/
  48. function resolve (name, spec, where, arg) {
  49. const res = new Result({
  50. raw: arg,
  51. name: name,
  52. rawSpec: spec,
  53. fromArgument: arg != null
  54. })
  55. if (name) res.setName(name)
  56. if (spec && (isFilespec.test(spec) || /^file:/i.test(spec))) {
  57. return fromFile(res, where)
  58. } else if (spec && /^npm:/i.test(spec)) {
  59. return fromAlias(res, where)
  60. }
  61. if (!HostedGit) HostedGit = require('hosted-git-info')
  62. const hosted = HostedGit.fromUrl(spec, {noGitPlus: true, noCommittish: true})
  63. if (hosted) {
  64. return fromHostedGit(res, hosted)
  65. } else if (spec && isURL.test(spec)) {
  66. return fromURL(res)
  67. } else if (spec && (hasSlashes.test(spec) || isFilename.test(spec))) {
  68. return fromFile(res, where)
  69. } else {
  70. return fromRegistry(res)
  71. }
  72. }
  73. function invalidPackageName (name, valid) {
  74. const err = new Error(`Invalid package name "${name}": ${valid.errors.join('; ')}`)
  75. err.code = 'EINVALIDPACKAGENAME'
  76. return err
  77. }
  78. function invalidTagName (name) {
  79. const err = new Error(`Invalid tag name "${name}": Tags may not have any characters that encodeURIComponent encodes.`)
  80. err.code = 'EINVALIDTAGNAME'
  81. return err
  82. }
  83. function Result (opts) {
  84. this.type = opts.type
  85. this.registry = opts.registry
  86. this.where = opts.where
  87. if (opts.raw == null) {
  88. this.raw = opts.name ? opts.name + '@' + opts.rawSpec : opts.rawSpec
  89. } else {
  90. this.raw = opts.raw
  91. }
  92. this.name = undefined
  93. this.escapedName = undefined
  94. this.scope = undefined
  95. this.rawSpec = opts.rawSpec == null ? '' : opts.rawSpec
  96. this.saveSpec = opts.saveSpec
  97. this.fetchSpec = opts.fetchSpec
  98. if (opts.name) this.setName(opts.name)
  99. this.gitRange = opts.gitRange
  100. this.gitCommittish = opts.gitCommittish
  101. this.hosted = opts.hosted
  102. }
  103. Result.prototype = {}
  104. Result.prototype.setName = function (name) {
  105. if (!validatePackageName) validatePackageName = require('validate-npm-package-name')
  106. const valid = validatePackageName(name)
  107. if (!valid.validForOldPackages) {
  108. throw invalidPackageName(name, valid)
  109. }
  110. this.name = name
  111. this.scope = name[0] === '@' ? name.slice(0, name.indexOf('/')) : undefined
  112. // scoped packages in couch must have slash url-encoded, e.g. @foo%2Fbar
  113. this.escapedName = name.replace('/', '%2f')
  114. return this
  115. }
  116. Result.prototype.toString = function () {
  117. const full = []
  118. if (this.name != null && this.name !== '') full.push(this.name)
  119. const spec = this.saveSpec || this.fetchSpec || this.rawSpec
  120. if (spec != null && spec !== '') full.push(spec)
  121. return full.length ? full.join('@') : this.raw
  122. }
  123. Result.prototype.toJSON = function () {
  124. const result = Object.assign({}, this)
  125. delete result.hosted
  126. return result
  127. }
  128. function setGitCommittish (res, committish) {
  129. if (committish != null && committish.length >= 7 && committish.slice(0, 7) === 'semver:') {
  130. res.gitRange = decodeURIComponent(committish.slice(7))
  131. res.gitCommittish = null
  132. } else {
  133. res.gitCommittish = committish === '' ? null : committish
  134. }
  135. return res
  136. }
  137. const isAbsolutePath = /^[/]|^[A-Za-z]:/
  138. function resolvePath (where, spec) {
  139. if (isAbsolutePath.test(spec)) return spec
  140. if (!path) path = require('path')
  141. return path.resolve(where, spec)
  142. }
  143. function isAbsolute (dir) {
  144. if (dir[0] === '/') return true
  145. if (/^[A-Za-z]:/.test(dir)) return true
  146. return false
  147. }
  148. function fromFile (res, where) {
  149. if (!where) where = process.cwd()
  150. res.type = isFilename.test(res.rawSpec) ? 'file' : 'directory'
  151. res.where = where
  152. const spec = res.rawSpec.replace(/\\/g, '/')
  153. .replace(/^file:[/]*([A-Za-z]:)/, '$1') // drive name paths on windows
  154. .replace(/^file:(?:[/]*([~./]))?/, '$1')
  155. if (/^~[/]/.test(spec)) {
  156. // this is needed for windows and for file:~/foo/bar
  157. if (!osenv) osenv = require('osenv')
  158. res.fetchSpec = resolvePath(osenv.home(), spec.slice(2))
  159. res.saveSpec = 'file:' + spec
  160. } else {
  161. res.fetchSpec = resolvePath(where, spec)
  162. if (isAbsolute(spec)) {
  163. res.saveSpec = 'file:' + spec
  164. } else {
  165. if (!path) path = require('path')
  166. res.saveSpec = 'file:' + path.relative(where, res.fetchSpec)
  167. }
  168. }
  169. return res
  170. }
  171. function fromHostedGit (res, hosted) {
  172. res.type = 'git'
  173. res.hosted = hosted
  174. res.saveSpec = hosted.toString({noGitPlus: false, noCommittish: false})
  175. res.fetchSpec = hosted.getDefaultRepresentation() === 'shortcut' ? null : hosted.toString()
  176. return setGitCommittish(res, hosted.committish)
  177. }
  178. function unsupportedURLType (protocol, spec) {
  179. const err = new Error(`Unsupported URL Type "${protocol}": ${spec}`)
  180. err.code = 'EUNSUPPORTEDPROTOCOL'
  181. return err
  182. }
  183. function matchGitScp (spec) {
  184. // git ssh specifiers are overloaded to also use scp-style git
  185. // specifiers, so we have to parse those out and treat them special.
  186. // They are NOT true URIs, so we can't hand them to `url.parse`.
  187. //
  188. // This regex looks for things that look like:
  189. // git+ssh://git@my.custom.git.com:username/project.git#deadbeef
  190. //
  191. // ...and various combinations. The username in the beginning is *required*.
  192. const matched = spec.match(/^git\+ssh:\/\/([^:#]+:[^#]+(?:\.git)?)(?:#(.*))?$/i)
  193. return matched && !matched[1].match(/:[0-9]+\/?.*$/i) && {
  194. fetchSpec: matched[1],
  195. gitCommittish: matched[2] == null ? null : matched[2]
  196. }
  197. }
  198. function fromURL (res) {
  199. if (!url) url = require('url')
  200. const urlparse = url.parse(res.rawSpec)
  201. res.saveSpec = res.rawSpec
  202. // check the protocol, and then see if it's git or not
  203. switch (urlparse.protocol) {
  204. case 'git:':
  205. case 'git+http:':
  206. case 'git+https:':
  207. case 'git+rsync:':
  208. case 'git+ftp:':
  209. case 'git+file:':
  210. case 'git+ssh:':
  211. res.type = 'git'
  212. const match = urlparse.protocol === 'git+ssh:' && matchGitScp(res.rawSpec)
  213. if (match) {
  214. setGitCommittish(res, match.gitCommittish)
  215. res.fetchSpec = match.fetchSpec
  216. } else {
  217. setGitCommittish(res, urlparse.hash != null ? urlparse.hash.slice(1) : '')
  218. urlparse.protocol = urlparse.protocol.replace(/^git[+]/, '')
  219. delete urlparse.hash
  220. res.fetchSpec = url.format(urlparse)
  221. }
  222. break
  223. case 'http:':
  224. case 'https:':
  225. res.type = 'remote'
  226. res.fetchSpec = res.saveSpec
  227. break
  228. default:
  229. throw unsupportedURLType(urlparse.protocol, res.rawSpec)
  230. }
  231. return res
  232. }
  233. function fromAlias (res, where) {
  234. const subSpec = npa(res.rawSpec.substr(4), where)
  235. if (subSpec.type === 'alias') {
  236. throw new Error('nested aliases not supported')
  237. }
  238. if (!subSpec.registry) {
  239. throw new Error('aliases only work for registry deps')
  240. }
  241. res.subSpec = subSpec
  242. res.registry = true
  243. res.type = 'alias'
  244. res.saveSpec = null
  245. res.fetchSpec = null
  246. return res
  247. }
  248. function fromRegistry (res) {
  249. res.registry = true
  250. const spec = res.rawSpec === '' ? 'latest' : res.rawSpec
  251. // no save spec for registry components as we save based on the fetched
  252. // version, not on the argument so this can't compute that.
  253. res.saveSpec = null
  254. res.fetchSpec = spec
  255. if (!semver) semver = require('semver')
  256. const version = semver.valid(spec, true)
  257. const range = semver.validRange(spec, true)
  258. if (version) {
  259. res.type = 'version'
  260. } else if (range) {
  261. res.type = 'range'
  262. } else {
  263. if (encodeURIComponent(spec) !== spec) {
  264. throw invalidTagName(spec)
  265. }
  266. res.type = 'tag'
  267. }
  268. return res
  269. }