/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const Module = require('module');
const RequireHook = require('@contrast/require-hook');
const agentEmitter = require('../agent-emitter');
const logger = require('../core/logger')('hooks:require');

class ModuleHook {
  constructor() {
    this.reqHook = new RequireHook(logger);
    this.reqHook.install();

    // RequireHook takes care of hooking but we still need to patch require to
    // emit 'require' events
    const origModLoad = Module._load;
    Module._load = function __loadAndEmit(...args) {
      const [request] = args;
      agentEmitter.emit('require', request);
      return Reflect.apply(origModLoad, this, args);
    };
  }

  /**
   * Collects instrumentation functions that will run on the specified
   * module's file at the time it is loaded via `require`.
   * @param {RequireHook.Descriptor} descriptor describes the module to hook
   * @param {Function} handler The function to run on the module at the time it is required
   */
  resolve(descriptor, handler) {
    this.reqHook.resolve(descriptor, handler);
  }

  /**
   * Reset the hooked state for a module so that it's handlers re-run.
   * NOTE: used in unit tests.
   * @param {string} name the name of the module
   */
  reset(name) {
    this.reqHook.reset(name);
  }
}

module.exports = new ModuleHook();
