Debian Codegraph @

pirates/src/index.js

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