-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
110 lines (95 loc) · 3.17 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
const fs = require('fs');
const path = require('path');
const resolver = require('resolve');
const { createReferenceMap, isRelative, getExtension } = require('./util');
const pathToCheckRelative = path.resolve(process.cwd(), 'app');
const referenceMap = createReferenceMap([
path.resolve(process.cwd(), 'app'),
process.cwd(),
]);
exports.interfaceVersion = 2;
exports.resolve = function resolve(source, file, config) {
const { customPathMappings = {}, customModuleMapping = {} } = config || {};
// TODO: write a test for this (when someone explicitly overrides a node_modules namespace)
if (Object.keys(customModuleMapping).length > 0) {
const baseModuleName = source.split('/')[0];
const mappingExists = customModuleMapping[baseModuleName];
if (mappingExists) {
source = source.replace(baseModuleName, mappingExists);
}
}
try {
try {
const resolvedPath = resolver.sync(source, { basedir: process.cwd() });
return {
found: true,
path: resolvedPath,
};
} catch (ex) {
if (isRelative(source)) {
const resolvedPaths = [
path.resolve(pathToCheckRelative, source),
path.resolve(path.dirname(file), source),
];
if (resolvedPaths.includes(pathToCheckRelative)) {
// this is the application path
return {
found: true,
path: path.resolve(
resolvedPaths[resolvedPaths.indexOf(pathToCheckRelative)],
'app.js'
),
};
} else {
for (const resolvedPath of resolvedPaths) {
try {
const theoreticallyWhereItShouldLive =
resolvedPath + getExtension(resolvedPath);
if (fs.existsSync(theoreticallyWhereItShouldLive)) {
return {
found: true,
path: theoreticallyWhereItShouldLive,
};
}
} catch (ex) {
// noop
}
}
}
} else {
const combinedReferencMap = { ...referenceMap, ...customPathMappings };
const found = Object.keys(combinedReferencMap).filter(match => {
const reg = new RegExp(`^${match}`);
return reg.exec(source);
});
if (found.length > 0) {
const foundMostRelevant = found.reduce(function(a, b) {
return a.length > b.length ? a : b;
});
const partFoundCheck = new RegExp(
`^${foundMostRelevant.replace('*', '(.+?)$')}`
);
const partFound = partFoundCheck.exec(source);
const theoreticallyWhereItShouldLive = path.resolve(
process.cwd(),
combinedReferencMap[foundMostRelevant].replace(
'*',
partFound[1] + getExtension(partFound[1])
)
);
if (fs.existsSync(theoreticallyWhereItShouldLive)) {
return {
found: true,
path: theoreticallyWhereItShouldLive,
};
} else {
return { found: false };
}
}
}
return { found: false };
}
} catch (ex) {
return { found: false };
}
};