UNPKG

2.3 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', {
4 value: true
5});
6exports.default = nodeModulesPaths;
7
8function _path() {
9 const data = _interopRequireDefault(require('path'));
10
11 _path = function _path() {
12 return data;
13 };
14
15 return data;
16}
17
18function _realpathNative() {
19 const data = require('realpath-native');
20
21 _realpathNative = function _realpathNative() {
22 return data;
23 };
24
25 return data;
26}
27
28function _interopRequireDefault(obj) {
29 return obj && obj.__esModule ? obj : {default: obj};
30}
31
32/**
33 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
34 *
35 * This source code is licensed under the MIT license found in the
36 * LICENSE file in the root directory of this source tree.
37 *
38 * Adapted from: https://github.com/substack/node-resolve
39 */
40function nodeModulesPaths(basedir, options) {
41 const modules =
42 options && options.moduleDirectory
43 ? Array.from(options.moduleDirectory)
44 : ['node_modules']; // ensure that `basedir` is an absolute path at this point,
45 // resolving against the process' current working directory
46
47 const basedirAbs = _path().default.resolve(basedir);
48
49 let prefix = '/';
50
51 if (/^([A-Za-z]:)/.test(basedirAbs)) {
52 prefix = '';
53 } else if (/^\\\\/.test(basedirAbs)) {
54 prefix = '\\\\';
55 } // The node resolution algorithm (as implemented by NodeJS and TypeScript)
56 // traverses parents of the physical path, not the symlinked path
57
58 let physicalBasedir;
59
60 try {
61 physicalBasedir = (0, _realpathNative().sync)(basedirAbs);
62 } catch (err) {
63 // realpath can throw, e.g. on mapped drives
64 physicalBasedir = basedirAbs;
65 }
66
67 const paths = [physicalBasedir];
68
69 let parsed = _path().default.parse(physicalBasedir);
70
71 while (parsed.dir !== paths[paths.length - 1]) {
72 paths.push(parsed.dir);
73 parsed = _path().default.parse(parsed.dir);
74 }
75
76 const dirs = paths
77 .reduce(
78 (dirs, aPath) =>
79 dirs.concat(
80 modules.map(moduleDir =>
81 _path().default.isAbsolute(moduleDir)
82 ? aPath === basedirAbs
83 ? moduleDir
84 : ''
85 : _path().default.join(prefix, aPath, moduleDir)
86 )
87 ),
88 []
89 )
90 .filter(dir => dir !== '');
91 return options.paths ? dirs.concat(options.paths) : dirs;
92}