index.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.addHook = addHook;
  6. var _module = _interopRequireDefault(require("module"));
  7. var _path = _interopRequireDefault(require("path"));
  8. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9. /* (c) 2015 Ari Porad (@ariporad) <http://ariporad.com>. License: ariporad.mit-license.org */
  10. const nodeModulesRegex = /^(?:.*[\\/])?node_modules(?:[\\/].*)?$/;
  11. // Guard against poorly mocked module constructors.
  12. const Module = module.constructor.length > 1 ? module.constructor : _module.default;
  13. const HOOK_RETURNED_NOTHING_ERROR_MESSAGE = '[Pirates] A hook returned a non-string, or nothing at all! This is a' + ' violation of intergalactic law!\n' + '--------------------\n' + 'If you have no idea what this means or what Pirates is, let me explain: ' + 'Pirates is a module that makes is easy to implement require hooks. One of' + " the require hooks you're using uses it. One of these require hooks" + " didn't return anything from it's handler, so we don't know what to" + ' do. You might want to debug this.';
  14. /**
  15. * @param {string} filename The filename to check.
  16. * @param {string[]} exts The extensions to hook. Should start with '.' (ex. ['.js']).
  17. * @param {Matcher|null} matcher A matcher function, will be called with path to a file. Should return truthy if the file should be hooked, falsy otherwise.
  18. * @param {boolean} ignoreNodeModules Auto-ignore node_modules. Independent of any matcher.
  19. */
  20. function shouldCompile(filename, exts, matcher, ignoreNodeModules) {
  21. if (typeof filename !== 'string') {
  22. return false;
  23. }
  24. if (exts.indexOf(_path.default.extname(filename)) === -1) {
  25. return false;
  26. }
  27. const resolvedFilename = _path.default.resolve(filename);
  28. if (ignoreNodeModules && nodeModulesRegex.test(resolvedFilename)) {
  29. return false;
  30. }
  31. if (matcher && typeof matcher === 'function') {
  32. return !!matcher(resolvedFilename);
  33. }
  34. return true;
  35. }
  36. /**
  37. * @callback Hook The hook. Accepts the code of the module and the filename.
  38. * @param {string} code
  39. * @param {string} filename
  40. * @returns {string}
  41. */
  42. /**
  43. * @callback Matcher A matcher function, will be called with path to a file.
  44. *
  45. * Should return truthy if the file should be hooked, falsy otherwise.
  46. * @param {string} path
  47. * @returns {boolean}
  48. */
  49. /**
  50. * @callback RevertFunction Reverts the hook when called.
  51. * @returns {void}
  52. */
  53. /**
  54. * @typedef {object} Options
  55. * @property {Matcher|null} [matcher=null] A matcher function, will be called with path to a file.
  56. *
  57. * Should return truthy if the file should be hooked, falsy otherwise.
  58. *
  59. * @property {string[]} [extensions=['.js']] The extensions to hook. Should start with '.' (ex. ['.js']).
  60. * @property {string[]} [exts=['.js']] The extensions to hook. Should start with '.' (ex. ['.js']).
  61. *
  62. * @property {string[]} [extension=['.js']] The extensions to hook. Should start with '.' (ex. ['.js']).
  63. * @property {string[]} [ext=['.js']] The extensions to hook. Should start with '.' (ex. ['.js']).
  64. *
  65. * @property {boolean} [ignoreNodeModules=true] Auto-ignore node_modules. Independent of any matcher.
  66. */
  67. /**
  68. * Add a require hook.
  69. *
  70. * @param {Hook} hook The hook. Accepts the code of the module and the filename. Required.
  71. * @param {Options} [opts] Options
  72. * @returns {RevertFunction} The `revert` function. Reverts the hook when called.
  73. */
  74. function addHook(hook, opts = {}) {
  75. let reverted = false;
  76. const loaders = [];
  77. const oldLoaders = [];
  78. let exts;
  79. // We need to do this to fix #15. Basically, if you use a non-standard extension (ie. .jsx), then
  80. // We modify the .js loader, then use the modified .js loader for as the base for .jsx.
  81. // This prevents that.
  82. const originalJSLoader = Module._extensions['.js'];
  83. const matcher = opts.matcher || null;
  84. const ignoreNodeModules = opts.ignoreNodeModules !== false;
  85. exts = opts.extensions || opts.exts || opts.extension || opts.ext || ['.js'];
  86. if (!Array.isArray(exts)) {
  87. exts = [exts];
  88. }
  89. exts.forEach(ext => {
  90. if (typeof ext !== 'string') {
  91. throw new TypeError(`Invalid Extension: ${ext}`);
  92. }
  93. const oldLoader = Module._extensions[ext] || originalJSLoader;
  94. oldLoaders[ext] = Module._extensions[ext];
  95. loaders[ext] = Module._extensions[ext] = function newLoader(mod, filename) {
  96. let compile;
  97. if (!reverted) {
  98. if (shouldCompile(filename, exts, matcher, ignoreNodeModules)) {
  99. compile = mod._compile;
  100. mod._compile = function _compile(code) {
  101. // reset the compile immediately as otherwise we end up having the
  102. // compile function being changed even though this loader might be reverted
  103. // Not reverting it here leads to long useless compile chains when doing
  104. // addHook -> revert -> addHook -> revert -> ...
  105. // The compile function is also anyway created new when the loader is called a second time.
  106. mod._compile = compile;
  107. const newCode = hook(code, filename);
  108. if (typeof newCode !== 'string') {
  109. throw new Error(HOOK_RETURNED_NOTHING_ERROR_MESSAGE);
  110. }
  111. return mod._compile(newCode, filename);
  112. };
  113. }
  114. }
  115. oldLoader(mod, filename);
  116. };
  117. });
  118. return function revert() {
  119. if (reverted) return;
  120. reverted = true;
  121. exts.forEach(ext => {
  122. // if the current loader for the extension is our loader then unregister it and set the oldLoader again
  123. // if not we can not do anything as we cannot remove a loader from within the loader-chain
  124. if (Module._extensions[ext] === loaders[ext]) {
  125. if (!oldLoaders[ext]) {
  126. delete Module._extensions[ext];
  127. } else {
  128. Module._extensions[ext] = oldLoaders[ext];
  129. }
  130. }
  131. });
  132. };
  133. }