index.cjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. const { dirname, join } = require('path')
  2. const { existsSync, readFileSync } = require('fs')
  3. const fs = require('fs').promises
  4. const { loadPackageJSON, isPackageListed } = require('./dist/shared.cjs')
  5. function resolveModule(name, options) {
  6. try {
  7. return require.resolve(name, options)
  8. }
  9. catch (e) {
  10. return undefined
  11. }
  12. }
  13. function importModule(path) {
  14. const mod = require(path)
  15. if (mod.__esModule)
  16. return Promise.resolve(mod)
  17. else
  18. return Promise.resolve({ default: mod })
  19. }
  20. function isPackageExists(name, options) {
  21. return !!resolvePackage(name, options)
  22. }
  23. function getPackageJsonPath(name, options) {
  24. const entry = resolvePackage(name, options)
  25. if (!entry)
  26. return
  27. return searchPackageJSON(entry)
  28. }
  29. async function getPackageInfo(name, options) {
  30. const packageJsonPath = getPackageJsonPath(name, options)
  31. if (!packageJsonPath)
  32. return
  33. const pkg = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'))
  34. return {
  35. name,
  36. version: pkg.version,
  37. rootPath: dirname(packageJsonPath),
  38. packageJsonPath,
  39. packageJson: pkg,
  40. }
  41. }
  42. function getPackageInfoSync(name, options) {
  43. const packageJsonPath = getPackageJsonPath(name, options)
  44. if (!packageJsonPath)
  45. return
  46. const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf8'))
  47. return {
  48. name,
  49. version: pkg.version,
  50. rootPath: dirname(packageJsonPath),
  51. packageJsonPath,
  52. packageJson: pkg,
  53. }
  54. }
  55. function resolvePackage(name, options = {}) {
  56. try {
  57. return require.resolve(`${name}/package.json`, options)
  58. }
  59. catch {
  60. }
  61. try {
  62. return require.resolve(name, options)
  63. }
  64. catch (e) {
  65. if (e.code !== 'MODULE_NOT_FOUND')
  66. throw e
  67. return false
  68. }
  69. }
  70. function searchPackageJSON(dir) {
  71. let packageJsonPath
  72. while (true) {
  73. if (!dir)
  74. return
  75. const newDir = dirname(dir)
  76. if (newDir === dir)
  77. return
  78. dir = newDir
  79. packageJsonPath = join(dir, 'package.json')
  80. if (existsSync(packageJsonPath))
  81. break
  82. }
  83. return packageJsonPath
  84. }
  85. module.exports = {
  86. resolveModule,
  87. importModule,
  88. isPackageExists,
  89. getPackageInfo,
  90. getPackageInfoSync,
  91. loadPackageJSON,
  92. isPackageListed,
  93. }
  94. Object.defineProperty(module.exports, '__esModule', { value: true, enumerable: false })