index.js 5.7 KB

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