index.js 6.1 KB

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