/**
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 path = require('path');
const semver = require('semver');
const { setCodeEventListener } = require('@contrast/fn-inspect');
const agentEmitter = require('./agent-emitter');
const logger = require('./core/logger')('contrast:library-usage');
const LibraryUsage = require('./reporter/models/app-update/library-usage');

const reportedFiles = new Set();
const type = semver.gte(process.version, '20.0.0') ? 'Function' : 'LazyCompile';

/**
 * start listening for v8 code events
 * @param {number} evalInterval how often to get code events
 */
module.exports.listen = function(evalInterval = 1) {
  const handler = (codeEvent) => {
    try {
      if (
        codeEvent.type !== type ||
        codeEvent.script.indexOf(`node_modules${path.sep}`) === -1 ||
        reportedFiles.has(codeEvent.script)
      ) {
        return;
      }

      reportedFiles.add(codeEvent.script);
      logger.trace(`new usage: ${codeEvent.script}`);

      const libUsage = new LibraryUsage(codeEvent.script);
      agentEmitter.emit('libraryUsage', libUsage);
    } catch (err) {
      logger.error('error occurred during code event handling: %o', err);
    }
  };

  setCodeEventListener(handler, evalInterval);
};
