async.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. var fs = require('fs');
  2. var path = require('path');
  3. var caller = require('./caller');
  4. var nodeModulesPaths = require('./node-modules-paths');
  5. var normalizeOptions = require('./normalize-options');
  6. var isCore = require('is-core-module');
  7. var realpathFS = fs.realpath && typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath;
  8. var defaultIsFile = function isFile(file, cb) {
  9. fs.stat(file, function (err, stat) {
  10. if (!err) {
  11. return cb(null, stat.isFile() || stat.isFIFO());
  12. }
  13. if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
  14. return cb(err);
  15. });
  16. };
  17. var defaultIsDir = function isDirectory(dir, cb) {
  18. fs.stat(dir, function (err, stat) {
  19. if (!err) {
  20. return cb(null, stat.isDirectory());
  21. }
  22. if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
  23. return cb(err);
  24. });
  25. };
  26. var defaultRealpath = function realpath(x, cb) {
  27. realpathFS(x, function (realpathErr, realPath) {
  28. if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr);
  29. else cb(null, realpathErr ? x : realPath);
  30. });
  31. };
  32. var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) {
  33. if (opts && opts.preserveSymlinks === false) {
  34. realpath(x, cb);
  35. } else {
  36. cb(null, x);
  37. }
  38. };
  39. var getPackageCandidates = function getPackageCandidates(x, start, opts) {
  40. var dirs = nodeModulesPaths(start, opts, x);
  41. for (var i = 0; i < dirs.length; i++) {
  42. dirs[i] = path.join(dirs[i], x);
  43. }
  44. return dirs;
  45. };
  46. module.exports = function resolve(x, options, callback) {
  47. var cb = callback;
  48. var opts = options;
  49. if (typeof options === 'function') {
  50. cb = opts;
  51. opts = {};
  52. }
  53. if (typeof x !== 'string') {
  54. var err = new TypeError('Path must be a string.');
  55. return process.nextTick(function () {
  56. cb(err);
  57. });
  58. }
  59. opts = normalizeOptions(x, opts);
  60. var isFile = opts.isFile || defaultIsFile;
  61. var isDirectory = opts.isDirectory || defaultIsDir;
  62. var readFile = opts.readFile || fs.readFile;
  63. var realpath = opts.realpath || defaultRealpath;
  64. var packageIterator = opts.packageIterator;
  65. var extensions = opts.extensions || ['.js'];
  66. var includeCoreModules = opts.includeCoreModules !== false;
  67. var basedir = opts.basedir || path.dirname(caller());
  68. var parent = opts.filename || basedir;
  69. opts.paths = opts.paths || [];
  70. // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
  71. var absoluteStart = path.resolve(basedir);
  72. maybeRealpath(
  73. realpath,
  74. absoluteStart,
  75. opts,
  76. function (err, realStart) {
  77. if (err) cb(err);
  78. else init(realStart);
  79. }
  80. );
  81. var res;
  82. function init(basedir) {
  83. if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) {
  84. res = path.resolve(basedir, x);
  85. if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
  86. if ((/\/$/).test(x) && res === basedir) {
  87. loadAsDirectory(res, opts.package, onfile);
  88. } else loadAsFile(res, opts.package, onfile);
  89. } else if (includeCoreModules && isCore(x)) {
  90. return cb(null, x);
  91. } else loadNodeModules(x, basedir, function (err, n, pkg) {
  92. if (err) cb(err);
  93. else if (n) {
  94. return maybeRealpath(realpath, n, opts, function (err, realN) {
  95. if (err) {
  96. cb(err);
  97. } else {
  98. cb(null, realN, pkg);
  99. }
  100. });
  101. } else {
  102. var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
  103. moduleError.code = 'MODULE_NOT_FOUND';
  104. cb(moduleError);
  105. }
  106. });
  107. }
  108. function onfile(err, m, pkg) {
  109. if (err) cb(err);
  110. else if (m) cb(null, m, pkg);
  111. else loadAsDirectory(res, function (err, d, pkg) {
  112. if (err) cb(err);
  113. else if (d) {
  114. maybeRealpath(realpath, d, opts, function (err, realD) {
  115. if (err) {
  116. cb(err);
  117. } else {
  118. cb(null, realD, pkg);
  119. }
  120. });
  121. } else {
  122. var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
  123. moduleError.code = 'MODULE_NOT_FOUND';
  124. cb(moduleError);
  125. }
  126. });
  127. }
  128. function loadAsFile(x, thePackage, callback) {
  129. var loadAsFilePackage = thePackage;
  130. var cb = callback;
  131. if (typeof loadAsFilePackage === 'function') {
  132. cb = loadAsFilePackage;
  133. loadAsFilePackage = undefined;
  134. }
  135. var exts = [''].concat(extensions);
  136. load(exts, x, loadAsFilePackage);
  137. function load(exts, x, loadPackage) {
  138. if (exts.length === 0) return cb(null, undefined, loadPackage);
  139. var file = x + exts[0];
  140. var pkg = loadPackage;
  141. if (pkg) onpkg(null, pkg);
  142. else loadpkg(path.dirname(file), onpkg);
  143. function onpkg(err, pkg_, dir) {
  144. pkg = pkg_;
  145. if (err) return cb(err);
  146. if (dir && pkg && opts.pathFilter) {
  147. var rfile = path.relative(dir, file);
  148. var rel = rfile.slice(0, rfile.length - exts[0].length);
  149. var r = opts.pathFilter(pkg, x, rel);
  150. if (r) return load(
  151. [''].concat(extensions.slice()),
  152. path.resolve(dir, r),
  153. pkg
  154. );
  155. }
  156. isFile(file, onex);
  157. }
  158. function onex(err, ex) {
  159. if (err) return cb(err);
  160. if (ex) return cb(null, file, pkg);
  161. load(exts.slice(1), x, pkg);
  162. }
  163. }
  164. }
  165. function loadpkg(dir, cb) {
  166. if (dir === '' || dir === '/') return cb(null);
  167. if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) {
  168. return cb(null);
  169. }
  170. if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null);
  171. maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) {
  172. if (unwrapErr) return loadpkg(path.dirname(dir), cb);
  173. var pkgfile = path.join(pkgdir, 'package.json');
  174. isFile(pkgfile, function (err, ex) {
  175. // on err, ex is false
  176. if (!ex) return loadpkg(path.dirname(dir), cb);
  177. readFile(pkgfile, function (err, body) {
  178. if (err) cb(err);
  179. try { var pkg = JSON.parse(body); } catch (jsonErr) {}
  180. if (pkg && opts.packageFilter) {
  181. pkg = opts.packageFilter(pkg, pkgfile);
  182. }
  183. cb(null, pkg, dir);
  184. });
  185. });
  186. });
  187. }
  188. function loadAsDirectory(x, loadAsDirectoryPackage, callback) {
  189. var cb = callback;
  190. var fpkg = loadAsDirectoryPackage;
  191. if (typeof fpkg === 'function') {
  192. cb = fpkg;
  193. fpkg = opts.package;
  194. }
  195. maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) {
  196. if (unwrapErr) return cb(unwrapErr);
  197. var pkgfile = path.join(pkgdir, 'package.json');
  198. isFile(pkgfile, function (err, ex) {
  199. if (err) return cb(err);
  200. if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb);
  201. readFile(pkgfile, function (err, body) {
  202. if (err) return cb(err);
  203. try {
  204. var pkg = JSON.parse(body);
  205. } catch (jsonErr) {}
  206. if (pkg && opts.packageFilter) {
  207. pkg = opts.packageFilter(pkg, pkgfile);
  208. }
  209. if (pkg && pkg.main) {
  210. if (typeof pkg.main !== 'string') {
  211. var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
  212. mainError.code = 'INVALID_PACKAGE_MAIN';
  213. return cb(mainError);
  214. }
  215. if (pkg.main === '.' || pkg.main === './') {
  216. pkg.main = 'index';
  217. }
  218. loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) {
  219. if (err) return cb(err);
  220. if (m) return cb(null, m, pkg);
  221. if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb);
  222. var dir = path.resolve(x, pkg.main);
  223. loadAsDirectory(dir, pkg, function (err, n, pkg) {
  224. if (err) return cb(err);
  225. if (n) return cb(null, n, pkg);
  226. loadAsFile(path.join(x, 'index'), pkg, cb);
  227. });
  228. });
  229. return;
  230. }
  231. loadAsFile(path.join(x, '/index'), pkg, cb);
  232. });
  233. });
  234. });
  235. }
  236. function processDirs(cb, dirs) {
  237. if (dirs.length === 0) return cb(null, undefined);
  238. var dir = dirs[0];
  239. isDirectory(path.dirname(dir), isdir);
  240. function isdir(err, isdir) {
  241. if (err) return cb(err);
  242. if (!isdir) return processDirs(cb, dirs.slice(1));
  243. loadAsFile(dir, opts.package, onfile);
  244. }
  245. function onfile(err, m, pkg) {
  246. if (err) return cb(err);
  247. if (m) return cb(null, m, pkg);
  248. loadAsDirectory(dir, opts.package, ondir);
  249. }
  250. function ondir(err, n, pkg) {
  251. if (err) return cb(err);
  252. if (n) return cb(null, n, pkg);
  253. processDirs(cb, dirs.slice(1));
  254. }
  255. }
  256. function loadNodeModules(x, start, cb) {
  257. var thunk = function () { return getPackageCandidates(x, start, opts); };
  258. processDirs(
  259. cb,
  260. packageIterator ? packageIterator(x, start, thunk, opts) : thunk()
  261. );
  262. }
  263. };