HTTP Base Options
@alias module:http.BodyParserOptions
@constructor
@param {Object} options
192503
function BodyParserOptions(options) {
  if (!(this instanceof BodyParserOptions))
    return new BodyParserOptions(options);

  this.keyLimit = 100;
  this.bodyLimit = 20 << 20;
  this.contentType = null;
  this.timeout = 10 * 1000;

  if (options)
    this.fromOptions(options);
}
1191871
function pPostUrl (url, body){
    var options = {
        method: 'POST',
        uri: url,
        body: body,
        json: true // Automatically stringifies the body to JSON
    };
    return rp(options);
}
179061
function HttpServer(options) {
  options = options || {};

  if (options.root) {
    this.root = options.root;
  }
  else {
    try {
      fs.lstatSync('./public');
      this.root = './public';
    }
    catch (err) {
      this.root = './';
    }
  }

  this.headers = options.headers || {};

  this.cache = options.cache === undefined ? 3600 : options.cache; // in seconds.
  this.showDir = options.showDir !== 'false';
  this.autoIndex = options.autoIndex !== 'false';
  this.gzip = options.gzip === true;
  this.contentType = options.contentType || 'application/octet-stream';

  if (options.ext) {
    this.ext = options.ext === true
      ? 'html'
      : options.ext;
  }

  var before = options.before ? options.before.slice() : [];

  before.push(function (req, res) {
    if (options.logFn) {
      options.logFn(req, res);
    }

    res.emit('next');
  });

  if (options.cors) {
    this.headers['Access-Control-Allow-Origin'] = '*';
    this.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Range';
    if (options.corsHeaders) {
      options.corsHeaders.split(/\s*,\s*/)
          .forEach(function (h) { this.headers['Access-Control-Allow-Headers'] += ', ' + h; }, this);
    }
    before.push(corser.create(options.corsHeaders ? {
      requestHeaders: this.headers['Access-Control-Allow-Headers'].split(/\s*,\s*/)
    } : null));
  }

  if (options.robots) {
    before.push(function (req, res) {
      if (req.url === '/robots.txt') {
        res.setHeader('Content-Type', 'text/plain');
        var robots = options.robots === true
          ? 'User-agent: *\nDisallow: /'
          : options.robots.replace(/\\n/, '\n');

        return res.end(robots);
      }

      res.emit('next');
    });
  }

  before.push(ecstatic({
    root: this.root,
    cache: this.cache,
    showDir: this.showDir,
    autoIndex: this.autoIndex,
    defaultExt: this.ext,
    gzip: this.gzip,
    contentType: this.contentType,
//    handleError: typeof options.proxy !== 'string'
    handleError: (!options.fallback || typeof options.proxy === 'string')
  }));

  if (typeof options.proxy === 'string') {
    var proxy = httpProxy.createProxyServer({});
    before.push(function (req, res) {
      proxy.web(req, res, {
        target: options.proxy,
        changeOrigin: true
      });
    });
  }

  if (options.fallback) {
    before.push(function (req, res) {
      if (res.statusCode === 404) {
        res.redirect(options.fallback.address, 301);
      }
    });
  }

  var serverOptions = {
    before: before,
    headers: this.headers,
    onError: function (err, req, res) {
      if (options.logFn) {
        options.logFn(req, res, err);
      }

      res.end();
    }
  };

  if (options.https) {
    serverOptions.https = options.https;
  }

  this.server = union.createServer(serverOptions);
}
242537
function hstsFactory(options/*, includeSubdomains*/) {
  options = options || {};
  if (arguments.length === 2) {
    options = {
      maxAge: arguments[0],
      includeSubdomains: arguments[1]
    };
  }
  if (options === true) {
    options = {
      includeSubdomains: true
    };
  }
  if (typeof options === 'number') {
    options = {
      maxAge: options
    };
  }


  var maxAge = options.maxAge || MAX_AGE;
  var subdomains = options.includeSubdomains || false;

  var str = 'max-age=' + maxAge;
  if (subdomains) {
    str += '; includeSubdomains';
  }
  return function hsts(req, res, next) {
    if (req.connection.encrypted || req.secure || req.connection.proxySecure) {
      res.setHeader(HEADER, str);
    }
    next();
  };
}
1253037
function Parser(options) {
    this.options = options || {};
    this.h = this.options.h || function (tagName, properties, value) {
        return value;
    };
    this.renderer = Object.assign(renderer, this.options.renderer || {});
}
313297
function toOptions (type, options) {
  if (Types.includes(type)) {
    options = Object.assign({ type: type }, options)
  }
  if (options._validated) {
    delete options._validated
    return options
  }
  if (Object.keys(options).length > 0) {
    options = baseParser._parseDefinition(
      options, { strict: true, userInput: false, _key: 'options' }
    )
  }
  return options
}
1186396
function parseOptions(options) {
    return {
        boolean: "boolean" in options ? options.boolean : true,
        number: "number" in options ? options.number : true,
        string: "string" in options ? options.string : true,
        allow: options.allow || []
    };
}
985729
function HttpConfig(options) {
    underscore.extend(this, HttpConfig._DEFAULT)
    CommonConfig.call(this, options)
    this.type = serverTypes.HTTP
}
1101044
function (options) {
        // Nothing to do
        if (!options) { return; }

        // The existing url is updated.
        _.has(options, 'url') && this.url.update(options.url);

        // The existing list of headers must be cleared before adding the given headers to it.
        options.header && this.headers.repopulate(options.header);

        // Only update the method if one is provided.
        _.has(options, 'method') && (this.method = _.isNil(options.method) ?
            DEFAULT_REQ_METHOD : String(options.method).toUpperCase());

        // The rest of the properties are not assumed to exist so we merge in the defined ones.
        _.mergeDefined(this, /** @lends Request.prototype */ {
            /**
             * @type {RequestBody|undefined}
             */
            body: _.createDefined(options, 'body', RequestBody),

            // auth is a special case, empty RequestAuth should not be created for falsy values
            // to allow inheritance from parent
            /**
             * @type {RequestAuth}
             */
            auth: options.auth ? new RequestAuth(options.auth) : undefined,

            /**
             * @type {ProxyConfig}
             */
            proxy: options.proxy && new ProxyConfig(options.proxy),

            /**
             * @type {Certificate|undefined}
             */
            certificate: options.certificate && new Certificate(options.certificate)
        });
    }
1154439
function request(method, address, body, options) {
  let timeout = null;
  return new Promise((resolve, reject) => {
    try {
      const opts = _.merge({}, this.options, options, url.parse(address), {
        method,
      });

      // handle optional timeout
      if (typeof opts.timeout === 'number') {
        setTimeout(() => {
          reject(new Error(`${method} "${address}" timed out`));
          timeout = null;
        }, Math.floor(opts.timeout));
      }

      // create some request middleware to potentially
      // add headers ahead of time for auth or set cors, etc.
      const before =
        typeof opts.before === 'function'
          ? opts.before.call(this.context, method, address, opts)
          : () => null;

      const proto = opts.protocol === 'https:' ? https : http;

      return Promise.resolve(before)
        .then(() => {
          clearTimeout(timeout);

          const req = proto.request(opts, res => {
            let data = '';
            res
              .on('data', d => {
                data += d;
              })
              .on('error', error => {
                clearTimeout(timeout);
                reject(error);
              })
              .on('end', () => {
                clearTimeout(timeout);
                const parsedData = processData(res, data, opts);
                return parsedData instanceof Error
                  ? reject(parsedData)
                  : resolve(parsedData);
              });
          });

          req.on('error', error => {
            clearTimeout(timeout);
            reject(error);
          });

          if (method === Method.PUT || method === Method.POST) {
            req.write(processBody(opts, body));
          }
          req.end();
        })
        .catch(error => {
          clearTimeout(timeout);
          return reject(error);
        });
    } catch (error) {
      clearTimeout(timeout);
      return reject(error);
    }
  });
}
339011
function BaseN(options) {

    var self = this;
    var opt = options || {};

    // assert
    if (opt.max && opt.length) {
        throw new Error('cannot specify both max and length');
    }

    // merge in default options
    for (var key in DEFAULT_OPTIONS) {
        if (!opt.hasOwnProperty(key)) {
            opt[key] = DEFAULT_OPTIONS[key];
        }
    }

    /**
     * a string of all allowed characters used for encoding/decoding.
     * @type {String}
     */
    self.characters = opt.characters;

    /**
     * number of unique characters used to encode ids.
     * @type {Number}
     */
    self.base = opt.base || opt.characters.length;

    /**
     * max length of id string.
     * @type {Number}
     */
    self.length = opt.length || self._findLength(opt.max);
}
844118
function prepareOptions(body) {
    const fetchOptions = Object.assign({}, fetchOptionsCommon);
    if (body) {
        try {
            fetchOptions.body = JSON.stringify(body);
        } catch (e) {
            console.warn('The form body are not added. Could not extract data from the body element', body);
        }
    }
    return fetchOptions;
}
548310
function HttpsConfig(options) {
    var httpsOptions = options && options.httpsOptions

    underscore.extend(this, HttpsConfig._DEFAULT)
    CommonConfig.call(this, options)
    this.httpsOptions = applyHttpsOptions.call(this, httpsOptions)
    this.type = serverTypes.HTTPS
}
520831
function jsonBodyParser(options) {
    assert.optionalObject(options, 'options');
    var opts = options || {};

    var override = opts.overrideParams;

    function parseJson(req, res, next) {
        // save original body on req.rawBody and req._body
        req.rawBody = req._body = req.body;

        if (req.getContentType() !== 'application/json' || !req.body) {
            return next();
        }

        var params;

        try {
            params = JSON.parse(req.body, opts.reviver);
        } catch (e) {
            return next(new errors.InvalidContentError('Invalid JSON: ' +
                e.message));
        }

        if (opts.mapParams === true) {
            if (Array.isArray(params)) {
                // if req.params exists, we have url params. we can't map an
                // array safely onto req.params, throw an error.
                if (req.params &&
                    Object.keys(req.params).length > 0 &&
                    !(req.params instanceof Array)) {
                    return next(new errors.InternalServerError(
                        'Cannot map POST body of [Array array] onto req.params'
                    ));
                }
                req.params = params;
            } else if (typeof (params) === 'object' && params !== null) {
                // else, try to merge the objects
                Object.keys(params).forEach(function (k) {
                    var p = req.params[k];

                    if (p && !override) {
                        return;
                    }
                    req.params[k] = params[k];
                });
            } else {
                // otherwise, do a wholesale stomp, no need to merge one by one.
                req.params = params || req.params;
            }
        }

        req.body = params;

        return next();
    }

    var chain = [];

    if (!opts.bodyReader) {
        chain.push(bodyReader(opts));
    }
    chain.push(parseJson);
    return chain;
}
1295839
function (options, callback) {
    var self = this,
        requestOptions = {
          path: _urlPrefix
    };

    if (typeof options === 'function') {
      callback = options;
      options = {};
    }

    self._request(requestOptions, function (err, body) {
      if (err) {
        return callback(err);
      }

      else if (!body || !body.loadBalancers) {
        return callback(new Error('Unexpected empty response'));
      }

      else {
        return callback(null, body.loadBalancers.map(function (loadBalancer) {
          return new lb.LoadBalancer(self, loadBalancer);
        }));
      }
    });
  }
179014
function(url, next, headers, options) {
    var headerStruct = {
      'User-Agent': 'request'
    };

    var params = {
      url : url,
      method : 'GET'
    };

    if (headers) {
      for (var k in headers) {
        if (headers.hasOwnProperty(k)) {
          headerStruct[k] = headers[k];
        }
      }
    }

    params.headers = headerStruct;
    params.gzip = true;

    if (options) {
      for (var k in options) {
        if (options.hasOwnProperty(k)) {
          params[k] = options[k];
        }
      }
    }

    if (next) {
      request(params, function(error, res, body) {
          if (res && res.headers && -1 !== res.headers['content-type'].indexOf('json') || -1 !== res.headers['content-type'].indexOf('javascript')) {
            try {
              body = JSON.parse(body);
            } catch (e) {
              error = e.message;
            }
          }

          if (404 === res.statusCode) {
            next('Not Found', body, res.headers, res.statusCode);
          } else {
            next(error, body, res ? res.headers : null, res ? res.statusCode : null);
          }
        }
      );
    } else {
      return request(params);
    }
  }
1327849
function(options) {
      options = langx.mixin({parse: true}, options);
      var entity = this;
      var success = options.success;
      options.success = function(resp) {
        var serverAttrs = options.parse ? entity.parse(resp, options) : resp;
        if (!entity.set(serverAttrs, options)) return false;
        if (success) success.call(options.context, entity, resp, options);
        entity.trigger('sync', entity, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    }