index.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. var util = require('util');
  2. var path = require('path');
  3. var EE = require('events').EventEmitter;
  4. var extend = require('extend');
  5. var resolve = require('resolve');
  6. var flaggedRespawn = require('flagged-respawn');
  7. var isPlainObject = require('is-plain-object');
  8. var mapValues = require('object.map');
  9. var fined = require('fined');
  10. var findCwd = require('./lib/find_cwd');
  11. var findConfig = require('./lib/find_config');
  12. var fileSearch = require('./lib/file_search');
  13. var parseOptions = require('./lib/parse_options');
  14. var silentRequire = require('./lib/silent_require');
  15. var buildConfigName = require('./lib/build_config_name');
  16. var registerLoader = require('./lib/register_loader');
  17. var getNodeFlags = require('./lib/get_node_flags');
  18. function Liftoff(opts) {
  19. EE.call(this);
  20. extend(this, parseOptions(opts));
  21. }
  22. util.inherits(Liftoff, EE);
  23. Liftoff.prototype.requireLocal = function(module, basedir) {
  24. try {
  25. this.emit('preload:before', module);
  26. var result = require(resolve.sync(module, { basedir: basedir }));
  27. this.emit('preload:success', module, result);
  28. return result;
  29. } catch (e) {
  30. this.emit('preload:failure', module, e);
  31. }
  32. };
  33. Liftoff.prototype.buildEnvironment = function(opts) {
  34. opts = opts || {};
  35. // get modules we want to preload
  36. var preload = opts.preload || [];
  37. // ensure items to preload is an array
  38. if (!Array.isArray(preload)) {
  39. preload = [preload];
  40. }
  41. // make a copy of search paths that can be mutated for this run
  42. var searchPaths = this.searchPaths.slice();
  43. // calculate current cwd
  44. var cwd = findCwd(opts);
  45. // if cwd was provided explicitly, only use it for searching config
  46. if (opts.cwd) {
  47. searchPaths = [cwd];
  48. } else {
  49. // otherwise just search in cwd first
  50. searchPaths.unshift(cwd);
  51. }
  52. // calculate the regex to use for finding the config file
  53. var configNameSearch = buildConfigName({
  54. configName: this.configName,
  55. extensions: Object.keys(this.extensions),
  56. });
  57. // calculate configPath
  58. var configPath = findConfig({
  59. configNameSearch: configNameSearch,
  60. searchPaths: searchPaths,
  61. configPath: opts.configPath,
  62. });
  63. // if we have a config path, save the directory it resides in.
  64. var configBase;
  65. if (configPath) {
  66. configBase = path.dirname(configPath);
  67. // if cwd wasn't provided explicitly, it should match configBase
  68. if (!opts.cwd) {
  69. cwd = configBase;
  70. }
  71. }
  72. // TODO: break this out into lib/
  73. // locate local module and package next to config or explicitly provided cwd
  74. /* eslint one-var: 0 */
  75. var modulePath, modulePackage;
  76. try {
  77. var delim = path.delimiter;
  78. var paths = (process.env.NODE_PATH ? process.env.NODE_PATH.split(delim) : []);
  79. modulePath = resolve.sync(this.moduleName, { basedir: configBase || cwd, paths: paths });
  80. modulePackage = silentRequire(fileSearch('package.json', [modulePath]));
  81. } catch (e) {}
  82. // if we have a configuration but we failed to find a local module, maybe
  83. // we are developing against ourselves?
  84. if (!modulePath && configPath) {
  85. // check the package.json sibling to our config to see if its `name`
  86. // matches the module we're looking for
  87. var modulePackagePath = fileSearch('package.json', [configBase]);
  88. modulePackage = silentRequire(modulePackagePath);
  89. if (modulePackage && modulePackage.name === this.moduleName) {
  90. // if it does, our module path is `main` inside package.json
  91. modulePath = path.join(path.dirname(modulePackagePath), modulePackage.main || 'index.js');
  92. cwd = configBase;
  93. } else {
  94. // clear if we just required a package for some other project
  95. modulePackage = {};
  96. }
  97. }
  98. var exts = this.extensions;
  99. var eventEmitter = this;
  100. var configFiles = {};
  101. if (isPlainObject(this.configFiles)) {
  102. var notfound = { path: null };
  103. configFiles = mapValues(this.configFiles, function(prop, name) {
  104. var defaultObj = { name: name, cwd: cwd, extensions: exts };
  105. return mapValues(prop, function(pathObj) {
  106. var found = fined(pathObj, defaultObj) || notfound;
  107. if (isPlainObject(found.extension)) {
  108. registerLoader(eventEmitter, found.extension, found.path, cwd);
  109. }
  110. return found.path;
  111. });
  112. });
  113. }
  114. return {
  115. cwd: cwd,
  116. preload: preload,
  117. configNameSearch: configNameSearch,
  118. configPath: configPath,
  119. configBase: configBase,
  120. modulePath: modulePath,
  121. modulePackage: modulePackage || {},
  122. configFiles: configFiles,
  123. };
  124. };
  125. Liftoff.prototype.handleFlags = function(cb) {
  126. if (typeof this.v8flags === 'function') {
  127. this.v8flags(function(err, flags) {
  128. if (err) {
  129. cb(err);
  130. } else {
  131. cb(null, flags);
  132. }
  133. });
  134. } else {
  135. process.nextTick(function() {
  136. cb(null, this.v8flags);
  137. }.bind(this));
  138. }
  139. };
  140. Liftoff.prototype.prepare = function(opts, fn) {
  141. if (typeof fn !== 'function') {
  142. throw new Error('You must provide a callback function.');
  143. }
  144. process.title = this.processTitle;
  145. var completion = opts.completion;
  146. if (completion && this.completions) {
  147. return this.completions(completion);
  148. }
  149. var env = this.buildEnvironment(opts);
  150. fn.call(this, env);
  151. };
  152. Liftoff.prototype.execute = function(env, forcedFlags, fn) {
  153. if (typeof forcedFlags === 'function') {
  154. fn = forcedFlags;
  155. forcedFlags = undefined;
  156. }
  157. if (typeof fn !== 'function') {
  158. throw new Error('You must provide a callback function.');
  159. }
  160. this.handleFlags(function(err, flags) {
  161. if (err) {
  162. throw err;
  163. }
  164. flags = flags || [];
  165. flaggedRespawn(flags, process.argv, forcedFlags, execute.bind(this));
  166. function execute(ready, child, argv) {
  167. if (child !== process) {
  168. var execArgv = getNodeFlags.fromReorderedArgv(argv);
  169. this.emit('respawn', execArgv, child);
  170. }
  171. if (ready) {
  172. preloadModules(this, env);
  173. registerLoader(this, this.extensions, env.configPath, env.cwd);
  174. fn.call(this, env, argv);
  175. }
  176. }
  177. }.bind(this));
  178. };
  179. function preloadModules(inst, env) {
  180. var basedir = env.cwd;
  181. env.preload.filter(toUnique).forEach(function(module) {
  182. inst.requireLocal(module, basedir);
  183. });
  184. }
  185. function toUnique(elem, index, array) {
  186. return array.indexOf(elem) === index;
  187. }
  188. module.exports = Liftoff;