"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ApiClient = void 0;
var _superagent = _interopRequireDefault(require("superagent"));
var _Paginable = _interopRequireDefault(require("./Paginable"));
var _uuid = require("uuid");
var _superagentRetryDelay = _interopRequireDefault(require("superagent-retry-delay"));
var _https = _interopRequireDefault(require("https"));
var _fs2 = _interopRequireDefault(require("fs"));
var _path = _interopRequireDefault(require("path"));
var _buffer = require("buffer");
var _ApiResponseMetadata = _interopRequireDefault(require("./models/common/v1/response/ApiResponseMetadata"));
var _Flag = _interopRequireDefault(require("./models/common/v1/config/Flag"));
var _ApiClient;
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _wrapRegExp() { _wrapRegExp = function _wrapRegExp(e, r) { return new BabelRegExp(e, void 0, r); }; var e = RegExp.prototype, r = new WeakMap(); function BabelRegExp(e, t, p) { var o = RegExp(e, t); return r.set(o, p || r.get(e)), _setPrototypeOf(o, BabelRegExp.prototype); } function buildGroups(e, t) { var p = r.get(t); return Object.keys(p).reduce(function (r, t) { var o = p[t]; if ("number" == typeof o) r[t] = e[o];else { for (var i = 0; void 0 === e[o[i]] && i + 1 < o.length;) i++; r[t] = e[o[i]]; } return r; }, Object.create(null)); } return _inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (r) { var t = e.exec.call(this, r); if (t) { t.groups = buildGroups(t, this); var p = t.indices; p && (p.groups = buildGroups(p, this)); } return t; }, BabelRegExp.prototype[Symbol.replace] = function (t, p) { if ("string" == typeof p) { var o = r.get(this); return e[Symbol.replace].call(this, t, p.replace(/\$<([^>]+)>/g, function (e, r) { var t = o[r]; return "$" + (Array.isArray(t) ? t.join("$") : t); })); } if ("function" == typeof p) { var i = this; return e[Symbol.replace].call(this, t, function () { var e = arguments; return "object" != _typeof(e[e.length - 1]) && (e = [].slice.call(e)).push(buildGroups(e, i)), p.apply(this, e); }); } return e[Symbol.replace].call(this, t, p); }, _wrapRegExp.apply(this, arguments); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }
function _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); }
function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }
function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }
function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); } /*
 * Nutanix Networking APIs
 *
 * OpenAPI spec version: 4.0.1
 *
 * NOTE: This class is auto generated by the Open API Dev Platform.
 *
 * Open API Dev Platform Codegen version: 16.9.0.8546-RELEASE
 *
 * Do not edit the class manually.
 *
 */
(0, _superagentRetryDelay["default"])(_superagent["default"]);
/**
* Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an
* application to use this class directly - the *Api and model classes provide the public API for the service. The
* contents of this file should be regarded as internal but are documented for completeness.
* @module ApiClient
* @version 4.0.1
*/
var _protocol = /*#__PURE__*/new WeakMap();
var _cookie = /*#__PURE__*/new WeakMap();
var _logger = /*#__PURE__*/new WeakMap();
var _verifySslFlag = /*#__PURE__*/new WeakMap();
var _defaultConnectTimeout = /*#__PURE__*/new WeakMap();
var _defaultReadTimeout = /*#__PURE__*/new WeakMap();
var _defaultMaxTimeout = /*#__PURE__*/new WeakMap();
var _LOG_LEVEL = /*#__PURE__*/new WeakMap();
var _ApiClient_brand = /*#__PURE__*/new WeakSet();
var ApiClient = exports.ApiClient = /*#__PURE__*/function () {
  /**
      * @alias module:ApiClient
      * @class
      */
  function ApiClient() {
    _classCallCheck(this, ApiClient);
    /*
    * Checks whether the given content type represents JSON.<br>
    * JSON content type examples:<br>
    * <ul>
    * <li>application/json</li>
    * <li>application/json; charset=UTF8</li>
    * <li>APPLICATION/JSON</li>
    * </ul>
    * @param {String} contentType The MIME content type to check.
    * @returns {Boolean} <code>true</code> if <code>contentType</code> represents JSON, otherwise <code>false</code>.
    */
    _classPrivateMethodInitSpec(this, _ApiClient_brand);
    // PRIVATE VARIABLES
    _classPrivateFieldInitSpec(this, _protocol, void 0);
    _classPrivateFieldInitSpec(this, _cookie, void 0);
    _classPrivateFieldInitSpec(this, _logger, void 0);
    _classPrivateFieldInitSpec(this, _verifySslFlag, void 0);
    _classPrivateFieldInitSpec(this, _defaultConnectTimeout, void 0);
    _classPrivateFieldInitSpec(this, _defaultReadTimeout, void 0);
    _classPrivateFieldInitSpec(this, _defaultMaxTimeout, void 0);
    _classPrivateFieldInitSpec(this, _LOG_LEVEL, void 0);
    _classPrivateFieldSet(_LOG_LEVEL, this, Object.freeze({
      DEBUG: {
        key: "DEBUG",
        value: Symbol(0)
      },
      INFO: {
        key: "INFO",
        value: Symbol(1)
      },
      WARN: {
        key: "WARN",
        value: Symbol(2)
      },
      ERROR: {
        key: "ERROR",
        value: Symbol(3)
      }
    }));

    /**
    * URI scheme for connecting to the cluster (HTTP or HTTPS using SSL/TLS)
    * @type {String}
    * @default https
    */
    this.scheme = 'https';

    /**
     * The hostname of the URL against which to resolve every API call's (relative) path.
     * @type {String}
     * @default localhost
    */
    this.host = typeof self === 'undefined' ? 'localhost' : self.location.hostname;

    /**
     * The port of the base URL.
     * @type {String}
     * @default 9440
    */
    this.port = typeof self === 'undefined' ? '9440' : self.location.port;

    /**
     * The authentication methods to be included for all API calls.
     * @type {Array.<String>}
     */
    this.authentications = {
      'apiKeyAuthScheme': {
        type: 'apiKey',
        'in': 'header',
        name: 'X-ntnx-api-key'
      },
      'basicAuthScheme': {
        type: 'basic'
      }
    };

    /**
     * The default HTTP headers to be included for all API calls.
     * @type {Array.<String>}
     * @default {}
     */
    this.defaultHeaders = {};
    _classPrivateFieldSet(_defaultConnectTimeout, this, 30000);
    _classPrivateFieldSet(_defaultReadTimeout, this, 30000);
    _classPrivateFieldSet(_defaultMaxTimeout, this, 10800000);

    /**
     * The default HTTP read timeout in milliseconds for all API calls.
     * @type {Number}
     * @default 30000
     */
    this.readTimeout = _classPrivateFieldGet(_defaultReadTimeout, this);

    /**
    * The default HTTP connection timeout in milliseconds for all API calls.
    * @type {Number}
    * @default 30000
    */
    this.connectTimeout = _classPrivateFieldGet(_defaultConnectTimeout, this);

    /**
     * If set to false an additional timestamp parameter is added to all API GET calls to
     * prevent browser caching
     * @type {Boolean}
     * @default true
     */
    this.cache = true;

    /**
     * Saved Cookies
     * @default null
     */
    _classPrivateFieldSet(_cookie, this, null);

    /**
     * The maximum number of redirects to be followed for all API calls.
     * @type {Number}
     * @default 1
     */
    this.maxRedirects = 1;

    /**
     * The maximum number of retry attempts to be made by the client
     * in case of server error.
     * @type {Number}
     * @default 5
     */
    this.maxRetryAttempts = 5;

    /**
     * The delay period (in milliseconds) between two consecutive retry attempts
     * @type {Number}
     * @default 3000
     */
    this.retryInterval = 3000;
    if (typeof self === 'undefined') {
      this.agent = new _superagent["default"].agent();
    }

    /**
     * Allow user to override superagent agent
     */
    this.requestAgent = null;

    /**
     * Allow SDK to print debug logs
     */
    this.debug = false;
    _classPrivateFieldSet(_logger, this, null);

    /**
     * Username for basic auth
     */
    this.username = null;

    /**
     * Password for basic auth
     */
    this.password = null;
    _classPrivateFieldSet(_verifySslFlag, this, true);

    /*
     * Non Browser Environment : path to directory where downloaded files will be stored
     * Browser Environment : WritableStream to pipe downloaded file to
     */
    this.downloadDestination = null;

    /*
     * Log file to write activity logs
     */
    this.loggerFile = null;
  }

  /**
   * Enable/Disable SSL Verification
   * @param verifySsl (boolean)
   */
  return _createClass(ApiClient, [{
    key: "verifySsl",
    get: function get() {
      return _classPrivateFieldGet(_verifySslFlag, this);
    }

    /**
     * Configure log file to write activity logs
     * @param logfile The destination file (write stream / string)
     */,
    set: function set(verifySsl) {
      if (verifySsl) {
        this.requestAgent = null;
      } else {
        this.requestAgent = new _https["default"].Agent({
          rejectUnauthorized: false
        });
      }
      _classPrivateFieldSet(_verifySslFlag, this, verifySsl);
    }
  }, {
    key: "loggerFile",
    set: function set(logfile) {
      if (logfile !== null && typeof logfile !== 'undefined') {
        if (typeof logfile === 'string' || logfile instanceof String) {
          logfile = _fs2["default"].createWriteStream(logfile, {
            flags: 'a'
          });
        }
        _classPrivateFieldSet(_logger, this, new console.Console({
          stdout: logfile,
          stderr: logfile
        }));
      }
    }

    /**
     * Adds key value pair to default headers map, (to be added to every API call request)
     * @param {String} key The key
     * @param {String} value The corresponding value
     */
  }, {
    key: "addDefaultHeader",
    value: function addDefaultHeader(key, value) {
      if (key === "Authorization") {
        _classPrivateFieldSet(_cookie, this, null);
      }
      this.defaultHeaders[key] = value;
    }

    /*
    * Returns a string representation for an actual parameter.
    * @param param The actual parameter.
    * @returns {String} The string representation of <code>param</code>.
    */
  }, {
    key: "paramToString",
    value: function paramToString(param) {
      if (param == undefined || param == null) {
        return '';
      }
      if (param instanceof Date) {
        return param.toJSON();
      }
      return param.toString();
    }
  }, {
    key: "buildUrl",
    value: function buildUrl(path, pathParams) {
      var _this = this;
      if (!path.match(/^\//)) {
        path = '/' + path;
      }

      // The protocol of the base URL, including the colon (:).
      _classPrivateFieldSet(_protocol, this, typeof self === 'undefined' ? this.scheme + ':' : self.location.protocol);
      var basePath = ''; //default
      if (_classPrivateFieldGet(_protocol, this) !== '' && this.host !== '' && this.port !== '') {
        basePath = _classPrivateFieldGet(_protocol, this) + '\/\/' + this.host + ':' + this.port;
      } else if (typeof self !== "undefined") {
        basePath = self.origin;
      }
      var url = basePath + path;
      url = url.replace(/\{([\w-]+)\}/g, function (fullMatch, key) {
        var value;
        if (pathParams.hasOwnProperty(key)) {
          value = _this.paramToString(pathParams[key]);
        } else {
          value = fullMatch;
        }
        return encodeURIComponent(value);
      });
      return url;
    }
  }, {
    key: "buildCollectionParam",
    value:
    /*
    * Builds a string representation of an array-type actual parameter, according to the given collection format.
    * @param {Array} param An array parameter.
    * @param {module:ApiClient.CollectionFormatEnum} collectionFormat The array element separator strategy.
    * @returns {String|Array} A string representation of the supplied collection, using the specified delimiter. Returns
    * <code>param</code> as is if <code>collectionFormat</code> is <code>multi</code>.
    */
    function buildCollectionParam(param, collectionFormat) {
      if (param == null) {
        return null;
      }
      switch (collectionFormat) {
        case 'csv':
          return param.map(this.paramToString).join(',');
        case 'ssv':
          return param.map(this.paramToString).join(' ');
        case 'tsv':
          return param.map(this.paramToString).join('\t');
        case 'pipes':
          return param.map(this.paramToString).join('|');
        case 'multi':
          //return the array directly as SuperAgent will handle it as expected
          return param.map(this.paramToString);
        default:
          throw new Error('Unknown collection format: ' + collectionFormat);
      }
    }

    /*
    * Sets API key for authentication
    *
    * @param {String} key The API key for authentication
    */
  }, {
    key: "setApiKey",
    value: function setApiKey(key) {
      if (key == undefined || typeof key === 'string' || key instanceof String) {
        this.authentications['apiKeyAuthScheme']['apiKey'] = key;
      } else {
        this.authentications['apiKeyAuthScheme']['apiKey'] = undefined;
      }
    }

    /*
    * Applies authentication headers to the request.
    * @param {Object} request The request object created by a <code>superagent()</code> call.
    * @param {Array.<String>} authNames An array of authentication method names.
    */
  }, {
    key: "addEtagToReservedMap",
    value: function addEtagToReservedMap(response, data) {
      if (response.hasOwnProperty("headers") && response.headers.hasOwnProperty("etag")) {
        var etagRef = response.headers.etag;
        if (data.getData() !== undefined) {
          if (Array.isArray(data.getData()) && data.getData().length > 0) {
            var _iterator = _createForOfIteratorHelper(data.getData()),
              _step;
            try {
              for (_iterator.s(); !(_step = _iterator.n()).done;) {
                var item = _step.value;
                if (item.hasOwnProperty("$reserved") && item.get$Reserved() !== undefined) {
                  item.get$Reserved()["ETag"] = etagRef;
                }
              }
            } catch (err) {
              _iterator.e(err);
            } finally {
              _iterator.f();
            }
          } else if (data.getData().hasOwnProperty("$reserved") && data.getData().get$Reserved() !== undefined) {
            data.getData().get$Reserved()["ETag"] = etagRef;
          }
        }
      }
      return data;
    }

    /**
    * Get ETag from an object if exists.
    * The ETag is usually provided in the response of the GET API calls,
    * which can further be used in other HTTP operations.
    *
    * @param object Object from which ETag needs to be retrieved
    * @returns {(String|null)} returns ETag header in the object if it's an API response object, otherwise null
    */
  }, {
    key: "callApi",
    value:
    /**
     * Invokes the REST service using the supplied settings and parameters.
     * @param {String} path The base URL to invoke.
     * @param {String} httpMethod The HTTP method to use.
     * @param {Object.<String, String>} pathParams A map of path parameters and their values.
     * @param {Object.<String, Object>} queryParams A map of query parameters and their values.
     * @param {Object.<String, Object>} headerParams A map of header parameters and their values.
     * @param {Object.<String, Object>} formParams A map of form parameters and their values.
     * @param {Object} bodyParam The value to pass as the request body.
     * @param {Array.<String>} authNames An array of authentication type names.
     * @param {Array.<String>} contentTypes An array of request MIME types.
     * @param {Array.<String>} accepts An array of acceptable response MIME types.
     * @param {(String|Array|Object|Function)} returnType The required type to return; can be a string for simple types or the
     * constructor for a complex type.
     * @returns {Promise} A {@link https://www.promisejs.org/|Promise} object.
     */
    function callApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts, returnType) {
      var _this2 = this;
      var url = this.buildUrl(path, pathParams);
      var request = (0, _superagent["default"])(httpMethod, url);

      // override request callback to retry only required status codes
      request.oldCallback = request.callback;
      request.callback = function (err, res) {
        if (res && res.status) {
          var status = res.status;
          if (status >= 400 && !(status === 401 || status === 408 || status === 429 || status === 503 || status === 504)) {
            this._maxRetries = 0;
          }
          if (res.status === 401) {
            this.unset("Cookie");
            this._maxRetries = 1;
          }
          if (status === 429) {
            var retryAfter = res.headers['retry-after'];
            if (retryAfter) {
              var delay = parseInt(retryAfter, 10) * 1000;
              this._retryDelays[this._retries] = delay;
            }
          }
        }
        this.oldCallback(err, res);
      };

      // apply authentications
      _assertClassBrand(_ApiClient_brand, this, _applyAuthToRequest).call(this, request, authNames);

      // set query parameters
      if (httpMethod.toUpperCase() === 'GET' && this.cache === false) {
        queryParams['_'] = new Date().getTime();
      }
      request.query(_assertClassBrand(_ApiClient_brand, this, _normalizeParams).call(this, queryParams));

      // set header parameters
      request.set(this.defaultHeaders).set(_assertClassBrand(_ApiClient_brand, this, _normalizeParams).call(this, headerParams));
      if ((this.defaultHeaders['NTNX-Request-Id'] === null || this.defaultHeaders['NTNX-Request-Id'] === undefined) && (headerParams['NTNX-Request-Id'] === null || headerParams['NTNX-Request-Id'] === undefined)) {
        var requestId = (0, _uuid.v4)();
        request.set(_assertClassBrand(_ApiClient_brand, this, _normalizeParams).call(this, {
          'NTNX-Request-Id': requestId
        }));
      }

      // Set User-Agent header only if it is not a browser environment
      var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
      if (!isBrowser) {
        this.downloadDestination = '.';
        request.set(_assertClassBrand(_ApiClient_brand, this, _normalizeParams).call(this, {
          'User-Agent': 'Nutanix-networking-js-client/4.0.1'
        }));
      }

      // set requestAgent if it is set by user
      if (this.requestAgent) {
        request.agent(this.requestAgent);
      }

      // set request timeouts
      var timeoutOptions = {};
      timeoutOptions["response"] = _assertClassBrand(_ApiClient_brand, this, _getValidTimeout).call(this, this.connectTimeout, _classPrivateFieldGet(_defaultConnectTimeout, this));
      timeoutOptions["deadline"] = _assertClassBrand(_ApiClient_brand, this, _getValidTimeout).call(this, this.readTimeout, _classPrivateFieldGet(_defaultReadTimeout, this));
      request.timeout(timeoutOptions);
      var contentType = headerParams.hasOwnProperty("Content-Type") ? headerParams["Content-Type"] : _assertClassBrand(_ApiClient_brand, this, _jsonPreferredMime).call(this, contentTypes);
      if (contentType) {
        // Issue with superagent and multipart/form-data (https://github.com/visionmedia/superagent/issues/746)
        if (contentType != 'multipart/form-data') {
          request.type(contentType);
        }
      } else if (!request.header['Content-Type']) {
        request.type('application/json');
      }
      _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).INFO, null, "Request URL :", httpMethod, url);
      _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).DEBUG, _assertClassBrand(_ApiClient_brand, this, _flatten), "Request Headers :", typeof request.header === "undefined" ? "" : request.header);
      if (contentType === 'application/x-www-form-urlencoded') {
        request.send(_assertClassBrand(_ApiClient_brand, this, _normalizeParams).call(this, formParams));
      } else if (contentType == 'multipart/form-data') {
        var _formParams = _assertClassBrand(_ApiClient_brand, this, _normalizeParams).call(this, formParams);
        for (var key in _formParams) {
          if (_formParams.hasOwnProperty(key)) {
            if (_assertClassBrand(_ApiClient_brand, this, _isFileParam).call(this, _formParams[key])) {
              // file field
              request.attach(key, _formParams[key]);
            } else {
              request.field(key, _formParams[key]);
            }
          }
        }
      } else if (contentType === 'application/octet-stream' && bodyParam !== null && typeof bodyParam !== 'undefined' && typeof bodyParam.pipe === 'function') {
        // FILE UPLOAD SUPPORT

        _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).INFO, null, "Piping octet-stream request");
        if (typeof bodyParam.pipe === 'function') {
          bodyParam.pipe(request);
        } else if (typeof require === 'function') {
          var webstream;
          try {
            webstream = require('stream/web');
          } catch (err) {
            _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).ERROR, null, "Error fetching steam/web");
          }
          if (bodyParam instanceof webstream.ReadableStream) {
            bodyParam.pipeTo(new webstream.WritableStream({
              write: function write(chunk) {
                request.write(chunk);
              },
              close: function close() {
                _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).INFO, null, "READABLE STREAM CLOSED");
              },
              abort: function abort(err) {
                _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).ERROR, null, "READABLE STREAM ABORTED");
              }
            }));
          } else {
            request.send(bodyParam);
          }
        } else {
          request.send(bodyParam);
        }
        return new Promise(function (resolve, reject) {
          request.on('error', function (err) {
            _assertClassBrand(_ApiClient_brand, _this2, _log).call(_this2, _classPrivateFieldGet(_LOG_LEVEL, _this2).DEBUG, null, "Caught the following error :", err);
            reject(err);
          }).on('response', function (response) {
            _assertClassBrand(_ApiClient_brand, _this2, _handleApiResponseForPromise).call(_this2, response, path, queryParams, returnType, resolve, reject);
          });
        });
      } else if (bodyParam) {
        request.send(bodyParam);
      }
      if (typeof returnType === 'Blob') {
        request.responseType('blob');
      } else if (returnType === 'String') {
        request.responseType('string');
      }
      _assertClassBrand(_ApiClient_brand, this, _attachCookies).call(this, request);
      _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).DEBUG, null, "Request Body :", typeof request._data === "undefined" ? "" : request._data);
      var accept = headerParams.hasOwnProperty("Accept") && headerParams["Accept"] != undefined ? headerParams["Accept"] : accepts.join(', ');
      var binaryMediaTypes = ['application/octet-stream', 'application/pdf', 'application/zip'];
      if (accept) {
        request.accept(accept);
      }
      return new Promise(function (resolve, reject) {
        request.buffer(false).redirects(0).retry(_this2.maxRetryAttempts, _this2.retryInterval, []).on('error', function (err) {
          _assertClassBrand(_ApiClient_brand, _this2, _log).call(_this2, _classPrivateFieldGet(_LOG_LEVEL, _this2).DEBUG, null, "Caught the following error :", err);
        }).end(function (error, response) {
          if (error) {
            _assertClassBrand(_ApiClient_brand, _this2, _log).call(_this2, _classPrivateFieldGet(_LOG_LEVEL, _this2).DEBUG, null, "Caught error during the request!");
            _assertClassBrand(_ApiClient_brand, _this2, _log).call(_this2, _classPrivateFieldGet(_LOG_LEVEL, _this2).ERROR, null, error);
            if (error.response !== null && typeof error.response !== 'undefined') {
              error.data = _assertClassBrand(_ApiClient_brand, _this2, _deserialize).call(_this2, error.response, returnType);
            } else {
              error.data = _assertClassBrand(_ApiClient_brand, _this2, _wrapErrorInResponse).call(_this2, error);
            }
            reject(error);
          } else {
            _assertClassBrand(_ApiClient_brand, _this2, _log).call(_this2, _classPrivateFieldGet(_LOG_LEVEL, _this2).INFO, null, "Response Status :", response.status);
            _assertClassBrand(_ApiClient_brand, _this2, _log).call(_this2, _classPrivateFieldGet(_LOG_LEVEL, _this2).DEBUG, _assertClassBrand(_ApiClient_brand, _this2, _flatten), "Response Headers :", response.headers);
            var _contentType = '';
            if (response.headers.hasOwnProperty('content-type')) {
              _contentType = response.headers["content-type"];
            }
            var fetchStream = binaryMediaTypes.some(function (binaryMediaType) {
              return _contentType.includes(binaryMediaType);
            });
            if (fetchStream) {
              /*
              * Browser environment :
              *    uses Web Streams, downloadDestination expected to be a WritableStream (i.e. sink for response to be streamed to)
              * Node.js environment :
              *    uses File System, downloadDestination expected to be a directory path, file is downloaded to this directory
              */
              if (isBrowser) {
                /*
                * Browser environment :
                *    - fetch webstream module
                *    - write file to WritableStream downloadDestination
                *    - if webstream if not available or downloadDestination is not instance of WritableStream
                *      code flow goes to main request.then execution
                */
                if (typeof require === 'function') {
                  var _webstream;
                  try {
                    _webstream = require('stream/web');
                  } catch (err) {
                    _assertClassBrand(_ApiClient_brand, _this2, _log).call(_this2, _classPrivateFieldGet(_LOG_LEVEL, _this2).ERROR, null, "Error fetching steam/web");
                  }
                  if (_this2.downloadDestination instanceof _webstream.WritableStream) {
                    // Piping Data
                    var writer = _this2.downloadDestination.getWriter();
                    try {
                      response.on('data', function (chunk) {
                        writer.write(chunk);
                      });
                    } catch (err) {
                      _assertClassBrand(_ApiClient_brand, _this2, _log).call(_this2, _classPrivateFieldGet(_LOG_LEVEL, _this2).ERROR, null, "Issue while downloading file", err);
                    }
                    response.on('end', function () {
                      _assertClassBrand(_ApiClient_brand, _this2, _log).call(_this2, _classPrivateFieldGet(_LOG_LEVEL, _this2).INFO, null, "Finished streaming response");
                      writer.close();
                      var data = _assertClassBrand(_ApiClient_brand, _this2, _deserialize).call(_this2, response, returnType);
                      resolve({
                        data: data,
                        response: response
                      });
                    }).on('error', function (err) {
                      _assertClassBrand(_ApiClient_brand, _this2, _log).call(_this2, _classPrivateFieldGet(_LOG_LEVEL, _this2).ERROR, null, "Caught the following error :", err);
                      err.data = _assertClassBrand(_ApiClient_brand, _this2, _wrapErrorInResponse).call(_this2, err);
                      reject(err);
                    });
                  } else {
                    var errMsg = "Incompatible downloadDestination for Browser Environment, must be WritableStream";
                    _assertClassBrand(_ApiClient_brand, _this2, _log).call(_this2, _classPrivateFieldGet(_LOG_LEVEL, _this2).ERROR, null, errMsg);
                    reject(errMsg);
                  }
                }
              } else {
                /*
                * Non Browser environment :
                *    - stream data to file
                *    - fetch response headers and body (if exists)
                *    - return in case of error or after stream finish
                *
                *    NOTE :
                *    superagent does not provide access to headers before pipe, therefore response is piped to
                *    file with temporary name, which is renamed to proper filename after Content-Disposition header is available
                */

                var tempFilename = _this2.downloadDestination + '/downloaded_file_' + Date.now() + '.txt'; // temporary filename
                var stream = _fs2["default"].createWriteStream(tempFilename);
                _assertClassBrand(_ApiClient_brand, _this2, _processDownloadedFile).call(_this2, response, stream, tempFilename, resolve, reject, returnType);
              }
            } else if (response.status == 302) {
              /*
              * Handling 302 Redirects
              * - Reads X-Redirect-Token header from response and writes into Cookie header for redirected request
              */
              var _tempFilename = _this2.downloadDestination + '/downloaded_file_' + Date.now() + '.txt'; // temporary filename
              var context = _this2;
              _assertClassBrand(_ApiClient_brand, _this2, _log).call(_this2, _classPrivateFieldGet(_LOG_LEVEL, _this2).INFO, null, "Redirecting to :", response.headers.location);
              var redirectRequest = (0, _superagent["default"])(httpMethod, response.headers.location);
              redirectRequest.set(request.header);
              if (response.headers.hasOwnProperty("x-redirect-token")) {
                _assertClassBrand(_ApiClient_brand, _this2, _log).call(_this2, _classPrivateFieldGet(_LOG_LEVEL, _this2).INFO, null, "Writing X-Redirect-Token into Cookie");
                redirectRequest.set("Cookie", response.headers["x-redirect-token"]);
              }
              redirectRequest.redirects(0);
              redirectRequest.buffer(false);
              var redirectedStream = _fs2["default"].createWriteStream(_tempFilename);
              redirectRequest.pipe(redirectedStream);
              redirectRequest.on('response', function (redirectResponse) {
                _assertClassBrand(_ApiClient_brand, context, _log).call(context, _classPrivateFieldGet(_LOG_LEVEL, context).INFO, null, "Received response after redirection :", redirectResponse.status);
                _assertClassBrand(_ApiClient_brand, context, _processDownloadedFile).call(context, redirectResponse, redirectedStream, _tempFilename, resolve, reject, returnType);
              });
            } else {
              _assertClassBrand(_ApiClient_brand, _this2, _handleApiResponseForPromise).call(_this2, response, path, queryParams, returnType, resolve, reject);
            }
          }
        });
      });
    }
  }], [{
    key: "getEtag",
    value: function getEtag(object) {
      var etag = null;
      if (object !== undefined) {
        if (object.hasOwnProperty('$reserved') && object.get$Reserved() !== undefined) {
          etag = this.getValueForCaseInsensitiveKeyMatch(object.get$Reserved(), 'ETag');
        }
        if (etag == null && object.hasOwnProperty("data") && object.getData().hasOwnProperty('$reserved') && object.getData().get$Reserved() !== undefined) {
          etag = this.getValueForCaseInsensitiveKeyMatch(object.getData().get$Reserved(), 'ETag');
        }
      }
      return etag;
    }
  }, {
    key: "getValueForCaseInsensitiveKeyMatch",
    value: function getValueForCaseInsensitiveKeyMatch(object, key) {
      if (object && key) {
        var searchKey = key.toLowerCase();
        var matchedKey = Object.keys(object).find(function (key) {
          return key.toLowerCase() === searchKey;
        });
        return matchedKey ? object[matchedKey] : null;
      }
      return null;
    }

    // Gets a valid timeout
    // 1. Sets to provided default timeout in case invalid value is passed
    // 2. Sets to default max value of 30 minutes in case a value of more than 30 minutes is passed
  }, {
    key: "addEtagReferenceToHeader",
    value: function addEtagReferenceToHeader(bodyParam, headerParams) {
      // set If-Match header from postBody $reserved map
      if (typeof bodyParam !== 'undefined' && bodyParam !== null) {
        if (bodyParam.hasOwnProperty('$reserved') && bodyParam.$reserved.hasOwnProperty('ETag')) {
          var eTagReference = bodyParam.$reserved['ETag'];
          if (typeof eTagReference !== 'undefined' && eTagReference !== null && eTagReference !== "") {
            headerParams['If-Match'] = eTagReference;
          }
        }
      }
    }

    /*
     * Parses an ISO-8601 string representation of a date value.
     * @param {String} str The date value as a string.
     * @returns {Date} The parsed date object.
     */
  }, {
    key: "parseDate",
    value: function parseDate(str) {
      return new Date(str);
    }

    /*
     * Parses queryParams and path to find a given query param value
     * @param {String} path The path given to callApi method
     * @param {Object.<String, Object>} queryParams The queryParams given to callApi method
     * @param {String} param Parameter name to look for
     * @param {String} defaultValue The default value for the missing param if not present
     * @returns {String} The value of given parameter
     */
  }, {
    key: "parseQueryParam",
    value: function parseQueryParam(path, queryParams, param, defaultValue) {
      var value = null;
      if (typeof queryParams !== 'undefined' && queryParams.hasOwnProperty(param)) {
        value = queryParams[param];
      }
      if (value === null && (typeof path === 'string' || path instanceof String)) {
        var escapedParam = param.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        var regexResult = path.match(new RegExp("".concat(escapedParam, "=([0-9]+)")));
        if (regexResult) {
          value = regexResult[1];
        }
      }
      if (value === null) {
        value = defaultValue;
      }
      return value;
    }

    /**
     * Converts a value to the specified type.
     * @param {(String|Object)} data The data to convert, as a string or object.
     * @param {(String|Array.<String>|Object.<String, Object>|Function)} type The type to return. Pass a string for simple types
     * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To
     * return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type:
     * all properties on <code>data<code> will be converted to this type.
     * @returns An instance of the specified type or null or undefined if data is null or undefined.
     */
  }, {
    key: "convertToType",
    value: function convertToType(data, type) {
      if (data === null || data === undefined) return data;
      switch (type) {
        case 'Boolean':
          return Boolean(data);
        case 'Integer':
          return parseInt(data, 10);
        case 'Number':
          return parseFloat(data);
        case 'String':
          return String(data);
        case 'Date':
          return ApiClient.parseDate(String(data));
        case 'Blob':
          return data;
        default:
          if (type === Object) {
            // generic object, return directly
            return data;
          } else if (typeof type === 'function') {
            // for model type like: User
            return type.constructFromObject(data);
          } else if (Array.isArray(type)) {
            // for array type like: ['String']
            var itemType = type[0];
            return data.map(function (item) {
              return ApiClient.convertToType(item, itemType);
            });
          } else if (_typeof(type) === 'object') {
            // for plain object type like: {'String': 'Integer'}
            var keyType, valueType;
            for (var k in type) {
              if (type.hasOwnProperty(k)) {
                keyType = k;
                valueType = type[k];
                break;
              }
            }
            var result = {};
            for (var k in data) {
              if (data.hasOwnProperty(k)) {
                var key = ApiClient.convertToType(k, keyType);
                var value = ApiClient.convertToType(data[k], valueType);
                result[key] = value;
              }
            }
            return result;
          } else {
            // for unknown type, return the data directly
            return data;
          }
      }
    }

    /**
     * Constructs a new map or array model from REST data.
     * @param data {Object|Array} The REST data.
     * @param obj {Object|Array} The target object or array.
     */
  }, {
    key: "constructFromObject",
    value: function constructFromObject(data, obj, itemType) {
      if (Array.isArray(data)) {
        for (var i = 0; i < data.length; i++) {
          if (data.hasOwnProperty(i)) obj[i] = ApiClient.convertToType(data[i], itemType);
        }
      } else {
        for (var k in data) {
          if (data.hasOwnProperty(k)) obj[k] = ApiClient.convertToType(data[k], itemType);
        }
      }
    }
  }]);
}();
/**
* The default API client implementation.
* @type {ApiClient}
* @memberOf ApiClient
*/
_ApiClient = ApiClient;
function _isJsonMime(contentType) {
  return Boolean(contentType != null && contentType.match(/^application\/json(;.*)?$/i));
}
/*
* Chooses a content type from the given array, with JSON preferred; i.e. return JSON if included, otherwise return the first.
* @param {Array.<String>} contentTypes
* @returns {String} The chosen content type, preferring JSON.
*/
function _jsonPreferredMime(contentTypes) {
  for (var i = 0; i < contentTypes.length; i++) {
    if (_assertClassBrand(_ApiClient_brand, this, _isJsonMime).call(this, contentTypes[i])) {
      return contentTypes[i];
    }
  }
  return contentTypes[0];
}
/*
* Checks whether the given parameter value represents file-like content.
* @param param The parameter to check.
* @returns {Boolean} <code>true</code> if <code>param</code> represents a file.
*/
function _isFileParam(param) {
  // fs.ReadStream in Node.js and Electron (but not in runtime like browserify)
  if (typeof require === 'function') {
    var _fs;
    try {
      _fs = require('fs');
    } catch (err) {}
    if (_fs && _fs.ReadStream && param instanceof _fs.ReadStream) {
      return true;
    }
  }

  // Buffer in Node.js
  if (typeof Buffer === 'function' && param instanceof Buffer) {
    return true;
  }

  // Blob in browser
  if (typeof _buffer.Blob === 'function' && param instanceof _buffer.Blob) {
    return true;
  }

  // File in browser (it seems File object is also instance of Blob, but keep this for safe)
  if (typeof File === 'function' && param instanceof File) {
    return true;
  }
  return false;
}
/*
* Normalizes parameter values:
* <ul>
* <li>remove nils</li>
* <li>keep files and arrays</li>
* <li>format to string with `paramToString` for other cases</li>
* </ul>
* @param {Object.<String, Object>} params The parameters as object properties.
* @returns {Object.<String, Object>} normalized parameters.
*/
function _normalizeParams(params) {
  var newParams = {};
  for (var key in params) {
    if (params.hasOwnProperty(key) && params[key] != undefined && params[key] != null) {
      var value = params[key];
      if (_assertClassBrand(_ApiClient_brand, this, _isFileParam).call(this, value) || Array.isArray(value)) {
        newParams[key] = value;
      } else {
        newParams[key] = this.paramToString(value);
      }
    }
  }
  return newParams;
}
function _applyAuthToRequest(request, authNames) {
  var _this3 = this;
  authNames.forEach(function (authName) {
    var auth = _this3.authentications[authName];
    switch (auth.type) {
      case 'basic':
        if (auth.username || auth.password) {
          request.auth(auth.username || '', auth.password || '');
        } else if (_this3.username || _this3.password) {
          request.auth(_this3.username || '', _this3.password || '');
        }
        _assertClassBrand(_ApiClient_brand, _this3, _log).call(_this3, _classPrivateFieldGet(_LOG_LEVEL, _this3).DEBUG, null, "Basic Auth applied to request");
        break;
      case 'apiKey':
        if (auth.apiKey) {
          var data = {};
          if (auth.apiKeyPrefix) {
            data[auth.name] = auth.apiKeyPrefix + ' ' + auth.apiKey;
          } else {
            data[auth.name] = auth.apiKey;
          }
          if (auth['in'] === 'header') {
            request.set(data);
          } else {
            request.query(data);
          }
        }
        _assertClassBrand(_ApiClient_brand, _this3, _log).call(_this3, _classPrivateFieldGet(_LOG_LEVEL, _this3).DEBUG, null, "apiKey applied to request");
        break;
      case 'oauth2':
        if (auth.accessToken) {
          request.set({
            'Authorization': 'Bearer ' + auth.accessToken
          });
        }
        _assertClassBrand(_ApiClient_brand, _this3, _log).call(_this3, _classPrivateFieldGet(_LOG_LEVEL, _this3).DEBUG, null, "oauth2 applied to request");
        break;
      default:
        _assertClassBrand(_ApiClient_brand, _this3, _log).call(_this3, _classPrivateFieldGet(_LOG_LEVEL, _this3).ERROR, null, "Unknown authentication type:", auth.type);
        throw new Error('Unknown authentication type: ' + auth.type);
    }
  });
}
/**
* Wraps errors in generic response format.
* @param {Object} error object encountered during request.
* @returns an error object with wrapped response within error.data .
*/
function _wrapErrorInResponse(error) {
  var response = {
    data: {},
    metadata: {}
  };
  response.data.status = error.status;
  response.data.message = error.message;
}
/**
* Deserializes an HTTP response body into a value of the specified type.
* @param {Object} response A SuperAgent response object.
* @param {(String|Array.<String>|Object.<String, Object>|Function)} returnType The type to return. Pass a string for simple types
* or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To
* return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type:
* all properties on <code>data<code> will be converted to this type.
* @returns A value of the specified type.
*/
function _deserialize(response, returnType) {
  if (response == null || returnType == null || response.status == 204) {
    return null;
  }

  // Handle text response
  if (response.headers && ['text/event-stream', 'text/html', 'text/xml', 'text/csv', 'text/javascript', 'text/markdown', 'text/vcard'].includes(response.headers['content-type'])) {
    var data = new returnType();
    data.data = new _buffer.Blob([response.text], {
      type: response.headers['content-type']
    });
    var flag = new _Flag["default"]();
    flag.name = "hasError";
    flag.value = false;
    var flags = [flag];
    var metadata = new _ApiResponseMetadata["default"]();
    metadata.flags = flags;
    data.metadata = metadata;
    return data;
  }

  // Rely on SuperAgent for parsing response body.
  // See http://visionmedia.github.io/superagent/#parsing-response-bodies
  var data = response.body;
  if (data == null || _typeof(data) === 'object' && typeof data.length === 'undefined' && !Object.keys(data).length) {
    // SuperAgent does not always produce a body; use the unparsed response as a fallback
    data = response.text;
  }
  return _ApiClient.convertToType(data, returnType);
}
/**
* Set pagination data if response is a Paginable object
* @param {Object} data The response data already passed through deserialize
* @param {String} path The path given to callApi method
* @param {Object.<String, Object>} queryParams The queryParams given to callApi method
*/
function _paginateIfNeeded(data, path, queryParams) {
  // If response is not a Paginable instance, nothing to do
  if (!(data instanceof _Paginable["default"])) {
    return;
  }
  // Retrieve current page number, defaults to 0
  var page = parseInt(this.constructor.parseQueryParam(path, queryParams, '$page', "0"), 10);
  // Retrieve current limit (results per page) number, defaults to 50
  var resultsPerPage = parseInt(this.constructor.parseQueryParam(path, queryParams, '$limit', "50"), 10);

  // Populate pagination data
  data.populatePaginationMetadata(this,
  // current ApiClient instance
  page, resultsPerPage);
}
function _getValidTimeout(timeout, defaultTimeout) {
  if (timeout <= 0) {
    timeout = defaultTimeout;
  } else if (timeout > _classPrivateFieldGet(_defaultMaxTimeout, this)) {
    timeout = _classPrivateFieldGet(_defaultMaxTimeout, this);
  }
  return timeout;
}
// If enabled, update cookie information to reuse in subsequent requests for a valid response
function _updateCookies(response) {
  if (response.hasOwnProperty("headers") && response.headers.hasOwnProperty("set-cookie")) {
    var finalCookie = "";
    var cookieList = response.headers["set-cookie"];
    if (cookieList.length > 0) {
      // add all cookies separated by ;
      var _iterator2 = _createForOfIteratorHelper(cookieList),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var cookieItem = _step2.value;
          cookieItem = cookieItem.split(";")[0];
          if (cookieItem.includes("=")) {
            cookieItem.trim();
            finalCookie = finalCookie.concat(cookieItem).concat(";");
          }
        }
        // remove trailing ;
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
      if (finalCookie !== "") {
        finalCookie = finalCookie.substr(0, finalCookie.length - 1);
      }
    }
    _classPrivateFieldSet(_cookie, this, finalCookie);
    _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).DEBUG, null, "Retained cookie :", finalCookie);
  } else {
    _classPrivateFieldSet(_cookie, this, null);
  }
}
// If enabled, attach saved cookies to request
function _attachCookies(request) {
  if (_classPrivateFieldGet(_cookie, this) != null) {
    request.set(_assertClassBrand(_ApiClient_brand, this, _normalizeParams).call(this, {
      'Cookie': _classPrivateFieldGet(_cookie, this)
    }));
  }
}
function _log(level, mapper) {
  for (var _len = arguments.length, messages = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
    messages[_key - 2] = arguments[_key];
  }
  // Set default log level to INFO
  if (_typeof(level) !== "object" || !("key" in level) || !("value" in level) || _typeof(level["value"]) !== "symbol") {
    level = _classPrivateFieldGet(_LOG_LEVEL, this).INFO;
  }
  if (!_assertClassBrand(_ApiClient_brand, this, _skipLogging).call(this, level)) {
    // Preprocess message to prefix with timestamp and log level
    messages = messages.map(function (message) {
      return typeof message === "string" ? message : mapper ? mapper(message) : JSON.stringify(message);
    });
    var message = messages.join(' ');
    message = _assertClassBrand(_ApiClient_brand, this, _getLocalDateTime).call(this) + ' ' + level.key + ' - ' + message;
    if (typeof _classPrivateFieldGet(_logger, this) !== "undefined" && _classPrivateFieldGet(_logger, this) !== null && typeof _classPrivateFieldGet(_logger, this).log === 'function') {
      _classPrivateFieldGet(_logger, this).log(message);
    } else {
      console.log(message);
    }
  }
}
function _skipLogging(level) {
  // Skip logging if log level is DEBUG but debug is not enabled.
  return !this.debug && level === _classPrivateFieldGet(_LOG_LEVEL, this).DEBUG;
}
function _getLocalDateTime() {
  // Current epoch UTC time in milliseconds
  var epochTime = Date.now();

  // "getTimezoneOffset" returns the difference, in minutes, between a date as evaluated in the UTC time zone,
  // and the same date as evaluated in the local time zone.
  // if you are in timezone UTC-1, outputs 60
  // if you are in timezone UTC+3, outputs -180
  var timezoneOffsetInMinutes = new Date().getTimezoneOffset();
  var timezoneOffsetInMilliseconds = timezoneOffsetInMinutes * 60 * 1000;

  // Create a new date with adjusted epoch time based on timezone offset
  var date = new Date(epochTime - timezoneOffsetInMilliseconds);
  return date.toISOString().slice(0, 23);
}
// A mapper function to flatten a simple non-nested (key:value) object to string
function _flatten(obj) {
  if (_typeof(obj) !== "object") {
    return obj;
  }
  var output = '\n';
  if (obj) {
    Object.keys(obj).forEach(function (e) {
      output += e + '=[' + obj[e] + ']\n';
    });
  }
  return output === '\n' ? obj : output;
}
// handle and deserialize received response
function _handleApiResponseForPromise(response, path, queryParams, returnType, resolve, reject) {
  try {
    var data = _assertClassBrand(_ApiClient_brand, this, _deserialize).call(this, response, returnType);
    _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).INFO, null, "Response Status :", response.status);
    _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).DEBUG, _assertClassBrand(_ApiClient_brand, this, _flatten), "Response Headers :", response.headers);
    _assertClassBrand(_ApiClient_brand, this, _updateCookies).call(this, response || {});
    _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).DEBUG, null, "Response Body :", data);
    if (response.status == 204 && data == null) {
      resolve({
        data: data,
        response: response
      });
    } else if (response.ok && data != null) {
      this.addEtagToReservedMap(response, data);
      _assertClassBrand(_ApiClient_brand, this, _paginateIfNeeded).call(this, data, path, queryParams);
      resolve({
        data: data,
        response: response
      });
    } else {
      _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).ERROR, null, data);
      reject(_objectSpread(_objectSpread({}, response.error), {}, {
        data: data
      }));
    }
  } catch (err) {
    _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).DEBUG, null, "Caught error while processing response!");
    _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).ERROR, null, err);
    err.data = _assertClassBrand(_ApiClient_brand, this, _wrapErrorInResponse).call(this, err);
    reject(err);
  }
}
function _processDownloadedFile(response, stream, tempFilename, resolve, reject, returnType) {
  var _this4 = this;
  _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).INFO, null, "Streaming response to : ", tempFilename);
  try {
    response.on('data', function (chunk) {
      stream.write(chunk);
    });
  } catch (err) {
    _assertClassBrand(_ApiClient_brand, this, _log).call(this, _classPrivateFieldGet(_LOG_LEVEL, this).ERROR, null, "Issue while downloading file", err);
  }
  var data = new returnType();
  // Fetch filename
  var filename = "";
  if (typeof response.headers['content-disposition'] !== 'undefined' && response.headers['content-disposition'] !== null) {
    var match = response.headers['content-disposition'].match(/*#__PURE__*/_wrapRegExp(/.*filename="(.*)".*/, {
      filename: 1
    }));
    var filepath = _path["default"].parse(match.groups['filename']);
    filename = this.downloadDestination + '/' + filepath.name + '_' + Date.now() + filepath.ext;
    data.data = {
      "path": _path["default"].parse(filename),
      $objectType: "Path"
    };
    var flag = new _Flag["default"]();
    flag.name = "hasError";
    flag.value = false;
    var flags = [flag];
    var metadata = new _ApiResponseMetadata["default"]();
    metadata.flags = flags;
    data.metadata = metadata;
  }
  response.on('end', function () {
    _assertClassBrand(_ApiClient_brand, _this4, _log).call(_this4, _classPrivateFieldGet(_LOG_LEVEL, _this4).INFO, null, "Finished streaming response");
    if (filename.length !== 0) {
      _assertClassBrand(_ApiClient_brand, _this4, _log).call(_this4, _classPrivateFieldGet(_LOG_LEVEL, _this4).INFO, null, "Content-Disposition header found [", filename, "] is final filename");
      stream.close();
      _fs2["default"].renameSync(tempFilename, filename);
      resolve({
        data: data,
        response: response
      });
    } else {
      _assertClassBrand(_ApiClient_brand, _this4, _log).call(_this4, _classPrivateFieldGet(_LOG_LEVEL, _this4).ERROR, null, "Content-Disposition header not found [", tempFilename, "] is final filename");
      resolve({
        data: data,
        response: response
      });
    }
  });
  response.on('error', function (err) {
    _assertClassBrand(_ApiClient_brand, _this4, _log).call(_this4, _classPrivateFieldGet(_LOG_LEVEL, _this4).ERROR, null, "Caught the following error :", err);
    error.data = _assertClassBrand(_ApiClient_brand, _this4, _wrapErrorInResponse).call(_this4, error);
    reject(err);
  });
}
ApiClient.instance = new ApiClient();