-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
131 lines (105 loc) · 3.02 KB
/
index.js
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
const path = require('path')
const fs = require('fs-extra')
const konan = require('konan')
const resolve = require('resolve')
const builtins = require('builtins')()
const ProgressBar = require('progress')
const blackList = builtins
const exts = ['.js', '.ts']
const cwd = process.cwd()
const depsPath = []
let topLevelFolder = ''
function resolveExists(path) {
if(fs.existsSync(path)) {
const stat = fs.statSync(path)
if(!stat.isFile()) {
path += '/index.js'
}
return path
}
return null
}
function resolvePkg(dep) {
try {
return resolve.sync(dep, {
basedir: cwd
})
}
catch(err) {
return null
}
}
function resolveExt(path) {
for(let ext of exts) {
if(fs.existsSync(path + ext)) {
return path + ext
}
}
return null
}
function findDeps(entry, dir) {
let fullPath = path.resolve(dir, entry)
let currentPath = null
const resolveFns = [
resolveExists.bind(null, fullPath),
resolvePkg.bind(null, entry),
resolveExt.bind(null, fullPath),
]
for(let resolveFn of resolveFns) {
let resolvedPath = resolveFn()
if(resolvedPath) {
currentPath = resolvedPath
break
}
}
if(currentPath && !blackList.includes(currentPath)) {
const currentDir = path.dirname(currentPath)
const entryFile = fs.readFileSync(currentPath, 'utf8')
const deps = konan(entryFile).strings
if (!depsPath.includes(currentPath)) {
if(!topLevelFolder) {
topLevelFolder = currentPath
}
if(!new RegExp(topLevelFolder).test(currentPath)) {
topLevelFolder = path.resolve(topLevelFolder, '../')
}
depsPath.push(currentPath)
if (deps.length) {
deps.forEach(depend => {
findDeps(depend, currentDir)
})
}
}
}
}
async function copyDeps(outputDir) {
const bar = new ProgressBar('copying [:bar] :percent', {
total: depsPath.length,
width: 50
})
await Promise.all(
depsPath.map(async depPath => {
const outputPath = getPathInOutputDir(depPath, outputDir)
fs.mkdirpSync(path.dirname(outputPath))
await fs.copyFile(depPath, outputPath)
bar.tick()
})
)
}
function getPathInOutputDir(depPath, outputDir) {
const basename = path.basename(depPath)
return outputDir + path.dirname(depPath).replace(topLevelFolder, '') + '/' + basename
}
async function extractDeps(entry, outputDir = '__output__') {
if(entry) {
console.log('analyzing...')
outputDir = path.resolve(cwd, outputDir)
findDeps(entry, cwd)
if (outputDir) {
await copyDeps(outputDir)
}
console.log(`Done! Check ${getPathInOutputDir(path.resolve(cwd, entry), outputDir)}`)
}
return Promise.resolve(depsPath)
}
module.exports = extractDeps