-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
97 lines (82 loc) · 2.84 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
var fs = require('fs');
var path = require('path');
var callerId = require('caller-id');
var glob = require('glob');
module.exports = function (options){
var defaultOptions = {
nodeModulesPath: './node_modules',
packageJsonPath: './package.json',
includeDev: false,
showWarnings: false
};
options = _extend(defaultOptions, (options || {}));
var buffer, packages, key, keys, caller, override;
buffer = fs.readFileSync(options.packageJsonPath);
packages = JSON.parse(buffer.toString());
keys = [];
var overrides = packages.overrides || {};
if(!path.isAbsolute(options.nodeModulesPath)) {
caller = callerId.getData();
options.nodeModulesPath = path.join(path.dirname(caller.filePath), options.nodeModulesPath);
}
if(!path.isAbsolute(options.packageJsonPath)) {
caller = callerId.getData();
options.packageJsonPath = path.join(path.dirname(caller.filePath), options.packageJsonPath);
}
for (key in packages.dependencies) {
override = overrides[key] || {};
keys = keys.concat(getMainFiles(options.nodeModulesPath + "/" + key, override, options.showWarnings));
}
if (options.includeDev) {
for (key in packages.devDependencies) {
override = overrides[key] || {};
keys = keys.concat(getMainFiles(options.nodeModulesPath + "/" + key, override, options.showWarnings));
}
}
return keys;
};
function _extend(object, source) {
var obj = {};
for (var key in object) {
obj[key] = source[key] || object[key];
}
return obj;
}
/**
* Gets the main files for a NPM module
* @param {String} modulePath Path to
* @param {Array|String} override Array of overrides for module
* @return {Array} Array of files for module
*/
function getMainFiles(modulePath, override, showWarnings) {
var json;
var files = [];
try {
json = JSON.parse(fs.readFileSync(modulePath + '/package.json'));
} catch (e) { /* it's ok */ }
if(override.ignore){
return [];
}
//Main override as string
if(typeof override.main == 'string'){
files = files.concat(
glob.sync(path.resolve(modulePath + "/" + override.main))
);
//Main override as array
} else if(typeof override.main == 'object') {
override.main.forEach( om => {
files = files.concat(
glob.sync(path.resolve(modulePath + "/" + om))
);
});
//No main override
} else if(json && json.main){
files = files.concat(
glob.sync(path.resolve(modulePath + "/" + json.main))
);
}
if (showWarnings && !files.length) {
console.warn('npmfiles: No main files found for module ' + path.relative(`${process.cwd()}/node_modules`, modulePath));
}
return files;
}