async.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 basedir = opts.basedir || path.dirname(caller());
  67. var parent = opts.filename || basedir;
  68. opts.paths = opts.paths || [];
  69. // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
  70. var absoluteStart = path.resolve(basedir);
  71. maybeRealpath(
  72. realpath,
  73. absoluteStart,
  74. opts,
  75. function (err, realStart) {
  76. if (err) cb(err);
  77. else init(realStart);
  78. }
  79. );
  80. var res;
  81. function init(basedir) {
  82. if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) {
  83. res = path.resolve(basedir, x);
  84. if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
  85. if ((/\/$/).test(x) && res === basedir) {
  86. loadAsDirectory(res, opts.package, onfile);
  87. } else loadAsFile(res, opts.package, onfile);
  88. } else if (isCore(x)) {
  89. return cb(null, x);
  90. } else loadNodeModules(x, basedir, function (err, n, pkg) {
  91. if (err) cb(err);
  92. else if (n) {
  93. return maybeRealpath(realpath, n, opts, function (err, realN) {
  94. if (err) {
  95. cb(err);
  96. } else {
  97. cb(null, realN, pkg);
  98. }
  99. });
  100. } else {
  101. var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
  102. moduleError.code = 'MODULE_NOT_FOUND';
  103. cb(moduleError);
  104. }
  105. });
  106. }
  107. function onfile(err, m, pkg) {
  108. if (err) cb(err);
  109. else if (m) cb(null, m, pkg);
  110. else loadAsDirectory(res, function (err, d, pkg) {
  111. if (err) cb(err);
  112. else if (d) {
  113. maybeRealpath(realpath, d, opts, function (err, realD) {
  114. if (err) {
  115. cb(err);
  116. } else {
  117. cb(null, realD, pkg);
  118. }
  119. });
  120. } else {
  121. var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
  122. moduleError.code = 'MODULE_NOT_FOUND';
  123. cb(moduleError);
  124. }
  125. });
  126. }
  127. function loadAsFile(x, thePackage, callback) {
  128. var loadAsFilePackage = thePackage;
  129. var cb = callback;
  130. if (typeof loadAsFilePackage === 'function') {
  131. cb = loadAsFilePackage;
  132. loadAsFilePackage = undefined;
  133. }
  134. var exts = [''].concat(extensions);
  135. load(exts, x, loadAsFilePackage);
  136. function load(exts, x, loadPackage) {
  137. if (exts.length === 0) return cb(null, undefined, loadPackage);
  138. var file = x + exts[0];
  139. var pkg = loadPackage;
  140. if (pkg) onpkg(null, pkg);
  141. else loadpkg(path.dirname(file), onpkg);
  142. function onpkg(err, pkg_, dir) {
  143. pkg = pkg_;
  144. if (err) return cb(err);
  145. if (dir && pkg && opts.pathFilter) {
  146. var rfile = path.relative(dir, file);
  147. var rel = rfile.slice(0, rfile.length - exts[0].length);
  148. var r = opts.pathFilter(pkg, x, rel);
  149. if (r) return load(
  150. [''].concat(extensions.slice()),
  151. path.resolve(dir, r),
  152. pkg
  153. );
  154. }
  155. isFile(file, onex);
  156. }
  157. function onex(err, ex) {
  158. if (err) return cb(err);
  159. if (ex) return cb(null, file, pkg);
  160. load(exts.slice(1), x, pkg);
  161. }
  162. }
  163. }
  164. function loadpkg(dir, cb) {
  165. if (dir === '' || dir === '/') return cb(null);
  166. if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) {
  167. return cb(null);
  168. }
  169. if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null);
  170. maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) {
  171. if (unwrapErr) return loadpkg(path.dirname(dir), cb);
  172. var pkgfile = path.join(pkgdir, 'package.json');
  173. isFile(pkgfile, function (err, ex) {
  174. // on err, ex is false
  175. if (!ex) return loadpkg(path.dirname(dir), cb);
  176. readFile(pkgfile, function (err, body) {
  177. if (err) cb(err);
  178. try { var pkg = JSON.parse(body); } catch (jsonErr) {}
  179. if (pkg && opts.packageFilter) {
  180. pkg = opts.packageFilter(pkg, pkgfile);
  181. }
  182. cb(null, pkg, dir);
  183. });
  184. });
  185. });
  186. }
  187. function loadAsDirectory(x, loadAsDirectoryPackage, callback) {
  188. var cb = callback;
  189. var fpkg = loadAsDirectoryPackage;
  190. if (typeof fpkg === 'function') {
  191. cb = fpkg;
  192. fpkg = opts.package;
  193. }
  194. maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) {
  195. if (unwrapErr) return cb(unwrapErr);
  196. var pkgfile = path.join(pkgdir, 'package.json');
  197. isFile(pkgfile, function (err, ex) {
  198. if (err) return cb(err);
  199. if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb);
  200. readFile(pkgfile, function (err, body) {
  201. if (err) return cb(err);
  202. try {
  203. var pkg = JSON.parse(body);
  204. } catch (jsonErr) {}
  205. if (pkg && opts.packageFilter) {
  206. pkg = opts.packageFilter(pkg, pkgfile);
  207. }
  208. if (pkg && pkg.main) {
  209. if (typeof pkg.main !== 'string') {
  210. var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
  211. mainError.code = 'INVALID_PACKAGE_MAIN';
  212. return cb(mainError);
  213. }
  214. if (pkg.main === '.' || pkg.main === './') {
  215. pkg.main = 'index';
  216. }
  217. loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) {
  218. if (err) return cb(err);
  219. if (m) return cb(null, m, pkg);
  220. if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb);
  221. var dir = path.resolve(x, pkg.main);
  222. loadAsDirectory(dir, pkg, function (err, n, pkg) {
  223. if (err) return cb(err);
  224. if (n) return cb(null, n, pkg);
  225. loadAsFile(path.join(x, 'index'), pkg, cb);
  226. });
  227. });
  228. return;
  229. }
  230. loadAsFile(path.join(x, '/index'), pkg, cb);
  231. });
  232. });
  233. });
  234. }
  235. function processDirs(cb, dirs) {
  236. if (dirs.length === 0) return cb(null, undefined);
  237. var dir = dirs[0];
  238. isDirectory(path.dirname(dir), isdir);
  239. function isdir(err, isdir) {
  240. if (err) return cb(err);
  241. if (!isdir) return processDirs(cb, dirs.slice(1));
  242. loadAsFile(dir, opts.package, onfile);
  243. }
  244. function onfile(err, m, pkg) {
  245. if (err) return cb(err);
  246. if (m) return cb(null, m, pkg);
  247. loadAsDirectory(dir, opts.package, ondir);
  248. }
  249. function ondir(err, n, pkg) {
  250. if (err) return cb(err);
  251. if (n) return cb(null, n, pkg);
  252. processDirs(cb, dirs.slice(1));
  253. }
  254. }
  255. function loadNodeModules(x, start, cb) {
  256. var thunk = function () { return getPackageCandidates(x, start, opts); };
  257. processDirs(
  258. cb,
  259. packageIterator ? packageIterator(x, start, thunk, opts) : thunk()
  260. );
  261. }
  262. };