forked from dependents/node-filing-cabinet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
408 lines (336 loc) · 12.2 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
'use strict';
const path = require('path');
const fs = require('fs');
const { createMatchPath } = require('tsconfig-paths')
const debug = require('debug')('cabinet');
/*
* most js resolver are lazy-loaded (only required when needed)
* e.g. dont load requirejs when we only have commonjs modules to resolve
* this makes testing your code using this lib much easier
*/
let getModuleType;
let resolve;
let amdLookup;
const stylusLookup = require('stylus-lookup');
const sassLookup = require('sass-lookup');
let ts;
let resolveDependencyPath;
const appModulePath = require('app-module-path');
let webpackResolve;
const isRelative = require('is-relative-path');
const defaultLookups = {
'.js': jsLookup,
'.jsx': jsLookup,
'.ts': tsLookup,
'.tsx': tsLookup,
'.scss': sassLookup,
'.sass': sassLookup,
'.styl': stylusLookup,
// Less and Sass imports are very similar
'.less': sassLookup
};
/**
* @param {Object} options
* @param {String} options.partial The dependency being looked up
* @param {String} options.filename The file that contains the dependency being looked up
* @param {String|Object} [options.config] Path to a requirejs config
* @param {String} [options.configPath] For AMD resolution, if the config is an object, this represents the location of the config file.
* @param {Object} [options.nodeModulesConfig] Config for overriding the entry point defined in a package json file
* @param {String} [options.nodeModulesConfig.entry] The new value for "main" in package json
* @param {String} [options.webpackConfig] Path to the webpack config
* @param {Object} [options.ast] A preparsed AST for the file identified by filename.
* @param {Object} [options.tsConfig] Path to a typescript config file
* @param {boolean} [options.noTypeDefinitions] Whether to return '.d.ts' files or '.js' files for a dependency
*/
module.exports = function cabinet(options) {
const {
partial,
filename,
} = options;
debug('Given filename: ' + filename);
const ext = path.extname(filename);
debug('which has the extension: ' + ext);
let resolver = defaultLookups[ext];
if (!resolver) {
debug('using generic resolver');
if (!resolveDependencyPath) {
resolveDependencyPath = require('resolve-dependency-path');
}
resolver = resolveDependencyPath;
}
debug(`found a resolver for ${ext}`);
options.dependency = partial;
const result = resolver(options);
debug(`resolved path for ${partial}: ${result}`);
return result;
};
module.exports.supportedFileExtensions = Object.keys(defaultLookups);
/**
* Register a custom lookup resolver for a file extension
*
* @param {String} extension - The file extension that should use the resolver
* @param {Function} lookupStrategy - A resolver of partial paths
*/
module.exports.register = function(extension, lookupStrategy) {
defaultLookups[extension] = lookupStrategy;
if (!this.supportedFileExtensions.includes(extension)) {
this.supportedFileExtensions.push(extension);
}
};
/**
* Exposed for testing
*
* @param {Object} options
* @param {String} options.config
* @param {String} options.webpackConfig
* @param {String} options.filename
* @param {Object} options.ast
* @return {String}
*/
module.exports._getJSType = function(options = {}) {
if (!getModuleType) {
getModuleType = require('module-definition');
}
if (options.config) {
return 'amd';
}
if (options.webpackConfig) {
return 'webpack';
}
if (options.ast) {
debug('reusing the given ast');
return getModuleType.fromSource(options.ast);
}
debug('using the filename to find the module type');
return getModuleType.sync(options.filename);
};
function getCompilerOptionsFromTsConfig(tsConfig) {
if (!ts) {
ts = require('typescript');
}
let compilerOptions = {};
debug('given typescript config: ', tsConfig);
if (!tsConfig) {
debug('no tsconfig given, defaulting');
} else if (typeof tsConfig === 'string') {
debug('string tsconfig given, parsing');
try {
const tsParsedConfig = ts.readJsonConfigFile(tsConfig, ts.sys.readFile);
compilerOptions = ts.parseJsonSourceFileConfigFileContent(tsParsedConfig, ts.sys, path.dirname(tsConfig)).options;
debug('successfully parsed tsconfig');
} catch (e) {
debug('could not parse tsconfig');
throw new Error('could not read tsconfig');
}
} else {
compilerOptions = ts.convertCompilerOptionsFromJson(tsConfig.compilerOptions).options;
}
debug('processed typescript config: ', tsConfig);
debug('processed typescript config type: ', typeof tsConfig);
return compilerOptions;
}
/**
* @private
* @param {Object} options
* @param {String} options.dependency
* @param {String} options.filename
* @param {String} options.directory
* @param {String} [options.config]
* @param {String} [options.webpackConfig]
* @param {String} [options.configPath]
* @param {Object} [options.nodeModulesConfig]
* @param {Object} [options.ast]
* @return {String}
*/
function jsLookup({dependency, filename, directory, config, webpackConfig, configPath, nodeModulesConfig, ast, tsConfig}) {
const type = module.exports._getJSType({
config: config,
webpackConfig: webpackConfig,
filename: filename,
ast: ast
});
switch (type) {
case 'amd':
debug('using amd resolver');
if (!amdLookup) {
amdLookup = require('module-lookup-amd');
}
return amdLookup({
config: config,
// Optional in case a pre-parsed config is being passed in
configPath: configPath,
partial: dependency,
directory: directory,
filename: filename
});
case 'commonjs':
debug('using commonjs resolver');
return commonJSLookup({dependency, filename, directory, nodeModulesConfig, tsConfig});
case 'webpack':
debug('using webpack resolver for es6');
return resolveWebpackPath({dependency, filename, directory, webpackConfig});
case 'es6':
default:
debug('using commonjs resolver for es6');
return commonJSLookup({dependency, filename, directory, nodeModulesConfig, tsConfig});
}
}
function tsLookup({dependency, filename, tsConfig, tsConfigPath, noTypeDefinitions}) {
debug('performing a typescript lookup');
if (typeof tsConfig === 'string') {
tsConfigPath = tsConfigPath || path.dirname(tsConfig)
}
let compilerOptions = getCompilerOptionsFromTsConfig(tsConfig);
// Preserve for backcompat. Consider removing this as a breaking change.
if (!compilerOptions.module) {
compilerOptions.module = ts.ModuleKind.AMD;
}
const host = ts.createCompilerHost({});
debug('with options: ', compilerOptions);
const namedModule = ts.resolveModuleName(dependency, filename, compilerOptions, host);
let result = '';
if (namedModule.resolvedModule) {
result = namedModule.resolvedModule.resolvedFileName;
if (namedModule.resolvedModule.extension === '.d.ts' && noTypeDefinitions) {
result = ts.resolveJSModule(dependency, path.dirname(filename), host) || result;
}
} else {
const suffix = '.d.ts';
const lookUpLocations = namedModule.failedLookupLocations
.filter((string) => string.endsWith(suffix))
.map((string) => string.substr(0, string.length - suffix.length));
result = lookUpLocations.find(ts.sys.fileExists) || '';
}
if (!result && tsConfigPath && compilerOptions.baseUrl && compilerOptions.paths) {
const absoluteBaseUrl = path.join(path.dirname(tsConfigPath), compilerOptions.baseUrl)
// REF: https://github.com/dividab/tsconfig-paths#creatematchpath
const tsMatchPath = createMatchPath(absoluteBaseUrl, compilerOptions.paths)
// REF: https://github.com/dividab/tsconfig-paths#creatematchpath
const resolvedTsAliasPath = tsMatchPath(dependency, undefined, undefined, ['.tsx', '.ts', '.js', '.jsx']) // Get absolute path by ts path mapping. `undefined` if non-existent
if (resolvedTsAliasPath) {
const stat = (() => {
try {
// fs.statSync throws an error if path is non-existent
return fs.statSync(resolvedTsAliasPath)
} catch (error) {
return undefined
}
})()
if (stat) {
if (stat.isDirectory()) {
// When directory is imported, index file is resolved
for (const indexFile of ['index.ts', 'index.tsx', 'index.js', 'index.jsx']) {
const filename = path.join(resolvedTsAliasPath, indexFile)
if (fs.existsSync(filename)) {
result = filename
break;
}
}
} else {
// if the path is complete filename
result = resolvedTsAliasPath
}
} else {
// For cases a file extension is omitted when being imported
for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {
const filenameWithExt = resolvedTsAliasPath + ext
if (fs.existsSync(filenameWithExt)) {
result = filenameWithExt
break;
}
}
}
}
}
debug('result: ' + result);
return result ? path.resolve(result) : '';
}
function commonJSLookup({dependency, filename, directory, nodeModulesConfig, tsConfig}) {
if (!resolve) {
resolve = require('resolve');
}
if (!dependency) {
debug('blank dependency given. Returning early.');
return '';
}
// Need to resolve partials within the directory of the module, not filing-cabinet
const moduleLookupDir = path.join(directory, 'node_modules');
debug('adding ' + moduleLookupDir + ' to the require resolution paths');
appModulePath.addPath(moduleLookupDir);
// Make sure the partial is being resolved to the filename's context
// 3rd party modules will not be relative
if (dependency[0] === '.') {
dependency = path.resolve(path.dirname(filename), dependency);
}
let result = '';
// Allows us to configure what is used as the "main" entry point
function packageFilter(packageJson) {
packageJson.main = packageJson[nodeModulesConfig.entry] ? packageJson[nodeModulesConfig.entry] : packageJson.main;
return packageJson;
}
const tsCompilerOptions = getCompilerOptionsFromTsConfig(tsConfig);
const allowMIxedJsAndTs = tsCompilerOptions.allowJs;
let extensions = ['.js', '.jsx'];
if (allowMIxedJsAndTs) {
extensions = extensions.concat(['.ts', '.tsx']);
}
try {
result = resolve.sync(dependency, {
extensions,
basedir: directory,
packageFilter: nodeModulesConfig && nodeModulesConfig.entry ? packageFilter : undefined,
// Add fileDir to resolve index.js files in that dir
moduleDirectory: ['node_modules', directory]
});
debug('resolved path: ' + result);
} catch (e) {
debug('could not resolve ' + dependency);
}
return result;
}
function resolveWebpackPath({dependency, filename, directory, webpackConfig}) {
if (!webpackResolve) {
webpackResolve = require('enhanced-resolve');
}
webpackConfig = path.resolve(webpackConfig);
let loadedConfig;
try {
loadedConfig = require(webpackConfig);
if (typeof loadedConfig === 'function') {
loadedConfig = loadedConfig();
}
} catch (e) {
debug('error loading the webpack config at ' + webpackConfig);
debug(e.message);
debug(e.stack);
return '';
}
const resolveConfig = Object.assign({}, loadedConfig.resolve);
if (!resolveConfig.modules && (resolveConfig.root || resolveConfig.modulesDirectories)) {
resolveConfig.modules = [];
if (resolveConfig.root) {
resolveConfig.modules = resolveConfig.modules.concat(resolveConfig.root);
}
if (resolveConfig.modulesDirectories) {
resolveConfig.modules = resolveConfig.modules.concat(resolveConfig.modulesDirectories);
}
}
try {
const resolver = webpackResolve.create.sync(resolveConfig);
// We don't care about what the loader resolves the dependency to
// we only wnat the path of the resolved file
dependency = stripLoader(dependency);
const lookupPath = isRelative(dependency) ? path.dirname(filename) : directory;
return resolver(lookupPath, dependency);
} catch (e) {
debug('error when resolving ' + dependency);
debug(e.message);
debug(e.stack);
return '';
}
}
function stripLoader(dependency) {
const exclamationLocation = dependency.indexOf('!');
if (exclamationLocation === -1) { return dependency; }
return dependency.slice(exclamationLocation + 1);
}