/
proxyquire.js
323 lines (275 loc) · 10.7 KB
/
proxyquire.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
'use strict'
/* jshint laxbreak:true, loopfunc:true */
var Module = require('module')
var path = require('path')
var resolve = require('resolve')
var ProxyquireError = require('./proxyquire-error')
var is = require('./is')
var assert = require('assert')
var fillMissingKeys = require('fill-keys')
var moduleNotFoundError = require('module-not-found-error')
var hasOwnProperty = Object.prototype.hasOwnProperty
function validateArguments (request, stubs) {
var msg = (function getMessage () {
if (!request) { return 'Missing argument: "request". Need it to resolve desired module.' }
if (!stubs) { return 'Missing argument: "stubs". If no stubbing is needed, use regular require instead.' }
if (!is.String(request)) { return 'Invalid argument: "request". Needs to be a requirable string that is the module to load.' }
if (!is.Object(stubs)) { return 'Invalid argument: "stubs". Needs to be an object containing overrides e.g., {"path": { extname: function () { ... } } }.' }
})()
if (msg) throw new ProxyquireError(msg)
}
function Proxyquire (parent) {
var self = this
var fn = self.load.bind(self)
var proto = Proxyquire.prototype
this._parent = parent
this._preserveCache = true
Object.keys(proto)
.forEach(function (key) {
if (is.Function(proto[key])) fn[key] = self[key].bind(self)
})
self.fn = fn
return fn
}
/**
* Disables call thru, which determines if keys of original modules will be used
* when they weren't stubbed out.
* @name noCallThru
* @function
* @private
* @return {object} The proxyquire function to allow chaining
*/
Proxyquire.prototype.noCallThru = function () {
this._noCallThru = true
return this.fn
}
/**
* Enables call thru, which determines if keys of original modules will be used
* when they weren't stubbed out.
* @name callThru
* @function
* @private
* @return {object} The proxyquire function to allow chaining
*/
Proxyquire.prototype.callThru = function () {
this._noCallThru = false
return this.fn
}
/**
* Will make proxyquire remove the requested modules from the `require.cache` in order to force
* them to be reloaded the next time they are proxyquired.
* This behavior differs from the way nodejs `require` works, but for some tests this maybe useful.
*
* @name noPreserveCache
* @function
* @private
* @return {object} The proxyquire function to allow chaining
*/
Proxyquire.prototype.noPreserveCache = function () {
this._preserveCache = false
return this.fn
}
/**
* Restores proxyquire caching behavior to match the one of nodejs `require`
*
* @name preserveCache
* @function
* @private
* @return {object} The proxyquire function to allow chaining
*/
Proxyquire.prototype.preserveCache = function () {
this._preserveCache = true
return this.fn
}
/**
* Loads a module using the given stubs instead of their normally resolved required modules.
* @param request The requirable module path to load.
* @param stubs The stubs to use. e.g., { "path": { extname: function () { ... } } }
* @return {*} A newly resolved module with the given stubs.
*/
Proxyquire.prototype.load = function (request, stubs) {
validateArguments(request, stubs)
// Find out if any of the passed stubs are global overrides
for (var key in stubs) {
var stub = stubs[key]
if (stub === null) continue
if (typeof stub === 'undefined') {
throw new ProxyquireError('Invalid stub: "' + key + '" cannot be undefined')
}
if (hasOwnProperty.call(stub, '@global')) {
this._containsGlobal = true
}
if (hasOwnProperty.call(stub, '@runtimeGlobal')) {
this._containsGlobal = true
this._containsRuntimeGlobal = true
}
}
// Ignore the module cache when return the requested module
return this._withoutCache(this._parent, stubs, request, this._parent.require.bind(this._parent, request))
}
// Resolves a stub relative to a module.
// `baseModule` is the module we're resolving from. `pathToResolve` is the
// module we want to resolve (i.e. the string passed to `require()`).
Proxyquire.prototype._resolveModule = function (baseModule, pathToResolve, stubs) {
try {
return resolve.sync(pathToResolve, {
basedir: path.dirname(baseModule),
extensions: Object.keys(require.extensions),
paths: Module.globalPaths
})
} catch (err) {
// If this is not a relative path (e.g. "foo" as opposed to "./foo"), and
// we couldn't resolve it, then we just let the path through unchanged.
// It's safe to do this, because if two different modules require "foo",
// they both expect to get back the same thing.
if (pathToResolve[0] !== '.') {
return pathToResolve
}
// If `pathToResolve` is relative, then it is *not* safe to return it,
// since a file in one directory that requires "./foo" expects to get
// back a different module than one that requires "./foo" from another
// directory. However, if !this._preserveCache, then we don't want to
// throw, since we can resolve modules that don't exist. Resolve as
// best we can. We also need to check if the relative module has @noCallThru.
var resolvedPath = path.resolve(path.dirname(baseModule), pathToResolve)
var moduleNoCallThru
if (hasOwnProperty.call(stubs, pathToResolve) && stubs[pathToResolve]) {
// pathToResolve is currently relative on stubs from _withoutCache() call
moduleNoCallThru = hasOwnProperty.call(stubs[pathToResolve], '@noCallThru') ? stubs[pathToResolve]['@noCallThru'] : undefined
} else if (hasOwnProperty.call(stubs, resolvedPath) && stubs[resolvedPath]) {
// after _withoutCache() alters stubs paths to be absolute
moduleNoCallThru = hasOwnProperty.call(stubs[resolvedPath], '@noCallThru') ? stubs[resolvedPath]['@noCallThru'] : undefined
}
if (!this._preserveCache || this._noCallThru || moduleNoCallThru) {
return resolvedPath
}
throw err
}
}
// This replaces a module's require function
Proxyquire.prototype._require = function (module, stubs, path) {
assert(typeof path === 'string', 'path must be a string')
assert(path, 'missing path')
var resolvedPath = this._resolveModule(module.filename, path, stubs)
if (hasOwnProperty.call(stubs, resolvedPath)) {
var stub = stubs[resolvedPath]
if (stub === null) {
// Mimic the module-not-found exception thrown by node.js.
throw moduleNotFoundError(path)
}
if (hasOwnProperty.call(stub, '@noCallThru') ? !stub['@noCallThru'] : !this._noCallThru) {
fillMissingKeys(stub, Module._load(path, module))
}
// We are top level or this stub is marked as global
if (module.parent === this._parent || hasOwnProperty.call(stub, '@global') || hasOwnProperty.call(stub, '@runtimeGlobal')) {
return stub
}
}
// Only ignore the cache if we have global stubs
if (this._containsRuntimeGlobal) {
return this._withoutCache(module, stubs, path, Module._load.bind(Module, path, module))
} else {
return Module._load(path, module)
}
}
Proxyquire.prototype._withoutCache = function (module, stubs, path, func) {
// Temporarily disable the cache - either per-module or globally if we have global stubs
var restoreCache = this._disableCache(module, path)
var resolvedPath = Module._resolveFilename(path, module)
// Resolve all stubs to absolute paths.
stubs = Object.keys(stubs)
.reduce(function (result, stubPath) {
var resolvedStubPath = this._resolveModule(resolvedPath, stubPath, stubs)
result[resolvedStubPath] = stubs[stubPath]
return result
}.bind(this), {})
// Override all require extension handlers
var restoreExtensionHandlers = this._overrideExtensionHandlers(module, stubs)
try {
// Execute the function that needs the module cache disabled
return func()
} finally {
// Restore the cache if we are preserving it
if (this._preserveCache) {
restoreCache()
} else {
var ids = [resolvedPath].concat(Object.keys(stubs).filter(Boolean))
ids.forEach(function (id) {
delete require.cache[id]
})
}
// Finally restore the original extension handlers
restoreExtensionHandlers()
}
}
Proxyquire.prototype._disableCache = function (module, path) {
if (this._containsGlobal) {
// empty the require cache because if we are stubbing C but requiring A,
// and if A requires B and B requires C, then B and C might be cached already
// and we'll never get the chance to return our stub
return this._disableGlobalCache()
}
// Temporarily delete the SUT from the require cache
return this._disableModuleCache(path, module)
}
Proxyquire.prototype._disableGlobalCache = function () {
var cache = require.cache
require.cache = Module._cache = {}
for (var id in cache) {
// Keep native modules (i.e. `.node` files).
// Otherwise, Node.js would throw a “Module did not self-register”
// error upon requiring it a second time.
// See https://github.com/nodejs/node/issues/5016.
if (/\.node$/.test(id)) {
require.cache[id] = cache[id]
}
}
// Return a function that will undo what we just did
return function () {
// Keep native modules which were added to the cache in the meantime.
for (var id in require.cache) {
if (/\.node$/.test(id)) {
cache[id] = require.cache[id]
}
}
require.cache = Module._cache = cache
}
}
Proxyquire.prototype._disableModuleCache = function (path, module) {
// Find the ID (location) of the SUT, relative to the parent
var id = Module._resolveFilename(path, module)
var cached = Module._cache[id]
delete Module._cache[id]
// Return a function that will undo what we just did
return function () {
if (cached) {
Module._cache[id] = cached
} else {
delete Module._cache[id]
}
}
}
Proxyquire.prototype._overrideExtensionHandlers = function (module, resolvedStubs) {
/* eslint node/no-deprecated-api: [error, {ignoreGlobalItems: ["require.extensions"]}] */
var originalExtensions = {}
var self = this
Object.keys(require.extensions).forEach(function (extension) {
// Store the original so we can restore it later
if (!originalExtensions[extension]) {
originalExtensions[extension] = require.extensions[extension]
}
// Override the default handler for the requested file extension
require.extensions[extension] = function (module, filename) {
// Override the require method for this module
module.require = self._require.bind(self, module, resolvedStubs)
return originalExtensions[extension](module, filename)
}
})
// Return a function that will undo what we just did
return function () {
Object.keys(originalExtensions).forEach(function (extension) {
require.extensions[extension] = originalExtensions[extension]
})
}
}
module.exports = Proxyquire