docs.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const log = require('npmlog')
  2. const pacote = require('pacote')
  3. const openUrl = require('./utils/open-url.js')
  4. const hostedFromMani = require('./utils/hosted-git-info-from-manifest.js')
  5. const BaseCommand = require('./base-command.js')
  6. class Docs extends BaseCommand {
  7. /* istanbul ignore next - see test/lib/load-all-commands.js */
  8. static get description () {
  9. return 'Open documentation for a package in a web browser'
  10. }
  11. /* istanbul ignore next - see test/lib/load-all-commands.js */
  12. static get name () {
  13. return 'docs'
  14. }
  15. /* istanbul ignore next - see test/lib/load-all-commands.js */
  16. static get params () {
  17. return [
  18. 'browser',
  19. 'registry',
  20. 'workspace',
  21. 'workspaces',
  22. 'include-workspace-root',
  23. ]
  24. }
  25. /* istanbul ignore next - see test/lib/load-all-commands.js */
  26. static get usage () {
  27. return ['[<pkgname> [<pkgname> ...]]']
  28. }
  29. exec (args, cb) {
  30. this.docs(args).then(() => cb()).catch(cb)
  31. }
  32. execWorkspaces (args, filters, cb) {
  33. this.docsWorkspaces(args, filters).then(() => cb()).catch(cb)
  34. }
  35. async docs (args) {
  36. if (!args || !args.length)
  37. args = ['.']
  38. await Promise.all(args.map(pkg => this.getDocs(pkg)))
  39. }
  40. async docsWorkspaces (args, filters) {
  41. await this.setWorkspaces(filters)
  42. return this.docs(this.workspacePaths)
  43. }
  44. async getDocs (pkg) {
  45. const opts = { ...this.npm.flatOptions, fullMetadata: true }
  46. const mani = await pacote.manifest(pkg, opts)
  47. const url = this.getDocsUrl(mani)
  48. log.silly('docs', 'url', url)
  49. await openUrl(this.npm, url, `${mani.name} docs available at the following URL`)
  50. }
  51. getDocsUrl (mani) {
  52. if (mani.homepage)
  53. return mani.homepage
  54. const info = hostedFromMani(mani)
  55. if (info)
  56. return info.docs()
  57. return 'https://www.npmjs.com/package/' + mani.name
  58. }
  59. }
  60. module.exports = Docs