1'use strict'
2module.exports = npa
3module.exports.resolve = resolve
4module.exports.toPurl = toPurl
5module.exports.Result = Result
6
7const { URL } = require('url')
8const HostedGit = require('hosted-git-info')
9const semver = require('semver')
10const path = global.FAKE_WINDOWS ? require('path').win32 : require('path')
11const validatePackageName = require('validate-npm-package-name')
12const { homedir } = require('os')
13const log = require('proc-log')
14
15const isWindows = process.platform === 'win32' || global.FAKE_WINDOWS
16const hasSlashes = isWindows ? /\\|[/]/ : /[/]/
17const isURL = /^(?:git[+])?[a-z]+:/i
18const isGit = /^[^@]+@[^:.]+\.[^:]+:.+$/i
19const isFilename = /[.](?:tgz|tar.gz|tar)$/i
20
21function npa (arg, where) {
22  let name
23  let spec
24  if (typeof arg === 'object') {
25    if (arg instanceof Result && (!where || where === arg.where)) {
26      return arg
27    } else if (arg.name && arg.rawSpec) {
28      return npa.resolve(arg.name, arg.rawSpec, where || arg.where)
29    } else {
30      return npa(arg.raw, where || arg.where)
31    }
32  }
33  const nameEndsAt = arg[0] === '@' ? arg.slice(1).indexOf('@') + 1 : arg.indexOf('@')
34  const namePart = nameEndsAt > 0 ? arg.slice(0, nameEndsAt) : arg
35  if (isURL.test(arg)) {
36    spec = arg
37  } else if (isGit.test(arg)) {
38    spec = `git+ssh://${arg}`
39  } else if (namePart[0] !== '@' && (hasSlashes.test(namePart) || isFilename.test(namePart))) {
40    spec = arg
41  } else if (nameEndsAt > 0) {
42    name = namePart
43    spec = arg.slice(nameEndsAt + 1) || '*'
44  } else {
45    const valid = validatePackageName(arg)
46    if (valid.validForOldPackages) {
47      name = arg
48      spec = '*'
49    } else {
50      spec = arg
51    }
52  }
53  return resolve(name, spec, where, arg)
54}
55
56const isFilespec = isWindows ? /^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/ : /^(?:[.]|~[/]|[/]|[a-zA-Z]:)/
57
58function resolve (name, spec, where, arg) {
59  const res = new Result({
60    raw: arg,
61    name: name,
62    rawSpec: spec,
63    fromArgument: arg != null,
64  })
65
66  if (name) {
67    res.setName(name)
68  }
69
70  if (spec && (isFilespec.test(spec) || /^file:/i.test(spec))) {
71    return fromFile(res, where)
72  } else if (spec && /^npm:/i.test(spec)) {
73    return fromAlias(res, where)
74  }
75
76  const hosted = HostedGit.fromUrl(spec, {
77    noGitPlus: true,
78    noCommittish: true,
79  })
80  if (hosted) {
81    return fromHostedGit(res, hosted)
82  } else if (spec && isURL.test(spec)) {
83    return fromURL(res)
84  } else if (spec && (hasSlashes.test(spec) || isFilename.test(spec))) {
85    return fromFile(res, where)
86  } else {
87    return fromRegistry(res)
88  }
89}
90
91const defaultRegistry = 'https://registry.npmjs.org'
92
93function toPurl (arg, reg = defaultRegistry) {
94  const res = npa(arg)
95
96  if (res.type !== 'version') {
97    throw invalidPurlType(res.type, res.raw)
98  }
99
100  // URI-encode leading @ of scoped packages
101  let purl = 'pkg:npm/' + res.name.replace(/^@/, '%40') + '@' + res.rawSpec
102  if (reg !== defaultRegistry) {
103    purl += '?repository_url=' + reg
104  }
105
106  return purl
107}
108
109function invalidPackageName (name, valid, raw) {
110  // eslint-disable-next-line max-len
111  const err = new Error(`Invalid package name "${name}" of package "${raw}": ${valid.errors.join('; ')}.`)
112  err.code = 'EINVALIDPACKAGENAME'
113  return err
114}
115
116function invalidTagName (name, raw) {
117  // eslint-disable-next-line max-len
118  const err = new Error(`Invalid tag name "${name}" of package "${raw}": Tags may not have any characters that encodeURIComponent encodes.`)
119  err.code = 'EINVALIDTAGNAME'
120  return err
121}
122
123function invalidPurlType (type, raw) {
124  // eslint-disable-next-line max-len
125  const err = new Error(`Invalid type "${type}" of package "${raw}": Purl can only be generated for "version" types.`)
126  err.code = 'EINVALIDPURLTYPE'
127  return err
128}
129
130function Result (opts) {
131  this.type = opts.type
132  this.registry = opts.registry
133  this.where = opts.where
134  if (opts.raw == null) {
135    this.raw = opts.name ? opts.name + '@' + opts.rawSpec : opts.rawSpec
136  } else {
137    this.raw = opts.raw
138  }
139
140  this.name = undefined
141  this.escapedName = undefined
142  this.scope = undefined
143  this.rawSpec = opts.rawSpec || ''
144  this.saveSpec = opts.saveSpec
145  this.fetchSpec = opts.fetchSpec
146  if (opts.name) {
147    this.setName(opts.name)
148  }
149  this.gitRange = opts.gitRange
150  this.gitCommittish = opts.gitCommittish
151  this.gitSubdir = opts.gitSubdir
152  this.hosted = opts.hosted
153}
154
155Result.prototype.setName = function (name) {
156  const valid = validatePackageName(name)
157  if (!valid.validForOldPackages) {
158    throw invalidPackageName(name, valid, this.raw)
159  }
160
161  this.name = name
162  this.scope = name[0] === '@' ? name.slice(0, name.indexOf('/')) : undefined
163  // scoped packages in couch must have slash url-encoded, e.g. @foo%2Fbar
164  this.escapedName = name.replace('/', '%2f')
165  return this
166}
167
168Result.prototype.toString = function () {
169  const full = []
170  if (this.name != null && this.name !== '') {
171    full.push(this.name)
172  }
173  const spec = this.saveSpec || this.fetchSpec || this.rawSpec
174  if (spec != null && spec !== '') {
175    full.push(spec)
176  }
177  return full.length ? full.join('@') : this.raw
178}
179
180Result.prototype.toJSON = function () {
181  const result = Object.assign({}, this)
182  delete result.hosted
183  return result
184}
185
186// sets res.gitCommittish, res.gitRange, and res.gitSubdir
187function setGitAttrs (res, committish) {
188  if (!committish) {
189    res.gitCommittish = null
190    return
191  }
192
193  // for each :: separated item:
194  for (const part of committish.split('::')) {
195    // if the item has no : the n it is a commit-ish
196    if (!part.includes(':')) {
197      if (res.gitRange) {
198        throw new Error('cannot override existing semver range with a committish')
199      }
200      if (res.gitCommittish) {
201        throw new Error('cannot override existing committish with a second committish')
202      }
203      res.gitCommittish = part
204      continue
205    }
206    // split on name:value
207    const [name, value] = part.split(':')
208    // if name is semver do semver lookup of ref or tag
209    if (name === 'semver') {
210      if (res.gitCommittish) {
211        throw new Error('cannot override existing committish with a semver range')
212      }
213      if (res.gitRange) {
214        throw new Error('cannot override existing semver range with a second semver range')
215      }
216      res.gitRange = decodeURIComponent(value)
217      continue
218    }
219    if (name === 'path') {
220      if (res.gitSubdir) {
221        throw new Error('cannot override existing path with a second path')
222      }
223      res.gitSubdir = `/${value}`
224      continue
225    }
226    log.warn('npm-package-arg', `ignoring unknown key "${name}"`)
227  }
228}
229
230function fromFile (res, where) {
231  if (!where) {
232    where = process.cwd()
233  }
234  res.type = isFilename.test(res.rawSpec) ? 'file' : 'directory'
235  res.where = where
236
237  // always put the '/' on where when resolving urls, or else
238  // file:foo from /path/to/bar goes to /path/to/foo, when we want
239  // it to be /path/to/bar/foo
240
241  let specUrl
242  let resolvedUrl
243  const prefix = (!/^file:/.test(res.rawSpec) ? 'file:' : '')
244  const rawWithPrefix = prefix + res.rawSpec
245  let rawNoPrefix = rawWithPrefix.replace(/^file:/, '')
246  try {
247    resolvedUrl = new URL(rawWithPrefix, `file://${path.resolve(where)}/`)
248    specUrl = new URL(rawWithPrefix)
249  } catch (originalError) {
250    const er = new Error('Invalid file: URL, must comply with RFC 8089')
251    throw Object.assign(er, {
252      raw: res.rawSpec,
253      spec: res,
254      where,
255      originalError,
256    })
257  }
258
259  // XXX backwards compatibility lack of compliance with RFC 8089
260  if (resolvedUrl.host && resolvedUrl.host !== 'localhost') {
261    const rawSpec = res.rawSpec.replace(/^file:\/\//, 'file:///')
262    resolvedUrl = new URL(rawSpec, `file://${path.resolve(where)}/`)
263    specUrl = new URL(rawSpec)
264    rawNoPrefix = rawSpec.replace(/^file:/, '')
265  }
266  // turn file:/../foo into file:../foo
267  // for 1, 2 or 3 leading slashes since we attempted
268  // in the previous step to make it a file protocol url with a leading slash
269  if (/^\/{1,3}\.\.?(\/|$)/.test(rawNoPrefix)) {
270    const rawSpec = res.rawSpec.replace(/^file:\/{1,3}/, 'file:')
271    resolvedUrl = new URL(rawSpec, `file://${path.resolve(where)}/`)
272    specUrl = new URL(rawSpec)
273    rawNoPrefix = rawSpec.replace(/^file:/, '')
274  }
275  // XXX end RFC 8089 violation backwards compatibility section
276
277  // turn /C:/blah into just C:/blah on windows
278  let specPath = decodeURIComponent(specUrl.pathname)
279  let resolvedPath = decodeURIComponent(resolvedUrl.pathname)
280  if (isWindows) {
281    specPath = specPath.replace(/^\/+([a-z]:\/)/i, '$1')
282    resolvedPath = resolvedPath.replace(/^\/+([a-z]:\/)/i, '$1')
283  }
284
285  // replace ~ with homedir, but keep the ~ in the saveSpec
286  // otherwise, make it relative to where param
287  if (/^\/~(\/|$)/.test(specPath)) {
288    res.saveSpec = `file:${specPath.substr(1)}`
289    resolvedPath = path.resolve(homedir(), specPath.substr(3))
290  } else if (!path.isAbsolute(rawNoPrefix)) {
291    res.saveSpec = `file:${path.relative(where, resolvedPath)}`
292  } else {
293    res.saveSpec = `file:${path.resolve(resolvedPath)}`
294  }
295
296  res.fetchSpec = path.resolve(where, resolvedPath)
297  return res
298}
299
300function fromHostedGit (res, hosted) {
301  res.type = 'git'
302  res.hosted = hosted
303  res.saveSpec = hosted.toString({ noGitPlus: false, noCommittish: false })
304  res.fetchSpec = hosted.getDefaultRepresentation() === 'shortcut' ? null : hosted.toString()
305  setGitAttrs(res, hosted.committish)
306  return res
307}
308
309function unsupportedURLType (protocol, spec) {
310  const err = new Error(`Unsupported URL Type "${protocol}": ${spec}`)
311  err.code = 'EUNSUPPORTEDPROTOCOL'
312  return err
313}
314
315function fromURL (res) {
316  let rawSpec = res.rawSpec
317  res.saveSpec = rawSpec
318  if (rawSpec.startsWith('git+ssh:')) {
319    // git ssh specifiers are overloaded to also use scp-style git
320    // specifiers, so we have to parse those out and treat them special.
321    // They are NOT true URIs, so we can't hand them to URL.
322
323    // This regex looks for things that look like:
324    // git+ssh://git@my.custom.git.com:username/project.git#deadbeef
325    // ...and various combinations. The username in the beginning is *required*.
326    const matched = rawSpec.match(/^git\+ssh:\/\/([^:#]+:[^#]+(?:\.git)?)(?:#(.*))?$/i)
327    if (matched && !matched[1].match(/:[0-9]+\/?.*$/i)) {
328      res.type = 'git'
329      setGitAttrs(res, matched[2])
330      res.fetchSpec = matched[1]
331      return res
332    }
333  } else if (rawSpec.startsWith('git+file://')) {
334    // URL can't handle windows paths
335    rawSpec = rawSpec.replace(/\\/g, '/')
336  }
337  const parsedUrl = new URL(rawSpec)
338  // check the protocol, and then see if it's git or not
339  switch (parsedUrl.protocol) {
340    case 'git:':
341    case 'git+http:':
342    case 'git+https:':
343    case 'git+rsync:':
344    case 'git+ftp:':
345    case 'git+file:':
346    case 'git+ssh:':
347      res.type = 'git'
348      setGitAttrs(res, parsedUrl.hash.slice(1))
349      if (parsedUrl.protocol === 'git+file:' && /^git\+file:\/\/[a-z]:/i.test(rawSpec)) {
350        // URL can't handle drive letters on windows file paths, the host can't contain a :
351        res.fetchSpec = `git+file://${parsedUrl.host.toLowerCase()}:${parsedUrl.pathname}`
352      } else {
353        parsedUrl.hash = ''
354        res.fetchSpec = parsedUrl.toString()
355      }
356      if (res.fetchSpec.startsWith('git+')) {
357        res.fetchSpec = res.fetchSpec.slice(4)
358      }
359      break
360    case 'http:':
361    case 'https:':
362      res.type = 'remote'
363      res.fetchSpec = res.saveSpec
364      break
365
366    default:
367      throw unsupportedURLType(parsedUrl.protocol, rawSpec)
368  }
369
370  return res
371}
372
373function fromAlias (res, where) {
374  const subSpec = npa(res.rawSpec.substr(4), where)
375  if (subSpec.type === 'alias') {
376    throw new Error('nested aliases not supported')
377  }
378
379  if (!subSpec.registry) {
380    throw new Error('aliases only work for registry deps')
381  }
382
383  res.subSpec = subSpec
384  res.registry = true
385  res.type = 'alias'
386  res.saveSpec = null
387  res.fetchSpec = null
388  return res
389}
390
391function fromRegistry (res) {
392  res.registry = true
393  const spec = res.rawSpec.trim()
394  // no save spec for registry components as we save based on the fetched
395  // version, not on the argument so this can't compute that.
396  res.saveSpec = null
397  res.fetchSpec = spec
398  const version = semver.valid(spec, true)
399  const range = semver.validRange(spec, true)
400  if (version) {
401    res.type = 'version'
402  } else if (range) {
403    res.type = 'range'
404  } else {
405    if (encodeURIComponent(spec) !== spec) {
406      throw invalidTagName(spec, res.raw)
407    }
408    res.type = 'tag'
409  }
410  return res
411}
412