Make a server request from the list of BidRequests.

@param {validBidRequests[]} - an array of bids
@return ServerRequest Info describing the request to the server.
545986
function(validBidRequests, bidderRequest) {
    return validBidRequests.map(bidRequest => {
      let gjid = Math.floor(Math.random() * 99999999);
      let sizes = generateSizeParam(bidRequest.sizes);
      let configId = bidRequest.params.placementId || '';
      let minCPM = bidRequest.params.minCPM || 0.0;
      let minCPC = bidRequest.params.minCPC || 0.0;
      let allowExplicit = bidRequest.params.explicit || 0;
      const body = {
        gjid: gjid,
        sizes: sizes,
        configId: configId,
        minCPM: minCPM,
        minCPC: minCPC,
        allowExplicit: allowExplicit,
        referrer: utils.getTopWindowUrl(),
        requestid: bidRequest.bidderRequestId,
        bidid: bidRequest.bidId
      };
      if (document.referrer) {
        body.referrer = document.referrer;
      }
      if (bidderRequest && bidderRequest.gdprConsent) {
        body.consent_string = bidderRequest.gdprConsent.consentString;
        body.consent_required = (typeof bidderRequest.gdprConsent.gdprApplies === 'boolean') ? bidderRequest.gdprConsent.gdprApplies : true;
      }
      return {
        method: 'GET',
        url: ENDPOINT_URL,
        data: body
      };
    });
  }
655708
function(serverResponse, {bidderRequest}) {
    serverResponse = serverResponse.body;
    const bids = [];
    if (!serverResponse || serverResponse.error) {
      let errorMessage = `in response for ${bidderRequest.bidderCode} adapter`;
      if (serverResponse && serverResponse.error) { errorMessage += `: ${serverResponse.error}`; }
      utils.logError(errorMessage);
      return bids;
    }

    if (serverResponse.tags) {
      serverResponse.tags.forEach(serverBid => {
        const rtbBid = getRtbBid(serverBid);
        if (rtbBid) {
          if (rtbBid.cpm !== 0 && includes(this.supportedMediaTypes, rtbBid.ad_type)) {
            const bid = newBid(serverBid, rtbBid, bidderRequest);
            bid.mediaType = parseMediaType(rtbBid);
            bids.push(bid);
          }
        }
      });
    }

    if (serverResponse.debug && serverResponse.debug.debug_info) {
      let debugHeader = 'AppNexus Debug Auction for Prebid\n\n'
      let debugText = debugHeader + serverResponse.debug.debug_info
      debugText = debugText
        .replace(/(<td>|<th>)/gm, '\t') // Tables
        .replace(/(<\/td>|<\/th>)/gm, '\n') // Tables
        .replace(/^<br>/gm, '') // Remove leading <br>
        .replace(/(<br>\n|<br>)/gm, '\n') // <br>
        .replace(/<h1>(.*)<\/h1>/gm, '\n\n===== $1 =====\n\n') // Header H1
        .replace(/<h[2-6]>(.*)<\/h[2-6]>/gm, '\n\n*** $1 ***\n\n') // Headers
        .replace(/(<([^>]+)>)/igm, ''); // Remove any other tags
      utils.logMessage('https://console.appnexus.com/docs/understanding-the-debug-auction');
      utils.logMessage(debugText);
    }

    return bids;
  }
262571
function getExclusiveBids(bidsReceived) {
  let bids = bidsReceived
    .map((bid) => Object.assign({}, bid, {[TARGETING_KEY_PB_CAT_DUR]: bid.adserverTargeting[TARGETING_KEY_PB_CAT_DUR]}));
  bids = groupBy(bids, TARGETING_KEY_PB_CAT_DUR);
  let filteredBids = [];
  Object.keys(bids).forEach((targetingKey) => {
    bids[targetingKey].sort(compareOn('responseTimestamp'));
    filteredBids.push(bids[targetingKey][0]);
  });
  return filteredBids;
}
691408
function _createServerRequest(bidRequest, gdprConsent) {
  const ttxRequest = {};
  const params = bidRequest.params;
  const element = document.getElementById(bidRequest.adUnitCode);
  const sizes = _transformSizes(bidRequest.sizes);
  const minSize = _getMinSize(sizes);

  const viewabilityAmount = _isViewabilityMeasurable(element)
    ? _getViewability(element, utils.getWindowTop(), minSize)
    : NON_MEASURABLE;

  const contributeViewability = ViewabilityContributor(viewabilityAmount);

  if (element === null) {
    utils.logWarn(`Unable to locate element with id: '${bidRequest.adUnitCode}'`);
  }

  /*
   * Infer data for the request payload
   */
  ttxRequest.imp = [];
  ttxRequest.imp[0] = {
    banner: {
      format: sizes.map(size => Object.assign(size, {ext: {}}))
    },
    ext: {
      ttx: {
        prod: params.productId
      }
    }
  };
  ttxRequest.site = { id: params.siteId };

  // Go ahead send the bidId in request to 33exchange so it's kept track of in the bid response and
  // therefore in ad targetting process
  ttxRequest.id = bidRequest.bidId;

  // Set GDPR related fields
  ttxRequest.user = {
    ext: {
      consent: gdprConsent.consentString
    }
  };
  ttxRequest.regs = {
    ext: {
      gdpr: (gdprConsent.gdprApplies === true) ? 1 : 0
    }
  };
  ttxRequest.ext = {
    ttx: {
      caller: [{
        'name': 'prebidjs',
        'version': '$prebid.version$'
      }]
    }
  };

  // Finally, set the openRTB 'test' param if this is to be a test bid
  if (params.test === 1) {
    ttxRequest.test = 1;
  }

  /*
   * Now construct the full server request
   */
  const options = {
    contentType: 'text/plain',
    withCredentials: true
  };
  // Allow the ability to configure the HB endpoint for testing purposes.
  const ttxSettings = config.getConfig('ttxSettings');
  const url = (ttxSettings && ttxSettings.url) || END_POINT;

  // Return the server request
  return {
    'method': 'POST',
    'url': url,
    'data': JSON.stringify(contributeViewability(ttxRequest)),
    'options': options
  }
}
88346
function validBidSize(adUnitCode, bid, bidRequests) {
  if ((bid.width || parseInt(bid.width, 10) === 0) && (bid.height || parseInt(bid.height, 10) === 0)) {
    bid.width = parseInt(bid.width, 10);
    bid.height = parseInt(bid.height, 10);
    return true;
  }

  const adUnit = getBidderRequest(bidRequests, bid.bidderCode, adUnitCode);

  const sizes = adUnit && adUnit.bids && adUnit.bids[0] && adUnit.bids[0].sizes;
  const parsedSizes = parseSizesInput(sizes);

  // if a banner impression has one valid size, we assign that size to any bid
  // response that does not explicitly set width or height
  if (parsedSizes.length === 1) {
    const [ width, height ] = parsedSizes[0].split('x');
    bid.width = parseInt(width, 10);
    bid.height = parseInt(height, 10);
    return true;
  }

  return false;
}
425680
function handleResponse(response, requestedBidders, bidderRequests, addBidResponse, done) {
    let result;
    let bids = [];

    try {
      result = JSON.parse(response);

      bids = protocolAdapter().interpretResponse(
        result,
        bidderRequests,
        requestedBidders
      );

      bids.forEach(({adUnit, bid}) => {
        if (isValid(adUnit, bid, bidderRequests)) {
          addBidResponse(adUnit, bid);
        }
      });

      bidderRequests.forEach(bidderRequest => events.emit(EVENTS.BIDDER_DONE, bidderRequest));
    } catch (error) {
      utils.logError(error);
    }

    if (!result || (result.status && includes(result.status, 'Error'))) {
      utils.logError('error parsing response: ', result.status);
    }

    done();
    doClientSideSyncs(requestedBidders);
  }
647485
function makeRequest(method, auth, url, qs, data, cb) {		// eslint-disable-line max-params
	const options = {
		method: method,
		headers: {
			'Content-Type': 'application/json',
			'Authorization': auth
		},
		url: url, // for debugging set to: "https://httpbin.org/get"
		qs: qs
	}

	if(data) {
		options.body = JSON.stringify(data)
	}

	request(options, createResponseHandler(cb))
}
1167077
function newBid(serverBid) {
  const bid = {
    ad: serverBid.seatbid[0].bid[0].adm,
    cpm: serverBid.seatbid[0].bid[0].price,
    creativeId: serverBid.seatbid[0].bid[0].adid,
    currency: serverBid.cur,
    dealId: serverBid.seatbid[0].bid[0].dealid,
    width: serverBid.seatbid[0].bid[0].w,
    height: serverBid.seatbid[0].bid[0].h,
    mediaType: serverBid.type,
    netRevenue: true,
    requestId: serverBid.id,
    ttl: serverBid.seatbid[0].bid[0].ttl || 300
  };

  if (serverBid.type == 'video') {
    Object.assign(bid, {
      vastXml: serverBid.seatbid[0].bid[0].vastXml,
      vastUrl: serverBid.seatbid[0].bid[0].vastUrl,
      ttl: 3600
    });
  }

  return bid;
}
1356213
function dispatchImps(bidRequests, refererInfo) {
  let secure = (refererInfo && refererInfo.referer.indexOf('https:') === 0);
  return bidRequests.map(bidRequest => buildImp(bidRequest, secure))
    .reduce((acc, curr, index) => {
      let bidRequest = bidRequests[index];
      let zoneId = bidRequest.params.zoneId;
      let host = bidRequest.params.host;
      acc[host] = acc[host] || {};
      acc[host][zoneId] = acc[host][zoneId] || [];
      acc[host][zoneId].push(curr);
      return acc;
    }, {});
}
43404
function RequestApi(constructorOptions) {

    LOG.debug('Instantiating new Request object');
    LOG.debug('Validating options');

    try {

        this.options =
            new requestOptions.Constructor().validate(constructorOptions);

    } catch (err) {

        LOG.error('Received error: %s', err);

        throw(
            err
        );

    }

    this.requests = [];
    this.batchId = 1;

}
1133981
function(validBidRequests, bidderRequest) {
    const auids = [];
    const bidsMap = {};
    const bids = validBidRequests || [];
    let priceType = 'net';
    let reqId;

    bids.forEach(bid => {
      if (bid.params.priceType === 'gross') {
        priceType = 'gross';
      }
      reqId = bid.bidderRequestId;
      if (!bidsMap[bid.params.uid]) {
        bidsMap[bid.params.uid] = [bid];
        auids.push(bid.params.uid);
      } else {
        bidsMap[bid.params.uid].push(bid);
      }
    });

    const payload = {
      u: utils.getTopWindowUrl(),
      pt: priceType,
      auids: auids.join(','),
      r: reqId
    };

    if (bidderRequest) {
      if (bidderRequest.timeout) {
        payload.wtimeout = bidderRequest.timeout;
      }
      if (bidderRequest.gdprConsent) {
        if (bidderRequest.gdprConsent.consentString) {
          payload.gdpr_consent = bidderRequest.gdprConsent.consentString;
        }
        payload.gdpr_applies =
          (typeof bidderRequest.gdprConsent.gdprApplies === 'boolean')
            ? Number(bidderRequest.gdprConsent.gdprApplies) : 1;
      }
    }

    return {
      method: 'GET',
      url: ENDPOINT_URL,
      data: utils.parseQueryStringParameters(payload).replace(/\&$/, ''),
      bidsMap: bidsMap,
    };
  }
1170726
function (serverResponse, bidRequests) {
    const body = serverResponse.body;
    if (!body.results || body.results.length < 1) {
      return [];
    }
    const bidRequest = bidRequests.bidRequest;
    const bidResponse = {
      requestId: bidRequest.bidId,
      cpm: body.cpm || 0,
      width: body.w ? body.w : 1,
      height: body.h ? body.h : 1,
      creativeId: body.creativeid || '',
      dealId: body.dealid || '',
      currency: getCurrencyType(),
      netRevenue: true,
      ttl: body.ttl || 10,
    };
    if (isNative(body)) {
      bidResponse.native = createNativeAd(body);
      bidResponse.mediaType = NATIVE;
    } else {
      // banner
      bidResponse.ad = createAd(body, bidRequest);
    }
    return [bidResponse];
  }
1323217
function adminRequest(params, cb) {
  params = params || {};
  var mbaasConf = params[constants.MBAAS_CONF_KEY];
  params[constants.MBAAS_CONF_KEY] = undefined;
  log.logger.debug({params: params}, "FH-MBAAS-CLIENT: adminRequest ");
  var fullParams = _.extend(_.clone(params), mbaasConf);
  log.logger.info({
    env: params.environment,
    domain: fullParams.domain,
    mbaasUrl: fullParams.__mbaasUrl
  }, "FH-MBAAS-CLIENT.adminRequest - calling mbaas:");
  var invalidParamError = validateAdminParams(fullParams);

  if (invalidParamError) {
    return cb(invalidParamError);
  }

  fullParams.data = fullParams.data || {};
  fullParams.data.notStats = params.notStats;
  fullParams = _buildAdminMbaasParams(fullParams);

  log.logger.debug({fullParams: fullParams}, "FH-MBAAS-CLIENT: adminRequest ");

  return doFHMbaaSRequest(fullParams, cb);
}
705296
function(validBidRequests) {
    let requests = [];
    validBidRequests.forEach(i => {
      let params = {
        jst: 'hb',
        ord: Math.random() * 10000000000000000,
        tz: getTz(),
        fl: getFl(),
        rr: getRr(),
        w: i.params.w,
        h: i.params.h,
        s: i.params.s,
        bidid: i.bidId,
        transactionid: i.transactionId,
        auctionid: i.auctionId
      };
      if (i.params.itu !== undefined) {
        params.itu = i.params.itu;
      }
      if (i.params.cur !== undefined) {
        params.cur = i.params.cur;
      }
      if (i.params.subid !== undefined) {
        params.subid = i.params.subid;
      }
      if (i.params.click3rd !== undefined) {
        params.click3rd = i.params.click3rd;
      }
      if (i.params.pubdata !== undefined) {
        for (let key in i.params.pubdata) {
          params['pubside_macro[' + key + ']'] = encodeURIComponent(i.params.pubdata[key]);
        }
      }
      requests.push({method: 'GET', url: 'https://ads.betweendigital.com/adjson', data: params})
    })
    return requests;
  }
562818
function(serverResponse, {bidRequest}) {
    const bidResponses = [];
    if (serverResponse.body) {
      const ads = serverResponse.body.ads;
      for (var index = 0; index < ads.length; index++) {
        const bidResponse = {
          requestId: ads[index].bidId,
          cpm: ads[index].cpm,
          width: ads[index].width,
          height: ads[index].height,
          creativeId: ads[index].creativeId,
          dealId: ads[index].dealId,
          currency: ads[index].currency,
          netRevenue: ads[index].netRevenue,
          ttl: ads[index].ttl,
          ad: ads[index].ad,
          mediaType: ads[index].mediaType
        };
        bidResponses.push(bidResponse);
      }
    }
    return bidResponses;
  }
707761
function(bidRequests, bidderRequest) {
    const userId = find(bidRequests, hasUserId);
    const pubcid = find(bidRequests, hasPubcid);
    const publisherId = find(bidRequests, hasPublisherId);
    const auctionId = find(bidRequests, hasAuctionId);
    let bidUrl = find(bidRequests, hasBidUrl);
    let url = find(bidRequests, hasUrl);
    let test = find(bidRequests, hasTestParam);
    const seats = find(bidRequests, hasSeatsParam);
    const deviceId = find(bidRequests, hasDeviceIdParam);
    const ifa = find(bidRequests, hasIfaParam);
    const tid = find(bidRequests, hasTidParam);
    bidUrl = bidUrl ? bidUrl.params.bidUrl : URL;
    url = url ? url.params.url : (config.getConfig('pageUrl') || utils.getTopWindowUrl());
    test = test ? test.params.test : undefined;
    var adRequests = bidRequests.map(bidToAdRequest);

    const payload = {
      auctionId: auctionId ? auctionId.auctionId : undefined,
      publisherId: publisherId ? publisherId.params.publisherId : undefined,
      userId: userId ? userId.params.userId : (pubcid ? pubcid.crumbs.pubcid : undefined),
      url: url,
      test: test,
      seats: seats ? seats.params.seats : undefined,
      deviceId: deviceId ? deviceId.params.deviceId : undefined,
      ifa: ifa ? ifa.params.ifa : undefined,
      tid: tid ? tid.params.tid : undefined,
      version: VERSION,
      gdprApplies: bidderRequest.gdprConsent ? bidderRequest.gdprConsent.gdprApplies : undefined,
      gdprConsent: bidderRequest.gdprConsent ? bidderRequest.gdprConsent.consentString : undefined,
      cookieSupport: !utils.isSafariBrowser() && utils.cookiesAreEnabled(),
      rcv: getAdblockerRecovered(),
      adRequests: [...adRequests]
    };
    const payloadString = JSON.stringify(payload);
    return {
      method: 'POST',
      url: bidUrl,
      data: payloadString,
    };
  }
1370389
function (serverResponse, bidRequest) {
    const bidResponses = [];
    // For this adapter, serverResponse is a list
    serverResponse.body.forEach(response => {
      const bid = createBid(response);
      if (bid) {
        bidResponses.push(bid);
      }
    });
    return bidResponses;
  }