/**
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 AsyncStorage = require('../../core/async-storage');
const { Scopes } = require('../../core/async-storage/scopes');
const patcher = require('../../hooks/patcher');
const moduleHook = require('../../hooks/require');
const { PATCH_TYPES } = require('../../constants');
const constants = {
  EVENTS: {
    FORM_PARSE: 'formidable-form-parse' // used when a form is parsed by formidable
  }
};

/**
 * Formidable is the multipart form parser.
 * This is how we hook into Kraken's file uploading.
 */
class Formidable {
  constructor({ agentEmitter }) {
    this.emitter = agentEmitter;
    const hook = this.hook.bind(this);
    moduleHook.resolve({ name: 'formidable' }, hook);
  }

  hook(Formidable) {
    const self = this;
    // Patch IncomingForm.parse to get access to the framework-supplied
    // callback which we can wrap. This is how the framework gets
    // the parsed multipart form.
    patcher.patch(Formidable.IncomingForm.prototype, 'parse', {
      name: 'Formidable.IncomingForm.prototype',
      patchType: PATCH_TYPES.PROTECT_SOURCE,
      alwaysRun: true,
      pre(wrapCtx) {
        const origCb = wrapCtx.args[1];
        wrapCtx.args[1] = AsyncStorage.bind(function(...cbArgs) {
          self.emitter.emit(constants.EVENTS.FORM_PARSE, cbArgs);

          // Run the callback in a scope that allows instrumentation. Otherwise,
          // the scope of the callback will be the scope in which patcher runs
          // pre/posts (NO_INSTRUMENTATION) since we're using `bind` above.
          if (origCb) {
            return Scopes.runInAllowAllScope(() => origCb.apply(this, cbArgs));
          }
        });
      }
    });
  }
}
module.exports = Formidable;
module.exports.constants = constants;
