/**
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 Brackets = require('./brackets');
const Comments = require('./comments');
const Concatenations = require('./concatenations');
const Placeholders = require('./placeholders');

/**
 * @module lib/util/JSCleanString
 */

/**
 * Normalizes a string that is presumed to have JavaScript code in it.
 * Note : Most instance methods are chainable, BUT, the order in which
 *        they are chained may have an effect on the resulting string.
 *        Results will depend both on the order of the methods as well
 *        as the characteristics of the string being normalized.
 */
class JSCleanString extends require('./clean-string-base') {
  constructor(string) {
    super(string);
    this._value = string;
  }

  /**
   * Removes all cases of inline or block comments from the
   * instance's underlying value.
   */
  cleanComments() {
    this._value = Comments.clean(this._value);
    return this;
  }

  /**
   * Mutative. Scans the string and merges all string concatenations into
   * a single string representation as if the concatenations were applied.
   * Examples:
   *   `'a'+"b"` => `ab`
   *   'some text `in-a-quote` + "!"' => 'some text `in-a-quote!`'
   * If any strings that were in the concatenation were template strings,
   * then the resultant string will use the <code>`</code> character.
   */
  cleanStringConcats() {
    this._value = Concatenations.clean(this._value);
    return this;
  }

  /**
   * Converts substrings that look like JavaScript bracket
   * accessors (['abcd']) into dot accessor equivalents.
   */
  cleanBrackets() {
    this._value = Brackets.clean(this._value);
    return this;
  }

  /**
   * Looks at template string placeholders and attempts to
   * remove them if their values are
   * - string literals
   * - ... more to come?
   */
  cleanPlaceholders() {
    this._value = Placeholders.clean(this._value);
    return this;
  }

  /**
   * Performs all cleaning operations on the given string.
   * @param   {String} str The string to clean.
   * @returns {String}
   */
  static clean(str) {
    return new JSCleanString(str)
      .cleanComments() /** 1 */
      .cleanStringConcats() /** 2 */
      .cleanPlaceholders() /** 3 */
      .cleanBrackets(); /** 4 */
  }
}

module.exports = JSCleanString;
