-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathindex.mjs
82 lines (69 loc) · 1.63 KB
/
index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { join, dirname } from 'path'
import { promises as fs, existsSync } from 'fs'
import { createCommonJS } from 'mlly'
export { loadPackageJSON, isPackageListed } from './dist/shared.mjs'
const { require } = createCommonJS(import.meta.url)
export function resolveModule(name, options) {
try {
return require.resolve(name, options)
}
catch (e) {
return undefined
}
}
export function importModule(path) {
return import(path).then((i) => {
if (i && i.default && i.default.__esModule)
return i.default
return i
})
}
export function isPackageExists(name, options) {
return !!resolvePackage(name, options)
}
export async function getPackageInfo(name, options) {
const entry = resolvePackage(name, options)
if (!entry)
return
const packageJsonPath = searchPackageJSON(entry)
if (!packageJsonPath)
return
const pkg = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'))
return {
name,
version: pkg.version,
rootPath: dirname(packageJsonPath),
packageJsonPath,
packageJson: pkg,
}
}
function resolvePackage(name, options = {}) {
try {
return require.resolve(`${name}/package.json`, options)
}
catch {
}
try {
return require.resolve(name, options)
}
catch (e) {
if (e.code !== 'MODULE_NOT_FOUND')
console.error(e)
return false
}
}
function searchPackageJSON(dir) {
let packageJsonPath
while (true) {
if (!dir)
return
const newDir = dirname(dir)
if (newDir === dir)
return
dir = newDir
packageJsonPath = join(dir, 'package.json')
if (existsSync(packageJsonPath))
break
}
return packageJsonPath
}