@contrast/dep-hooks
Intercept calls to require in order to modify or replace exports.
Usage
@contrast/agentify composes dep-hooks onto core as core.depHooks and
installs it during startup (it is depHooks in installOrder), so components
only register handlers:
core.depHooks.resolve({ name: 'express', version: '>=4' }, (xport, metadata) => {
// modify xport, or return a replacement
});
The DepHooks class is also exported (require('@contrast/dep-hooks').DepHooks)
for use outside the agent. Its constructor takes { logger, messages, appInfo }.
.resolve(descriptor, ...handlers)
Options:
-
descriptor: This can be a string or an object describing the module you want to intercept. If a string is used, or if the version field of the descriptor isn't set, all versions of the described module will be matched. Descriptors can have aname,version, andfileproperty. -
handlers: The remaining arguments are the handlers which will be invoked when the described module isrequire'd. Each handler is passed the exported module and metadata including the module's root directory and its name and version as seen in itspackage.jsonfile. If a handler returns a truthy value, then that value will replace the return value ofrequire.
Note: Registered handlers run once per unique instance of an export matching a descriptor.
.install()
This will monkey-patch Module.prototype.require so that exports can be
intercepted. The monkey-patching will only happen once regardless of how many
times this is invoked.
.uninstall()
This will reset Module.prototype.require to its value before being
monkey-patched by the instance.
Examples
Use case: For express versions greater than or equal to 4, intercept the
export of the package's lib/view.js file (relative to the package's base
directory) and apply a tag to the exported function.
core.depHooks.resolve(
{
name: 'express',
version: '>=4',
file: 'lib/view.js',
},
(xport, metadata) => {
// From the package's package.json:
// - metadata.name
// - metadata.version
// The package's root directory:
// - metadata.packageDir
// xport === function View() { /*...*/ }
xport['I was intercepted'] = true;
},
);
Use case: Intercept all versions of body-parser and replace the exported
functions.
core.depHooks.resolve({ name: 'body-parser' }, (xport, metadata) => {
// From the package's package.json:
// - metadata.name
// - metadata.version
// The package's root directory:
// - metadata.packageDir
// xport === function bodyParser() { /*...*/ }
return function bodyParserReplacement() {
/*...*/
};
});